Multiplayer Rock-Paper-Scissors Objective

Given a nonempty multiset of Rock, Paper, and Scissors, output the winning figure according to the special rule.

Background

For a multiplayer RPS, if all three figures come out, usually it's considered a draw. But by that rule, the probability to draw would dramatically increase when there are many and many players.

Let's resolve that by a special rule.

Input

Though defined as a multiset, the input type and format doesn't matter. Valid formats of the input include:

A multiset
A sequential container with or without guarantee of order
An size-3 array of integers representing the count of each of RPS

Also, Rock, Paper, and Scissors may be encoded by an arbitrary type.

The Special Rule and Output

Let's say \$r\$ Rocks, \$p\$ Papers, and \$s\$ Scissors-es(?) are given.

If one of them is zero, output the winning figure of the other two.
If none of them is zero, allot them a score by multiplicating the number of themselves and the number of the figure they win to. That is, Rock gets score \$r×s\$, Paper gets score \$p×r\$, and Scissors get score \$s×p\$.

If the scores don't tie, output the figure with the maximum score.
If the scores tie by two figures, output the winning figure amongst the two figures.
Otherwise, output a fourth value indicating draw.

Otherwise, output either the only figure or the fourth value.

The output type and format doesn't matter.

Rule about code golf

Invalid inputs (Empty container, contains a fourth value, etc) fall into don't care situation.

Example

Given the following input:

[Rock, Rock, Rock, Paper, Paper, Scissors, Scissors]

Rock gets score 3×2=6, Paper gets score 2×3=6, and Scissors get score 2×2=4. Since Paper wins to Rock, the output is Paper.

Python, 41 bytes

lambda r,s,p:[s>p<=r>0,p>r<=s>0,r>s<=p>0]

Try it online!

Takes counts as (r,s,p). Outputs a three-element list with True at the position of the winner, or all False's if there's a tie or only a single figure appearing.

Rock:     [True, False, False]
Scissors: [False, True, False]
Paper:    [False, False, True]
Tie:      [False, False, False]

We use an alternate characterization without multiplication (except when only one figure is present). Below is the condition for Rock winning, with Scissors and Paper having similar conditions.

  Rock wins if: Paper has the fewest, strictly fewer than Scissors but possibly the same as Rock.

We can write this in Python as s>p<=r using inequality chaining.

Unfortunately, this doesn't correctly handle the special case when r=p=0, saying that Rock wins even though only Scissors is present. To fix this, we strengthen the condition for Rock to win to include r>0 via s>p<=r>0, which makes the only-Scissors case give all False for every condition, matching a tie.

44 bytes

lambda r,s,p:r*s==s*p==p*r or[s>p<=r,p>r<=s]

Try it online!

Takes counts as (r,s,p). Outputs as:

Rock:     [True, False]
Scissors: [False, True]
Paper:    [False, False]
Tie:      True

The "Tie" case also includes where there's only a single figure present.


Code Golf: Gibberish Echo This is my first code golf challenge, as such I am not entirely certain if it is suitable as a Code Golf challenge, but it's all a learning experience.

The challenge is that in as few characters as possible, using whichever language you prefer, develop a code to complete the following:

Take a value from stdin
Return a value to stdout that contains the same characters as the value at stdin in a different order. Not necessarily random, but following the restrictions set out below.

Here are a few restrictions:

All characters that are contained in the stdin value must appear in stdout value
Characters must appear in stdout the same amount of times they appear in stdin
The order of characters in the output, cannot be identical to the order of characters in input, for more than two consecutive characters. Regardless of the source of the character in the input. That is, the input and output must not have a common substring of length 3 or greater.
Any input where no solution can be found under the previous rule, is considered an invalid input

Examples: aaaa, bbbb
you do not need to test for invalid inputs, assume all inputs are valid.
The length of stdout must be the same as the length of stdin
You may use any method to scramble the initial value, there is nothing off limits here.

Example:

  stdin: Hello There

  stout: loTeHle reh

Note: a character in this context can be any valid ASCII character

CJam, 31 27 bytes

l:I{mr[_I]{_,((,\f>3f<}/&}g

Test it here.

Same approach as my Mathematica answer. It keeps generating random permutations of the input, until the substring restriction is satisfied. I think this can be golfed a bit further.


Obfuscated FizzBuzz Golf Create the shortest possible obfuscated FizzBuzz implementation.

To be considered obfuscated, it should satisfy at least one of the following:

Does not contain any of the words "Fizz", "Buzz", or "FizzBuzz"
Does not contain the numbers 3, 5, or 15.
Use any of the above in a misleading way.

Remember: The goal is to be short and hard to follow.

The code sample which inspired this question follows:

public class Default
{
        enum FizzBuzz
        {
            Buzz = 1,
            Fizz,
            FizzBuzz
        }
        public static void Main(string[] args)
        {
            byte[] foo =
              Convert.FromBase64String("IAmGMEiCIQySYAiDJBjCIAmGMEiCIQySYA==");
            MemoryStream ms = new MemoryStream(foo);
            byte[] myByte = new byte[1];
            do
            {
                FizzBuzz fb;
                ms.Read(myByte, 0, 1);
                for (int i = 0; i < 4; i++)
                {
                    fb = (FizzBuzz)(myByte[0] >> (2 * i)
                         & (int)FizzBuzz.FizzBuzz);
                    Console.Out.WriteLine( (((int)fb > 0) ? "" + fb : ""
                         + ((ms.Position - 1) * 4 + i + 1)));
                }
            } while (ms.Position < ms.Length);
        }
}


Hardcoding the Cops and Robbers (Robbers) This is a cops-and-robbers challenge. The Cops' thread to this challenge is here

An interesting question to think about is the following:

  If I have a sequence of numbers how many of them do I have to provide before it is clear what sequence I am talking about?

For example if I want to talk about the positive integers in order starting from \$1\$, I could say \$1,2,3, \dots\$, but is that really enough?

I have one way of answering this question, and being a code-golfer It involves code-golf.  You have provided enough terms of a sequence if the shortest code that produces those terms produces all the terms of the sequence.  If we think about this in terms of code-golf, this would mean you have provided enough test cases such that the shortest code that passes the test-cases does the desired task.

Challenge

This challenge is a cops-and-robbers challenge.  In which cops will be presenting test-cases and robbers will have to find a shorter way to spoof the test-cases other than the intended sequence. Cops will present the following things:

A piece of code that takes a positive integer as input and produces an integer as output.  This code can be either zero or one indexed but it should be clear what the indexing is.  This code will define your sequence.
Any relevant platform or language requirements that might effect the output, for example the size of longint.
A number \$n\$, along with the first \$n\$ terms of the sequence as calculated by the code.  These will act as "test-cases".

Robbers will be finding a program in the same language that is shorter than the one presented and passes all the test cases (produces the same output for the first \$n\$ inputs as the cop's code). The robber's code must also differ in output from the cop's program for some number larger than \$n\$.

Scoring

Robbers will be scored in the number of cracks they find with more cracks being better.  An answer can be cracked again by finding a valid answer shorter than the original crack. If an answer is cracked a second time the point is given to the second cracker rather than the first.

cQuents, Stephen's answer, 3 bytes

z~$

Try it online!

How it works

z     Last item in the sequence
 ~    Concat
  $   Current index

Looks like the sequences should be identical, but this gives 12345678910 for n = 10 while "::$ gives 1234567891.


Superior Highly Composite Numbers A superior highly composite number is an integer where the ratio of its count of divisors to some power of the number is as high as possible. Expressing this as a formula:

Let d(n) be the number of divisors of n, including the number itself. For a given integer n, if there exists a number e such that d(n)/n^e is greater than or equal to d(k)/k^e for every integer k, then n is a highly composite number.

For more, see Superior highly composite number at Wikipedia, or A002201 at OEIS.

Here are the initial values:

2, 6, 12, 60, 120, 360, 2520, 5040, 55440, 720720, 1441440, 4324320, 21621600, 367567200, 6983776800, 13967553600, 321253732800, 2248776129600, 65214507758400, 195643523275200, 6064949221531200

Your challenge is to take an index n, and output the nth number in this sequence.

You may use 0 or 1 indexing, and you may make a program which is only correct up to the limits of your language's data type(s), as long as it can handle the first 10 values at a minimum.

This is code golf. Standard loopholes apply.


Buy the most appropriate items A store is having a big sale.
If your price reaches $199 or more, you can reduce it by $100.
You can buy each product only once.
Here's an example list of products: (in order to simplify, the names of the products are represented by letters)

+------+-------+
| name | price |
+------+-------+
| A    | 26.9  |
| B    | 24.9  |
| C    | 49.9  |
| D    | 28.9  |
| E    | 14.9  |
| F    | 16.9  |
| G    | 19.9  |
| H    | 19    |
| I    | 14.9  |
| J    | 14.9  |
| K    | 26.9  |
+------+-------+

Input

A list of product price, such as the above example.
N the item list size    10 <= N <= 100
X a price

Output

The best shopping strategy to save money. Find out the least expensive purchase list with a total price of more than X,
and output:

The most appropriate total price (before deduction), for the data above, X = $199, and the most appropriate total price is 199.2

Notes

Your code can be a function (method) or a full working program.
Make your algorithm as fast as possible (less time complexity)!
If codes have the same time complexity, the one which uses less space wins.

Python 2, \$O(2^{n/2})\$

import sys
def subsetsum(nums, target):
#    totalsum = sum(nums)
#    if(totalsum == target):
#        return target
#    if(totalsum < target):
#        return -1

    sumsA = {}
    sumsB = {}
    for n in nums[::2]:
        for k,v in sumsA.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsA:
                sumsA[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsA loop: "
                    return target
    minsum = sys.maxsize
    for n in nums[1::2]:
        for k,v in sumsB.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsB:
                sumsB[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsB loop: "
                    return target
                for a in sumsA:
                    combsum = a + newsum
                    if combsum == target:
                        print "target found in combined sumsA and sumsB loop: "
                        return target
                    if combsum > target and combsum < minsum:
                        minsum = combsum
    print "target",target,"not found, so return the closest alternative: "
    return minsum

# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)

Try it online.
My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.
The program uses the Knapsack Meet-in-the-middle approach. It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.


Sequential Multiplication Your objective is to write a program that takes an input, and, when chained together N times, performs "sequential multiplication". What is sequential multiplication, you may ask? It's a sequence with a seed a defined as thus:

f(0) = a
f(n+1) = f(n)*(f(n)-1)

So, let a = 5. Thus, f(0) = 5, f(1) = f(0)*(f(0)-1) = 5*4 = 20, and f(2) = f(1)*(f(1)-1) = 20*19 = 380.

If your program was ABC, then ABC should take input a and output f(1). Program ABCABC should output f(2), etc. Your program series should only take input once and only output once.

This is a code-golf so the shortest program in bytes wins. Standard loopholes are banned.

Jelly, 3 bytes

×’$

Try it online!

How it works

×’$    Main link (or part thereof). Argument (initially input): n

 ’     Compute n - 1.
×      Multiply n by (n - 1).
  $    Combine the previous two atoms into a monadic quicklink.

Repeating the snippet n times will execute it n times, resulting in the desired output.


Am I over the speed limit? Given an ascii-art road and the time it took me to cross it, tell me if I was speeding.

Units

Distance is in the arbitrary unit of d. Time is in the arbitrary unit of t.

The road

Here is a simple road:

10=====

The 10 means 10 d per t. That is the speed limit for the road. The road has 5 =s, so its d is 5. Therefore, if I cross that road in 0.5 t, I went 10 d per t, because 5/0.5 = 10. The speed limit of that road is 10, so I stayed within the speed limit.

But if I cross that road in 0.25 t, I went 20 d per t, because 5/0.25 = 20. The speed limit of that road is 10, so I went 10 over the speed limit.

Examples and calculations

Note that input 1 is the time I took to travel the road, and input 2 is the road itself.

Here is a complex road:

Input 1: 1.5
Input 2: 5=====10=====

The fastest I could have (legally) gone on the first road (the first 5 =s) is 5 d per t. Since 5 (distance) divided by 5 (speed limit) is 1, the fastest I could have gone on that road is 1 t.

On the next road, the speed limit is 10 and the distance is also 5, the fastest I could cross that is 0.5 (5/10). Totaling the minimum times results in 1.5, meaning I went at exactly the speed limit.

Note: I know, I might have been going really fast on one road and really slow on another and still cross in 1.5, but assume the best here.

A final example:

Input 1: 3.2
Input 2: 3.0==========20===

The first road is 10 long and has a speed limit of 3, so the minimum time is 3.33333... (10 / 3.)

The second road is 3 long and has a speed limit of 20, so the minimum time is 0.15 (3 / 20.)

Totaling the times results in 3.483333333... I crossed it in 3.2, so I had to be speeding somewhere.

Notes:

You must output one distinct value if I am undoubtedly speeding, and another different value if I might not be.
Your program or function may require input or output to have a trailing newline, but please say so in your submission.
Your first input will be my speed. It will be a positive float or integer or string.
Your second input will be the road. It will always match the regex ^(([1-9]+[0-9]*|[0-9]+\.[0-9]+)=+)+\n?$. You may test out potential inputs here if you are interested.
You may take input in 2 parameters of a function or program, in 2 separate files, from STDIN twice, or from a space-separated string passed to STDIN, a function, a file or a command-line parameter.
If you would like to, you can change the order of the inputs.
Any questions? Ask below in comments and happy code-golfing!

Python 2, 71 bytes

m,s=input()
for c in s.split('=')[:-1]:s=float(c or s);m-=1/s
print m<0

Try it online!

Python's dynamic type system can take quite some abuse.

Splitting the input string s.split('=') turns k equal signs into k-1 empty-string list elements (except at the end, where one must be cut off). For example,

"3.0===20====".split('=')[:-1] == ['3.0', '', '', '20', '', '', '']

The code iterates over these elements, updating the current speed s each time it sees a number. The update is done as s=float(c or s), where if c is a nonempty string, we get float(c), and otherwise c or s evaluates to s, where float(s) just keeps s. Note that c is a string and s is a number, but Python doesn't require doesn't require consistent input types, and float accepts either.

Note also that the variable s storing the speed is the same one as taking the input string. The string is evaluated when the loop begins, and changing it within the loop doesn't change what is iterated over. So, the same variable can be reused to save on an initialization. The first loop always has c as a number, so s=float(c or s) doesn't care about s's initial role as a string.

Each iteration subtracts the current speed from the allowance, which starts as the speed limit. At the end, the speed limit has been violated if this falls below 0.


Clearly parenthesize APL trains In APL, you can write tacit functions, called trains. How they work is irrelevant for this challenge. Here are the different ways they can be grouped, using ⍴ as the function:

⍴      -> ⍴
⍴⍴     -> ⍴⍴
⍴⍴⍴    -> ⍴⍴⍴
⍴⍴⍴⍴   -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴  -> ⍴⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴⍴))
...

The order remains the same. The procedure is that as long as there are strictly more than 3 functions, the last 3 functions are grouped into one function. If we meet a nested train, we parenthesize that first, before continuing. Here is the procedure applied to ⍴⍴⍴⍴⍴⍴:

Step 0: ⍴⍴⍴⍴⍴⍴
There are strictly more than 3 functions, repeat.
Step 1: ⍴⍴⍴(⍴⍴⍴)
There are strictly more than 3 functions, repeat.
Step 2: ⍴(⍴⍴(⍴⍴⍴))
There are 3 or less functions, we're done.

Here is the same procedure applied to ⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴:

Step 0: ⍴⍴⍴(⍴⍴)⍴(⍴⍴⍴⍴(⍴⍴⍴))⍴⍴
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
  Step 0: ⍴⍴⍴⍴(⍴⍴⍴)
  There are strictly more than 3 functions, repeat.
  We have met a nested train, applying procedure to that first:
    Step 0: ⍴⍴⍴
    There are 3 or less functions, we're done.
  Step 1: ⍴⍴(⍴⍴(⍴⍴⍴))
  There are 3 or less functions, we're done.
Step 1: ⍴⍴⍴(⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)
There are strictly more than 3 functions, repeat.
We have met a nested train, applying procedure to that first:
  Step 0: ⍴⍴
  There are 3 or less functions, we're done.
Step 2: ⍴⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴))
There are strictly more than 3 functions, repeat.
Step 3: ⍴(⍴⍴((⍴⍴)⍴((⍴⍴(⍴⍴(⍴⍴⍴)))⍴⍴)))
There are 3 functions or less, we're done.

Input

For this challenge, input will be simplified. This means that you can choose 2 different chars for opening and closing parentheses and 1 char for functions, different from the ones chosen for parentheses. The chars you choose must be consistent. The input will not be empty, and will not contain parentheses with no content (i.e. ()).

Output

Again, you may choose 3 different chars, 2 for parentheses and 1 for functions. Note that they need not be the same as the ones chosen for input, but they must be consistent.

Rules

If there are parentheses which only enclose one function within them in the input, you must remove them in the output. Your output may not contain unneeded parentheses (i.e. enclosing only one function, or enclosing the whole output).
You don't need to implement the algorithm used here, as long as your solution is valid for this challenge.
Input and output are strings in the format explained in the Input and Output sections. The input will have at least one character.
Using the standard loopholes is strictly forbidden.
This is code-golf, so shortest answer wins. However, there won't be an accepted answer, since this is a per-language competition, and to encourage answering in languages in which this task would result in longer code compared to code written in other languages.

Test cases

The chars used here are ()⍴, you should replace them with your chosen chars.

⍴                          -> ⍴
⍴                          -> ⍴
⍴⍴                         -> ⍴⍴
⍴⍴⍴                        -> ⍴⍴⍴
⍴⍴⍴⍴                       -> ⍴(⍴⍴⍴)
⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴⍴            -> ⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴(⍴⍴⍴))))))
⍴⍴⍴⍴⍴(⍴⍴⍴)⍴⍴(⍴(⍴⍴⍴)⍴⍴⍴)⍴⍴⍴ -> ⍴(⍴⍴(⍴⍴((⍴⍴⍴)⍴(⍴(⍴(⍴⍴⍴)(⍴⍴⍴))(⍴⍴⍴)))))
(⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)            -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
(⍴⍴⍴)(⍴⍴⍴)⍴⍴⍴              -> (⍴⍴⍴)(⍴⍴⍴)(⍴⍴⍴)
⍴⍴(⍴)⍴⍴                    -> ⍴⍴(⍴⍴⍴)
((⍴⍴))                     -> ⍴⍴
⍴⍴((⍴⍴))⍴⍴                 -> ⍴⍴((⍴⍴)⍴⍴)

