Build a working game of Tetris in Conway's Game of Life Here is a theoretical question - one that doesn't afford an easy answer in any case, not even the trivial one.

In Conway's Game of Life, there exist constructs such as the metapixel which allow the Game of Life to simulate any other Game-of-Life rule system as well. In addition, it is known that the Game of Life is Turing-complete.

Your task is to build a cellular automaton using the rules of Conway's game of life that will allow for the playing of a game of Tetris.

Your program will receive input by manually changing the state of the automaton at a specific generation to represent an interrupt (e.g. moving a piece left or right, dropping it, rotating it, or randomly generating a new piece to place onto the grid), counting a specific number of generations as waiting time, and displaying the result somewhere on the automaton. The displayed result must visibly resemble an actual Tetris grid.

Your program will be scored on the following things, in order (with lower criteria acting as tiebreakers for higher criteria):

Bounding box size — the rectangular box with the smallest area that completely contains the given solution wins.
Smaller changes to input — the fewest cells (for the worst case in your automaton) that need to be manually adjusted for an interrupt wins.
Fastest execution — the fewest generations to advance one tick in the simulation wins.
Initial live cell count — smaller count wins.
First to post — earlier post wins.

This began as a quest but ended as an odyssey.
Quest for Tetris Processor, 2,940,928 x 10,295,296
The pattern file, in all its glory, can be found here, viewable in-browser here.
This project is the culmination of the efforts of many users over the course of the past 1 & 1/2 years.  Although the composition of the team has varied over time, the participants as of writing are the following:

PhiNotPi
El'endia Starman
K Zhang
Blue (Muddyfish)
Cows quack (Kritixi Lithos)
Mego
Quartata

We would also like to extend our thanks to 7H3_H4CK3R, Conor O'Brien, and the many other users who have put effort into solving this challenge.
Due to the unprecedented scope of this collaboration, this answer is split in parts across multiple answers written by the members of this team.  Each member will write about specific sub-topics, roughly corresponding to the areas of the project in which they were most involved.
Please distribute any upvotes or bounties across all members of the team.
Table of Contents

Overview
Metapixels and VarLife
Hardware
QFTASM and Cogol
Assembly, Translation, and the Future
New Language and Compiler

Also consider checking out our GitHub organization where we've put all of the code we've written as part of our solution.  Questions can be directed to our development chatroom.

Part 1: Overview
The underlying idea of this project is abstraction.  Rather than develop a Tetris game in Life directly, we slowly ratcheted up the abstraction in a series of steps.  At each layer, we get further away from the difficulties of Life and closer to the construction of a computer that is as easy to program as any other.
First, we used OTCA metapixels as the foundation of our computer. These metapixels are capable of emulating any "life-like" rule.  Wireworld and the Wireworld computer served as important sources of inspiration for this project, so we sought to create a similar constuction with metapixels.  Although it is not possible to emulate Wireworld with OTCA metapixels, it is possible to assign different metapixels different rules and to build metapixel arrangements that function similarly to wires.
The next step was to construct a variety of fundamental logic gates to serve as the basis for the computer.  Already at this stage we are dealing with concepts similar to real-world processor design.  Here is an example of an OR gate, each cell in this image is actually an entire OTCA metapixel.  You can see "electrons" (each representing a single bit of data) enter and leave the gate.  You can also see all of the different metapixel types that we used in our computer: B/S as the black background, B1/S in blue, B2/S in green, and B12/S1 in red.

From here we developed an architecture for our processor.  We spent significant effort on designing an architecture that was both as non-esoteric and as easily-implementable as possible.  Whereas the Wireworld computer used a rudimentary transport-triggered architecture, this project uses a much more flexible RISC architecture complete with multiple opcodes and addressing modes.  We created an assembly language, known as QFTASM (Quest for Tetris Assembly), which guided the construction of our processor.
Our computer is also asynchronous, meaning that there is no global clock controlling the computer.  Rather, the data is accompanied by a clock signal as it flows around the computer, which means we only need to focus on local but not global timings of the computer.
Here is an illustration of our processor architecture:

From here it is just a matter of implementing Tetris on the computer.  To help accomplish this, we have worked on multiple methods of compiling higher-level language to QFTASM.  We have a basic language called Cogol, a second, more advanced language under development, and finally we have an under-construction GCC backend.  The current Tetris program was written in / compiled from Cogol.
Once the final Tetris QFTASM code was generated, the final steps were to assemble from this code to corresponding ROM, and then from metapixels to the underlying Game of Life, completing our construction.
Running Tetris
For those who wish to play Tetris without messing around with the computer, you can run the Tetris source code on the QFTASM interpreter.  Set the RAM display addresses to 3-32 to view the entire game. Here is a permalink for convenience: Tetris in QFTASM.
Game features:

All 7 tetrominoes
Movement, rotation, soft drops
Line clears and scoring
Preview piece
Player inputs inject randomness

Display
Our computer represents the Tetris board as a grid within its memory.  Addresses 10-31 display the board, addresses 5-8 display the preview piece, and address 3 contains the score.
Input
Input to the game is performed by manually editing the contents of RAM address 1.  Using the QFTASM interpreter, this means performing direct writes to address 1.  Look for "Direct write to RAM" on the interpreter's page.  Each move only requires editing a single bit of RAM, and this input register is automatically cleared after the input event has been read.
value     motion
   1      counterclockwise rotation
   2      left
   4      down (soft drop)
   8      right
  16      clockwise rotation

Scoring system
You get a bonus for clearing multiple lines in a single turn.
1 row    =  1 point
2 rows   =  2 points
3 rows   =  4 points
4 rows   =  8 points


Calculate the sine of a float (in radians)… …without using any operator/function besides addition (+), subtraction (-), multiplication (*), division (/), modulo (%), exponent/power pow() or any of the standard C bitwise operators (<<, >>, ~, &, |, ^) or unary operators (—, ++) or assignment/comparison operators (=, ==).

If these symbols represent a different operation in your chosen language, go with the spirit of the question and don't use them.

Rules:

You cannot use any mathematical functions your language might offer (Mathematica, looking at you.)
You cannot use any operator besides the bitwise operators or the arithmetic operators listed above.
Your output should be a float and be correct to at least 2 decimal places when truncated/rounded.
You can use constants your language's standard libraries might provide.
You can hardcode the values, but your program should work correctly for all floats (up to 2 decimal places) between 0 and 2π;

This is code-golf, so the shortest answer wins.

Example:

Input: 3.141592653 / 2
Output: 1.00xxxxxx…

Please also post an ungolfed version of your code.

Python 83 69

Based on Bhaskara I's sine approximation formula

Implementation

def f(x):p=3.14;x,s=x%p,(4,-4,4)[int(x/p)];return s/(12.34/x/(p-x)-1)

Ungolfed

def apxsine(radian):
    pi = 3.14 # Approximate to 2 decimal places
    sign = (4,-4,4)[radian % pi]
    return sign / (12.34/radian/(pi - radian) - 1))

Deduction

Demo

>>> from math import pi, sin
>>> any(round(abs(f(e) - sin(e)), 2) for e in (e/180.*pi for e in range(0,360)))
False

JUst realized that if I would have opted for Euler's formula route, the code would be shorter (49 characters). But then it uses Complex numbers and am not sure if the call to the real method would be valid in the current question context.

f=lambda x:((2.72**(x*1j)-2.72**(-x*1j))/2j).real


The max() is not enough Intro

A friend posed this question today in a slightly different way - "Can a single [Python] command determine the largest of some integers AND that they aren't equal?".

While we didn't find a way to do this within reasonable definitions of "a single command", I thought it might be a fun problem to golf.

 Challenge

"Return the largest of a list of integers if-and-only-if they are not all equal."

More specifically:

Given a string containing only a comma-separated list of integers:

If they are all equal, return/output nothing
Else, return/output the largest

Rules

The input must be a string containing only a comma-separated list of integers
The output must be either nothing (no output of any kind), or else the largest element from the input, represented as it is in the input

Entries may be a full program or just a function, provided you provide some way to test them!

Assumptions

Assume input list elements may be more than one digit but no larger than
( 232 − 1 )
Assume the input list has no more than a million elements
Assume the input will not include negative values
Assume the input will never be empty

For the avoidance of doubt, the explanation of the challenge given just after "More specifically" shall supersede the statement of the challenge above it ("Return the largest...").

 Examples

(1) All equal:

Input: 1,1
Output:

(2) Dissimilar:

Input: 1,2
Output: 2

(3) Zero!:

Input: 0,0,0,0,0,0,0,1,0,0
Output: 1

(4) Random:

Input: 7,3,8,4,8,3,9,4,6,1,3,7,5
Output: 9

(5) Larger numbers, larger list:

Input: 627,3894,863,5195,7789,5269,8887,3262,1448,3192
Output: 8887

Additional examples:

(6) All equal, larger list:

Input: 7,7,7,7,7,7,7,7,7
Output:

(7) All equal, larger list, larger numbers:

Input: 61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976,61976
Output:

(8) Not equal, larger list, larger numbers:

Input: 96185,482754,96185,96185,96185,96185,96185,96185,7,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,96185,961185,96185,96185,96185
Output: 961185

Scoring

This is code-golf, so the code with the shortest number of bytes wins!

R, 50 37 bytes

-33 bytes thanks to digEmAll! -13 bytes thanks to rturnbull!

x=scan(se=",");if(any(diff(x)))max(x)

Try it online!


Regex that matches everything but itself You must make a regex that matches everything except itself. For example, PPCG must not match PPCG, but must match everything else, like something, PPC,  and PPCG!.

Surrounding slashes are not considered part of the regex in flavors where they are usually part of the syntax. The same is true of all delimiters.

The regex needs to match the entire string, not just a substring.

You may choose your flavor, but you can't use a flavor newer than this challenge. Please pick a flavor that is easily tested.

Shortest regex in bytes wins.

(Sandbox (deleted))

PCRE flavour, 45 bytes

^(?!\^()(?R){2}\z)|\1\Q(?!\^()(?R){2}\z)|\1\Q

Try it at regex101.

This is a simple modification of jimmy23013's brilliant solution to the opposite challenge. We just need to make two changes:

In this challenges, the delimiters shouldn't be matched so we drop them from the regex as well. However, that could lead to infinite recursion, because then no characters would be matched before the (?R) call. To fix this, we match the ^ explicitly with \^ to have one character before we enter the recursion.
We need to negate the result which is as simple as wrapping everything after the ^ in a negative lookahead to ensure that the input isn't equal to the string.