This challenge has been posted in the Sandbox. If you have the required privilege, you can view the sandbox post here.

APL (Dyalog Classic), 71 68 65 63 bytes

0{⍵≡⍕⍵:⍵⋄⍬≡⍵:'⍬'⋄1=≢⍵:⍺∇⊃⍵⋄3≥≢⍵:⍺⌽')(',⍣⍺∊1∇¨⍵⋄⍺∇¯3(↓,∘⊂1∇↑)⍵}⍎

Try it online!

The characters I chose for I/O are '(', ')', and '⍬'.

This solution is itself an APL train.

⍎ parses the input as if it's a nested array - a tree with empty numeric vectors (⍬) as leaves.

The dfn (i.e. lambda - { }) traverses the tree recursively and converts it to a properly parenthesised string. The left argument ⍺ controls whether parentheses should be added to the current level if necessary.

The dfn handles the following cases based on the right argument:

if it's already a string (⍵≡⍕⍵), return it
if it's ⍬, return the char '⍬'
if it's a singleton, just dig deeper (∇ is the symbol for a recursive call)
if its length is ≤3, recurse for each of the items and surround with () if necessary
otherwise, recurse for the 3-tail, prepend all but the 3-tail, and recurse again


Find the nth decimal of pi There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...
Challenge
For any integer in the range of 0 <= n <= 10000 display the nth decimal of pi.
Rules

Decimals are every number after 3.
Your program may be a function, or a full program
You must output the result in base 10
You may get n from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded
You may use 1-based indexing if that's native to your language of choice
You don't have to deal with invalid input (n == -1, n == 'a' or n == 1.5)
Builtins are allowed, if they support up to at least 10k decimals
Runtime doesn't matter, since this is about the shortest code and not the fastest code
This is code-golf, shortest code in bytes wins

Test cases
f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5

For reference, here are the first 100k digits of pi.

05AB1E, 3 bytes
žs¤

Explained
žs   # push pi to N digits
  ¤  # get last digit

Try it online
Uses 1-based indexing.
Supports up to 100k digits.


A twist of a trivial sequence Introduction
Consider a sequence of integers \$f\$ defined as follows:

\$f(2) = 2\$
If \$n\$ is an odd prime, then \$f(n) = \frac{f(n-1) + f(n+1)}2\$
If \$n = p\cdot q\$ is composite, then \$f(n) = f(p)\cdot f(q)\$

It's not very hard to see that \$f(n) = n\$ for every \$n \ge 2\$, and thus computing \$f\$ wouldn't be a very interesting challenge.
Let's make a twist to the definition: halve the first case and double the second case.
We get a new sequence \$g\$ defined as follows:

\$g(2) = 1\$
If \$n\$ is an odd prime, then \$g(n) = g(n-1) + g(n+1)\$
If \$n = p\cdot q\$ is composite, then \$g(n) = g(p)\cdot g(q)\$

The task
Your task is to take an integer \$n \ge 2\$ as input, and produce \$g(n)\$ as output.
You don't have to worry about integer overflow, but you should be able to compute \$g(1025) = 81\$ correctly, and your algorithm should theoretically work for arbitrarily large inputs.
You can write a full program or a function.
The lowest byte count wins.
Example
I claimed above that \$g(1025) = 81\$, so let's compute it by hand.
The prime factorization of 1025 gives
1025 = 5*5*41 => g(1025) = g(5)*g(5)*g(41)

Since 41 is prime, we get
g(41) = g(40) + g(42)

Next, we compute the prime factorizations of 40 and 42:
40 = 2*2*2*5 => g(40) = g(2)*g(2)*g(2)*g(5) = g(5)
42 = 2*3*7 => g(42) = g(2)*g(3)*g(7) = g(3)*g(7)

For these small primes we get
g(3) = g(2) + g(4) = 1 + 1 = 2
g(5) = g(4) + g(6) = 1 + 2 = 3
g(7) = g(6) + g(8) = 2 + 1 = 3

This means that
g(41) = g(40) + g(42) = g(5) + g(3)*g(7) = 3 + 2*3 = 9

and
g(1025) = g(5)*g(5)*g(41) = 3*3*9 = 81

Test cases
Here are the values of \$g\$ up to 50.
2 -> 1
3 -> 2
4 -> 1
5 -> 3
6 -> 2
7 -> 3
8 -> 1
9 -> 4
10 -> 3
11 -> 5
12 -> 2
13 -> 5
14 -> 3
15 -> 6
16 -> 1
17 -> 5
18 -> 4
19 -> 7
20 -> 3
21 -> 6
22 -> 5
23 -> 7
24 -> 2
25 -> 9
26 -> 5
27 -> 8
28 -> 3
29 -> 9
30 -> 6
31 -> 7
32 -> 1
33 -> 10
34 -> 5
35 -> 9
36 -> 4
37 -> 11
38 -> 7
39 -> 10
40 -> 3
41 -> 9
42 -> 6
43 -> 11
44 -> 5
45 -> 12
46 -> 7
47 -> 9
48 -> 2
49 -> 9
50 -> 9