For the details of this quining approach, see jimmy's amazing answer.


Name an arbitrary string This should be easy: given an arbitrary string, your program will give it a name.

Requirements

Your program will accept an input of a UTF8 string, and output a string representing the input's "name", how you define this name is arbitrary, but it must comply with some conditions.

I/O Ranges

The input will at most be 382 UTF 8 characters long (making the input space 1112064^382 long). Don't ask me why this number, it was random. Your program must support all of them. Consider not forcing you to deal with arbitrary input size an act of mercy.

You can use any character set to build your output space. ASCII, Unicode, only Wingdings characters, etc. all are fair game. This output space must be smaller than the input space (easy enough), and name collisions must be uniformly distributed (every name will refer to roughly the same number of input strings, ~1% fluctuation is the max. accepted difference).

Yes I'm asking you to build a watered down hash function. Just in case you're wondering.

Name collisions must be sufficiently rare that it does not happen in everyday use. 1 in \$2^{100}\$ sounds reasonable enough a limit. This forces your output space to be at least 7540 bits long (the input space is a little larger than \$2^{7640}\$). (I tried cheating my own challenge by only outputting 0 and 1, you are not allowed to cheat like I did).

Conditions

Name collisions must be rare enough (see above) and must not be, by any method, deliberately generated. This is similar to hash collisions.
Name space must be smaller that input space (whats the point of having a name longer than the string)
Your program must be deterministic. Same string must be assigned the same name every time.

Winning

The program with a name of at most 10 characters long and pronounceable (edit: since someone pointed out pronounceable is hard to define, this condition is now changed to <=10 characters of the same spoken language) wins. If this win condition is not met, scoring is lowest byte wins as usual.

The same language above means any one of the languages that people use. If one language uses some characters from another, that is fine as long as it is within normal use. (French uses English characters, for example) Mixing different language's characters that are not within formal use is not allowed (e.g. Korean characters and English alphabets)

Also give your program's name in the answer, even though it is unlikely to be <=10 characters and/or unpronounceable. I am curious what your program is called.

05AB1E, 2 bytes
₂∍

Try it online!

Explanation
 ₂                - 26
  ∍               - Extend/shorten to this length

Extend will repeat the string until it is length 26, shorten will remove chars from the right until it is length 26.
This means that some strings will be slightly more likely (the repeated ones since ab, abab, ababab, ababababab etc all produce ababababababababababababab, but it will fall within the 1%, since these cases of collision only occur for strings below length 26.

05AB1E, 8 bytes (Winning)
HSAsèJ₆∍

Try it online!
Program's name: faegdahbbafaegdahbbafaegdahbbafaegda

Explanation
HSAsèJ          - Convert it to a string of the first 10 letters of the english alphabet
      ₆∍        - Extend shorten to base 36 (10^36 > 2^100)

Can definitely be shorter, but why bother. It wins.


Implement the Zundoko Kiyoshi function Background

The Zundoko Kiyoshi function originates from this tweet by kumiromilk. Translated from Japanese, it reads roughly as follows:

  The test for my Java lecture had a problem that said "Implement and describe your own function". I made it continuously output either "zun" or "doko" randomly; if the sequence "zun", "zun", "zun", "zun", "doko" appears, it outputs "ki-yo-shi!" and terminates. Then I got full marks and earned a unit.

This is in reference to Kiyoshi Hikawa's song Kiyoshi no Zundoko Bushi: when he sings the aforementioned line, the crowd cheers "ki-yo-shi!" in response.

Task

Write a program or function that takes no input and replicates the behavior outlined in the tweet:

Repeatedly output either zun or doko, choosing uniformly randomly each time.
If the sequence ["zun", "zun", "zun", "zun", "doko"] appears in the output, output ki-yo-shi! and halt.

Example output:

doko
zun
zun
doko
doko
zun
zun
zun
zun
zun
doko
ki-yo-shi!

Rules

This is code-golf, so shortest answer in bytes wins.
Your output can be a list of strings, or each string printed with some delimiter.
Your output has to be non-deterministic.

JavaScript (ES6), 72 bytes
f=x=>x%17^2?['doko ','zun '][j=Math.random()*2|0]+f(x<<7|j):'ki-yo-shi!'

Try it online!
How?
We keep track of the last 5 words in a 32-bit integer stored in \$x\$ (which is initially undefined). At each iteration, we left-shift it by 7 positions and set the LSB to \$0\$ for doko or \$1\$ for zun.
The sequence zun, zun, zun, zun, doko results in:
x = 10000001000000100000010000000
or \$270549120\$ in decimal, which is the only value for which we have \$x\equiv 2\pmod{17}\$, as shown in this table. This is our halt condition.


The Programming Language Quiz, Mark II - Robbers Cops challenge
The Robbers' Challenge

Find a vulnerable answer. That is, an answer which hasn't been cracked yet and which isn't safe yet either.

Crack it by figuring out its language. That is, find any language in which the given program is a valid program (subject to the rules outlined in the Cops' Challenge above). It doesn't matter if this is the language the cop intended.
Once you have found a working language, post an answer to the Robbers' thread and comment below the Cop's answer. If you don't have enough reputation to comment, say this in your answer and someone will comment for you.

The output format must be the same as the cop's intended solution in order to constitute a valid crack.
Every user only gets one guess per answer. This includes telling other people the answer, or hints towards your guesses. You must not crack your own answer (obviously...).
The user who cracked the largest number of answers wins the robbers' challenge. Ties are broken by the sum of bytes of cracked answers (more is better).
Good luck Robbers!


Generating Fermat primes Given a number n, print the nth prime Fermat number, where the Fermat numbers are of the form 22k+1. This code should theoretically work for any n (i.e. don't hardcode it), although it is not expected to terminate for n > 4. (It should not return 4294967297 for n=5, as 4294967297 is not a prime number.)

Do note that while all Fermat primes are of the form 22n+1, not all numbers of the form 22n+1 are prime. The goal of this challenge is to return the n-th prime.

Test cases

0 -> 3
1 -> 5
2 -> 17
3 -> 257
4 -> 65537

Rules

Standard loopholes are disallowed.
0-indexing and 1-indexing are both acceptable.
This is code-golf, lowest byte-count wins.

Related: Constructible n-gons

Python 2, 53 bytes

k=input();F=2
while k:F*=F;k-=3**(F/2)%-~F/F
print-~F

Try it online!

Uses Pépin's test.

Python 2, 54 bytes

f=lambda k,F=4:k and f(k-3**(F/2)%-~F/F,F*F)or F**.5+1

Try it online!


Hereditary Base Change Background

In this challenge, a base-b representation of an integer n is an expression of n as a sum of powers of b, where each term occurs at most b-1 times. For example, the base-4 representation of 2015 is

4^5 + 3*4^4 + 3*4^3 + 4^2 + 3*4 + 3

Now, the hereditary base-b representation of n is obtained by converting the exponents into their base-b representations, then converting their exponents, and so on recursively. Thus the hereditary base-4 representation of 2015 is

4^(4 + 1) + 3*4^4 + 3*4^3 + 4^2 + 3*4 + 3

As a more complex example, the hereditary base-3 representation of

7981676788374679859068493351144698070458

is

2*3^(3^(3 + 1) + 2) + 3 + 1

The hereditary base change of n from b to c, denoted H(b, c, n), is the number obtained by taking the hereditary base-b representation of n, replacing every b by c, and evaluating the resulting expression. For example, the value of

H(3, 2, 7981676788374679859068493351144698070458)

is

2*2^(2^(2 + 1) + 2) + 2 + 1 = 2051

The Challenge

You are given as input three integers b, c, n, for which you may assume n >= 0 and b, c > 1. Your output is H(b, c, n). The shortest byte count wins, and standard loopholes are disallowed. You can write either a function or a full program. You must be able to handle arbitrarily large inputs and outputs (bignums).

Test Cases

4 2 3 -> 3
2 4 3 -> 5
2 4 10 -> 1028
4 4 40000 -> 40000
4 5 40000 -> 906375
5 4 40000 -> 3584
3 2 7981676788374679859068493351144698070458 -> 56761
2 3 2051 -> 35917545547686059365808220080151141317047

Fun Fact

For any integer n, the sequence obtained by

n1 = n
n2 = H(2, 3, n1) - 1
n3 = H(3, 4, n2) - 1
n4 = H(4, 5, n3) - 1
....

eventually reaches 0. This is known as Goodstein's theorem.

Python 2, 55
H=lambda b,c,n,s=0:n and n%b*c**H(b,c,s)+H(b,c,n/b,s+1)

A recursive solution. Like the recursive algorithm to convert between bases, except it recurses on the exponent as well.
We split n into two parts, the current digit n%b, and all other digits n/b. The current place value is stored in the optional parameter s. The current digit is converted to base c with c** and the exponent s is converted recursively. The remainder is then converted the same way, as +H(b,c,n/b,s+1) but the place value s is one higher.
Unlike base conversion, hereditary base conversion required remembering the current place value in the recursion for it to converted.
For ease of reading, here's what it looks like when b and c are fixed global constants.
H=lambda n,s=0:n and n%b*c**H(s)+H(n/b,s+1)


DropSort it like it's hot As described in this question:

  Dropsort, designed by David Morgan-Mar, is an example of a linear-time "sorting algorithm" that produces a list that is, in fact, sorted, but contains only some of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is simply removed from the list and discarded.

To use one of their test cases, an input of {1, 2, 5, 4, 3, 7} yields {1, 2, 5, 7}, as 4 and 3 are both dropped for being smaller than the previously "sorted" value, 5.

We don't want "sorting" algorithms, we want them to be the real deal. Therefore, I want you to write a program that, given a list of numbers, outputs a list of DropSorted lists (to be a complete sorting algorithm, we would need to merge these lists, but
merging two sorted lists has been done before, and asking you to do it again is pretty much asking two questions, so this question is specifically the "splitting" step of our complete DropSort).

The arrangement and content of our lists is crucial, however. The output of your program must be equivalent to the output of a DropSort, followed by a DropSort of the discarded values, and so on until you have only have a list of sorted chains. Again, borrowing the existing test suite (and adding two more):

Input                  -> Output
{1, 2, 5, 4, 3, 7}     -> {{1, 2, 5, 7}, {4}, {3}}
{10, -1, 12}           -> {{10, 12}, {-1}}
{-7, -8, -5, 0, -1, 1} -> {{-7, -5, 0, 1}, {-8, -1}}
{9, 8, 7, 6, 5}        -> {{9}, {8}, {7}, {6}, {5}}
{10, 13, 17, 21}       -> {{10, 13, 17, 21}}
{10, 10, 10, 9, 10}    -> {{10, 10, 10, 10}, {9}}  //Note equivalent values aren't dropped
{5, 4, 3, 8, 7, 6}     -> {{5, 8}, {4, 7}, {3, 6}}
{0, 2, 5, 4, 0, 7}     -> {{0, 2, 5, 7}, {4}, {0}}

You may assume the input is non-empty.

This is code-golf, so standard rules apply!

Haskell, 67 59 58 bytes

(q:r)!x|x<last q=q:r!x|1<2=(q++[x]):r
_!x=[[x]]
foldl(!)[]

Explanation: Given a list of lists (that are already sorted) and a value x, the ! operator will place x at the end of the first list whose last element is less than or equal to x. If no such list exists, the list [x] is placed at the end.

Try it online.


Incremental Game Time Format Incremental Game Time Format

Goal

Incremental games often have a countdown timer expressing the days, hours, minutes and seconds until a task is complete.  Depending on the space available, they can be formatted as:

2d 13h
23h 59m 48s
14m
3h 0m 0s

The goal of this code golf is to write a function or program that performs this formatting.

Inputs

The total number of seconds.
The maximum number of segments to output.

Output

Segments include:

0w weeks
0d days
0h hours
0m minutes
0s seconds

Each segment is separated by a single space.
Displayed segments must be contiguous.  For example, you will not show hours and seconds without showing minutes, even if there are zero minutes.
Single-digit values do not have leading zeros, though a value of zero must be shown as 0.
Values are rounded down.
The first segment displayed is the first non-zero value.

Test Cases

seconds  segments  output
     0      1      0s
   123      1      2m
   123      2      2m 3s
   123      3      2m 3s
 82815      3      23h 0m 15s
307891      2      3d 13h
307891      4      3d 13h 31m 31s
604800      1      1w
604800      6      1w 0d 0h 0m 0s

Winning

The lowest byte-count solution in one week will win "acceptance".

Edits

Clarified which segment is first, as shown in examples.
Added test case 4 as per request.

CJam (snapshot), 41 38 bytes

q~"<<^X^G"{imd\}%W%"wdhms":s.+_{0=}#><S*

The above uses caret notation, since two of the characters are unprintable.

Thanks to @Sp3000 for golfing off 2 bytes.

Testing

The latest stable release (0.6.5) has a bug that can cause {}# to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (i).

To run this with code with the online interpreter, click this permalink or copy the code from this paste.

Alternatively, you can download and build the latest snapshot by executing the following commands:

hg clone http://hg.code.sf.net/p/cjam/code cjam-code
cd cjam-code/
ant

You can create the CJam file like this:

base64 -d > game-time.cjam <<< cX4iPDwYByJ7aW1kXH0lVyUid2RobXMiOnMuK197MD19Iz48Uyo=

How it works

q~        e# Read an evaluate the input.
"<<^X^G"  e# Push the string corresponding to the array [60 60 24 7
{         e# For each character:
  i       e#   Replace it by its code point.
  md      e#   Push divisor and residue of the division by that code point.
  \       e#   Swap their order.
}%
W%        e# Reverse the resulting array.
"wdhms":s e# Push ["w" "d" "h" "m" "s"].
.+        e# Perform vectorized concatenation.
_         e# Push a copy.
{0=}#     e# Find the index of the first pair with positive integer.
>         e# Remove the preceding pairs.
<         e# Truncate to the number of pairs specified in the input.
S*        e# Join, separating by spaces.


Make this dice game fair This challenge is adapted from the British Informatics Olympiad.

Dice game
Two players are playing a dice game where they each roll a pair of dice, and the highest sum wins. The pairs of dice have the same number of sides, but do not have to have the same values on each side. Therefore, the game is fair if for both pairs of dice all possible sums can be made with equal probability.
For example, if Player 1 has the following dice:
{1,2,3,4,5,6} {1,2,3,4,5,6}

Then they can produce the following sums:
    1  2  3  4  5  6
 +------------------
1|  2  3  4  5  6  7
2|  3  4  5  6  7  8
3|  4  5  6  7  8  9
4|  5  6  7  8  9  10
5|  6  7  8  9  10 11
6|  7  8  9  10 11 12

If Player 2 has:
{1,2,2,3,3,4} {1,3,4,5,6,8}

They can produce:
    1  2  2  3  3  4
 +------------------
1|  2  3  3  4  4  5
3|  4  5  5  6  6  7
4|  5  6  6  7  7  8
5|  6  7  7  8  8  9
6|  7  8  8  9  9  10
8|  9  10 10 11 11 12

This game is fair as the minimum for both is 2, the maximum is 12, and each sum occurs the same number of times, e.g 7 can be made 6 ways with each pair.

Challenge
Write a program/function that takes two dice as input, and optionally an integer representing the number of sides each dice contain, and prints/returns a different pair of dice that could be used to play a fair game with the two input dice, or any falsey value if there is no solution different from the input.

Specifications

The number of sides on both dice must be the same, and equal to the number of sides on the input pair of dice. This number will always be an integer greater than or equal to 1.

The two dice returned can be the same, but the pair must not be the same as the input pair.

Different order pairs are not different; {1,2,3} {4,5,6} is the same as {4,5,6} {1,2,3}.

Your program does not need to produce a result quickly, as long as it will eventually produce correct output.

The values on the input pair of dice dice will always be integers between 1 and 9 inclusive, but the values returned can be any integer ≥1.

If there is more than one possible solution, only one needs to be returned.

Input/Output can be in any reasonable format.

Test Cases
6
1 2 2 3 3 4
8 6 5 4 3 1

1 2 3 4 5 6
1 2 3 4 5 6

4
1 1 1 1
1 4 5 8

1 1 4 4
1 1 5 5

3
1 3 5
2 4 6

False

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

Any of the following:

1 2 2 3 3 4 4 5       |    1 2 2 3 5 6 6 7   |    1 2 3 3 4 4 5 6
1 3 5 5 7 7 9 11      |    1 3 3 5 5 7 7 9   |    1 2 5 5 6 6 9 10

Jelly, 34 bytes

+þµFṢ
ç©ṀRœċL}Œċµç/⁼®µÐf
,Ṣ€,Ṛ$ḟ@ç

Returns a list of all possible pairs of dice up to ordering of dice and faces* (excluding any that are the same dice as the input pair).

Try it online!

This is a brute-forcer, and is not efficient (too slow to even run the 6-face test case at TIO).

+þµFṢ - Link 1, sorted sums: dieA, dieB
 þ    - outer product with
+     -     addition (make a table of the sums, a list of lists)
  µ   - monadic chain separation
   F  - flatten into one list
    Ṣ - sort

ç©ṀRœċL}Œċµç/⁼®µÐf - Link 2, all possible fair dice pairs (including input): dieA, dieB
ç                  - call the last link (1) as a dyad
 ©                 - save the result to the register for later use too
  Ṁ                - maximum (the largest sum)
   R               - range [1,2,...,maxSum]
       }           - use right argument (dice B) to turn the monad into a dyad:
      L            -     length
    œċ             - all combinations with replacement (i.e. all dice with faces between 1 and maxSum inclusive [overkill, but golfier than less])
        Œċ         - all pairs of these dice
          µ        - monadic chain separation
               µÐf - filter keep:
            /      -     reduce with:
           ç       -         last link (1) as a dyad (the sorted sums of the current pair)
              ®    -     retrieve register value (the sorted sums of the input pair)
             ⁼     -     equal?