Haskell, 69 bytes

x#a|x<3=1|a>x=a#2+(x-1)#2|mod x a<1,a<x=a#2*div x a#2|b<-a+1=x#b
(#2)

Usage example: (#2) 1025 -> 81

The parameter a is counted up until it divides x or it reaches x (i.e. x is prime). It it one byte shorter to test for a > x and add a further condition (a < x) to the modulus test instead of testing for a == x, because the former binds a to x+1, which helps in the recursive call. Compare:

|a==x=(x+1)#2+(x-1)#2|mod x a<1=
|a>x=a#2+(x-1)#2|mod x a<1,a<x=


Power-Ending Patterns When you look at the last decimal digit of each power of a non-negative integer a repeating pattern forms. For example, 3:
3^1 =     3
3^2 =     9
3^3 =    27
3^4 =    81
3^5 =   243
3^6 =   729
3^7 =  2187
3^8 =  6561
3^9 = 19683

The last digits go 3971 which repeats indefinitely. In fact any number we choose that ends in 3 has that same pattern because none of the other digits can have an effect on the ones place during repeated multiplication.
What's curious is that some numbers have a much shorter cycle of power-ending digits. For example with 5 the powers all end in 5 so the pattern, written as short as possible, is simply 5.
Looking at the minimal power-ending digits patterns for 0 through 9 we get:
0 -> 0
1 -> 1
2 -> 2486
3 -> 3971
4 -> 46
5 -> 5
6 -> 6
7 -> 7931
8 -> 8426
9 -> 91

(The lengths of these being 11442 repeated is a curious tidbit itself.)
Remember, any numbers above 9 will have the same pattern as their last digit as was explained above with 3.
Challenge
Your challenge here is to write a program that takes in any non-negative integer and outputs its minimal power-ending digit pattern.
The exact output formatting, whether string or list, doesn't matter. For example, here are some potential inputs followed by valid potential outputs:
900 -> [0]
11 -> 1
2 -> 2486
303 -> 3, 9, 7, 1
44 -> 4 6
45 -> 5
666 -> "6"
3857 -> [7 9 3 1]
118 -> '8426'
129 -> [9, 1]

The shortest code in bytes wins.

Python 3, 44 43 40 bytes

Based off of mabel's answer but using dictionary comprehensions:

lambda n:[*{n**i%10:0for i in[1,2,3,4]}]

Saved 1 byte thanks to mabel.

Saved 3 bytes thanks to xnor.

You can try it online


Shortest route through a one-way system My home town, Rhyl, has a one-way traffic system which seems to have been designed to keep people away from their destination for as long as possible. Your task, should you choose to attempt it, is to produce a program to give the shortest route through such a traffic system.

Input

Input will be on STDIN, and will be a list of start and end points followed by a blank line followed by a list of queries, as follows:

A B
B A
B C
C D
D C

A D
C A
B A

Each road can only be travelled in the direction(s) given, so, in the above example the road A - B is a two way street whereas B - C is a one-way street from B to C. Travelling from C to B is prohibited.

Start and end points will all be represented by a single upper-case letter.

Output

Output should be the shortest route (measured by number of points visited) from the given start point to the given end point for each query received. If no such route exists, output a blank line. If more than one shortest route exists, output the first when sorting all shortest routes lexicographically.

For the above example the output would be:

A B C D

B A

Test Scripts

As before I'm providing tests for this task based on scripts written by Joey and Ventero:-

Bash
PowerShell

and also tests and expected output for anyone who can't use the above scripts

Plain text

Usage: ./test [your program and its arguments]

Rewards

All answers which have obviously had some attempt at golfing that meet the spec and pass all the tests will get my upvote. The shortest working answer by 26/01/2012 will be accepted.

Haskell, 223 207 characters

main=interact$unlines.f.break null.map words.lines
s%[f,t]=[[f]]#t where[]#_="";x#t|y@(_:_)<-[z|z<-x,last z==t]=unwords$minimum y|1<3=s&x#t
s&z=[x++[b]|x<-z,[a,b]<-s,last x==a,notElem b x];f(s,_:q)=map(s%)q


Check whether letters of word are in alphabetical order Write a function/program that accepts a string of lower/uppercase letters [A-Za-z] as input, that checks whether the occuring letters are unique and in alphabetical order (ignoring lower and uppercase) or not. The output must be truthy if they are unique and in alphabetical order and falsy if not.

Here some testcases

a                           true
abcdefGHIjklmnopqrSTUVWXyz  true
aa                          false
puz                         true
puzz                        false
puzZ                        false
puZ                         true
PuZ                         true
pzu                         false
pzU                         false
abcdABCD                    false
dcba                        false

If you want, run your program on all words of a wordlist like this one and and post some interesting ones =).

Score

Lowest number of bytes wins.

CJam, 8 bytes

lel_$_&=

Here is a test harness for all examples in the challenge. This returns 0 or 1 (which are falsy and truthy, respectively, in CJam).

And here is a script to filter the word list in the question (takes a few seconds to run). You'll have to copy the word list into the input field manually, because it's too long for a permalink.

Explanation

l        "Read input.";
 el      "Convert to lower case.";
   _$    "Get a copy and sort it.";
     _&  "Remove duplicates (by computing the set intersection with itself).";
       = "Check for equality with original (lower case) word.";


Area enclosed by perimeter loop Find the area of a region of unit cells given its perimeter loop as a sequence of 90-degree turns.

For example, take the three-cell region

XX
X

whose perimeter loop we draw

L<S<L
v   ^
S R>L
v ^
L>L

Each turn is marked as left (L), straight (S), or right (R). Starting from the R, the turns are RLLSLSLL. So, given input RLLSLSLL, we should output 3 for the area.

The input sequence is guaranteed to trace out a loop enclosing a single region on its left.

The path ends back at the start point, facing the initial direction, forming a loop.
The loop does not cross or touch itself.
The loop goes counterclockwise around a region.

I/O

You can take input as a list or string of characters LSR, or as  numbers -1, 0, 1 for left, straight, right. Output is a positive integer. Floats are OK.

Test cases

The inputs are given in both formats followed by their respective outputs.

RLLSLSLL
LLLL
SLLSLL
LSRRSLLSSLSSLSSL
SSSSSLSSSSSLSSSSSLSSSSSL

[1, -1, -1, 0, -1, 0, -1, -1]
[-1, -1, -1, -1]
[0, -1, -1, 0, -1, -1]
[-1, 0, 1, 1, 0, -1, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1]
[0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1]

3
1
2
7
36

Brain-Flak, 112 bytes

(([]){[{}]<{({}()){{}<>([{}]<([{}])>)(<>)}<>(({}[({})])[({}{})])<>}{}<>>({}<({}())>)<>([])}{})({()<({}()())>}{})

Try it online!

This program uses Green's theorem to compute the area

The current location is stored on the right stack, in a format that depends on the direction faced.

Direction  top  second
north       -x       y
west        -y      -x
south        x      -y
east         y       x

In all instances, the second value on the stack will increase by 1, and the line integral for the area decreases by half the value on the top of the stack.  To compensate, the end of the program divides the running total by -2.

# For each number in input
(([]){[{}]

  # Evaluate turn-handling to zero
  <

    # If turn:
    {

      # If right turn:
      ({}()){{}

        # Negate both values on other stack (reverse direction)
        <>([{}]<([{}])>)

      (<>)}

      # Swap the two stack elements and negate the new top of stack
      # This performs a left turn.
      <>(({}[({})])[({}{})])<>

    }{}

  <>>

  # Evaluate as top of stack and...
  ({}<

    # increment the number below it
    ({}())

  >)<>

([])}{})

# Divide total by -2
({()<({}()())>}{})


Can I join the music box? The magic music box (MMB)

This explains the motivation for the challenge, feel free to ignore.

The magic music box is a word game played by a group of people, where one is the owner of the magic music box and the other people are trying to put words inside the magic music box.

Rules for the game with humans: the game goes in turns, one person at a time. In your turn, you have to say a word you want to put in the MMB and the MMB owner says if your word can get in or not, depending on the game criterion. If you are the MMB owner, you have to say a word that can go in the MMB.

The task

You have to code a function/program that receives a word as input (in any sensible format) and outputs Truthy or Falsy. Truthy if the word can go in the MMB and Falsy otherwise.

For a word to be able to go in the MMB, it has to contain at least one of the following seven strings:

do
re
mi
fa
sol
la
si

Input

A lowercase "word" in any sensible format, for example:

a string
a list of characters
a list of ASCII values of the characters

Test cases

(Edited test cases to include obsolete, also, some answers may not have it yet)

far -> Truthy
solace -> Truthy
boat -> Falsy
shrimp -> Falsy
fire -> Truthy
summit -> Truthy
biscuit -> Falsy
bullet -> Falsy
doctor -> Truthy
blast -> Truthy
college -> Falsy
subsidiary -> Truthy
obsolete -> Truthy
also -> Falsy

05AB1E, 15 14 bytes

’ïêo‡Åefa’7äåà

Try it online!

’ïêo‡Åefa’        # dictionary string "soldosimilarefa" (using the words sold and similar)
          7ä      # split in 7 parts of almost-equal length (excess length goes to the first parts)
            å     # for each part, check if it’s in the input
             à    # maximum


Word Poker, Who Wins? The input will be two five letter words. They don't actually have to be dictionary words, just any five letters each, all lowercase or all uppercase, your choice. Only A-Z will appear in the input words and they will always be 5 characters in length.

Your program is to score them both as though they were poker hands and output the higher hand. Of course suits won't apply here, only rankings so there's no flushes.

The typical poker ranking system goes: '1 pair', '2 pairs', '3 of a kind', 'straight', 'full house', '4 of a kind', '5 of a kind', and of course there is the possibility the hand (or word in this case) could be worth nothing.

In the case of ties, letters closer to A are considered higher, so a pair of As beats a pair of Bs. In some cases both hands might be identical, but in a different order (or not), in that case output either hand or a resorted version of it.

This external page contains information about how to identify the winner and especially addresses ties within the specific rankings, in case you aren't familiar with how to score poker hands.

In the case of straights: the letters must be adjacent in the alphabet and are not allowed to wrap around. So 'defgh' in any order is a straight, 'xyzab' is not.

Examples of how to score a single hand:

word   | scored as
---------------------
ccccc  | 5 of a kind     <-- highest ranking
woooo  | 4 of a kind
opopo  | full house
vurst  | straight
vovvu  | 3 of a kind
ppoww  | 2 pairs
upper  | 1 pair
kjsdf  | high card only (in this case D) <-- lowest ranking

So the program will actually produce results like this:

input        |  output
-----------------------
voviu,kjsdf  |  voviu     because a pair beats nothing
opoqo,upper  |  opoqo     because 3 of a kind beats a pair
woooo,ggegg  |  ggegg     because 4 Gs beats 4 Os
queue,hopup  |  queue     because 2 pairs beats 1 pair
lodpl,ddkop  |  ddkop     because pair DD beats pair LL
huhyg,hijht  |  huhyg     both have pair HH, but G beats I
ddffh,ccyyz  |  ccyyz     both have 2 pairs, but CC(yyz) beats DD(ffh)
okaok,nkunk  |  nkunk     KK ties with KK, but NN beats OO
abcdf,bcdef  |  bcdef     because it is a straight
qtery,retyq  |  qtery     identical! so doesnt matter
abedc,vyxwz  |  abedc     because it is a "higher" straight
hhhij,hijkl  |  hijkl     because straight beats 3 of a kind
aaabb,zzzzz  |  zzzzz     because nothing beats 5 of a kind

The order of the letters in both the input and output are irrelevant, so the order in your output can be different than the input, but the same inventory of letters needs to be present.

The output must contain exactly five letters -- no more, no less.

The usual codegolf rules apply. Shortest code wins.

JavaScript (224 218 213 bytes)
s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

Ungolfed:
s=>t=>(
  v=s=>(
    o={},
    l=n=0,
    z=3.5,
    [...s].sort().map(c=>(
      n+=o[c]=-~o[c],
      z*=!l|l+1==(l=c.charCodeAt())
    )),
    [n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]
  ),
  w=v(s),x=v(t),
  w[0]>x[0] || w[0]==x[0] && w[1]<x[1] ? s : t
)

After map() runs, n + z determines the ranking of a hand:

(You can understand why I initialized z to 3.5.)
In case of a tie, Object.keys(o).sort() is used to determine the higher ranking hand.
Snippet:

f=

s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

console.log(/voviu/.test(f('voviu')('kjsdf')))       //because a pair beats nothing
console.log(/opoqo/.test(f('opoqo')('upper')))       //because 3 of a kind beats a pair
console.log(/ggegg/.test(f('woooo')('ggegg')))       //because 4 Gs beats 4 Os
console.log(/queue/.test(f('queue')('hopup')))       //because 2 pairs beats 1 pair
console.log(/ddkop/.test(f('lodpl')('ddkop')))       //because pair DD beats pair LL
console.log(/huhyg/.test(f('huhyg')('hijht')))       //both have pair HH, but G beats I
console.log(/ccyyz/.test(f('ddffh')('ccyyz')))       //both have 2 pairs, but CC(yyz) beats DD(ffh)
console.log(/nkunk/.test(f('okaok')('nkunk')))       //KK ties with KK, but NN beats OO
console.log(/bcdef/.test(f('abcdf')('bcdef')))       //because it is a straight
console.log(/qtery|retyq/.test(f('qtery')('retyq'))) //identical! so doesnt matter
console.log(/abedc/.test(f('abedc')('vyxwz')))       //because it is a "higher" straight
console.log(/hijkl/.test(f('hhhij')('hijkl')))       //because straight beats 3 of a kind
console.log(/zzzzz/.test(f('aaabb')('zzzzz')))       //because nothing beats 5 of a kind


Is This a Real Tree? You should write a program or function which receives a string as input and outputs or returns if the input is an ASCII tree.

  _
\/  /
 \_/
  |
  |

ASCII trees consist of characters / \ | _ spaces and newlines.

The non-whitespace characters connect two edge points of their cells by a line segment:

/ connects the bottom left and top right corners
\ connects the bottom right and top left corners
| connects the middle points of the bottom edge and top edge
_ connects the bottom left and bottom right corners and the middle point of the bottom edge

(Note that this means that | can only connect with | or _ but not with / or \.)

An ASCII picture is called a tree if the following rules apply:

Exactly one point (the root) of exactly one character touches to the bottom edge of the last row.
You can reach any point of any line segment by:

starting from the root
using only the line segments
never going into a downward direction (not even sideways downward)

Input

A string consisting of the characters / \ | _ space and newline containing at least one non-whitespace character.
You can choose of two input format:

No unnecessary whitespace around the tree (as seen in the examples).
No unnecessary whitespace around the tree (as seen in the examples) except spaces on the right side of the rows to make all rows the same length.

Trailing newline is optional.

Output

A consistent truthy value if the input is an ascii tree.
A consistent falsy value if the input isn't an ascii tree.

Examples

Valid trees:

|

  _
\/  /
 \_/
  |
  |

/ /    \/
\ \____/
 \/
 /
/

 \___/
 /   \
 \___/
   |
   |

   __/
 _/
/

____
  \  ___
 \ \/
  \/\_____/
 \/  \/
  \__/
    |
    |

Invalid trees (with extra explanations which are not parts of the inputs):

\/
 \_______/
  \__   /
   | \_/    <- reachable only on with downward route
   |

_           <- multiple roots

\/          <- multiple root characters

/\          <- multiple roots

|           <- unreachable part

|

 __/
/           <- unreachable parts
|

\____/
 |  |       <- multiple roots

_\__/       <- unreachable parts (_ and \ don't connect to each other)
|

This is code-golf so the shortest entry wins.

Mathematica, 345 300 bytes

Still quite long, but I guess it's a start...

(s=StringSplit;v=Reverse;#=="|"||#=="\\"||#=="/"&[""<>s@#]&&(g={};i=0;(c={i,++j};d={i,j+1/2};e=2d-c;g=Join[g,Switch[#,"|",{d->{1,0}+d},"/",{c->c+1},"\\",{e->{i+1,j}},"_",{c->d,d->e,e->c},_,{}]])&/@Characters[++i;j=0;#]&/@{##};Sort@VertexOutComponent[Graph@g,g[[1,1]]]==Union@@List@@@g)&@@v@s[#,"
"])&

Here is a slightly ungolfed version:

(
  s = StringSplit;
  v = Reverse;
  # == "|" || # == "\\" || # == "/" &[
      "" <> s@#
      ] && (
      g = {};
      i = 0;
      (
           c = {i, ++j};
           d = {i, j + 1/2};
           e = 2 d - c;
           g = Join[g, Switch[#,
              "|", {d -> {1, 0} + d},
              "/", {c -> c + 1},
              "\\", {e -> {i + 1, j}},
              "_", {c -> d, d -> e, e -> c},
              _, {}
              ]]
           ) & /@ Characters[
          ++i;
          j = 0;
          #
          ] & /@ {##};
      Sort@VertexOutComponent[Graph@g, g[[1, 1]]] ==
       Union @@ List @@@ g
      ) & @@ v@s[#, "\n"]
) &

This defines an unnamed function which takes the string as input and returns True or False.

The basic idea is first to check that there's a single root, and then to build an actual (directed) Graph object to check if all vertices can be reached from the root. Here is how we build the graph:

Imagine an integer grid overlaid onto the ASCII art, where integer coordinates correspond to the corners of the character cells. Then on each of the cells there are six relevant points that can be connected. Here is an example, where I've also labelled the points a to f:

     |                 |
     |                 |
---(2,3)---(2.5,3)---(3,2)---
     | d      e      f |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     |                 |
     | a      b      c |
---(2,2)---(2.5,2)---(3,2)---
     |                 |
     |                 |

So we can build a graph whose vertices are these half-integer coordinates, and whose edges are determined by the non-space characters in the input. | connects b to e, / connects a to f and \ connects c to d. Note that these must be directed edges to ensure that we're never moving downwards while traversing the graph later. For _ we can go either way, so in theory we need four edges a -> b, b -> a, b -> c, c -> b. However, we can notice that all that matters is that there's a cycle containing all three vertices, so we can shorten this to three edges: a -> b, b -> c, c -> a.

Building this graph is quite simple in Mathematica, because any object can act as a vertex, so I can actually build a graph whose vertices are the coordinate pairs.

Finally, we check that every vertex can be reached from the root. The root's coordinate is easily found as the very first vertex we added to the graph. Then the shortest way I have found to check if all vertices can be reached is to check if the VertexOutComponent of the root (i.e. the set of all vertices reachable from the root) is identical to the set of all vertices in the graph.


Delete some bits and count Consider all 2^n different binary strings of length n and assume n > 2.  You are allowed to delete exactly b < n/2 bits from each of the binary strings, leaving strings of length n-b remaining. The number of distinct strings remaining depends on which bits you delete. Assuming your aim is to leave as few remaining different strings as possible, this challenge is to write code to compute how few can you leave as a function of n.

Example, n=3 and b = 1.  You can leave only the two strings 11 and 00.

For n=9 and b = 1,2,3,4 we have 70,18,6,2

For n=8 and b = 1,2,3 we have 40,10,4

For n=7 and b = 1,2,3 we have 20,6,2

For n=6 and b = 1,2 we have 12,4

For n=5 and b = 1,2 we have 6,2

This question was originally posed by me in 2014 in a different form on MO.

Input and output

Your code should take in an integern and output a single integer for each value of b starting at b = 0 and increasing.

Score

Your score is the largest n for which your code completes for all b < n/2 in under a minute on my Linux based PC.  In case of tie breaks, the largest b your code gets to for the joint largest n wins. In case of tie breaks on that criterion too, the fastest code for the largest values of n and b decides. If the times are within a second or two of each other, the first posted answer wins.

Languages and libraries

You can use any language of library you like. Because I have to run your code, it would help if it was free (as in beer) and worked in Linux.

Python 2.7 / Gurobi n=9

This solution is very straight usage of Gurobi's ILP solver for the boolean Mixed-Integer Problems (MIP).

The only trick is to take out symmetry in 1's complement to halve the problem sizes.

Using Gurobi LLC's limited time "free" licence we are restricted to 2000 constraints, but solving 10 del 1 is well outside the 60 second time-limit anyway on my laptop.

from gurobipy import *
from itertools import combinations

def mincover(n,d):
    bs = pow(2,n-1-d)
    m = Model()
    m.Params.outputFlag = 0
    b = {}
    for i in range(bs):
      b[i] = m.addVar(vtype=GRB.BINARY, name="b%d" % i)
    m.update()
    for row in range(pow(2,n-1)):
      x = {}
      for i in combinations(range(n), n-d):
        v = 0
        for j in range(n-d):
          if row & pow(2,i[j]):
            v += pow(2,j)
        if v >= bs:
          v = 2*bs-1-v
        x[v] = 1
      m.addConstr(quicksum(b[i] for i in x.keys()) >= 1)
    m.setObjective(quicksum(b[i] for i in range(bs) ), GRB.MINIMIZE)
    m.optimize()
    return int(round(2*m.objVal,0))

for n in range(4,10):
    for d in range((n//2)+1):
        print n, d, mincover(n,d)

UPDATE+CORR: 10,2 has optimal solution size 31 (see e.g.) Gurobi shows no symmetric solution of size 30 exists (returns problem infeasible) .. [my attempt to show asymmetric feasibility at 30 remained inconclusive after 9.5hrs runtime]
e.g. bit patterns of integers 0 7 13 14    25 28 35 36 49 56 63 64 95 106 118 128 147 159 170 182 195 196 200 207 225 231 240 243 249 252 255 or 0 7 13 14 19 25 28 35 36 49 56 63 64 95 106 118 128     159 170 182 195 196 200 207 225 231 240 243 249 252 255


Let's practice the scoring rules of 421! 421 is a rather popular dice game in France and some other European countries. It is mostly played in bars and pubs to determine who's going to buy the next round of drinks. The full game is usually played in two rounds, with tokens that each player tries to get rid of, but this is irrelevant here. (Wikipedia page in French.)

The game is played with 3 standard cube dice.

Task

Your task is to sort a non-empty list of distinct 3-dice rolls [ X,Y,Z ] from highest to lowest, by applying the scoring rules of this game.

Basic scoring

4,2,1 is the highest possible combination. Depending on the rules, it may score 8, 10 or 11 points. Because we are sorting the rolls rather than counting the points, the exact value doesn't matter.
Three Aces: 1,1,1 is the second highest combination and scores 7 points.
Two-Aces: X,1,1 (where X is 2 to 6) scores X points.
Three-of-a-Kind: X,X,X (where X is 2 to 6) scores X points.
Straights: X,X+1,X+2 scores 2 points.
All other rolls score 1 point.

Settling ties

Whenever two rolls give the same number of points, the following rules apply:

A Two-Aces is better than a Three-of-a-Kind. Example: 5,1,1 beats 5,5,5.
The Three-of-a-Kind 2,2,2 is better than a straight. Example: 2,2,2 beats 4,5,6.
Straights are ordered from lowest to highest. Example: 4,5,6 beats 2,3,4.
All other rolls are settled by sorting the dice from highest to lowest. Example: 6,5,2 beats 6,4,3. (Therefore, the lowest possible combination in the game is 2,2,1.)

Below are the 56 possible distinct rolls ordered from highest to lowest:

421 111 611 666 511 555 411 444 311 333 211 222 654 543 432 321
665 664 663 662 661 655 653 652 651 644 643 642 641 633 632 631
622 621 554 553 552 551 544 542 541 533 532 531 522 521 443 442
441 433 431 422 332 331 322 221

Challenge rules

You may take the rolls in any reasonable format, such as a list of lists [[3,2,1],[4,2,1]], a list of strings ["321","421"], a list of integers [321,421], etc. However, each die must be clearly identifiable with a value from 1 to 6.
For each roll, you can assume that the dice are sorted either from lowest to highest or from highest to lowest, as long as it is consistent. Please state in your answer which order you're expecting, if any.
The shortest answer in bytes wins!

Test cases

Using lists of strings with the dice sorted from highest to lowest:

Inputs

[ "321", "654" ]
[ "222", "321", "211" ]
[ "333", "311", "331", "111" ]
[ "111", "222", "333", "444" ]
[ "321", "421", "521", "621" ]
[ "422", "221", "442", "421", "222" ]
[ "222", "111", "421", "211", "651", "652", "543" ]

Expected outputs

[ "654", "321" ]
[ "211", "222", "321" ]
[ "111", "311", "333", "331" ]
[ "111", "444", "333", "222" ]
[ "421", "321", "621", "521" ]
[ "421", "222", "442", "422", "221" ]
[ "421", "111", "211", "222", "543", "652", "651" ]


In The Jailhouse Now Challenge
Given an integer n (where 4<=n<=10**6) as input create an ASCII art "prison door"* measuring n-1 characters wide and n characters high, using the symbols from the example below.

Example
╔╦╗
╠╬╣
╠╬╣
╚╩╝

The characters used are as follows:
┌───────────────┬─────────┬───────┐
│ Position      │ Symbol  │ Char  │
├───────────────┼─────────┼───────┤
│ Top Left      │    ╔    │ 9556  │
├───────────────┼─────────┼───────┤
│ Top           │    ╦    │ 9574  │
├───────────────┼─────────┼───────┤
│ Top Right     │    ╗    │ 9559  │
├───────────────┼─────────┼───────┤
│ Right         │    ╣    │ 9571  │
├───────────────┼─────────┼───────┤
│ Bottom Right  │    ╝    │ 9565  │
├───────────────┼─────────┼───────┤
│ Bottom        │    ╩    │ 9577  │
├───────────────┼─────────┼───────┤
│ Bottom Left   │    ╚    │ 9562  │
├───────────────┼─────────┼───────┤
│ Left          │    ╠    │ 9568  │
├───────────────┼─────────┼───────┤
│ Inner         │    ╬    │ 9580  │
└───────────────┴─────────┴───────┘

Rules

You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
For the purposes of this challenge, in languages where the symbols used to build the "door" are multi-byte characters, they may be counted towards your score as a single byte each.
All other characters (single- or multi-byte) should be counted as normal.
Output may not contain any trailing spaces but a trailing newline is permitted if absolutely necessary.
This is code-golf so lowest byte count wins.

Test Cases
Input: 4
Output:
╔╦╗
╠╬╣
╠╬╣
╚╩╝

Input: 8
Output:
╔╦╦╦╦╦╗
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╚╩╩╩╩╩╝

Input: 20
Output:
╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝

* Yes, I'm aware that the bigger it gets the less it looks like a prison door! :D

Java 11, 156 151 148 118 89 bytes

n->"╔"+"╦".repeat(n-=3)+"╗\n"+("╠"+"╬".repeat(n)+"╣\n").repeat(n+1)+"╚"+"╩".repeat(n)+"╝"

Try it online.
Old 118 bytes answer in Java 8:
n->{String a="╔",b="╠",c="╚";for(int i=n;i-->3;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";}

-30 bytes by creating a port of @raznagul C# (.NET Core) answer, after I golfed 5 bytes.
Try it here.
Explanation:
n->                    // Method with integer parameter and String return-type
  "╔"                  //  The top-left corner
  +"╦"                 //  Appended with the top edge
      .repeat(n-=3)    //  Repeated input-3 times (-2 for the corners, -1 for width)
  +"╗\n"               //  Appended with the top-right corner and a newline
  +("╠"                //   The left edge
    +"╬"               //   Appended with the middle part
        .repeat(n)     //   Repeated input-3 times (-2 for edges, -1 for width)
    +"╣\n"             //   Appended with the right edge and a newline
          ).repeat(n+1)//  And repeat this entire line n-2 times (-2 for first/last rows)
  +"╚"                 //  Appended with the bottom-left corner
  +"╩"                 //  Appended with the bottom edge
      .repeat(n)       //  Repeated input-3 times
  +"╝"                 //  Appended with the bottom-right corners


A Peak Experience: Quickly Visit All the Peaks I am standing at point (0,0) in a H x W map where the altitude is represented by digits, for example:

1132
2221
1230    # H = 3, W = 4

I'd like to experience the views from every peak, which in this case are the areas with altitude 3. However, climbing up hills is not an easy task, and I am also running out of time.

Challenge

The challenge is to find the quickest path to visit all the peaks and come back.

Shortest program wins.

Input

H, W - height and width of the map (Integers) (optional, may be a list/tuple or two separate integer inputs)
The map, given as H sets of W digits (0-9), in any convenient format (2D list, string separated by newlines, etc.)

Output

Shortest time taken to visit every peak and come back to your starting point (Integer)

Conditions

The altitude of a given area is represented by a digit from 0 to 9.
The "peak" is defined by the area with the highest altitude.
The path must both begin and end at the top-left (0,0) area.
You can only move to areas adjacent to your current area, and you may not move diagonally.

It takes 3 minutes to move from one area to another if there is no change in altitude.
It takes 11 minutes to climb up; that is, moving from one area to another area that is exactly 1 unit higher.
It takes 2 minutes to climb down; that is, moving from one area to another area that is exactly 1 unit lower.
You cannot move to areas that are more than 1 unit higher or lower than where you are. (You cannot go from an area with altitude 1 to an adjacent area with altitude, say, 3)

A path to all the peaks is guaranteed
Maximum number of peaks is 15.

Samples

Input

4 5
32445
33434
21153
12343

Output

96

Explanation

You start at the top-left 3. You have to visit the two 5s that are located at (0,4) and (3,3) and come back to the 3 at (0,0) in the shortest time possible.

3  2  4->4->5
V     ^
3->3->4  3  4

2  1  1  5  3

1  2  3  4  3    # 3 + 3 + 11 + 3 + 3 + 11 = 34 minutes to visit 1st peak

3  2  4  4  5
            V
3  3  4  3  4
            V
2  1  1  5  3
         ^  V
1  2  3  4<-3    # 2 + 2 + 3 + 11 + 11 = 29 minutes to visit 2nd

3  2  4  4  5
^
3  3  4  3  4
^
2  1  1  5  3
^        V
1<-2<-3<-4  3    # 2 + 2 + 2 + 2 + 11 + 11 + 3 = 33 minutes to come back

# 34 + 29 + 33 = 96 minutes total is the answer

Input

2 7
6787778
5777679

Output

75

Mathematica 745 681 bytes

The basic idea is to make a weighted graph of possible moves. Weights are the time it takes to move from one place to the next.  The path with the least weight will be the quickest.

The input digits are placed in an r by c (rows by columns) rectangular array and then three distinct representations come into play: (1) an r by c grid graph, where each vertex corresponds to a cell in the array, (2) (rc) by (rc) weighted adjacency matrix that holds weights corresponding to the time it takes (2, 3, or 11 minutes) to move from one location (in the grid graph) to another, and (3) a directed, weighted adjacency graph constructed from the matrix.

The grid graph helps determine which cells (i.e. which vertices) are possibly reachable from each vertex--"possibly reachable" because a neighboring cell must not only be right, left, above or below a given cell.  It's value must also be within 1 unit of distance from the neighbor (e.g., a 3 does not connect to a  neighboring 5 or a 1).  If vertex a is not connected to vertex b then the adjacency matrix cells {a,b} and {b,a} will have a value of ∞.  Accordingly, the weighted adjacency graph will not have an edge from a to b, nor from b to a.

The weighted adjacency graph serves to determine the minimum distance (GraphDistance) and shortest route between any vertices.  The optimal path must begin with 1, touch each of the peaks, and return to 1.  In this case, "shortest route" is not necessarily the one with the fewest moves.  It is the one with the shortest overall time, measured in edge weights.

Golfed

o=Sequence;v[a_<->b_,z_]:=(m_~u~q_:={Quotient[m-1,q[[2]]]+1,1+Mod[m-1, q[[2]]]};j=z[[o@@u[a,i=Dimensions@z]]];k=z[[o@@u[b,i]]];Which[j==k,{{a,b}->3,{b,a}->3},j==k-1,{{a,b}->11,{b,a}->2},j==k+1,{{a,b}->2,{b,a}->11},2<4,{{a,b}->∞, {b, a}->∞}]);w@e_:=Module[{d,x,l,y},x=Map[ToExpression,Characters/@Drop[StringSplit@e,2],{2}];d_~l~c_:=d[[2]](c[[1]]-1)+c[[2]];g_~y~p_:=(Min[Plus@@(GraphDistance[g,#,#2]&@@@#)&/@(Partition[#,2,1]&/@({1,o@@#,1}&/@Permutations@p))]);y[WeightedAdjacencyGraph[ReplacePart[ConstantArray[∞,{t=Times@@(d=Dimensions@x),t}],Flatten[#~v~x &/@Union@Flatten[EdgeList[GridGraph@Reverse@d,#<->_]&/@Range@(Times@@d),1],1]]], l[Dimensions@x, #] & /@ Position[x, Max@x]]

Longer, more readable form

(*determines a weight (number of minutes) to go from vertex a to b and from b to a*)
weight[a_ <-> b_, dat_]:=
  Module[{cellA,cellB,dim,valA,valB,vertexToCell},

  (*Convert graph vertex index to cell location*)
  vertexToCell[m_,dimen_]:={Quotient[m-1,dim[[2]]]+1,1+Mod[m-1,dimen[[2]]]};
     dim=Dimensions[dat];
     cellA = vertexToCell[a,dim];
     cellB = vertexToCell[b,dim];
     valA=dat[[Sequence@@cellA]];
     valB=dat[[Sequence@@cellB]];
     Which[
       valA==valB,{{a,b}-> 3,{b,a}-> 3},
       valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
       valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
       2<4,{{a,b}->∞,{b,a}->∞}]];

(* weights[] determines the edge weights (times to get from one position to the next), makes a graph and infers the shortest distance
from vertex 1 to each peak and back.  It tries out all permutations of peaks and
selects the shortest one. Finally, it returns the length (in minutes) of the shortest trip. *)

weights[str_]:=
  Module[{d,dat,neighbors,cellToVertex,peaks,z,gd},
  dat=Map[ToExpression,Characters/@Drop[StringSplit[str],2],{2}];
  cellToVertex[dim_,cell_]:=dim[[2]] (cell[[1]]-1)+cell[[2]];
  peaks[dat_]:= cellToVertex[Dimensions[dat],#]&/@Position[dat,peak =Max[dat]];

     (* to which cells should each cell be compared? neighbors[] is a function defined within weights[]. It returns a graph, g, from which graph distances will be derived in the function gd[] *)
  neighbors[dim_]:=
  Union@Flatten[EdgeList[GridGraph[Reverse@dim],#<->_]&/@Range@(Times@@dim),1];
    d=Dimensions[dat];
    m=ReplacePart[ConstantArray[∞,{t=Times@@d,t}],
     (*substitutions=*)
    Flatten[weight[#,dat]&/@neighbors[d],1]];
    g=WeightedAdjacencyGraph[m,VertexLabels->"Name",ImageSize->Full,GraphLayout->"SpringEmbedding"];

    (* finds shortest path.  gd[] is also defined within weights[] *)
  gd[g3_,ps_]:=
    Module[{lists,pairs},
    pairs=Partition[#,2,1]&/@({1,Sequence@@#,1}&/@Permutations@ps);
    Min[Plus@@(GraphDistance[g3,#,#2]&@@@#)&/@pairs]];

  gd[g,peaks[dat]]]

Tests

weights["4 5
 32445
 33434
 21153
 12343"]

96.

weights@"2 7
 6787778
 5777679"

75.

weights@"3 4
 1132
 2221
 1230"

51.

Explanation

Think of lines 2-5 of the  following input

"4 5
 32445
 33434
 21153
 12343"

as representing an array with 4 rows and 5 columns:

where each vertex corresponds to a digit from the input array: 3 is at vertex 1, 2 is at vertex 2, 4 is at vertex 3, another 4 at vertex 4, 5 at vertex 5, etc. The grid graph is only a rough approximation of the graph we are aiming for. It is undirected. Furthermore, some of the edges will be unavailable. (Remember: we cannot move from a position to another that is more than 1 height unit above or below the current one.)  But the grid graph let's us easily find those vertices that are next to any chosen vertex.  This reduces the number of edges we need to consider, in the first example (a 4 by 5 grid), from 400 (20 * 20) to 62 (31 *2 is the number of edges in the grid graph).  In the same example, only 48 of the edges are operative;  14 are not.

The following 20 by 20 weighted adjacency matrix represents the distance between all pairs of vertices from the grid graph.

The key code which decides on which number to assign is below.

Which[
      valA==valB,{{a,b}-> 3,{b,a}-> 3},
      valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
      valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
      2<4,{{a,b}->∞,{b,a}->∞}]

Cell {1,2}--in one-indexing-- contains the value 2 because the move from vertex 1 to vertex 2 is downhill.
Cell {2,1} contains 11 because the move from vertex 2 to vertex 1 is uphill.
The 3's in cells {1,6} and {6,1} signify that the movement is neither up nor down.
Cell {1,1} contains ∞ because it is not connected to itself.

The following graph shows the structure underlying the above input.  The colored arrows show the optimal path from vertex 1 to the peaks (at 5 and 14) and back to 1.  Blue arrows correspond to moves at the same level (3 min); red arrows mean ascent (11 min.) and green arrows indicate descent (2 min).

The path from vertex 1 (cell {1,1} to the two peaks and back to vertex 1:

3 + 3 + 11 + 3 + 3 + 11 + 2 + 2 + 3 + 11 + 11 + 2 + 2 + 2 + 2 + 11 + 11 + 3

96


A graph and its seven closures Background
A little while ago, someone posted an interesting puzzle on Math.SE:

What is the smallest digraph (directed graph) G where the following eight graphs are all distinct:

G, the original graph
Reflexive closure of G
Symmetric closure of G
Transitive closure of G
Reflexive symmetric closure of G
Symmetric transitive closure of G
Reflexive transitive closure of G
Reflexive symmetric transitive closure of G

A quick refresher on the terminology:

A reflexive graph satisfies: for every vertex X of G, the edge (X,X) is present in G.
A symmetric graph satisfies: for every pair of vertices X and Y of G, if the edge (X,Y) is present in G, the edge (Y,X) is also present.
A transitive graph satisfies: for every triple of vertices X, Y, and Z of G, if the edges (X,Y) and (Y,Z) are present in G, the edge (X,Z) is also present.
A reflexive/symmetric/transitive closure of G is the smallest superset of G that satisfies the given property. Note that, for example, symmetric transitive closure is not equal to symmetric closure of transitive closure in general.

For example, the following (from the original Math.SE post) shows an example graph that satisfies the original question:

Challenge
Given a digraph G, determine if it satisfies the above puzzle (G and its seven closures are all distinct).
The input digraph G can be represented in any reasonable way: adjacency matrix, adjacency list, flat lists of vertices and edges, etc. Since the answer is always false when isolated vertices are not allowed, the representation must include some representation of the list of vertices.
For output, you can choose to

output truthy/falsy using your language's convention (swapping is allowed), or
use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

The shortest code in bytes wins.
Test cases
Truthy
# the example in the image
vertices: [1, 2, 3, 4, 5, 6]
edges: [[1, 2], [2, 3], [3, 4], [4, 2], [4, 5]]
adjacency matrix:
[[0, 1, 0, 0, 0, 0],
 [0, 0, 1, 0, 0, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 1, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]]

# the smallest answer in Math.SE
vertices: [1, 2, 3, 4]
edges: [[1, 2], [2, 3]]
adjacency matrix:
[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]]

Falsy
# the incorrect answer in Math.SE
vertices: [1, 2, 3]
edges: [[1, 2], [2, 3]]
adjacency matrix:
[[0, 1, 0],
 [0, 0, 1],
 [0, 0, 0]]

# a modification of 4-vertex correct answer, ST=RST
vertices: [1, 2, 3, 4]
edges: [[1, 2], [2, 3], [4, 4]]
adjacency matrix:
[[0, 1, 0, 0],
 [0, 0, 1, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 1]]

J, 71 58 bytes
Takes in the adjacency matrix.
*/@~:@(,([+./@,#)"#/~^:_"2)@(,s@r,(s=:+.|:),:r=:[+.=@i.@#)

Try it online!
How it works
First the original, s, r and r->s variants are computed, then all their transitive closures. Albeit the operations are not commutative, I believe calculating the transitive closure last will work here (r->t is equal to r->t->r as r just adds the diagonal, which was already set. s->t is equal to s->t->s as every transition was already symmetric. s->r is equal to r->s as every reflexion is symmetric.) Though this might be wrong, and if it is, I'm happy to slap some ^:_ on there. :-)

r=:+.=@i.@#: original matrix OR the diagonal =@i.@#.
s=:+.|:: original matrix OR its transposition |:.
,s@r,s,:r: original matrix and all its variants in a list.
([+./@,#)"#/~^:_"2: until the result does not change ^:_:  for every node: take the neighboring rows #, append them to the current row [ , and OR them together +./.
*/@~:: ~: returns whether each element of the list is unique, then AND */ those booleans.


Khinchin's constant to as many decimal places as possible in 64 bytes or less Khinchin's constant is a curious mathematical constant that, according to Wolfram MathWold, is "notoriously difficult to calculate to high precision".

Here it is to 100 digits:

  2.685452001065306445309714835481795693820382293994462953051152345557218859537152002801141174931847697...

Write a program in 64 bytes or less that outputs Khinchin's constant to the maximum number of correct decimal places.

You may not use any built in library constants or functions directly relating to Khinchin's constant. (e.g. Math.Khinchin(precision) is definitely not allowed.)
You may use math libraries to compute logarithms, summations, etc.
You may hardcode all or part of your answer.
Your program must produce finite output and run in less than an hour on a reasonably modern computer (such as those listed here).
You must output to stdout. There is no input.
You may use any characters you want as long as http://mothereff.in/byte-counter registers 64 bytes or less.

Scoring

Your score is the number of successive digits in Khinchin's constant your program outputs correctly, starting with 2.68... You may output incorrect digits but only the last correct digit is counted towards your score.

For example, an output of

  2.68545200206530644530971483548179569382038229399446295305115234555721

would score 9 points. One for each of the digits 2 6 8 5 4 5 2 0 0 but nothing after the 2 that should be a 1.

CJam - 118

2'."*;TeT?_aN{.i9B*ZEay
G`9~eW}nE=Lr-`B}    )D>9m9"136b

Try it at http://cjam.aditsu.net/

Since stackexchange destroys some of the characters, here's a program that generates the program above; run it first, then run its output:

"2'.\""685452001065306445309714835481795693820382293994462953051152345557218859537152002801141174931847697995153465905288090 136b:c"\"136b"

Explanation:

2 pushes 2
'. pushes the dot
"…" is a string containing the rest of the digits in encoded form
128b converts the string to a number, treating the characters as digits in base 128 (via their ASCII code)


How to improve Ruby code under some restrictions I'm (still) trying to make another submission to the Largest Number Printable question, and I've got the following bit of code:

f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:$n}
h=[],$n=?~.ord,[]
h=f[h]until h==p($n+=$n)-$n

Ungolfed:

f=->{b,c,d=a
if b
  if a==b # a is not an array
    return a-1
  elsif a==a-[0] # a does not contain 0
    t = [b,c,f[d]]
    return [t,c-1,b]
  else # a is an array containing 0
    return b
  end
else # if a == []
  return $n
end}

$n = 126
h = [[],n,[]]

until h==0 do
  $n += $n
  p $n
  h = f[h]
end

The conditions I'm working with:

Maximum 100 bytes.
No digits allowed in my code.

My code is currently at 108 bytes, but I can't figure out how to golf it further.

The h==p($n+=$n)-$n may be replaced with h==0, but I can't use digits and I still need to print $n and apply $n+=$n in the until loop.

I'm also satisfied with code that replaces $n+=$n with $n+=1, but I can't use digits unfortunately.

Any suggestions?

105

You can save three bytes by declaring n as a local variable (instead of a global) before f:

n=?~.ord
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:n}
h=[],n,[]
h=f[h]until h==p(n+=n)-n


Shortest Code to Translate a PHP array NOTE: This question was migrated from https://stackoverflow.com/q/27134588/1442685

PHP QUESTION

Almost purely out of curiousity, how can I take an array like this:

array( 'fruit' => 'banana', 'drink' => 'milk')

And convert it to an array like this:

array( 'fruit=banana', 'drink=milk')

Requirements

Cannot use anonymous functions
If needed, can only use array_* functions that accept callable if that callable is native to PHP
Must be a one-liner solution

This is not for a class. I'm curious to see how clever one can be with array functions. Given the requirements, is it possible?

explode('&',http_build_query($a))

33 bytes


A long long time ago, in a galaxy ... right here Task
Given a positive integer return the geologic era and period it was that many million years ago.
Input/output
The input is a string or integer; the output is a string. Eras and periods are separated by slashes (/). Input will always be between 0 and 542 inclusive
Data
The possible outputs for eras and periods and their corresponding time periods (in millions of years) are:

Cenozoic 0 - 66

Quaternary 0 - 3
Neogene 4 - 23
Paleogene 24 - 66

Mesozoic 67 - 252

Cretaceous 67 - 145
Jurassic 146 - 201
Triassic 202 - 252

Paleozoic 253 - 542

Permian 253 - 299
Carboniferous 300 - 359
Devonian 360 - 419
Silurian 420 - 444
Ordovician 445 - 485
Cambrian 486 - 542

Submissions will be scored by byte count. Lowest byte count wins.
Test cases
314 -> Paleozoic/Carboniferous
0 -> Cenozoic/Quaternary
542 -> Paleozoic/Cambrian
100 -> Mesozoic/Cretaceous


Wild MISSINGNO appeared! I think is about time to do another Pokemon challenge! Even if Pokémon Go is not as mainstream as it used to be...

The task.

Just draw a MISSINGNO. MISSINGNO is an unofficial Pokémon species found in the video games Pokémon Red and Blue. IGN has noted MISSINGNO appearance in Pokémon Red and Blue as one of the most famous video game glitches.

How MISSINGNO looks like?

This Pokémon is a 3 tiles wide 7 tiles high image of random pixels. Each tile is 8x8 pixels. Considering x as horizontal coordinate which increases from left to right, y as vertical coordinate which increases from top to bottom and [x, y] as coordinate system, the tiles [0, 0], [0, 1] and [0, 2] are blank. The original MISSINGNO appears in Game Boy color roughly as the screenshot below:

Your MISSINGNO.

Your MISSINGNO shoudn't be exactly as the one in the screenshots above, but it should follow this pattern:

Should be formed of 21 tiles, 3 tiles wide 7 tiles high.
Every tile should have at least 9 colors, more than 9 colors is alowed, less is forbidden.
Every tile should have the same pixels in width and in heigth: this is, every tile should be a square.
Every tile should be of the same size, but they can be of any arbitrary size as long as they can show at least 9 colors (a MISSINGNO of 21 tiles of 3x3 pixels is as valid as one with 21 1000x1000 pixels tiles).
Tiles [0, 0], [0, 1] and [0, 2] should be transparent (alpha 0), look at How MISSINGNO looks like? to know the coordinates system.
Transparent means transparent. So any color is acceptable as long as it is completely transparent (alpha 0).
The opaque tiles shall be completely opaques, no transparent or semi-transparent pixels allowed.
Repeated opaque tiles are forbidden.
As long as the tiles follows the rules above, they can be anything: either procedural random pixels tiles or (as an example) pictures from google image search are alowed.

Your output.

Your output should be a image in any format your language supports.

The size of the image should be 3 * tile width wide and 7 * tile height high with no additional pixels alowed. So if you're using 3x3 tiles the image size should be: 9 pixels width and 21 pixels high, with 42x42 tiles the image size should be: 126 pixels width and 294 pixels high.
The ouptut image should be different every program call. Look at Your MISSINGNO to know about the size of the tiles.
The task is to generate the MISSINGNO image, not to show it. So as long as the image is generated the program is valid (but please, upload your results! all of us want to enjoy them!).

Your program.

It can accept a single integer value, this value will be the size of the MISSINGNO tiles.

You can assume that the input will be always possitive and equal to or greater than 3. Look at Your MISSINGNO to know about the size of the tiles.
If no input is provided, the default value is 8.

This is code golf, so the shortest code in bytes win!

JavaScript ES6 + HTML, 148 146 143 137 + 24 22 = 172 170 167 159 bytes

HTML

<canvas id=c></canvas>

JavaScript

d=c.getContext`2d`;for(x=0;x<9;x++)for(y=0;y<21;y++)if(x>2||y>8)d.fillStyle='#'+(Math.random()*0xFFF<<0).toString(16),d.fillRect(x,y,1,1)

Saved 8 bytes thanks to ETHproductions.

The image in the snippet has been scaled by 10 pixels to be more visible.

var d = c.getContext`2d`;
for(var x = 0; x < 90; x+=10) {
 for(var y = 0; y < 210; y+=10) {
  if (x > 20 || y > 80) {
   d.fillStyle = '#'+(Math.random()*0xFFF<<0).toString(16);
   d.fillRect(x, y, 10, 10);
  }
 }
}
<canvas id="c" width="90" height="210"></canvas>


This cat has bugs? Really? Challenge:

Read input (within visible ASCII range) and output with a few modifications:

In each set of 10 characters of the input randomly (50/50):

replace one character* (with a random** one within visible ASCII range) (ex. lumberjack becomes lumbeZjack)
or remove one character (ex. lumberjack becomes lmberjack)

* If the set is of less than 10 characters, you don't have to modify it, but you can.
** The character can be the same as the one input, as long as it's still random.

Example:

Input: Go home cat! You're drunk!
Output: Go hom cat! YouLre drunk!
(just a example, since output could be random, don't use as a test case)

Rules:

code-golf, least characters wins!

Pyth, 27 25 bytes
VczTpXNOT?<JOr\ \ÞKC127JK

Test suite available here.
Thanks to Maltysen for shaving off 2 bytes.
Explanation
VczTpXNOT?<JOr\ \ÞKC127JK    z autoinitalizes to input, T autoinitializes to 10
 czT                         chop input into strings of length 10, returned as list of strings
V                            for each string N in this list:
            Or\ \Þ            randomly pick a char between ' ' (32) and 'Þ' (222)
           J                  and assign it to variable J
                  KC127       assign the DEL char to variable K
         ?<J      K           if J < K:
     XNOT              J       replace a random character in N with J
         ?<J      K           else:
     XNOT               K      replace a random character in N with K
    p                         print this string with no trailing newline

As is often the case, I feel that this is a bit of a naive method and may be improved upon. Usually I find something obvious while typing up the explanation but nothing jumped out at me this time.


Download a file from the Internet Introduction
Yes, it's as simple as that. Download any file from the internet!
Rules
You must use your language's API.
You must output the file you downloaded to STDOUT, the console, a file, etc.
Input should be empty, or the URL you wish to download, but the url must count to byte count..
Good luck!


Construct the Jacobian matrix Take the vector of unknowns , and apply some generic differentiable function . The Jacobian is then given by a matrix  such that:

For example, suppose m=3 and n=2. Then (using 0-based indexing)

The Jacobian of f is then

The goal of this challenge is to print this Jacobian matrix.

Input

Your program/function should take as input two positive integers m and n, which represent the number of components of f and u respectively. The input may come from any source desired (stdio, function parameter, etc.). You may dictate the order in which these are received, and this must be consistent for any input to your answer (please specify in your answer).

Output

Something which represents the Jacobian matrix. This representation must explicitly spell out all elements of the Jacobian matrix, but the exact form of each term is implementation defined so long as is unambiguous what is being differentiated and with respect to what, and every entry is outputted in a logical order. Example acceptable forms for representing a matrix:

A list of lists where each entry of the outer list corresponds to a row of the Jacobian, and each entry of the inner list corresponds to a column of the Jacobian.
A string or textual output where each line is a row of the Jacobian, and each delimiter separated entry in a line corresponds to a column of the jacobian.
Some graphical/visual representation of a matrix. Example: what is shown by Mathematica when using the MatrixForm command
Some other dense matrix object where every entry is already stored in memory and can be queried (i.e. you can't use a generator object). Example  would be how Mathematica internally represents a Matrix object

Example entry formats:

A string of the form d f_i/d u_j, where i and j are integers. Ex: d f_1/d u_2. Note that these spaces between d and f_1 or x_2 are optional. Additionally, the underscores are also optional.
A string of the form d f_i(u_1,...,u_n)/d u_j or d f_i(u)/d u_j. That is, the input parameters of the function component f_i are optional, and can either be explicitly spelled out or left in compact form.
A formatted graphical output. Ex.: what Mathematica prints when you evaluate the expression D[f_1[u_,u_2,...,u_n],u_1]

You may choose what the starting index for u and f are (please specify in your answer). The output may be to any sink desired (stdio, return value, output parameter, etc.).

Test cases

The following test cases use the convention m,n. Indexes are shown 0-based.

1,1
[[d f0/d u0]]

2,1
[[d f0/d u0],
 [d f1/d u0]]

2 2
[[d f0/d u0, d f0/d u1],
 [d f1/d u0, d f1/d u1]]

1,2
[[d f0/d u0, d f0/d u1]]

3,3
[[d f0/d u0, d f0/d u1, d f0/d u2],
 [d f1/d u0, d f1/d u1, d f1/d u2],
 [d f2/d u0, d f2/d u1, d f2/d u2]]

Scoring

This is code golf; shortest code in bytes wins. Standard loopholes are forbidden. You are allowed to use any built-ins desired.

Python, 63 bytes

lambda m,n:["df%d/du%%d "%i*n%tuple(range(n))for i in range(m)]

For m=3,n=2, outputs

['df0/du0 df0/du1 ', 'df1/du0 df1/du1 ', 'df2/du0 df2/du1 ']

The string formatting is 1 byte shorter than the more obvious

lambda m,n:[["df%d/du"%i+`j`for j in range(n)]for i in range(m)]


Scoring 6,5,4 (AKA Ship, Captain, and Crew) Inspired and looted from this dice challenge by Arnauld

Input

You are given a 5x1 or 1x5 (your choice) dice matrix which consist of binary 3x3 sub-matrices.

Goal

Given a valid dice matrix, you are to score it using the rules of 6,5,4 which are as follows:

If the roll contains 6,5,4, add the other two dice together and that is your score. E.g. 4,X,5,6,Y = X+Y
Otherwise, the score is 0. E.g. 5,5,5,4,1 = 0

Wiki article for the game

Dice patterns

$$\begin{align}
&1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0}
&&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\
&3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0}
&&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\
&5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1}
&&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1}
\end{align}$$

Rules

The matrix is guaranteed to only contain valid faces but will include the 2,3 and 6 permutations. You can also take it in either orientation in whatever way is convenient. Please state the chosen orientation in your answer.
Output the calculated score
Standard Loopholes are forbidden
This is code-golf.

Examples

// 2,5,2,4,6: Output should be: 4
[ [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ],
  [ 1,0,1 ],
  [ 0,1,0 ],
  [ 1,0,1 ],
  [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ],
  [ 1,0,1 ],
  [ 0,0,0 ],
  [ 1,0,1 ],
  [ 1,1,1 ],
  [ 0,0,0 ],
  [ 1,1,1 ] ]

// 1,6,2,4,6: Output should be: 0
[ [ 0,0,0, 1,0,1, 1,0,0, 1,0,1, 1,1,1  ],
  [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0  ],
  [ 0,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1  ] ]

// 5,6,6,4,6: Output should be: 12
[ [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1  ],
  [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0  ],
  [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1  ] ]

// 3,3,4,5,6: Output should be: 6
[ [ 0,0,1, 1,0,0, 1,0,1, 1,0,1, 1,1,1  ],
  [ 0,1,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0  ],
  [ 1,0,0, 0,0,1, 1,0,1, 1,0,1, 1,1,1  ] ]

// 2,5,2,5,6: Output should be: 0
[ [ 0,0,1, 1,0,1, 1,0,0, 1,0,1, 1,1,1  ],
  [ 0,0,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0  ],
  [ 1,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1  ] ]

05AB1E, 15 bytes

3ôO<O©3LsK_P®O*

Try it online! or Check out a test suite!

Uses the same trick as Chas Brown and Lynn use: decrementing each integer in each 3x3 sub-matrix rather than subtracting 15 at the end. Expects input in column format.

How it works

3ôO<OD3LsK_PsO* – Full program.
3ô              – Split the input in 3x3 matrices representing dice faces.
  O<O           – Sum each, subtract one and sum each again.
                  This works because after the first O there are 3 elements in each
                  list and there are 5 lists in total, so 3 * 5 = 15 = 4 + 5 + 6.
     ©          – Copy this to the register.
      3LsK      – Push [1, 2, 3] and perform set subtraction. In this scenario, we
                  have already subtracted 3 from each list, so [1, 2, 3] represent
                  the actual dice values [4, 5, 6]. If the resulting list is empty,
                   that means that those values do exist in our roll. Therefore:
          _P    – Produce a list of zeros of that length and take the product
                  (4,5,6 isn't in the dice roll if the list is empty
                  and this method assures that in this case the product is 1, else 0)
            ®O* – Sum what's in the register and multiply by that.


Bijective function ℤ → ℤⁿ It is trivially possible to create a bijective function from \$\mathbb{Z}\$ (the set of all integers) to \$\mathbb{Z}\$ (e.g. the identity function).

It is also possible to create a bijective function from \$\mathbb{Z}\$ to \$\mathbb{Z}^2\$ (the set of all pairs of 2 integers; the cartesian product of \$\mathbb{Z}\$ and \$\mathbb{Z}\$). For example, we could take the lattice representing integer points on a 2D plane, draw a spiral from 0 outwards, and then encode pairs of integers as the distance along the spiral when it intersects that point.

(A function which does this with natural numbers is known as a pairing function.)

In fact, there exists a family of these bijective functions:

$$f_k(x) : \mathbb{Z} \to \mathbb{Z}^k$$

The Challenge

Define a family of functions \$f_k(x)\$ (where \$k\$ is a positive integer) with the property that \$f_k(x)\$ bijectively maps integers to \$k\$-tuples of integers.

Your submission should, given inputs \$k\$ and \$x\$, return \$f_k(x)\$.

This is code-golf, so the shortest valid answer (measured in bytes) wins.

Specifications

Any family \$f_k(x)\$  can be used as long as it fulfills the above criteria.
You are encouraged to add a description of how your function family works, as well as a snippet to compute the inverse of the function (this is not included in your byte count).
It is fine if the inverse function is uncomputable, as long as you can prove it the function is bijective.
You can use any suitable representation for signed integers and lists of signed integers for your language, but you must allow inputs to your function to be unbounded.
You only need to support values of \$k\$ up to 127.

Alice, 14 12 bytes

/O
\i@/t&Yd&

Try it online!

Inverse function (not golfed):

/o     Q
\i@/~~\ /dt&Z

Try it online!

Explanation

Alice has a built-in bijection between ℤ and ℤ2, which can be computed with Y (unpack) and its inverse Z  (pack). Here is an excerpt from the docs explaining the bijection:

  The details of the bijection are likely irrelevant for most use cases. The main point is that it lets the user encode two integers in one and extract the two integers again later on. By applying the pack command repeatedly, entire lists or trees of integers can be stored in a single number (although not in a particularly memory-efficient way). The mapping computed by the pack operation is a bijective function ℤ2 → ℤ (i.e. a one-to-one mapping). First, the integers {..., -2, -1, 0, 1, 2, ...} are mapped to the natural numbers (including zero) like {..., 3, 1, 0, 2, 4, ...} (in other words, negative integers are mapped to odd naturals and non-negative integers are mapped to even naturals). The two natural numbers are then mapped to one via the Cantor pairing function, which writes the naturals along the diagonals of the first quadrant of the integer grid. Specifically, {(0,0), (1,0), (0,1), (2,0), (1,1), (0,2), (3,0), ...} are mapped to {0, 1, 2, 3, 4, 5, 6, ...}. The resulting natural number is then mapped back to the integers using the inverse of the earlier bijection. The unpack command computes exactly the inverse of this mapping.

As alluded to above, we can use this unpack operation to map ℤ to ℤk as well. After applying it to the initial integer, we can unpack the second integer of the result again, which gives us a list of three integers. So k-1 applications of Y give us k integers as the result.

We can compute the inverse by packing the list up with Z from the end.

So the program itself has this structure:

/O
\i@/...d&

This is just a basic template for a program which reads a variable number of decimal integers as input and prints a variable number as the result. So the actual code is really just:

t   Decrement k.
&   Repeat the next command k-1 times.
Y   Unpack.

One thing I'd like to address is "why would Alice have a built-in for a ℤ → ℤ2 bijection, isn't that golfing language territory"? As with most of Alice's weirder built-ins, the main reason is Alice's design principle that every command has two meanings, one for Cardinal (integer) mode and one for Ordinal (string) mode, and these two meanings should be somehow related to give Cardinal and Ordinal mode the feeling that they are mirror universes where things are sort of the same but also different. And quite often I had a command for one of the two modes I wanted to add, and then had to figure out what other command to pair it with.

In the case of Y and Z Ordinal mode came first: I wanted to have a function to interleave two strings (zip) and separate them again (unzip). The quality of this that I wanted to capture in Cardinal mode was to form one integer from two and be able to extract the two integers again later, which makes such a bijection the natural choice.

I also figured that this would actually be very useful outside of golfing, because it lets you store an entire list or even tree of integers in a single unit of memory (stack element, tape cell or grid cell).


The infinite power tower The challenge
Quite simple, given an input x, calculate it's infinite power tower!
x^x^x^x^x^x...

For you math-lovers out there, this is x's infinite tetration.
Keep in mind the following:
x^x^x^x^x^x... = x^(x^(x^(x^(x...)))) != (((((x)^x)^x)^x)^x...)

Surprised we haven't had a "simple" math challenge involving this!*
Assumptions

x will always converge.
Negative and complex numbers should be able to be handled
This is code-golf, so lowest bytes wins!
Your answers should be correct to at least 5 decimal places

Examples
Input >> Output

1.4 >> 1.8866633062463325
1.414 >> 1.9980364085457847
[Square root of 2] >> 2
-1 >> -1
i >> 0.4382829367270323 + 0.3605924718713857i
1 >> 1
0.5 >> 0.641185744504986
0.333... >> 0.5478086216540975
1 + i >> 0.6410264788204891 + 0.5236284612571633i
-i >> 0.4382829367270323 -0.3605924718713857i
[4th root of 2] >> 1.239627729522762

*(Other than a more complicated challenge here)

APL (Dyalog), 4 bytes

*⍣≡⍨

Try it online!

* power

⍣ until

≡ stable

⍨ selfie


Inject Textual Rickrolls Because rickrolling is the greatest meme on Earth, you [know the rules and so do I] are to write the shortest code that can textually rickroll the unsuspecting reader.  Let [you down] there be an input text which contains letters, punctuation, and spaces.  Anytime a [lie and hurt you] phrase from the first two stanzas appears in the text...

We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

...insert the rest of the line in brackets afterwards.

Input

Input is a single line string containing only printable ASCII with optional trailing newline.

Output

Output is a single-line string.  Any time that a group of words (defined as the input string split on spaces) matches a group of words in lines of the lyrics above, insert the remaining words of the line into the string, grouped in square brackets.

Additional Description:

This is code-golf, fewest bytes wins.  You may write a program or function.

matching should be case insensitive: we're is converted to we're [no strangers to love] even though We're is capitalized in the lyrics.
matching should be greedy.  Does he know the answer? should be converted to Does he know the [rules and so do I] answer? instead of Does he know [the rules and so do I] the [rules and so do I] answer?
If a word appears more than once in the provided lyrics, choose any of the occurrences to complete the line.
If a word is the last word in the lyric line, don't insert anything after it.
Punctuation is included as part of a "word."  I'm is a single word and cannot match with I.  Similarly, you. doesn't match with any lyrics because of the period.

Some words like I appear multiple times throughout the lyrics as well as at the end of a line.  Since the rule is that any occurrence in the above lyrics can be used, and one of those occurrences is at the end of a line, no matching of I is necessary.  The other option for I is [just wanna tell you how I'm feeling].

If two matches overlap, you may choose either one. This means that how I'm thinking could become how I'm [feeling] thinking [of] OR how [I'm feeling] I'm thinking [of] since the I'm could be part of either how I'm or I'm thinking.  If, however the input text was simply I'm thinking, then the output should be I'm thinking [of].

Additional test cases:

I don't know what I'm doing with my life.
is converted to
I [just wanna tell you how I'm feeling] don't know [the rules and so do I] what I'm [thinking of] doing with my life.
Many additional solutions are possible, since words like `I` appear multiple times.

Will someone please save me from these memes?
is converted to
Will someone please save me from [any other guy] these memes?

Two strangers walked into a bar.  One said "hello."  The other said "goodbye."
is converted to
Two strangers [to love] walked into a [lie and hurt you] bar.  One said "hello."  The [rules and so do I] other [guy] said "goodbye."

Challenge inspired by this dude.

gawk, 316+377 = 693

First command line parameter is the lyrics' filename (375 bytes + 2 for invocation = 377). Rickrolls all other files. Prints to stdout.

BEGIN{FPAT="[^ ]+ *";OFS=""}func d(a){b=tolower(a);sub(/ *$/,"",b);return b}FNR==NR{for(s=$0;NF;$0=s=$0){for(i=1;i<NF;i++){k=k $i;$i="";v[d(k)]="["$0"] "}$0=s;k=$1=""}next}{for(s=$0;NF;$0=s=$0){for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)="");k=v[d($0)];if($0!~/ $/)k=" "k;printf($0 k);for($0=s;j-->=0;$(j+2)="");}print""}

Ungolfed

BEGIN{FPAT="[^ ]+ *";OFS=""}
func d(a){b=tolower(a);sub(/ *$/,"",b);return b}
FNR==NR{
  for(s=$0;NF;$0=s=$0){
    for(i=1;i<NF;i++)
    {
      k=k $i;
      $i="";
      v[d(k)]="["$0"] "
    }
    $0=s;
    k=$1=""
  }
  next
}
{
  for(s=$0;NF;$0=s=$0){
    for(j=NF;(--j)>0&&!(d($0) in v);$(j+1)="");
    k=v[d($0)];
    if($0!~/ $/)k=" "k;
    printf($0 k);
    for($0=s;j-->=0;$(j+2)="");
  }
  print""
}

Test results

Input:

we're
We're
Does he know the answer?
I
how I'm thinking
I'm thinking
I don't know what I'm doing with my life.
Will someone please save me from these memes?
Two strangers walked into a bar.  One said "hello."  The other said "goodbye."
gonna run

Output:

we're [no strangers to love]
We're [no strangers to love]
Does he know the [rules and so do I] answer?
I [just wanna tell you how I'm feeling]
how I'm [feeling] thinking [of]
I'm thinking [of]
I [just wanna tell you how I'm feeling] don't know [the rules and so do I] what I'm [thinking of] doing with my life.
Will someone please save me from [any other guy] these memes?
Two strangers [to love] walked into a [lie and hurt you] bar.  One said "hello."  The [rules and so do I] other [guy] said "goodbye."
gonna run [around and desert you]


Programming with Bits and Bytes In this challenge you are going to write an interpreter for a simple language I've made up. The language is based on a single accumulator A, which is exactly one byte in length. At the start of a program, A = 0. These are the languages instructions:

!: Inversion

This instruction simply inverts every bit of the accumulator. Every zero becomes a one and every one becomes a zero. Simple!

>: Shift Right

This instruction shifts every bit in A one place to the right. The leftmost bit becomes a zero and the rightmost bit is discarded.

<: Shift Left

This instruction shifts every bit in A one place to the left. The rightmost bit becomes a zero and the leftmost bit is discarded.

@: Swap Nybbles

This instruction swaps the top four bits of A with the bottom four bits. For example, If A is 01101010 and you execute @, A will be 10100110:

 ____________________
 |                  |
0110 1010    1010 0110
      |_______|

That's all the instructions! Simple, right?

Rules

Your program must accept input once at the beginning. This will be a line of code. This is not an interactive interpreter! You can only accept input once and do not have to loop back to the start once that line has been executed.
Your program must evaluate said input. Every character that is not mentioned above is ignored.
Your program should then print out the final value of the accumulator, in decimal.
Usual rules for valid programming languages apply.
Standard loopholes are disallowed.
This is code-golf, smallest byte count wins.

Here are some small programs to test out your submissions. Before the arrow is the code, after it is the expected result:

! -> 255
!>> -> 63
!<@ -> 239
!nop!&6*! -> 255

Enjoy!

Pyth, 36 35 bytes

u%@[t_G/G2yGi_jGJ16JG)x"!><@"H256z0

Test harness

The internal representation of the accumulator is an integer. This integer is mod-ed by 256 on each iteration, as desired. The operations performed are -G-1, G/2, G*2 and G converted to base 16, reversed, and converted back to base 10, where G is the accumulator.

I missed the line about ignoring everything else. This has been remedied. Thanks, @Dennis.