,Ṣ€,Ṛ$ḟ@ç - Main link: dieA, dieB
,         - pair - [dieA, dieB]
 Ṣ€       - sort €ach - [dieASorted, dieBSorted]
     $    - last two links as a monad:
    Ṛ     -     reverse - [dieBSorted, dieASorted]
   ,      -     pair - [[dieASorted, dieBSorted], [dieBSorted, dieASorted]]
        ç - call the last link (2) as a dyad (with dieA, dieB)
       @  - reversed @rguments:
      ḟ   -     filter out - removes any results that are equivalent to the input pair.

* i.e. if [[1,1,4,4],[1,1,5,5]] is a possibility (like in one of the examples) there wont be a [[1,1,5,5],[1,1,4,4] or [[1,4,1,4],[1,1,5,5]], etc.


Compressed days of the week Given an input of a list of days of the week, output the shortest sorted
representation of the list.

The format of the input is a string consisting of one or more of the
two-character substrings Su (Sunday), Mo (Monday), Tu (etc.), We, Th,
Fr, and Sa. The input may not necessarily be given in sorted order.

To convert the input to the output format,

Sort the input by day of week, starting from Sunday (ex. ThMoSaSuFrTuWe ->
SuMoTuWeThFrSa).
Reduce the abbreviations down to one letter if it leaves no ambiguity. For
example, SuMoTuWe should become SMTW because the first S couldn't
possible be Saturday, as that would make the output unsorted (same for the
T). However, ThFrSa should become ThFS, as both Tuesday and Thursday come
before Friday and reducing it down to TFS would create ambiguity.
If the output is now MTWTF, output D instead (which stands for
"weekdays"). Similarly, SS should become E for weekend. Finally,
SMTWTFS should become A for all days.

The input and output must both be a single string.

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

Test cases:

In              Out    | In              Out
-----------------------|--------------------
SuTu            STu    | SuTuWe          STW
SuTuSa          STuS   | SuWeTh          SWT
TuThSa          TTS    | TuThSu          STT
Su              Su     | Sa              Sa
WeTh            WT     | FrTh            ThF
WeTu            TW     | FrTu            TuF
FrWeMo          MWF    | SaWeSu          SWS
ThTu            TT     | We              W
ThTuMoFrWe      D      | SaSu            E
SuMoWeTuThFr    SMTWTF | ThMoSaSuFrTuWe  A

Retina, 152 88
Massively golfed with @Martin's and @randomra's help!  Thanks both of you!
^
SuMoTuWeThFrSa
([A-Z].)(?!.*\1)

T`l``Su\B|\BSa|o|r|u?We.?.?|uTh
^MTWTF$
D
SS
E
.{7}
A

Try it online.  A couple of the lines start with m`  with this online interpreter link.  This is so the program works with multiple input lines (to run all tests in one shot).  However, multiple input lines is not a requirement, so these are not included above or in my score.


Sort these bond ratings The task

The credit rating agencies assign ratings to bonds according to the credit-worthiness of the issuer, and the "Big Three" credit rating agencies use a similar (though not identical) tiered rating system. These have a clear, logical order - using the S&P tiers, AAA > AA+ > AA > AA- > A+ > ... > BBB > B > ... > C. Moody's uses a similar system, but names their tiers differently (Aaa > Aa1 > Aa2 > ... > Baa1 > ... > C).

Your task is to design a program which takes as input a list of strings representing bond rating tiers and output the same list, sorted in descending order from the highest tier (AAA/Aaa) to the lowest tier (C).

Input / Output

You may choose the format of the input (list, one per argument, CSV file). You may assume that every item in the input list is a valid rating string and that all rating strings in a list came from the same rating agency. Additionally, you may assume that none of the funky NA-style ratings such as "NR" or "WR" will be included - this is strictly from "Aaa/AAA" to "C". There may be duplicate ratings in the input list, and if found they should not be removed.

You may also choose the format of the output as is appropriate for your language, with the only restriction being that it should be outputting some standard text encoding like UTF-8 or ASCII.

Rules and scoring

This is code golf, so lowest byte count wins, standard loopholes disallowed. Please specify what the input and output format is.

Example program and test cases

The example Python program below can be used as a standard example of the correct sort order. The lists Moody and SP are the orderings to use.

Moody = ['Aaa', 'Aa1', 'Aa2', 'Aa3', 'A1', 'A2', 'A3',
         'Baa1', 'Baa2', 'Baa3', 'Ba1', 'Ba2', 'Ba3',
         'B1', 'B2', 'B3', 'Caa', 'Ca', 'C']

SP = ['AAA', 'AA+', 'AA', 'AA-', 'A+', 'A', 'A-',
      'BBB+', 'BBB', 'BBB-', 'BB+', 'BB', 'BB-',
      'B+', 'B', 'B-', 'CCC', 'CC', 'C']

test_cases = [
    (['Aa2', 'Aaa', 'Aa1'], ['Aaa', 'Aa1', 'Aa2']),
    (['AA', 'AA-', 'AA+'], ['AA+', 'AA', 'AA-']),
    (['Baa1', 'Ba1', 'A1', 'B1', 'Aaa', 'C', 'Caa', 'Aa1'],
     ['Aaa', 'Aa1', 'A1', 'Baa1', 'Ba1', 'B1', 'Caa', 'C']),
    (['BBB+', 'BB+', 'A+', 'B+', 'AAA', 'C', 'CCC', 'AA+'],
     ['AAA', 'AA+', 'A+', 'BBB+', 'BB+', 'B+', 'CCC', 'C']),
    (['B3', 'B1', 'B2'], ['B1', 'B2', 'B3']),
    (['B-', 'B+', 'B'], ['B+', 'B', 'B-']),
    (['B3', 'Caa', 'Aa1', 'Caa', 'Ca', 'B3'],
     ['Aa1', 'B3', 'B3', 'Caa', 'Caa', 'Ca']),
    (['B-', 'CCC', 'AA+', 'CCC', 'CC', 'B-'],
     ['AA+', 'B-', 'B-', 'CCC', 'CCC', 'CC'])
]

mdy_sort = lambda x: Moody.index(x)
sp_sort = lambda x: SP.index(x)

for l_in, l_out in test_cases:
    sort_key = mdy_sort if set(l_in).issubset(set(Moody)) else sp_sort
    assert sorted(l_in, key=sort_key) == l_out

Test cases

In case the python-style test case formatting is inconvenient, I've output it as space-delimited input strings (grouped in two-line pairs input followed by output):

Aa2 Aaa Aa1
Aaa Aa1 Aa2

AA AA- AA+
AA+ AA AA-

Baa1 Ba1 A1 B1 Aaa C Caa Aa1
Aaa Aa1 A1 Baa1 Ba1 B1 Caa C

BBB+ BB+ A+ B+ AAA C CCC AA+
AAA AA+ A+ BBB+ BB+ B+ CCC C

B3 B1 B2
B1 B2 B3

B- B+ B
B+ B B-

B3 Caa Aa1 Caa Ca B3
Aa1 B3 B3 Caa Caa Ca

B- CCC AA+ CCC CC B-
AA+ B- B- CCC CCC CC

Note: I mention the "Big Three" but only specify Moody's and S&P here - the reason is that the third, Fitch, uses the same system as S&P when you don't take into account the NA-style ratings, so including Fitch would be redundant.

ES6, 71 65 bytes

a=>a.sort((b,c)=>r(b)>r(c)||-1,r=s=>s.replace(/[^A-z]*$/,"z$&,"))

By inserting a z after the letters and suffixing a , we just have to sort the strings lexically.

Edit: Saved 6 bytes thanks to @user81655.


Print three columns vertically separated by space(s) Task

Take input string separated by space.
Sort the words alphabetically.
Print them out vertically in 3 columns separated by space(s).

Challenge

All three column's heights should be as evenly weighted as possible.
All three column's should be left aligned.

This is code-golf, so shortest code wins!
Example
If the input is:
"cat caterpillar pie frog elephant pizza",

The output should be:
cat         elephant pie
caterpillar frog     pizza

Please beware of cases, if input is:
"a b c d e f g"

Should be printed as:
a c e
b d f
    g

# or

a d f
b e g
c

# and not

a d g
b e
c f

Husk, 24 17 bytes

TmoTT' §CȯmLTC3Ow

Try it online!

Explanation

This was a surprisingly tricky challenge, as Husk currently lacks a builtin for breaking a list into a given number of parts.

TmoTT' §CȯmLTC3Ow  Implicit input, say s="bbb a cc ddd e"
                w  Split at spaces: x=["bbb","a","cc","ddd","e"]
             C3    Cut into slices of length 3: [["bbb","a","cc"],["ddd","e"]]
            T      Transpose: [["bbb","ddd"],["a","e"],["cc"]]
         ȯmL       Map length: [2,2,1]
                   These are the correct lengths of the columns.
       §C      O   Sort x and split into these lengths: [["a","bbb"],["cc","ddd"],["e"]]
                   These are the columns of the correct output, without padding.
 mo                For each column,
    T'             transpose and pad with spaces: [["ab"," b"," b"],["cd","cd"," d"],["e"]]
   T               then transpose back: [["a  ","bbb"],["cc ","ddd"],["e"]]
T                  Transpose the whole list: [["a  ","cc ","e"],["bbb","ddd"]]
                   Implicitly join each row by spaces,
                   join the resulting strings by newlines and print.


Confusing Alphabet Staircase Given no input, output this interesting alphabet pattern in either case (the case has to be consistent) via an accepted output method:

A
AB
ACBC
ADBDCD
AEBECEDE
AFBFCFDFEF
AGBGCGDGEGFG
AHBHCHDHEHFHGH
AIBICIDIEIFIGIHI
AJBJCJDJEJFJGJHJIJ
AKBKCKDKEKFKGKHKIKJK
ALBLCLDLELFLGLHLILJLKL
AMBMCMDMEMFMGMHMIMJMKMLM
ANBNCNDNENFNGNHNINJNKNLNMN
AOBOCODOEOFOGOHOIOJOKOLOMONO
APBPCPDPEPFPGPHPIPJPKPLPMPNPOP
AQBQCQDQEQFQGQHQIQJQKQLQMQNQOQPQ
ARBRCRDRERFRGRHRIRJRKRLRMRNRORPRQR
ASBSCSDSESFSGSHSISJSKSLSMSNSOSPSQSRS
ATBTCTDTETFTGTHTITJTKTLTMTNTOTPTQTRTST
AUBUCUDUEUFUGUHUIUJUKULUMUNUOUPUQURUSUTU
AVBVCVDVEVFVGVHVIVJVKVLVMVNVOVPVQVRVSVTVUV
AWBWCWDWEWFWGWHWIWJWKWLWMWNWOWPWQWRWSWTWUWVW
AXBXCXDXEXFXGXHXIXJXKXLXMXNXOXPXQXRXSXTXUXVXWX
AYBYCYDYEYFYGYHYIYJYKYLYMYNYOYPYQYRYSYTYUYVYWYXY
AZBZCZDZEZFZGZHZIZJZKZLZMZNZOZPZQZRZSZTZUZVZWZXZYZ

Trailing spaces and newlines are acceptable, standard loopholes are disallowed, and this happens to be code-golf, so the shortest answer in bytes wins!

Jelly, 9 bytes

ØAjṪ$Ƥż¹Y

Try it online!

How it works

ØAjṪ$Ƥż¹Y  Main link. No arguments.

ØA         Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
     Ƥ     Map the link to the left over all prefixes, i.e., ["A", "AB", ...].
    $        Combine the two links to the left into a chain.
   Ṫ           Tail; yield and remove the last letter of each prefix.
  j            Join the remainder, using that letter as separator.
      ż¹   Zip the resulting strings and the letters of the alphabet.
        Y  Separate the results by linefeeds.


Print NxN spiral of ascending numbers The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

4

Output:

01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07

I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.


Tips for golfing in Lua What general tips do you have for golfing in Lua? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Lua (e.g. "remove comments" is not an answer). Please post one tip per answer.

In addition to the ones already posted, here are some tricks I've gathered over time, in no specific order...

For the function calls that only have one parameter delimited by a symbol (" for strings, { for tables), the parameter doesn't need to be wrapped around parentheses.
For example, instead of doing print("hello"), you can simply do : print"hello"
Remove as much whitespace as possible - this is especially easy to do after a symbol that closes strings (or before one opening), function calls, tables... Instead of print(42) a=1 you can do print(42)a=1. Other example: print(a and-1 or-2).
Use the ternary operator when you can! Instead of if a>0 then print("hello") else print("goodbye") end, prefer print(a>0 and "hello" or "goodbye"). More info here.
(This can actually get even better : print(a>0 and"hello"or"goodbye"))
Use the colon-call syntactic sugar when you can : instead of string.rep(str,12), do str:rep(12). That also works on non-variables this way (and only this way) : ("a"):rep(5)
Instead of doing tonumber(str) just do str+0
For functions with no parameters, instead of defining them the usual way (function tick() blabla() end), you can do : ticks=loadstring"blabla()", which saves 1 or more bytes, depending on the content. Also, if you define multiple functions, localize loadstring to a 1-char variable before and you'll save a lot of bytes ;). Credits to Jim Bauwens for this trick.
Lua considers empty string (and 0 too unlike other languages) as true in conditional tests, so, for example, instead of doing while 1 do ... end, save 1 byte by writing while''do ... end


Partial tq interpreter In this task you are expected to provide a list output given an input tq program. The tq programs will not contain whitespace inside them.

What is tq, in the first place?

tq is a lazy-evaluated language that is designed with the idea that array items should be accessable during the definition of them. In tq, there is no explicit separator of an array, only special arrangements of monadic/dyadic functions and nilads.

The following program is a program printing [123] (Pretend that tq doesn't support strings because we aren't dealing with them in this case):

123

This defines a list with the first item being the number 123, after which all items in the list will be outputted inside a list.

In tq, numbers are supported to allow multiple-digits. So this defines a list with 2 items:

12+12,5

In this test case, you are expected to output the list [24,5]. Let's explain it step by step.

12+12   # This evaluates 12 + 12 in the current item in the list, returning 24
     ,  # A separator. This separates two items when they could be potentially
        # ambiguous when they are applied without a separator.
      5 # This evaluates 5 in the current item in the list, returning 5
        # The comma is simply a no-op that doesn't require parsing.

So you think that tq is not hard at all to implement? Well, remember that tq also has a special feature of accessing the items in an array before the array is defined!

555th123

We introduce two new atoms:

t (tail) means access the last item in the list
h (head) means access the first item in the list

Therefore our list is going to yield:

[555,123,555,123]

Now take a look at this program:

555ps123

We introduce 2 more atoms:

p Yield the next item before (previous) the current position
s Yield the next item after (succeeding)the current position

This yields the list:

[555,555,123,123]

A quick reference of the tq language

Just assume that you only have two operands for the operators.

[0-9] starts a number. Numbers will only be positive integers, i.e. no decimals and negative numbers.
, This is a separator of different items when it is given that two consecutive indexes will be ambiguous with each other without a separator. In tq all of the remaining characters can act as a separator, but in this case it is a good idea to implement only , for the ease of your implementation.
+ and * These are arithmetic operators. Usually in tq, they may be applied multiple times, e.g. 1+2+3, but in your implementation, input will be provided so that this will not happen and only 1+2 will happen (there will not be applications multiple times).
t return the last item in the list. If the code is t1,2,3 it shall return [3,1,2,3].
h return the first item in the list. If the code is 1,2,3h it shall return [1,2,3,1].
p returns the item before the current item. If the code is 0,1,p,3,4 the code shall return [0,1,1,3,4].
s returns the item after the current item. If the code is 0,1,s,3,4 the code shall return [0,1,3,3,4].

Additional rules (with some examples)

You also have to implement multiple hops. E.g. 1th should yield [1,1,1]
If you know that something is going to form a loop, e.g. 1sp2, the cells that form the loop should be removed. Therefore the previous example will yield [1,2].
Out of bounds indexing will yield the closest index of the indexed item that is a number. E.g. 1,2s should yield [1,2,2]
If any possible indexing fails, you may do whatever operation you prefer.

More test cases

4p*p will yield [4,16]
1p+s2 will yield [1,3,2]
1,2,3h+t4,5,6 will yield [1,2,3,7,4,5,6]
3ppss6 will yield [3,3,3,6,6,6]

Jelly, 131 bytes

+Ø+o+2$};;1N;Ø½“spth+*”żF
ṣ”,µeþØD,Øa¤Ḥ2¦SSƝ>2k)Ẏµe€⁾+*oḊ$k)µJç€LyⱮ"ƲVḢf?€€ØDAƑƇ.ị;@Ʋµṙ-+;×ɗị@ƭ/$¹L’$?¹Nị⁸¹L’$?ɗAƑ?€AƑ?F¥€`ÐLAƑƇFṖṖ

Try it online!

A full program taking a tq program string as its input and returning a list of integers. Still needs more golfing, but seems to work ok. Doesn’t use eval except for converting numbers from string to integer (which wouldn’t be an eval in most languages).


Write an interpreter for my esoteric language Jumper I have thought up esoteric language Jumper. Later you will see why.

It operates with random-access-memory with bytes as cells. RAM is zero indexed and initially filled with zeros.
When trying access cells with negative indexes error should be displayed and program terminated.
When trying read at larger index than last, zero should be returned.
When trying write at larger index than last, RAM should be increased to multiple of 1024 and new cells filled with zeros (technically you can increase RAM not to multiple of 1024, reason was performance boost, so if it costs you a lot of characters you can do it not to multiple of 1024).
Program also has pointer to cell in RAM which initially is zero
When program starts executing a prompt for input string should be displayed (or take input from command line arguments, it's up to you). Input string should not contain null character (zero byte). Then input string is written to RAM starting at zero index.
When program ends executing a box with program output is displayed - contents of RAM from zero index to first zero byte excluding.

Now, most interesting part, syntax.

Program consists of commands (unary operators-prefixes) and their arguments. Commands and arguments may be delimited with spaces or new lines but not necessary. However spaces inside arguments are invalid, for example, # 2 = 4 is valid, but # 2 = 4 4 is not.
Program can have comments between (). Comments can't be nested - for example, in (abc(def)ghi) comment is (abc(def). Comments can be placed anywhere.

#123 sets RAM pointer to 123 (any positive decimal integer or zero).
>123 increments RAM pointer by 123 (any positive decimal integer).
<123 decrements RAM pointer by 123 (any positive decimal integer).
=123 writes 123 (any unsigned 8-bit decimal integer) in current cell.
+123 adds 123 (any unsigned 8-bit decimal integer) to current cell (modulo 256).
-123 subtracts 123 (any unsigned 8-bit decimal integer) from current cell (modulo 256).
:123 - "goto" - goes to command number 123 (first is 0). You can control flow of your program only with goto's - it has to jump - that's why I decided to call this language Jumper.

If argument is missing - think of it is 1 for ><+- commands or 0 for #=: commands.

Also, there is command modifier - ? (prefix to command), it executes next command only if current cell is not zero, else skips that command. Can be applied to any command.
For example, ?:17 - goes to command 17 if current cell is not zero.

If program is invalid or error occurs during runtime can be displayed message "Error". Because of this is CodeGolf, such short message will be fine.

Your task

Write shortest interpreter for this language.

Some test programs

(prints "Hello world!" regardless of input)
=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=

(appends "!" to the end of input string)
?:2 :4 >1 :0 =33 >1 =0

Ruby, 447 bytes

p,i=$*
l=(i||'').length
r=[0]*l
l.times{|j|r[j]=i[j].ord}
i=j=0
s=p.gsub(/\(.*?\)|\s/,'')
q=s.scan(/(\?)?([#<>=+:-])(\d*)/)
e=->{abort"Error"}
p[/\d\s+\d/]||q*''!=s ?e[]:(r+=[0]until i+1<r.length
c=q[j]
j+=1
f=c[1]
c[0]&&r[i]==0?next: a=c[2]==''? '><+-'[f]?1:0:c[2].to_i
'=+-'[f]&&a>255?e[]: f==?#?i=a :f==?>?i+=a :f==?<?i-=a :f==?=?r[i]=a :f==?+?r[i]+=a :f==?-?r[i]-=a :j=a
i<0?e[]:r[i]%=256)while j<q.length
puts r.first(r.index 0).map(&:chr)*''

Takes both the program and the input via command line arguments.

EDIT: Fixed a few bugs, and added support for invalid syntax at the cost of 40 bytes (while adding a few other optimisations).


Mapping between integer and pronounceable word Purpose

The idea is to provide the code necessary to map a 32-bit integer to/from a pronouncable word of 9 characters maximum. That could be useful, for example, to make a serial number easier to remember, or type in a form.

Both the method for translating an integer to the corresponding word and for translating back a word to the corresponding integer are required.

Rules

There must be a one-to-one mapping between integers and words, and the whole set of 32-bit integers (or, put in another way, any integer from 0 to 4294967295) must be mappable. Although, obviously, not all words will be meaningful, and inputting words that don't map to an integer may have unspecified behavior.

You are free to decide on exactly which set of "pronouncable" words is meaningful, and how the mapping is done, but words must at least follow these rules:

Only the basic 26 letters (A...Z) should be used as characters. Accents, casing, etc... should not be used to extend the possible combinations.
9 characters maximum per word.
two consonants (BCDFGHJKLMNPQRSTVWXZ - 20 possiblities) should not be placed next to each other (they must be surrounded by vowels).
two vowels (AEIOUY - 6 possibilities) should not be placed next to each other (they must be surrounded by consonants).

Note: the simplest scheme where you have all words constructed as CVCVCVCVC (C being a consonant and V a vowel) gives 4147200000 combinations, and a 32 bit integer has 4294967296 possible values, so it is not enough. You need to expand the number of combinations, either by allowing shorter words, or by allowing VCVCVCVCV combinations, as well.

Other standard rules apply, and standard loopholes are forbidden.

Inputs/Outputs

For each submission, two pieces of code must be provided:

One that takes an integer as argument/input and returns/prints the corresponding word
One that takes a word as argument/input and returns/prints the corresponding integer

Alternatively, you can choose to submit a single piece of code that handles both operations:

When given an integer as an input, it outputs the corresponding word
When given a string as an input, it outputs the corresponding integer

Winning condition

This is a code-golf, the answer which has the fewest bytes (when summing both pieces of code, for solutions opting for the separated pieces of code) wins.

PHP, 353 Bytes

Encoding + Decoding

is_numeric($argn) contains the boolean. It is true if the input is an integer.

$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);if(is_numeric($a=$argn)){$r=($a)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r;}else{for($p=1;$i++<strlen($a);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s;}

PHP, 190 Bytes (Encode) + 195 Byte (Decode) = 385 Bytes

Encoding

$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);$r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r;

5391360000=26*120**4 combinations are available

Online Version Encoding without E_NOTICE

Expanded

$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);
sort($c); # End of Prepare the two array
$r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6]; #base 26 decision input mod 26 <6 end with vowel
$a=$a/26^0; #integer division input with 26
while($a){
    $z=count($t=in_array($r[0],$v)?$c:$v); # use vowel if last entry is consonant and viceversa
    $r=$t[$n=$a%$z].$r; # base 6 or base 20 decision
    $a=$a/$z^0; # divide through base
}echo$r; # Output result

Input => Output

4294967296 => TYPYQACOV
333 => DAT
1 => E
7 => C
4294967276 => UTOPOQAMI

If you need always 9 Byte result please replace while($a) with while(strlen($r)<9) + 10 Bytes

Decoding

$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);for($p=1;$i++<strlen($a=$argn);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s;

Expanded

$c=array_diff(range("A","Z"),$v=["A","E","I","O","U","Y"]);
sort($c); # End of Prepare the two array
for($p=1;$i++<strlen($a=$argn);){
    $u=($b=in_array($a[-$i],$c))?$c:$v; # find use array for $a[-$i]
    $s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0); # sum value
    $p*=$i>1?count($u):26; # raise multiple for next item
}echo$s;

Input => Output

ABABABABE => 1
E => 1
UTOPOQAMI => 4294967276
BABABADAT => 333
DAT => 333
TYPYQACOV => 4294967296

Online Version Decoding without E_NOTICE

Additional Check

If we need a check if a string is valid.

Add $x.=$b?:0; in the end of the decoding loop + 10 Bytes

Replace echo$s; with echo!preg_match('#([01])\1$#',$x)?$s:_; + 32 Bytes


Implement strategy for Jacks or Better Video You are dealt five cards from a single deck. Implement a strategy for Jacks or Better Video Poker that has an expected revenue of at least 99.46%. Output the cards you want to hold.

The shortest code wins.

You are not required to implement the suggested strategy. Optimum play is also acceptable.

Input is read from standard input, output is written to standard output. Cards are identified as pairs of number (2,...,9,T,J,Q,K,A) and suit (S,H,D,C - spades, hearts, diamonds, clubs): 3C - three of clubs, QH - queen of hearts.

Examples:

$ ./jacks                               |
3C JC 5C QC 3H                          |<< input
3C 3H                                   |<< output
$ ./jacks                               |
3C 4C 5C 6C 7C                          |<< input
3C 4C 5C 6C 7C                          |<< output

I did it!!!

import java.io.*;
// 427 lines 200
public class Base {

    static char suit (String tokens) {  return  tokens.charAt (1); }
    public static char num (String tokens) { return tokens.charAt (0);}

    public static void checkPair (String [] tokens)
    {
        for (int a = 0; a < 4; ++a)
        for (int b = a+1; b < 5; ++b)
            if (num (tokens [a]) == num (tokens [b]))
                System.out.print (tokens [a] + " " + tokens [b]);
    }

    public static void checkThreeKind (String [] tokens)
    {
        for (int a = 0; a < 3; ++a)
            if (num (tokens [a]) == num (tokens [a+1]))
                for (int b = 2; b < 5; ++b)
                    if (num (tokens [a]) == num (tokens [b]))
                        System.out.print (tokens [a] + " " + tokens [a+1] + " " + tokens [b]);
    }

    static void checkTwoPair (String [] tokens)
    {
        for (int i = 0; i < 5; i++)
        for (int j = 1; j < 5; j++)
            //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
            if (num (tokens [i]) == num (tokens [j]))
                for (int y = 0; y <= 4; y++)
                    for (int x = 1; x <= 4; x++)
                        if ((i != y) && (j != x) && (y != x) && (i != j))
                            if (num (tokens [y]) == num (tokens [x]))
                                if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                        (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                    eblock (tokens);
    }

    static void checkHighFlush (String [] tokens)
    {
        if (suit (tokens [0]) == suit (tokens [1]) &&
            suit (tokens [0]) == suit (tokens [2]) &&
            suit (tokens [0]) == suit (tokens [3]) &&
            suit (tokens [0]) == suit (tokens [4]))
        {
            String outputString = "";
            for (int i = 0; i < tokens.length; i++)
                outputString  += tokens [i] + " ";
            System.out.println (outputString);
            System.exit (0);
        }
        for (int i = 0; i <= 4; i++)
            for (int j= 1; j<= 4; j++)
                //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
                if (suit (tokens [i]) == suit (tokens [j]))
                    for (int y = 0; y <= 4; y++)
                        for (int x = 1; x <= 4; x++)
                            if ((i != y) && (j != x) && (y != x) && (i != j))
                            {
                                if (suit (tokens [i]) == suit (tokens [x]) &&
                                        suit (tokens [i]) == suit (tokens [y]))
                                {
                                    if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                            (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                        eblock (tokens);
                                }
                            }
    }

     static void checkFourKind (String [] tokens)
     {
        if (num (tokens [0]) == num (tokens [1]))
        {
            if (num (tokens [0]) == num (tokens [2]))
                if (num (tokens [0]) == num (tokens [3]) || num (tokens [0]) == num (tokens [4]))
                    eblock (tokens);
            if (num (tokens [0]) == num (tokens [3]))
                if (num (tokens [0]) == num (tokens [4]))
                    eblock (tokens);
        }
        if (num (tokens [1]) == num (tokens [2]))
            if (num (tokens [1]) == num (tokens [3]))
                if (num (tokens [1]) == num (tokens [4]))
                    eblock (tokens);
    }

    static void checkStraight (String [] tokens)
    {
        int [] ints = new int [5];
        for (int i = 0; i <= 4; i++)
        {
            switch (num (tokens [i]))        {
            case 'T': ints [i] = 10;
            case 'J': ints [i] = 11;
            case 'Q': ints [i] = 12;
            case 'K': ints [i] = 13;
            case 'A': ints [i] = 14;
            default:  ints [i] = num (tokens [i]) - '0';
        }
        }
        for (int i = 0; i <= 3; i++)
        for (int j= 1; j<= 4; j++)
            //First Increment is pair 1 2, followed by 1 3, 1 4, and 1, 5 then 2 3, 2 4, 2 5, then 3 4, 3 5 then 4 5
            if ((ints [i]+1) == ints [i+1])
                for (int y = 0; y <= 4; y++)
                    for (int x = 1; x <= 4; x++)
                        if ((i != y) && (j != x) && (y != x) && (i != j))
                        {
                            if (ints[i] + 2 == ints[y] && ints[i] + 3 == ints [x])
                            {
                                if ((tokens [i] != tokens [j]) && (tokens [i] != tokens [y]) && (tokens [j] != tokens [y]) &&
                                        (tokens [i] != tokens [x]) && (tokens [j] != tokens [x]) && (tokens [y] != tokens [x]))
                                {
                                    for (int a : new int[] {i, j, y, x})
                                        System.out.print (tokens [a] + " ");
                                    System.out.println ();
                                    System.exit (0);
                                }
                            }
                            java.util.Arrays.sort (ints);
                            if (( (ints [i]+1 == ints [j]) && (ints [i]+3 == ints [y]) && (ints [i]+4 == ints [x])))
                            {
                                for (int a : new int[] {i, j, y, x})
                                    System.out.print (tokens [a] + " ");
                                System.out.println ();
                                System.exit (0);
                            }
                        }
    }

    static void checkHighCard (String [] tokens)
    {
        int [] ints = new int [5];
        for (int i = 0; i <= 4; i++)
        {
            switch (num (tokens [i]))        {
            case 'T': ints [i] = 10;
            case 'J': ints [i] = 11;
            case 'Q': ints [i] = 12;
            case 'K': ints [i] = 13;
            case 'A': ints [i] = 14;
            default:  ints [i] = num (tokens [i]) - '0';
        }
        }
        int marker = 0;
        if (ints [0] > ints [1]) marker = 1;
        if (ints [1] > ints [2]) marker = 2;
        if (ints [2] > ints [3]) marker = 3;
        if (ints [3] > ints [4]) marker = 4;
        System.out.println (tokens [marker]);
    }

    static void eblock (String[] tokens)
    {
        for (int i = 0; i < 5; i++)
            System.out.print (tokens [i] + " ");
        System.out.println ();
        System.exit (0);
    }

    static void checkFullHouse (String [] tokens)
    {
        String [] test = new String [5];
        int counter = 0;
        int sum = 0;

        for (int i = 0; i <= 4; i++)
        test [i] = tokens [i];
        for (int i = 0; i <=4; i++)
        {
        for (int j = 1; j <= 4; j++)
        {
            if (num (test [i]) == num (tokens [j]))
                counter++;
        }
        if (counter > 1)
            sum++;
        counter = 0;
        }
        if (sum == 5) eblock (tokens);
    }

    public static void main (String [] args) throws IOException
    {
        String inputString = new BufferedReader (new InputStreamReader (System.in)).readLine ();
        String [] tokens = inputString.split (" ");
        java.util.Arrays.sort (tokens);
        checkFourKind (tokens);
        checkHighFlush (tokens);
        checkFullHouse (tokens);
        checkStraight (tokens);
        checkTwoPair (tokens);
        checkThreeKind (tokens);
        checkPair (tokens);
        checkHighCard (tokens);
    }
}


Calculate a User's Reputation Challenge

Given a user's name (not ID, we have that challenge already), output their current reputation and their ID.

Input

Input will be a single string which is the user's username. You may assume that this user exists.

Output

Output will be two integers to either STDOUT or STDERR which will be the user's reputation and the user's ID. They must be in that specific order and can be output in any reasonable format

Specifics

The reputation output must not be more than 10 minutes out of date.
Your program may not throw any errors during normal execution
Standard loopholes apply (including No URL Shorteners)
If there is more than one user with that username, you may output the stats of any user with that username. This is also why you must output the ID.
The reputation to be output is the reputation of the user on PPCG, not the network total score.

The Stack Exchange API site can be found here. You can read the documentation from there.

JavaScript (ES6), 145 139 136 125 123 117 bytes

a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert)

Saved 6 bytes thanks to Shaggy and 6 bytes thanks to Cyoce.

I'm not sure if it should output all users with the same name, or just one of them; this code outputs all of them.

f=a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert)

f("tom")


Parse the Bookworm dictionary format I've recently been indulging myself in some nostalgia
in the form of Bookworm Deluxe:

In case you haven't seen it before,
it's a word game where the goal is to connect adjacent tiles to form words.
In order to determine whether a string is a valid word,
it checks it against its internal dictionary,
which is stored in a compressed format that looks like this:

aa
2h
3ed
ing
s
2l
3iis
s
2rdvark
8s
4wolf
7ves

The rules for unpacking the dictionary are simple:

Read the number at the start of the line,
and copy that many characters from the beginning of the previous word.
(If there is no number,
copy as many characters as you did last time.)
Append the following letters to the word.

So, our first word is aa,
followed by 2h,
which means "copy the first two letters of aa and append h,"
forming aah.
Then 3ed becomes aahed,
and since the next line doesn't have a number,
we copy 3 characters again to form aahing.
This process continues throughout the rest of the dictionary.
The resulting words from the small sample input are:

aa
aah
aahed
aahing
aahs
aal
aaliis
aals
aardvark
aardvarks
aardwolf
aardwolves

Your challenge is to perform this unpacking
in as few bytes as possible.

Each line of input will contain zero or more digits 0-9
followed by one or more lowercase letters a-z.
You may take input and give output
as either a list of strings,
or as a single string with words separated by any character other than 0-9/a-z.

Here is another small test case
with a few edge cases not covered in the example:

abc cba 1de fg hi 0jkl mno abcdefghijk 10l
=> abc cba cde cfg chi jkl mno abcdefghijk abcdefghijl

You may also test your code on the full dictionary:
input,
output.

Vim, 57 bytes

:%s/\a/ &
:%norm +hkyiwjP
:g/\d/norm diw-@"yl+P
:%s/ //g

Try it online!


Go to opposite corner of rectangle in all directions - Harder This is essentially the same thing as this question, except harder. You are again to write a program that gets from the lower-left corner of a rectangle to the upper-right corner. However, this time diagonal moves are allowed.

The program will accept an ordered pair (width, height), and use these as the dimensions for a rectangle. Your program will then create an ASCII-art of the solution (use . for an empty square, # for part of the solution, and X for starting square) and count the number of moves it takes to reach the endpoint.

Example

Input: (5, 6)

Output:

....#
....#
...#.
..#..
.#...
X....
Move count: 5

Shortest answer in bytes wins!

Pyth, 46 45 44 bytes

eSKtMQjsM_mm?sJ,kd?q#J.umtWbbNeSKK\#\.\XhQeQ

Try it here.

Explanation:

move-count-printing:

  K     assign K to...
     Q  the input, a 2-length array...
   tM   with each element decremented
eS      take the max and output it (this is the number of moves)

main path-finding logic:

    mm                     hQeQ  map over x-values and y-values...
        J,kd                     assign J to [x,y]
      ?s                         if both x and y are NOT zero (sum is truthy)...
            ?q#J[...]              if [x,y] is present in [...] (see below)...
                     \#            ... put a # at this position in the output
                       \.          ... else, put a . at this position
                         \X      ... else, put the X here (at [0,0])
jsM_                             reverse and output in the proper format

the [...] part in the code above, which finds positions where #s go:

.u      eSKK  cumulative reduce on <number of moves> elements, starting at K,
                which is [max_x, max_y] as assigned at the beginning
  m    N      map over x and y...
   tWbb       decrement, only if the value is > 0


Seven Segment Scrolling Sandbox Post

Intro

The information panels are everywhere. When the technology became cheaper, the paper posters were transformed into luminous signs that show words that appear on one side and come out on the other, like the one on the figure:

When one of these signs starts up, it usually starts empty and the text leaves from the right side to the left, moving until it disappears.

Its functionality is to go on and off the small light bulbs (LEDs) to give the sensation of movement.

If instead of text we only need to show numbers, the poster can be much less sophisticated using the so-called seven-segment markers like the following:

In this case each number is represented by the combination on / off of only 7 light segments that allow to represent all the numbers:

The question we ask ourselves is how many changes of lights (how many on and off) should be made to pass through one of these posters a certain number?

For example, to show the 123 in a 3-digit sign that starts with all the LEDs off we will have:

This makes a total of 42 changes of lights.

Challenge

Given a non-negative number and a positive sign length calculate the number of lights changes.

Rules

Assume input consist in a non-negative number (N >= 0) and a positive sign length (M > 0)
Assume Sign length >= Number length (M >= digits(N))

Test cases

123, 3        => 42
45, 5         => 60
111, 3        => 12
98765, 10     => 220
0, 3          => 36

Python 2, 129 126 119 104 bytes

def f(n,k,p=0):z=p<1or n>0;q=-~ord('}/lx2Z^o~z'[n%10])*z;return(z and f(n/10,k,q))+k*bin(p^q).count('1')

Try it online!

Thx for a big 15 bytes from ovs.

As specified, takes a non-negative number and a positive sign length, and returns total changes.


Case invert your quine Write a quine which attempts to invert the case of as many ascii characters in the source code as possible. For example in javascript:
(x=function(y){return ('(x='+y+')(x)').toUpperCase();})(x)

Standard quine rules apply.

The score is given by number of bytes in the source code - number of case inversions. For example, the quine above has a score of 29.

The program with the lowest score wins. If two programs have the same score then the shorter one wins.

><>, score 479 - 479 = 0
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllbfppllfepeeppppgglcepppbeppppppppppplfdppedpddpgglcdppbdpfcpecpggldcppllccpbcpplfbpebppldbppcbpggcbglefgpgbeglefgpgcbglefgpgggggedglefgpgccglefgpgfdglefgpgebglefgpgecglefgpggdcglefgpgceglefgpgeeglefgpgbcglefgpgfbglefgpgcdgfefgpbdgeefgpfegdefgpccgcefgpfdgbefgpdbgaefgpppddglefgpgbcglefgpgfcglefgpgdbglefgpgdcglefgpgecglefgpgddglefgpgdbglefgplffpbfgffgefgpcbgefgefgp

Try it online!
How it works
Very few useful instructions in ><> are letters.
However, we still have the l, pushing the length of the stack to the stack. As such, it's possible to (very verbosely) push arbitrary values to the stack. Thus, strings can be encoded in a similar fashion to brainfuck, using a to increase the length of the stack, and g or p to reduce it.
As per usual quine rules, g is not used to read the source code itself, instead maintaining registers at locations such asbb and bc and so on.
The string encoded is the prefix:
"r&:20&3-:&?.p48*-od0l2)?.;lllll"]"
Which after over 7,000 instructions outputs the original string in upper case.


Thinking inside the circle In as few characters of code as you can, create an algorithm which will pack the least number of rectangles necessary to completely fill a rasterized circle with integer radius r and return the parameters necessary to create each rectangle.

In the above image, the cyan portion is the "idealized" circle. The darkened cells have been selected by a rasterization algorithm. The area to be filled in is within the black line around the cyan circle.

Here's one way to fill that circle:

Here's another:

The fine print:

All units will/must be centimeters.
Rectangles should be in the format [x y width height], where x and y is the position of the upper left corner and width and height are positive numbers for the width and height from that point.

Example: [10 20 40 20][-10 -20 20 40] ...

Rectangles may overlap each other, but their bounds must be within or coincident to the rasterized circle. Rectangles must not extend past those bounds.
The algorithm's results must match what would be expected from the bounds given by the Midpoint Circle Algorithm with parameters x = 0, y = 0, r = radius.
While there might be a minimum number of rectangles needed to fill the circle, finding them might make your code longer than it's worth with respect to the length of the code. (see scoring system below)
It isn't necessary to actually draw anything. Just return the rectangles needed.
Coordinate system should be Cartesian, so not display graphics definition. Eg. (+x, +y) quadrant is north-east of (0, 0), (+x, -y) is south-east, (-x, -y) is south-west, and (-x, +y) is north-west.

To test for correctness, use your chosen rasterization method to draw a circle. Draw the rectangles from your rectangle packing algorithm. Check for gaps inside the circle or pixels outside the circle.

Expected signature of function:

(ℕ radius) → {(ℤ x, ℤ y, ℕ width, ℕ height), ...}

The very complex scoring system:

[code characters]*([rectangles for radius of 10]/10
                   + [rectangles for radius of 100]/100
                   + [rectangles for radius of 1000]/1000)

Lowest score wins. In the event of a tie, winner will be the most popular.

Winner will be selected at midnight GMT, January 16th 2014.

Pre-rule-change answer:

C# / ECMAScript 6 - 12

r=>r

Because overlapping rectangles are allowed, we need at most r rectangles.

Proof:

With a circle of radius 10, it can be filled with 10 rectangles. Each rectangle has been highlighted in a distinct colour.

Older pre-rule-change answer:

C# / ECMAScript 6 - 0.444

r=>1

I believe this meets all the rules as of the time of this writing.

It evaluates to the number of rectangles required to fill a circle, rasterized with this algorithm:

inCircle = max(|x|,|y|) <= radius

This algorithm doesn't yield very high-quality results, but it can still be useful. The popular video game Minecraft uses this algorithm.


Implement String.prototype.toLowerCase() Implement String.prototype.toLowerCase()

Description

The toLowerCase method returns the value of the string converted to lowercase. toLowerCase does not affect the value of the string itself.

Conditions
Let count chars inside function and ignore all bootstrap code:

String.prototype.toLowerCase = function(){
  // code that count here
}

Other languages are welcome but JavaScript implemantation is target of this question. Let's just focus on ASCII charachters .

Example input and output:

"sOmeText".toLowerCase(); => "sometext"

Example implementation:

String.prototype.toLowerCase = function(){
  return this.split('').map(function(c){
     var cc = c.charCodeAt(0);
     if (cc > 64 && cc < 91) {
        return String.fromCharCode(cc + 32);
     }
     return c;
  }).join('');
}

Javascript 70 68

Building from @grc's answer:

for(s=i='';c=this[i++];s+=(parseInt(c,36)||c).toString(36));return s

Convert character to integer then back (works since Number.toString(36) will always be lowercase)

Test case: http://jsfiddle.net/Vh2TW/2/

input:

console.log('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`-=_+{}[]:;\\\'\"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz'.toLowerCase())

output:

abcdefghijklmnopqrstuvwxyz1234567890~`-=_+{}[]:;\'"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz

Update: -2 characters, thanks @copy


Diagonal Alphabet To the Input Inspired by this post. For those marking this question as a duplicate I urge you to actually read the question to see that mine is a modification of the one linked. The one linked does not ask for an input and is to just print the alphabet diagonally.

The Challenge

Given an input between 1-26 inclusively, print the alphabet diagonally, but begin printing vertically at the index of the given input.

Examples

Given the input:

16

Your program should output:

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

Input:

4

Output:

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

Input:

1

Output:

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

Input:

26

Output:

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

Scoring

This is code-golf, so the shortest answer in each language wins.

Good luck!

Charcoal, 9 bytes

↘✂β⁰Ｎ↓✂βη

Try it online!

How it works

↘✂β⁰Ｎ↓✂βη
 ✂β⁰Ｎ         the alphabet from position 0 to the input
↘               print diagonally, down and to the right
        ✂βη    the alphabet starting from the position of the input
       ↓        print downwards

This solution no longer works in the current version of Charcoal (most likely due to a bug fix), but the issue is resolved for 10 bytes with ↘✂β⁰Ｎ↓✂βＩθ.


Calculate the sum of the first n prime numbers I'm surprised that this challenge isn't already here, as it's so obvious.  (Or I'm surprised I couldn't find it and anybody will mark it as a duplicate.)
Task
Given a non-negative integer \$n\$, calculate the sum of the first \$n\$ primes and output it.
Example #1
For \$n = 5\$, the first five primes are:

2
3
5
7
11

The sum of these numbers is \$2 + 3 + 5 + 7 + 11 = 28\$, so the program has to output \$28\$.
Example #2
For \$n = 0\$, the "first zero" primes are none.  And the sum of no numbers is - of course - \$0\$.
Rules

You may use built-ins, e.g., to check if a number is prime.
This is code-golf, so the lowest number of bytes in each language wins!

6502 machine code routine, 75 bytes
A0 01 84 FD 88 84 FE C4 02 F0 32 E6 FD A0 00 A5 FD C9 04 90 1F 85 64 B1 FB 85
65 A9 00 A2 08 06 64 2A C5 65 90 02 E5 65 CA D0 F4 C9 00 F0 DC C8 C4 FE D0 DB
A5 FD A4 FE 91 FB C8 D0 C8 A9 00 18 A8 C4 FE F0 05 71 FB C8 D0 F7 60

Expects a pointer to some temporary storage in $fb/$fc and the number of primes to sum up in $2. Returns the sum in A (the accu register).
Never did some prime checks in 6502 machine code, so here it finally comes ;)
Note this starts giving wrong results for inputs >= 14. This is because of overflow, the code works with the "natural" number range of the 8bit platform which is 0 - 255 for unsigned.
Commented disassembly
; function to sum the first n primes
;
; input:
;   $fb/$fc: pointer to a buffer for temporary storage of primes
;   $2:      number of primes to sum (n)
; output:
;   A:       sum of the first n primes
; clobbers:
;   $fd:     current number under primality test
;   $fe:     number of primes currently found
;   $64:     temporary numerator for modulo check
;   $65:     temporary divisor for modulo check
;   X, Y
 .primesum:
A0 01       LDY #$01            ; init variable for ...
84 FD       STY $FD             ; next prime number to test
88          DEY                 ; init number of found primes
 .mainloop:
84 FE       STY $FE             ; store current number of found primes
C4 02       CPY $02             ; compare with requested number
F0 32       BEQ .sum            ; enough primes -> calculate their sum
 .mainnext:
E6 FD       INC $FD             ; check next prime number
A0 00       LDY #$00            ; start check against first prime number
 .primecheckloop:
A5 FD       LDA $FD             ; load current number to check
C9 04       CMP #$04            ; smaller than 4?
90 1F       BCC .isprime        ; is a prime (shortcut to get list started)
85 64       STA $64             ; store to temp as numerator
B1 FB       LDA ($FB),Y         ; load from prime number table
85 65       STA $65             ; store to temp as divisor
A9 00       LDA #$00            ; init modulo to 0
A2 08       LDX #$08            ; iterate over 8 bits
 .bitloop:
06 64       ASL $64             ; shift left numerator
2A          ROL A               ; shift carry into modulo
C5 65       CMP $65             ; compare with divisor
90 02       BCC .bitnext        ; smaller -> to next bit
E5 65       SBC $65             ; otherwise subtract divisor
 .bitnext:
CA          DEX                 ; next bit
D0 F4       BNE .bitloop
C9 00       CMP #$00            ; compare modulo with 0
F0 DC       BEQ .mainnext       ; equal? -> no prime number
C8          INY                 ; next index in prime number table
C4 FE       CPY $FE             ; checked against all prime numbers?
D0 DB       BNE .primecheckloop ; no -> check next
 .isprime:
A5 FD       LDA $FD             ; prime found
A4 FE       LDY $FE             ; then store in table
91 FB       STA ($FB),Y
C8          INY                 ; increment number of primes found
D0 C8       BNE .mainloop       ; and repeat whole process
 .sum:
A9 00       LDA #$00            ; initialize sum to 0
18          CLC
A8          TAY                 ; start adding table from position 0
 .sumloop:
C4 FE       CPY $FE             ; whole table added?
F0 05       BEQ .done           ; yes -> we're done
71 FB       ADC ($FB),Y         ; add current entry
C8          INY                 ; increment index
D0 F7       BNE .sumloop        ; and repeat
 .done:
60          RTS

Example C64 assembler program using the routine:
Online demo
Code in ca65 syntax:
.import primesum   ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    4               ; maximum length of a valid unsigned
                                        ; 8-bit number input
convbuf:        .res    3               ; 3 BCD digits for unsigned 8-bit
                                        ; number conversion
primebuf:       .res    $100            ; buffer for primesum function

.data
prompt:         .byte   "> ", $0
errmsg:         .byte   "Error parsing number, try again.", $d, $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

input:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #4
                jsr     readline

                lda     linebuf         ; empty line?
                beq     input           ; try again

                lda     #<linebuf       ; convert input to int8
                ldy     #>linebuf
                jsr     touint8
                bcc     numok           ; successful -> start processing
                lda     #<errmsg        ; else show error message and repeat
                ldy     #>errmsg
                jsr     $ab1e
                bcs     input

numok:
                sta     $2
                lda     #<primebuf
                sta     $fb
                lda     #>primebuf
                sta     $fc
                jsr     primesum        ; call function to sum primes
                tax                     ; and ...
                lda     #$0             ;
                jmp     $bdcd           ; .. print result

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

; parse / convert uint8 number using a BCD representation and double-dabble
.proc touint8
                sta     $fb
                sty     $fc
                ldy     #$0
                sty     convbuf
                sty     convbuf+1
                sty     convbuf+2
scanloop:       lda     ($fb),y
                beq     copy
                iny
                cmp     #$20
                beq     scanloop
                cmp     #$30
                bcc     error
                cmp     #$3a
                bcs     error
                bcc     scanloop
error:          sec
                rts
copy:           dey
                bmi     error
                ldx     #$2
copyloop:       lda     ($fb),y
                cmp     #$30
                bcc     copynext
                cmp     #$3a
                bcs     copynext
                sec
                sbc     #$30
                sta     convbuf,x
                dex
copynext:       dey
                bpl     copyloop
                lda     #$0
                sta     $fb
                ldx     #$8
loop:           lsr     convbuf
                lda     convbuf+1
                bcc     skipbit1
                ora     #$10
skipbit1:       lsr     a
                sta     convbuf+1
                lda     convbuf+2
                bcc     skipbit2
                ora     #$10
skipbit2:       lsr     a
                sta     convbuf+2
                ror     $fb
                dex
                beq     done
                lda     convbuf
                cmp     #$8
                bmi     nosub1
                sbc     #$3
                sta     convbuf
nosub1:         lda     convbuf+1
                cmp     #$8
                bmi     nosub2
                sbc     #$3
                sta     convbuf+1
nosub2:         lda     convbuf+2
                cmp     #$8
                bmi     loop
                sbc     #$3
                sta     convbuf+2
                bcs     loop
done:           lda     $fb
                clc
                rts
.endproc


Write a pluralization function for Russian In English, nouns can take on two different forms depending on whether they are singular (one) or plural (anything else). For example, we would say "1 dog" but "2 dogs", "0 dogs", "57 dogs" and so forth.

In Russian, there are three categories. Instead of "1 dog, 2 dogs, 5 dogs", in Russian it would be "1 собака, 2 собаки, 5 собак".

The categories are divided according to the following logic:

"Singular": used for 1 and any number ending in 1, except for numbers ending in 11.

Examples: 1 собака, 21 собака, 101 собака

"Few": used for 2, 3, and 4, and any number ending in 2, 3, or 4 except for numbers ending in 12, 13, and 14.

Examples: 2 собаки, 3 собаки, 4 собаки, 32 собаки, 43 собаки, 104 собаки

"Many": anything that is not considered "Singular" or "Few".

Examples: 0 собак, 5 собак, 11 собак, 13 собак, 25 собак, 111 собак, 114 собак

The challenge

Given an integer input in the range [0, 1000], return 1 if it belongs to the "singular" category, 2 if it belongs to the "few" category, and 5 if it belongs to the "many" category.

Your program may be a function or it can use STDIN. You may print to STDOUT or return a value from the function

This is a code golf challenge, so the solution with the fewest number of bytes wins.

Python 2, 36 bytes

lambda n:'5521'[n%~9/-3>>n/10%~9/-9]

Try it online!

Same length arithmetically:

lambda n:5/(n%~9/-3>>n/10%~9/-9or 1)

Let's first look at simpler code that doesn't account for teens.

lambda n:'5521'[n%~9/-3]

Here, we want a mapping of the one's digit to an output that works like

[5, 1, 2, 2, 2, 5, 5, 5, 5, 5][n%10]

But, rather than take n modulo 10 (%10), we can do n%-10, which maps to the intervals [-9..0] to give remainders:

> [n%~9 for n in range(10)]
[0, -9, -8, -7, -6, -5, -4, -3, -2, -1]

This is promising because the first two entries 0 and -9 are far apart, and they need to be sent to different outputs. Also, -10 can be shortened to ~9.

From here, floor-dividing by /-3 gives chunks of 3 with the right starting spot

> [n%~9/-3 for n in range(10)]
[0, 3, 2, 2, 2, 1, 1, 1, 0, 0]

To get the desired output, we now just need to map 0->5, 1->5, 2->2, 1->1, which we do with the string selection '5521'[_].

Now, we also need numbers ending in 11 to 15 to always give 5. We first do this by detecting whether then tens digit is 1. Taking n/10 to remove the last digit, we then apply %~9 as before to get the outcomes

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

for respective final digits. The digit of 1 that we want to detect is mapped to the extremal value -9. Floor-dividing by -9 turns it to 1 and everything else to 0.

> [k%~9/-9 for k in range(10)]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]

Finally, we make this indicator being 1 always give output 5. This is done by bit-shifting the result of n%~9/-3 right by the indicator. The result of 0,1,2,3 always bit-shifts right to 0 or 1, which gives an output of 5 as desired.