Compressing a DNA-like string Challenge:

Write a a program to take an array of 24 4-letter strings, and output a compressed (lossless) representation of the array. You should also provide a program to decompress your representations.

Input:

The input will be comprised of 4 letter words using each of [G,T,A,C] exactly once (e.g. GTAC, ATGC, CATG, etc). There are always exactly 24 words, so the full input is something like:

GTAC CATG TACG GACT GTAC CATG TACG GACT GTAC CATG TACG GACT GTAC CATG TACG GACT GTAC CATG TACG GACT GTAC CATG TACG GACT

So there are \$4!=24\$ possibilities for each word, and 24 words in total.

Output:

The output should be a printable ASCII string that can be decompressed back into the input string. Since this is lossless compression, each output should match to exactly one input.

Example:

>>> compress(["GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT"])
"3Ax/8TC+drkuB"

Winning Criterion

Your code should minimize the output length. The program with the shortest output wins. If it's not consistent, the longest possible output will be the score.

Edit: Based on helpful feedback comments, I would like to amend the criterion to add:

If two entries have the same results, the shortest code measured in characters wins.  If an entry is length dependent, a length of 1 million words is the standard.

However, I fear the community angrily telling me I didn't say it right and downvoting me to the abyss, so I leave to community editors to see if it makes sense with code golf traditions

Python (output-length: 18 or 19, mean 18.80)

#list of the 24 possible words
Lbase = ['GTAC','GTCA','GATC','GACT','GCTA','GCAT','TGAC',\
'TGCA','TAGC','TACG','TCGA','TCAG','AGTC','AGCT','ATGC',\
'ATCG','ACGT','ACTG','CGTA','CGAT','CTGA','CTAG','CAGT','CATG']

#base-64 alphabet (used only in the output string-representation)
alph = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/'

#change a bijective list-representation base from b to newb
def chg_bij_base(L, b, newb):
    n = sum([L[i]*b**i for i in range(len(L))])
    L = []
    while n > 0:
        L.append(1+(n-1)%newb)
        n = (n-1)//newb
    return L

#convert a bijective list-repr. to base-64 string-repr.
def list_to_str(Lin):
    L24 = [Lbase.index(w)+1 for w in Lin]
    L64 = chg_bij_base(L24,24,64)
    return ''.join([alph[i-1] for i in L64])

#convert a base-64 string to the corresponding base-64 list-repr.
def str_to_list(s):
    L64 = [alph.index(c)+1 for c in s]
    L24 = chg_bij_base(L64,64,24)
    return [Lbase[i-1] for i in L24]

Test run:

Lin = ["GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT", "GTAC", "CATG", "TACG", "GACT"]

#convert input list to a base-64 string
lts = list_to_str(Lin)

#convert the base-64 str back to the list
stl = str_to_list(lts)

print(len(lts))
print(lts)
print(stl == Lin)

Test output:

18
acFZIBuiiZJ+dwUn2V
True

This uses bijective numeration (which has no 0 digit) to get invertibility.

NB: When using base-64 with this method, all output strings for the above problem are either 18 or 19 characters. (A million random inputs gave an average of 18.80.) The same method works with other bases:

base         output-length
---------    -------------
56 - 58      19
59 - 69      18 or 19
70 - 73      18
74 - 88      17 or 18
89 - 96      17
...          ...
233 - 256    14


Draw the Hilbert Curve A Hilbert Curve is a type of space-filling curve, and it basically maps a line to a plane. Each point in the line corresponds to just one point in the plane, and each point in the plane corresponds to just one point on the line. Shown are iterations 0 through 4 of the Hilbert Curve:

Iterations 0 up to 4:

The objective of this task: Write code that draws the fourth iteration of the Hilbert Curve, as defined above. Your code should be complete - in other words, if you create a function to draw the Hilbert Curve, your code must call that function. The output can either be displayed directly on the screen, or you can write the output to an image file. The curve may be rotated or flipped, but lines must intersect at right angles and the output cannot be stretched. ASCII art is appreciated but will not be accepted. Shortest code in bytes wins!

MATL, 39 38 bytes
O5:"tZjJ*JQ-wJq+t2+&y2j+_v2/]XG25Y01ZG

This takes the number of iterations as input. If you want to hard-code it, replace i by the number.
The program is a port of the Matlab code by Jonas Lundgren shown here.
The result is shown below. You can also try it at MATL Online! It takes a couple of seconds to produce the output. This compiler is experimental; you may need to refresh the page and press "Run" again if it doesn't initially work.

Explanation
O          % Push 0. This is the initial value of "z" in the original code
5:"        % Do 5 times
  t        %   Duplicate
  Zj       %   Complex conjugate
  J*       %   Multiply by 1j (imaginary unit). This is "w" in the original code
  JQ-      %   Subtract 1+1j
  w        %   Swap: brings copy of "z" to top
  Jq+      %   Add 1-1j
  t        %   Duplicate
  2+       %   Add 2
  &y       %   Duplicate the third element from top
  2j+_     %   Add 2j and negate
  v        %   Concatenate the three matrices vertically
  2/       %   Divide by 2
]          % End
XG         % Plot (in complex plane). The numbers are joined by straight lines
25Y0       % Push string 'square'
1ZG        % Make axis square


Regex: Match an egalitarian series Introduction

I don't see many regex challenges on here, so I would like to offer up this deceptively simple one which can be done in a number of ways using a number of regex flavours. I hope it provides regex enthusiasts with a bit of fun golfing time.

Challenge

The challenge is to match what I've very loosely dubbed an "egalitarian" series: a series of equal numbers of different characters. This is best described with examples.

Match:

aaabbbccc
xyz
iillppddff
ggggggoooooollllllffffff
abc
banana

Don't match:

aabc
xxxyyzzz
iilllpppddff
ggggggoooooollllllfff
aaaaaabbbccc
aaabbbc
abbaa
aabbbc

To generalize, we want to match a subject of the form (c1)n(c2)n(c3)n...(ck)n for any list of characters c1 to ck, where ci != ci+1 for all i, k > 1, and n > 0.

Clarifications:

Input will not be empty.
A character may repeat itself later in the string (eg. "banana")
k > 1, so there will always be at least 2 different characters in the string.
You can assume only ASCII characters will be passed as input and no character will be a line terminator.

Rules

(Thank you to Martin Ender for this excellently-stated block of rules)

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's e modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly, e.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex must match the entire string for valid egalitarian strings and yield no matches for invalid strings. You may use as many capturing groups as you wish.

You may assume that the input will always be a string of two or more ASCII characters not containing any line-terminators.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually /.../) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

Criteria

This is good ol' fashioned golf, so forget efficiency and just try to get your regex as small as possible.

Please mention which regex flavour you have used and, if possible, include a link showing an online demo of your expression in action.

.NET flavour, 48 bytes

^(.)\1*((?<=(\5())*(.))(.)(?<-4>\6)*(?!\4|\6))+$

Try it online! (using Retina)

Well, turns out that not negating the logic is simpler after all. I'm making this a separate answer, because the two approaches are completely different.

Explanation

^            # Anchor the match to the beginning of the string.
(.)\1*       # Match the first run of identical characters. In principle,
             # it's possible that this matches only half, a quarter, an
             # eighth etc of of the first run, but that won't affect the
             # result of the match (in other words, if the match fails with
             # matching this as the entire first run, then backtracking into
             # only matching half of it won't cause the rest of the regex to
             # match either).
(            # Match this part one or more times. Each instance matches one
             # run of identical letters.
  (?<=       #   We start with a lookbehind to record the length
             #   of the preceding run. Remember that the lookbehind
             #   should be read from the bottom up (and so should
             #   my comments).
    (\5())*  #     And then we match all of its adjacent copies, pushing an
             #     empty capture onto stack 4 each time. That means at the
             #     end of the lookbehind, we will have n-1 captures stack 4,
             #     where n is the length of the preceding run. Due to the
             #     atomic nature of lookbehinds, we don't have to worry
             #     about backtracking matching less than n-1 copies here.
    (.)      #     We capture the character that makes up the preceding
             #     run in group 5.
  )
  (.)        #   Capture the character that makes up the next run in group 6.
  (?<-4>\6)* #   Match copies of that character while depleting stack 4.
             #   If the runs are the same length that means we need to be
             #   able to get to the end of the run at the same time we
             #   empty stack 4 completely.
  (?!\4|\6)  #   This lookahead ensures that. If stack 4 is not empty yet,
             #   \4 will match, because the captures are all empty, so the
             #   the backreference can't fail. If the stack is empty though,
             #   then the backreference will always fail. Similarly, if we
             #   are not at the end of the run yet, then \6 will match
             #   another copy of the run. So we ensure that neither \4 nor
             #   \6 are possible at this position to assert that this run
             #   has the same length das the previous one.
)+
$            # Finally, we make sure that we can cover the entire string
             # by going through runs of identical lengths like this.


BWInf 2011, question 5: Twin towns This is a challenge that was originally a tas for the German Bundeswettbewerb Informatik (federal competition of computer science [?]), a competition for highschool students. As opposed to the original question, where you have to find a good solution and write some documentation, I want you to golf this. I try to replicate the question as good as possible:
Challenge
Many towns in Europe have so-called twin towns. This year, there is a special Jubilee where each pair of twin-towns in the EU organizes a festival to celebrate their partnership. To ensure that no city has to organize too many festivals, each city has a limit of festivals it can organize. Is it possible to distribute the festivals among the twin-towns in a way, such that each pair of twin-towns organizes one festival in one the two towns and no town organizes more festivals than it is allowed to? If yes, explain how.
This is a map of some towns, their partnerships and their limits of festivals.
partnerships http://dl.dropbox.com/u/1869832/partnerships.png
Requirements

Your program must terminate the problem in one minute each for both testcases. (See below)

Refer to the testcases for the input format.

The output should be empty iff no solution exists and should have the following format otherwise: One line for each pair of twin towns, a if city1 organizes the festival, b otherwise.
  <city1>, <city2>, <a/b>

The solution with the least number of characters that satisfies the requirements wins. In case of a tie, the program that was submitted first wins.

Usual code-golf rules apply.

Testcases
The original task had two testcases. I have uploaded them on github.

C#, 1016 992 916 chars

Takes 4 seconds for me on the large test set; performance can easily be improved a lot by making X a HashSet<s> rather than a List<s>.

using System;using System.Collections.Generic;using System.IO;using System.Linq;using
s=System.String;class D<T>:Dictionary<s,T>{}class E:D<int>{static void Main(s[]x){s
S="",T=">",l;s[]b;D<E>R=new D<E>(),P=new D<E>();R[S]=new E();R[T]=new E();foreach(s L in
File.ReadAllLines(x[0])){b=L.Split('"');s f=b[1];R[T][f]=0;R[f]=new E();P[f]=new
E();R[f][T]=int.Parse(b[0].Trim());}foreach(s L in File.ReadAllLines(x[1])){b=L.Split('"');s
f=b[1],t=b[3],v=f+t;R[v]=new
E();R[v][S]=R[f][v]=R[t][v]=0;P[f][t]=R[S][v]=R[v][f]=R[v][t]=1;}for(;;){List<s>X=new
s[]{S}.ToList(),A=X.ToList();w:while((l=A.Last())!=T){foreach(s t in
R[l].Keys){if(!X.Contains(t)&R[l][t]>0){X.Add(t);A.Add(t);goto
w;}}A.RemoveAt(A.Count-1);if(!A.Any())goto q;}l=S;foreach(s n in
A.Skip(1)){R[l][n]--;R[n][l]++;l=n;}}q:if(R[S].Values.Contains(1))return;foreach(s
f in P.Keys)foreach(s t in P[f].Keys)Console.WriteLine(f+", "+t+", "+"ba"[R[f][f+t]]);}}

This uses the reduction to max flow which I hinted at earlier in comments. The vertices are

A newly generated source S and sink T.
The partnerships.
The cities.

The edges are

From the source to each partnership with flow capacity 1.
From each partnership to each city in the partnership with flow capacity 1.
From each city to the sink with flow capacity equal to that city's budget.

The algorithm is Ford-Fulkerson with DFS. It is obvious a priori that each augmenting path will increase the flow by 1, so the golfing optimisation of removing the computation of the path's flow has no negative effect on performance.

There are other possible optimisations by making assumptions such as "The names of the input files will never be the same as the names of the cities", but that's a bit iffy IMO.


Am I a Pillai prime? A Pillai prime is a prime number \$p\$ for which there exists some positive \$m\$ such that \$(m! + 1) \equiv 0 \:(\text{mod } p)\$ and \$p \not\equiv  1\:(\text{mod }m)\$.

In other words, an integer \$p\$ is a Pillai prime if it is a prime number, if there exists another positive integer \$m\$ such that the factorial of \$m\$, plus \$1\$ is divisible by \$p\$ and if \$p - 1\$ isn't divisible by \$m\$.

Given a positive integer as input, decide whether it is a Pillai prime. The sequence of Pillai primes is OEIS A063980.

For example, \$23\$ is a Pillai prime because:

It is a prime number, having only 2 factors.
\$m = 14\$ and \$m = 18\$ satisfy the above conditions: \$23 \mid (14! + 1)\$ and \$14\$ does not divide \$22\$; \$23 \mid (18! + 1)\$ and \$18\$ does not divide \$22\$ either.

Test cases

Truthy:

23
59
83
109
139
593

Falsy:

5
7
8
73
89
263
437

For the truthy cases, the respective m's are [(23, [14, 18]), (59, [15, 40, 43]), (83, [13, 36, 69]), (109, [86]), (139, [16]), (593, [274])].

You can either follow the standard decision-problem output format (that is, truthy / falsy values) or have a consistent value for Pillai primes and a non-consistent value otherwise or vice-versa.

You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (in bytes) for every language wins.

Python 2, 115 111 110 109 bytes

-6 bytes thanks to Mr. Xcoder

lambda n:n>2and cmp(*map(all,zip(*[[n%x==1or~f(x)%n,n%x]for x in range(2,n)])))<0
f=lambda x:0**x or x*f(x-1)

Try it online!

The functions consist of two parts ~-n%x<1or~f(x)%n>0 that verifies if n don't satisfies the "Pillai conditions", and n%x>0 for the prime validation.
After that all is applied to both items, the first item will contain False/0 if there is a valid "Pillai number", and the second will contain True/1 if n is prime.
These are passed to cmp that will return -1 in this cenario (is a valid Pillai prime). The other combinations [[0, 0], [1, 0], [1, 1]] will return 0 or 1


Compute modular inverse Given two positive numbers \$x\$ and \$n\$ with \$x<2^n\$, write the shortest possible function to compute \$x^{-1} \mod 2^n\$.  In other words, find \$y\$ such that \$xy=1 \mod 2^n\$.
Your function must complete in a reasonable time for at least \$n=64\$, so exhaustive search will not work.
If the inverse does not exist, you must indicate that to the caller somehow (throw an exception, return a sentinel value, etc).
If you're wondering where to start, try the Extended Euclidean Algorithm.

Python, 29 bytes

lambda x,n:pow(x,2**n-1,2**n)

This returns 0 for even x. It uses Euler’s theorem, with the observation that 2^n − 1 is divisible by 2^(n − 1) − 1, via Python’s builtin fast modular exponentiation. This is plenty fast enough for n up to 7000 or so, where it starts taking more than about a second.


Sort-a-number. Sorta Inspired by the ill-fated sorting-a-numbers-digits-without-using-an-array, but I thought it made a better code golf than SO question.

Given a positive integer, sort the digits in that integer.

Lowest score wins!

Start with 0 points.
Add one point per character.
Add 20 points for each array you use.
Add 10 points for each multi-character string in your code. (Except the initial input as long as it is converted to an integer without any other operations done on it.)
Add 32 points if the maximum number of digits your program can handle is limited by your program (as opposed to the machine).
Subtract 10 points if your code can change the direction of the sort given another argument (whatever you want, but for example 0 for descending sort and 1 for ascending.)

Every language is different, but the idea is to avoid any kind of iterable-of-digits hackery.

Example:

Input: 52146729

Output: 97654221 or 12245679

Notes:

Use any built-in sorting capabilities your programming language provides, but if that sort feature involves strings or arrays, take the penalty!
You can write the solution as a function that takes an integer directly, or as a program that takes an argument from argv, a file or stream and converts it to an integer. As long as you convert it to an integer immediately and discard the original char* input without doing any further operations on it, no penalty applies.
The penalties apply not only to string literals in your program text, but any part of your program feature that arguably inputs or outputs a string or iterable. For example, JavaScript String.prototype.split has at least one string as input (this) and an Array as output, so +30 for using that.
I've tried to make these rules guide the principle of the algorithm design, not the initial/final I/O (hence note #2). I don't think the penalty ought to apply to int(input()) even if input's signature says it returns a string, as long as that expression is the initial entry point of the program. Likewise, if the final output of the program is print(x) and x must be a string, the penalty doesn't apply to the last-ditch string casting operation. All that said, I explicitly never said that this had to be a program or where the I/O had to come from or go. A function that takes an int and returns an int would serve, and wouldn't suffer from these ambiguities.

Haskell 106

t=10;d=divMod;s z|z<w z=s$w z|t>0=z
w x|x<t=x|y>z=(q*t+y)*t+z|t>0=y+t*(w v)where{(v,y)=d x t;(q,z)=d v t}

example:

ghci> s 502010406072952146729521467295214672952146729
999997777766666555554444422222222221111100000

An answer that doesn't dodge the question.

An explanation was requested, here it is ungolfed. It's a very inefficient bubble sort.

-- t=10 - alias for 10. d=divMod - alias for divMod.
-- The alias for '10' turns out to be unnecessary; inlining it
-- and using '1>0' for True has the same character count. It's
-- a relic of earlier versions of the code.

-- 's': if no digits need swapped, return the number,
-- otherwise return 's' applied to the number with
-- that pair of digits swapped.
sort z=
  let temp=sort_pair z
  -- because we are sorting in descending order,
  -- sorting a pair of digits always increases the number.
  -- testing > costs one less char than ==.
  if z<temp then
    -- golfed version uses guards instead of if/else to save space.
    -- t>0 is '10 > 0', which is 'True', in fewer chars.
    sort temp
  else
    z
-- 'w': recursively swap one pair of out of order digits, or
-- return the original number if no pairs needed swapped.
sort_pair x=
  -- haskell does the assignments below lazily, they aren't
  -- calculated unless I use them. 'divMod' lets me do this
  -- with fewer chars.
  let y = x `mod` 10 -- last digit
      v = x `div` 10 -- all but last digit
      z = v `mod` 10 -- second last digit
      q = v `div` 10 -- all but last 2 digits
  in
  if x < 10 then
    x
  else if y > z then
    -- last 2 digits are out of order. swap them & return
    -- This is rearranged using Horner's method to save space
    -- http://en.wikipedia.org/wiki/Horner%27s_method
    -- ... although it turns out not to save anything, it's a relic.
    (q * 10 + y)*10 + z
  else
    -- last digit is ok, so try sort_pair on remaining digits
    let temp = sort_pair v in
    -- put last digit back on the end and return
    -- having the bracketed expression last here
    -- let me remove a space before 'where'
    y+(10*temp)

Shorter answers exist in Haskell, equivalent to some of the others posted, eg:

import Data.List;s=read.sort.show::Integer->Integer

... scores 52+20=72, or this, scoring 45+20=65:

import Data.List;main=interact(reverse.sort)

... but the spirit of the question - no arrays, strings, or characters - is more interesting.


Cryptographic hash golf (robbers) This contest is over.

  There are no remaining crackable answer in the cops challenge.

Companion thread of Cryptographic hash golf

As a reminder, here are the rules for robbers from the main challenge:

  Task

  Crack any of the cops' submissions by posting the following in the
  robbers' thread: two messages M and N in I such that
  H(M) = H(N) and M ≠ N.

  Scoring

  Cracking each cop submissions gains you one point. The robber with the most points wins.

  In the case of a tie, the tied robber that cracked the longest
  submission wins.

  Additional rules

  Every cop submission can only be cracked once.
  If a cop submission relies on implementation-defined or undefined behavior, you only have to find a crack that works (verifiably) on
  your machine.
  Each crack belongs to a separate answer in the robbers' thread.
  Posting an invalid cracking attempt bans you from cracking that particular submission for 30 minutes.
  You may not crack your own submission.

  Example

    Python 2.7, 22 bytes by user8675309

1

    and

18

Leaderboard

eBusiness: 3 cracks, 393 bytes
Martin Büttner: 3 cracks, 299 bytes
jimmy23013: 3 cracks, 161 bytes
Sp3000: 3 cracks, 44 bytes
tucuxi: 2 cracks, 239 bytes
Vi.: 2 cracks, 87 bytes
feersum: 1 crack, 216 bytes
mathmandan: 1 crack, 139 bytes
squeamish ossifrage: 1 crack, 134 bytes

Python, 109 bytes by Sp3000
Note that Martin cracked first, so I'm not sure if this deserves points. On the other hand, I did make a preimage attack rather than a simple collision - a much stronger result. This means that you can give it an arbitrary hash value, and it will construct an input that generates that hash value.
M = 2**128

# The hash to crack.
def jenkins(n):
    h = 42
    while n:
        h += n & (M - 1)
        n >>= 128
        h *= 1025
        h ^= h >> 6
        h %= M

    h *= 9
    h ^= h >> 11
    h *= 32769

    return h % M

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def invxorshift(h, s):
    r = h >> s
    while r:
        h ^= r
        r >>= s
    return h

def moddiv(a, b):
    return (a * modinv(b, M)) % M

def jenkins_crack(h):
    h = moddiv(h, 32769)
    h = invxorshift(h, 11)
    h = moddiv(h, 9)
    h = invxorshift(h, 6)
    h = moddiv(h, 1025)
    h -= 42
    return h

And to show that it works:
>>> from crack import *
>>> n = 2**128 + 1337
>>> h = jenkins(n)
>>> n2 = jenkins_crack(h)
>>> h2 = jenkins(n2)
>>> n != n2
True
>>> h == h2
True

And to give a particular set of numbers that collide:
N: 2**128
M: 43617


NATO phonetic spelling can take long NATO phonetic alphabet is a spelling alphabet that associate to each of the 26 letters of the English alphabet one word (table below) that is easy to understand over the radio or telephone. For example, if you want to communicate the word CAT over the telephone, you do the following spelling:
CHARLIE ALFA TANGO
But what if you are unsure if the spelling was understood correctly? Well, you do the spelling of the spelling:
CHARLIE HOTEL ALFA ROMEO LIMA INDIA ECHO ALFA LIMA FOXTROT ALFA TANGO ALFA NOVEMBER GOLF OSCAR
But now you are worry that the spelling of the spelling was not understood  correctly, so you cannot help yourself but doing the spelling of the spelling of the spelling:
CHARLIE HOTEL ALFA ROMEO LIMA INDIA ECHO HOTEL OSCAR TANGO ECHO LIMA   ALFA LIMA FOXTROT ALFA ROMEO OSCAR MIKE ECHO OSCAR LIMA INDIA MIKE ALFA   INDIA NOVEMBER DELTA INDIA ALFA ECHO CHARLIE HOTEL OSCAR ALFA LIMA FOXTROT ALFA LIMA INDIA MIKE ALFA FOXTROT OSCAR XRAY TANGO ROMEO OSCAR TANGO   ALFA LIMA FOXTROT ALFA TANGO ALFA NOVEMBER GOLF OSCAR ALFA LIMA FOXTROT ALFA NOVEMBER OSCAR VICTOR ECHO MIKE BRAVO ECHO ROMEO GOLF OSCAR LIMA FOXTROT OSCAR SIERRA CHARLIE ALFA ROMEO
Challenge: Write a function that takes as input a word and returns as output the number of letters of the 100th iteration of NATO spelling. Examples:
MOUSE -> 11668858751132191916987463577721689732389027026909488644164954259977441
CAT -> 6687458044694950536360209564249657173012108297161498990598780221215929
DOG -> 5743990806374053537155626521337271734138853592111922508028602345135998

Notes:

Whitespaces do not count. Only letters do.
Both uppercase and lowercase letters are fine (including combinations of uppercase and lowercase).
If you want to use a programming language without support for large integers, returning the result modulo 2^32 is fine too.
The result must be an exact integer, not an approximation (like floating point).
The first iteration of CAT is CHARLIE ALFA TANGO (CAT is the 0th iteration).

Big Note:
If your program stores the spelling string, there's no way it is not going to run out of memory: the 100th iteration of MOUSE requires more than 10^70 bytes; the whole data on the Internet is estimated to be below 10^30 bytes.
NATO spelling Table:
A -> ALFA
B -> BRAVO
C -> CHARLIE
D -> DELTA
E -> ECHO
F -> FOXTROT
G -> GOLF
H -> HOTEL
I -> INDIA
J -> JULIETT
K -> KILO
L -> LIMA
M -> MIKE
N -> NOVEMBER
O -> OSCAR
P -> PAPA
Q -> QUEBEC
R -> ROMEO
S -> SIERRA
T -> TANGO
U -> UNIFORM
V -> VICTOR
W -> WHISKEY
X -> XRAY
Y -> YANKEE
Z -> ZULU


Generating an adequate password Story

I need to remember a lot of passwords and don't want to use the same one for multiple websites so I came up with a rule, but the rule shouldn't be transparent so what I do is:

Think of a long word or concept such as breadpudding.
Replace the first letter with the site we are logging into. If we are logging into google, our word becomes greadpudding.
Make the first letter uppercase.
Change the second letter to an @ sign.
If the password starts with a non-consonant, add a certain number (such as 1234); otherwise, add another number (such as 4321).

Ta da, you now have an adequate password.

This process is arduous though so I need a program to generate this for me based on the following:

Problem

Given input:

a : the initial word, which is a string and is always lowercase, and is guaranteed to be longer than 3 characters.
b : the site we are logging into, which is a string and is always lowercase, and is guaranteed to be non-empty.
c : the number for non-consonants, which is a positive integer that may have leading zeroes.
d : the number for consonants, which is a positive integer that may have leading zeroes.

Output a string based on above criteria.

Test cases

Input a="volvo", b="gmail", c=5555, d="0001"

G@lvo0001

Input a="sherlock", b="9gag", c=31415926535, d=3

9@erlock31415926535

Input a="flourishing", b="+google", c=11111, d=2222

+@ourishing11111

Rules

y is a consonant.
If you decide c or d is an integer, you may parse it as such, and leading zeroes can be ignored (0091 gets treated as 91).
Trailing whitespace and newlines are allowed.
You may output the result to STDOUT or return the result in a function.
Characters allowed in a and b are [a-z0-9!@#$%^&*()_+=-].
You may accept the 4 inputs in any consistent order.

This is code-golf. Shortest code in bytes wins.

Python 3, 69 bytes

lambda a,b,*c:b[0].upper()+"@"+a[2:]+c[b[0]in"bcdfghjklmnpqrstvwxyz"]

Try it online!


Tips for golfing in Fishing I recently found out about the Fishing language, and it is now a favorite of mine. However, I'm finding it difficult to do anything cool with it, including code golf. Are there any tips for golfing with Fishing to use the least characters? And any string manipulation tricks would be cool, as I am finding that difficult in Fishing.

a and m work on strings too

Though it isn't explicitly stated in the spec, a (add) and m (multiply), at least in the official Ruby interpreter, also work on strings.

Say you had two cells with strings in them at the end of the tape, and wanted to concatenate and print them. You could do it with c:

c{{P

However, as long as you don't want to preserve the original value of your first cell, you could append the second string directly onto the first with a and avoid having to go to the end of the tape:

aP

Now let's say you want to print 20 spaces. The naive way to do it would be to simply hardcode them:

`                    `P

As long as the cell to the right is free, though, you can save 11 instructions by using m:

` `{`20`n}mP

Note, however, that due to the way Ruby works, you cannot do this with the order of the cells reversed (i.e. multiply a number by a string); that causes an error.


Sleep for 1000 years Some sleep commands implement a delay of an integer number of seconds. However, 232 seconds is only about 100 years. Bug! What if you need a larger delay?

Make a program or a function which waits for 1000 years, with an error of less than ±10%. Because it's too time-consuming to test, please explain how/why your solution works! (unless it's somehow obvious)

You don't need to worry about wasting CPU power - it can be a busy-loop. Assume that nothing special happens while your program waits - no hardware errors or power failures, and  the computer's clock magically continues running (even when it's on battery power).

What the solution should do after the sleep is finished:

If it's a function: return to caller
If it's a program: terminate (with or without error) or do something observable by user (e.g. display a message or play a sound)

C (gcc), 40 36 32 29 26 24 bytes

i;f(){--i&&f(sleep(7));}

Try it online!

-3 thanks to @gastropner.

-1 recursive approach thanks to @AZTECCO.

4294967295*7/86400/365.25 ~ 952.69


Pseudo-quine polyglot language-detection counters Quines are fun. Polyglots are fun, too. Polyglot Quines exist, but we can raise the bar even higher.

Write a file that contains a valid program for languages α, β, and γ. When the file is executed (possibly after compiling it) as a language α or β program, the program's output shall be of the same form as a valid submission to this contest. If your file is executed as a language γ program, it shall output a number. The value of this number is the chain of previous executions of the program interpreted as a binary number.

This explanation might be a bit hard to understan, so here is an example. Let Α, Β, and Γ be functions that execute their input as a language α, β, or γ resp. program and return the output of these programs. Let x be a valid submission to this contest. Then the following expression, where we process x through language β, α, β, α, α, β, and γ in this order, shall yield 41, since 4110 = 1010012.

  Γ(Β(Α(Α(Β(Α(Β(x)))))))

You may not assume that penultimate execution in the chain is an execution in language β. For the case where your original submission is directly executed as a language γ program, it shall print 0.

Your program shall behave correctly for up to sixteen compilations in the chain; that is, the highest number your program might print out at the end is 215 - 1. Of course, your program is allowed to support longer compilation chains.

This is a popularity contest to encourage creative solutions. The submission with the highest vote tally wins.

Python 2, Python 3, ><> (Fish)

#;n0
import sys
x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])n'
v=int(1/2*2)
sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])

Python explanation

The Python 2 and Python 3 interpreters work similarly except the v=int(1/2*2) variable gets different values (0 and 1) as Python 2 uses float division and Python 3 uses integer division.

In every run they add the expression +0*2 or +1*2  to the first line (after #;n) and to the x string (after the last write command). The ><> interpreter uses the first addition and the Pythons use the second one to create correct quines.

Code after B(A(B(B(x)))):

#;n+1*2+0*2+1*2+1*20
import sys
x='\\\'\nn#;n0import sysx=v=int(1/2*2)sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])+1*2+0*2+1*2+1*2n'
v=int(1/2*2)
sys.stdout.write(x[4:7]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[7:8]),sys.stdout.write(x[2:3]),sys.stdout.write(x[8:18]),sys.stdout.write(x[2:3]),sys.stdout.write(x[18:20]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[0:1]),sys.stdout.write(x[1:2]),sys.stdout.write(x[0:1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[3:4]),sys.stdout.write(x[4:7]),sys.stdout.write(x[7:8]),sys.stdout.write(x[8:18]),sys.stdout.write(x[18:20]),sys.stdout.write(x[20:32]),sys.stdout.write(x[32:851]),sys.stdout.write(chr(43)+str(v)+chr(42)+chr(50)),sys.stdout.write(x[851:-1]),sys.stdout.write(x[3:4]),sys.stdout.write(x[1:2]),sys.stdout.write(x[2:3]),sys.stdout.write(x[20:32]),sys.stdout.write(x[2:3]),sys.stdout.write(x[32:851])

><> (Fish) explanation

When you run the ><> interpreter the code pointer bounces back from the # wraps around the first line and starting from the end of the first line and heading West starts pushing numbers onto the stack. If an operator comes (+ or *) it pops the top two elements from the stack and pushes back the result. With this method we end up with the base2 representation of the previous runs (13 in the former example). This is the desired number so we output it with n and terminate with ;.


Implement a model of computation using a type system Implement any model of computation as powerful as a Turing machine using any existing language's type system.

Your solution should handle the computation using the language's type system, not the language's regular Turing complete features, nor a macro system.  It is however acceptable to use the language's regular features for IO, typical boilerplate, etc. so long as your program's Turing completeness hangs on the type system.

You are certainly welcome to use optional type system features that require compiler options to activate.

Please specify how to program and run your machine, ala "edit these numbers/constructs in the source, compile it and run it."

As an example, there is an implementation of brainfuck in C++ template meta-programming.  In fact, brainfuck is more complex than necessary because it offers user IO separate from its tape.  A few simpler models of computation include Brainfuck's ancestor P", λ-calculus, the (2,3) Turing Machine, and Conway's Game of Life.

We'll declare the winner to be whoever minimizes : their code's length plus 10 times the number of commenters who assert they already knew the language had a turing complete type system.

My limited Haskell-fu has come up with this implementation of SK-calculus in Haskell's type system:

data S = S
data K = K
data A l r = A l r

class C i o | i -> o
instance C (A (A K a) b) a
instance C (A (A (A S a) b) c) (A (A a c) (A b c))


Help recalculate your rep! A couple months ago, we had a discussion on meta about increasing the reputation awarded for upvotes on questions. Here's the basics of our current reputation system for votes:1

A question upvote U is worth 5 reputation.
An answer upvote u is worth 10 reputation.
A question or answer downvote d is worth -2 reputation.

There have been many different suggestions for a new system, but the current most popular is identical to the above, but with question upvotes scaled to +10 rep. This challenge is about calculating how much more rep you would earn if this system were put into place.

Let's look at an example. If the voting activity was UUUUuuuuUUUUUduuudUU, then you'd earn 121 under the current system:

U x 4 x  5 =  20 =  20
u x 4 x 10 =  40 =  60
U x 5 x  5 =  25 =  85
d x 1 x -2 =  -2 =  83
u x 3 x 10 =  30 = 113
d x 1 x -2 =  -2 = 111
U x 2 x  5 =  10 = 121
Total:             121

But the same activity would earn 176 under the new system:

U x 4 x 10 =  40 =  40
u x 4 x 10 =  40 =  80
U x 5 x 10 =  50 = 130
d x 1 x -2 =  -2 = 128
u x 3 x 10 =  30 = 158
d x 1 x -2 =  -2 = 156
U x 2 x 10 =  20 = 176
Total:             176

You would gain 55 rep from this scenario.

So far, calculating the changed rep isn't that hard; just count the number of Us and multiply by 5. Fortunately, the rep system isn't that simple: there is also a rep cap, which is the most reputation you can earn from votes in one UTC day. This is set to 200 on all sites.

Also, the rep cap applies in real time: if you have already earned 196 rep and you receive an answer upvote, you will now have 200 rep. If you get a downvote right after that, the 2 rep will be subtracted from 200, so you will have 198 rep.

With the voting activity UUUuuuuUUUUuuuuUUUUUUUd, you would earn 148 rep under the current system:

U x 3 x  5 =  15 =  15
u x 4 x 10 =  40 =  55
U x 4 x  5 =  20 =  75
u x 4 x 10 =  40 = 115
U x 7 x  5 =  35 = 150
d x 1 x -2 =  -2 = 148
Total:             148

But you would earn 198 under the new system:

U x 3 x 10 =  30 =  30
u x 4 x 10 =  40 =  70
U x 4 x 10 =  40 = 110
u x 4 x 10 =  40 = 150
U x 7 x 10 =  70 = 200 (rep capped)
d x 1 x -2 =  -2 = 198
Total:             198

Thus, the increase is 50 rep.

Challenge

Your challenge is to write a program or function that takes in a multi-line string and outputs the total rep that would be gained with the above algorithm. Each line counts as 1 UTC day, so the rep cap only applies once per line.

Test cases

(One or more lines of input, followed by the output integer.)

UUUuudd
15

UUUuUUUUuUuuUUUUudUUUUuU
57

UUUuUUUUuUuuUUUUudUUUUuU
UUUuudd
72

uuuuuuu
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
uuuuuuuuuuuuuuuuuuuu
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
0

UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
5

(empty string)
0

UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU
4

UUUuuuuuUUUuuUUUUUUuuuUUUuuUUUUuuuuUUUdddddddUU
UuuUUUudUU
UUUUUUUUUuuuuuuUUUUUUuuUUUUUUuuuuuUUUUUUUUuUUUuuuuUUUUuuuUUUuuuuuuUUUUUUUUuuUUUuuUU
UUu
U
d
UU
UUUUUUUUUUUU
119

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

Related challenges: Calculate the bounded cumulative sum of a vector, Calculate your stack exchange reputation

1 This is a highly simplified version of the system. You also lose 1 rep for downvoting an answer, and there exist unupvotes, which are weird and follow rules of their own; and undownvotes, which don't even have rules to follow.

ES6, 104 bytes

s=>s.split`
`.map(l=>(g=U=>[...l].map(c=>(r+=eval(c))>200?r=200:0,r=0)|r,t+=g(10)-g(5)),u=10,d=-2,t=0)|t

Calculates the before and after rep for each line. My first use of eval!


ASCII-visualize a graph Your mission, should you choose to accept it, is to input a series of point pairs that form a graph, like this:

  A,B C,A B,A A,D A,E F,G C,G

You must then output an ASCII visualization of the graph.

For example, A,B C,A C,D could be:

A-----------------B
 \
  \
   C---------D

Edit: As per the comments, here are some input constraints:

each node has at most 5 connections (+20 if you can handle more)
the graph is planar, i.e. no lines cross (+200 if you can handle even one crossover!)
there are at most 16 nodes (+20 if you can handle more)

Your score is 999 - (your code length) + (any bonuses).

Start your engines :)

APL (171 166 162 chars, all bonuses: 999 - 171 166 162  + 20 + 20 + 200 = 1068 1073 1077)

This is the longest golfed APL program I've written so far. This might be slightly cheating, but there's nothing in the question that actually disallows this. What I'm doing is putting all the nodes on a vertical line and drawing the graph as an arc diagram. It is obviously still a graph though.

It still took me a few hours.

V←' '⍴⍨99,⍨2×⍴P←∪,C←(2,⍨2÷⍨⍴G)⍴G←G/⍨⎕A∊⍨G←⍞⋄V[2×⍳⍴P;50]←P⋄M←1⋄G←⍴D←{⍵[⍋⍵]}¨↓P⍳C⋄{V[A B←⍵;L←50+M×⌽⍳G]∘←'-'⋄V[A+⍳B-A;⊃L]∘←'|'⋄V[⍵;⊃L]∘←'+'⋄M×←¯1⋄G-←1}¨2×D[⍒|-/↑D]⋄V

The nodes must be single uppercase letters, so it supports 26 nodes maximum. It can handle crossed lines, and each node can have as many connections as the display will handle.

Example output:

A,B C,A C,D

      +-A--+
      |    |
      +-B  |
           |
        C+-+
         |
        D+

A,B C,A B,A A,D A,E F,G C,G

          +--A-+-+-+
          |    | | |
          |  B-+ | |
          |      | |
        +-+--C   | |
        |        | |
        |    D---+ |
        |          |
        |    E-----+
        |
        |   +F
        |   |
        +---+G

 T,H E,Q U,I C,K B,R O,W N,F O,X J,U M,P S,O V,E R,T H,E L,A Z,Y D,O G,S

               +---+----------T
               |   |
               |   +-------+--H
               |           |
               |           +--E---------+-------+
               |                        |       |
               |              Q---------+       |
               |                                |
               |     +--------U---------------+ |
               |     |                        | |
               |     +--------I               | |
               |                              | |
               |              C-------+       | |
               |                      |       | |
               |              K-------+       | |
               |                              | |
               |       +------B               | |
               |       |                      | |
               +-------+------R               | |
                                              | |
             +----------------O-----+-----+-+ | |
             |                      |     | | | |
             |                W-----+     | | | |
             |                            | | | |
             |           +----N           | | | |
             |           |                | | | |
             |           +----F           | | | |
             |                            | | | |
             |                X-----------+ | | |
             |                              | | |
             |                J-------------|-+ |
             |                              |   |
             |                M---+         |   |
             |                    |         |   |
             |                P---+         |   |
             |                              |   |
             |   +------------S-------------+   |
             |   |                              |
             |   |            V-----------------+
             |   |
             |   |            L-+
             |   |              |
             |   |            A-+
             |   |
             |   |           +Z
             |   |           |
             |   |           +Y
             |   |
             +---|------------D
                 |
                 +------------G


Encode the backwards alphabet cipher Given a string of text that contains lowercase letters, encode it as follows: (I will be using abcdef)

First, encode the alphabet cipher, but this time, 0-indexed. 000102030405
Reverse it. 504030201000
Loop through the string.

If the next two digits together are 25 or smaller, encode those two numbers. 5 04 03 02 01 00 0
Otherwise, encode one number. f e d c b a a

Join. fedcbaa

Test cases

abcdef                          fedcbaa
abcdefghijklmnopqrstuvwxyz      fyxwvucjsrqponmlktihgfedcbaa
helloworld                      dbromylloha
ppcg                            gcfpb
codegolf                        fboqedema
programmingpuzzlesandcodegolf   fboqedemddkiobpzuzqdscmkhqerpb

Encoder (not golfed)

Remember, this is code-golf, so the code with the fewest bytes wins.


Create Fluffy Blocks (randomly inspired by this question)

Let's make a drawing from some pipes | and hyphens -. Choosing a subset, if chosen carefully, you can form a rectangular box or block shape (meaning that the corners are formed by |- or -|). For this challenge, we're concerned only with identifying the corners -- the vertical and horizontal pieces of the block shape can be made of either | or -, and the block may be hollow.

Here's the original drawing, and the subset showing a block shape.

|--|---|     |--|---|
|-|||-|| --> |      |
|------|     |------|

However, note that the following subsets from this same example do not make a block, because the corners are not all -| or |-

|--|
|-||

||-||
----|

|-|
---

Each combination of -| or |- can only form one corner. This means that the smallest possible block shape is these eight characters

|--|
|--|

and that these six characters do not form a block shape, since the corners are being "doubled up."

|-|
|-|

The challenge here is to turn these blocks fluffy. How? Replace every hard-edged straight character that forms the block edges (both corners and sides) with a much rounder, fluffier character, in this case, an o. But, don't fill in the block - we only want to get rid of the hard edges and sharp corners.

|--|---|     oooooooo
|-|||-|| --> o-|||-|o
|------|     oooooooo

Input

A 2D string representation of the pipe/hyphen diagram. Input can be as a multiline string, an array of strings, etc., however is convenient for your language. The input is guaranteed to be rectangular (i.e., every row will be the same length), and will only contain | and -.

Output

The same diagram, with the "block" characters replaced with o as described above and the remaining characters unchanged. The result can be printed to the screen or STDOUT, returned from a function, etc.

Rules

Note that blocks can overlap (see example #8) and blocks can share corners (see example #5).
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

#1
-|--|
|--|-
|--||

-|--|
oooo-
oooo|

#2
|--|---|
|-|||-||
|------|

oooooooo
o-|||-|o
oooooooo

#3
|||||

|||||

#4
|-----|
||---|-
||---|-
|-----|

ooooooo
ooooooo
ooooooo
ooooooo

#5
-|--|--|
|||-|--|
-|-----|

-ooooooo
|o|-oooo
-ooooooo

#6
|-||-|
|----|

oooooo
oooooo

#7
--|--|-
|-----|

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

#8
|-----|---
||--||-|--
||||--|--|
|-|-||||-|
|--|--|-||
---||---||
---|-----|

ooooooo---
o|--||o|--
o||ooooooo
o-|o||o|-o
ooooooo-|o
---o|---|o
---ooooooo

Perl, 448 bytes

$_=<>;$o=$_;~y/-|/Aa/;$N=$_;while($n ne $N){$n=$N;$c=$N;$M=$c;while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){if($N eq $n){substr($N,(length $1)+(length $2),1)="X"}substr($M,-(length $6)-1,1)="X";$c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;while($c=~/A/g){substr($o,(pos $c)-1,1)="o"}$c=$M}}$o=~y/;/\n/;print$o

I haven't used perl before so there's going to be massive room for improvement here (especially since I was mostly glad to get it working, so haven't tried to optimise it yet). I was a bit disappointed that the regular expression language didn't have some of the features I wanted, but I think it does pretty well.

Usage

Takes input on stdin, with lines semicolon-separated (optionally add a semicolon to the end to make the final printed output end with a newline). Outputs to stdout. Example command:

printf -- "-|--|--|;|||-|--|;-|-----|;" | perl boxes.perl

Breakdown

$_=<>; # Load input
$o=$_; # Create output variable
~y/-|/Aa/; # Replace - and | with A and a so that we can use case insensitive tricks later
$N=$_;
# For each distinct top-left corner...
while($n ne $N){
    $n=$N;
    $c=$N;
    $M=$c;
    # For each distinct box...
    while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){
        if($N eq $n){
            # mark top-left corner used (x)
            substr($N,(length $1)+(length $2),1)="X"
        }
        # mark bottom-right corner used (x)
        substr($M,-(length $6)-1,1)="X";

        # Fill in sides of identified box
        $c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;
        1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;

        # Replace output chars with "o" where box was found
        while($c=~/A/g){
            substr($o,(pos $c)-1,1)="o"
        }

        # Continue to next box
        $c=$M
    }
}

# Convert to nice output & print
$o=~y/;/\n/;
print$o


Charcoal, 106 95 92 91 79 77 bytes

”∨+!rþW∕oc	σ�<7↗OKd↶!(⊞”«5βＧ◨“Ｏ�c∕)ÿ6T”‖Ｂ←→→→,Ｆ³‖ＭＪ⁹¦³Ｆ6137542«ιＭ⁸→»↑Ｆ⁸«Ｍ⁸←←'

Try it online! Edit: Saved 11 bytes by looping over the shirt numbers. Saved 3 bytes by working out how Ｊ worked. Saved a further byte by using separate mirror instructions. Saved 12 bytes thanks to @ASCII-only by compressing the half player string. Saved 2 bytes by repeating the mirror in a loop. Explanation:

”∨+!rþW∕oc	σ�<7↗OKd↶!(⊞”«5βＧ◨“Ｏ�c∕)ÿ6T”
            Print the right half of a player as a compressed string
‖Ｂ←         Butterfly to create the left half of the player
→→→,        Fix up the left foot
Ｆ³‖Ｍ        Mirror three times to end up with 8 footballers
Ｊ⁹¦³Ｆ6137542«ιＭ⁸→»↑
            Fix up the shirt numbers
Ｆ⁸«Ｍ⁸←←'    Fix up the right eyes

Edit: The above code no longer works in current Charcoal; the string compression appears to have changed and the reflect command now accepts a multidirection and leaves the cursor in a different position. However it's possible to adapt the code to run in current charcoal for the same byte count. Try it online! Link is to verbose version of code. (Note that the deverbosifier tries to compress 6137542 for some reason although it's unnecessary.) It then becomes possible to golf a further byte off. Try it online! Link is to verbose version of code.


Convert YYYYMM to MMMYY Basing on this SO question.
Challenge is rather simple: given a date period in the format YYYYMM output it in the format MMMYY.
Rules:

The input will be a number or a string exactly 6 characters long, consisting only of digits.
Last two digits will be between 01 and 12.
Output must be in the form MMMYY, where MMM represents uppercase three-letter code for the month (below) and YY represents two last digits of the YYYY part of the input.

List of months with corresponding code:
MM    MMM
01    JAN
02    FEB
03    MAR
04    APR
05    MAY
06    JUN
07    JUL
08    AUG
09    SEP
10    OCT
11    NOV
12    DEC

Examples:
Input     Output
201604    APR16
200001    JAN00
000112    DEC01
123405    MAY34

Python 3, 70 bytes

from time import*
lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper()

This uses the built-in strftime and strptime functions.

For 1 byte more, here's a version which parses the string manually:

lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4]

This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte).


Score a Cribbage Hand This challenge is to score a Cribbage hand.  If you don't play Cribbage, you've got some learning to do.  We play with a standard poker deck, and a hand consists of four cards plus the "up card".  There are two types of hand: normal, and a 'crib hand'.

Cards come in the format vs where v is one of: A23456789TJQK (T for ten) and s is one of SCDH.  A hand will be given in the form (for example)

AS 2D 3H JS | 4S

where 4S is the up card.  A crib hand will have the format

JD 3C 4H 5H | 5S !

Face cards have a value of 10, and the ace has a value of 1.  Scoring is performed as follows.

Fifteens: for each subset of five cards whose sum is 15, add two points.
Pairs: for each pair of cards with the same rank (not value), add two points.
Runs: for each maximal run of consecutive cards of length longer than 2, add the length of the run in points.
Flush: if all five cards are the same suit, add five points.  Otherwise, if all but the up card are the same suit, add four points.  If this is a crib hand, the four-point variant is not counted.
Nobs: if there is a jack in hand with the same suit of the up card, add one point.

Notes:

Triples and fours of a kind are not special -- there are three pairs in a triple, so a triple is worth 6 points.
Runs can overlap.  For example, AS AH 2D 3C | 2C (a double double run) has four runs of length 3 and two pair, so is worth 3+3+3+3+2+2 = 16 points.
Only maximal runs are counted, so KS QD JD TC | 9S is worth 5 points, since it is a run of 5.  The sub-runs are not counted.

House Rule:

It's impossible to score 19 points in a hand.  Instead of zero, report a score of 19.

Examples:

5S 5H 5D JS | KS
21

AS 2D 3H JS | 4S !
9

JD 3C 4H 5H | 5S
12

9S 8S 7S 6S | 5H !
9

9S 8S 7S 6S | 5H
13

8D 7D 6D 5D | 4D !
14

8D 7D 6D 5D | 4D
14

AD KD 3C QD | 6D
19

This is code golf.  Shortest solution wins.

C, 364 388 chars

It's big and ugly (though not as big as it once was):

char*L="CA23456789TJQKDHS",b[20],p[15],r[5],s[5],v,i=4,t,m,q;
g(j){++p[r[i]=strchr(L,b[j])-L];s[i]=strchr(L,b[j+1])-L;}
f(j,u){u==15?v+=2:++j<5&&f(j,u,f(j,u+(r[j]>9?10:r[j])));}
main(){gets(b);for(g(14);i--;r[i]^11|s[i]^s[4]||++v)g(i*3);
for(f(i,0);++i<15;v+=q?q*q-q:t>2?t*m:0,t=q?t+1:0,m=q?m*q:1)q=p[i];
while(++t<5&&s[t]==*s);v+=t>4-!b[16]?t:0;printf("%d\n",v?v:19);}

(Line breaks were added to make it easier to read; those aren't included in the above tally.)

The problem description didn't specify if the code needed to check for invalid input, so naturally I assumed that the program was free to misbehave at will if the input, say, contained extra whitespace.

Here's the ungolfed version:

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

/* A-K correspond to values 1-13. Suit values are arbitrary.
 */
static char const *symbols="CA23456789TJQKDHS";

/* Used as both an input buffer and to bucket cards by rank.
 */
static char buf[20];

/* The cards.
 */
static int rank[5], suit[5];

/* The cards broken down by rank.
 */
static int buckets[15];

static int score;
static int touching, matching, i;

/* Read card number i from buf at position j.
 */
static void getcard(int j)
{
    rank[i] = strchr(symbols, buf[j]) - symbols;
    suit[i] = strchr(symbols, buf[j+1]) - symbols;
    ++buckets[rank[i];
}

/* Recursively find all combinations that add up to fifteen.
 */
static void fifteens(int j, int total)
{
    for ( ; j < 5 ; ++j) {
        int subtotal = total + (rank[j] > 9 ? 10 : rank[j]);
        if (subtotal == 15)
            score += 2;
        else if (subtotal < 15)
            fifteens(j + 1, subtotal);
    }
}

int main(void)
{
    fgets(buf, sizeof buf, stdin);
    score = 0;

    /* Read cards from buf */
    for (i = 0 ; i < 4 ; ++i)
        getcard(i * 3);
    getcard(14);

    /* Score fifteens */
    fifteens(0, 0);

    /* Score any runs and/or pairs */
    touching = 0;
    matching = 1;
    for (i = 1 ; i < 15 ; ++i) {
        if (buckets[i]) {
            score += buckets[i] * (buckets[i] - 1);
            ++touching;
            matching *= buckets[i];
        } else {
            if (touching > 2)
                score += touching * matching;
            touching = 0;
            matching = 1;
        }
    }

    /* Check for flush */
    for (i = 1 ; i < 5 && suit[i] == suit[0] ; ++i) ;
    if (i >= (buf[17] == '!' ? 5 : 4))
        score += i;

    /* Check for hisnob */
    for (i = 0 ; i < 4 ; ++i)
        if (rank[i] == 11 && suit[i] == suit[4])
            ++score;

    printf("%d\n", score ? score : 19);
    return 0;
}


Generate an ascii-art non-intersecting path Given 2 integer inputs representing the size of the field, x and y, output a path through the field.

Example output for 5, 4:

#
#
# ###
### #

The whole field is 5 by 4, and there is a path made of hashmarks crossing the field.

The path should always start in the top left corner, and go to the bottom right.  The whole path should be randomized every time the program is run.  Every valid path should be a possible output.

The rules for paths are:

Made of hashmarks
Every hash is only connected to 2 other hashes (i.e. the path does not intersect or run alongside itself)

The non-hash spaces can be filled it with any other character, but it must be consistent (i.e. all spaces, all periods, etc.)

Examples:

2, 2

##
 #

3, 4

##
 ##
  #
  #

5, 5

#####
    #
    #
    #
    #

6, 5

## ###
 # # #
## # #
# ## #
###  #

7, 9

#######
      #
####  #
#  #  #
#  #  #
#  #  #
#  ####
#
#######

This kind of path is similar to a self-avoiding random walk, however it can't be adjacent to itself unlike a true SAW.

Path continuity and path touching are both defined without diagonals.

Befunge, 344 bytes
&v>>>#p_:63p:43g`\!+v>/*53g+\01g:2%2*1-\2/!*63g+\0\:v
 40$ v++!\`g14:p35:\<^2\-1*2%2p10::%4+g00:\g36\g35-1_v
#11^$_83p73v >1+:41g`!#v_$,1+:43g`!#v_@>->2>+00p+141^_
<p1^     vp< ^,g+7g36:<<<<1+55p36:<<<< ^1?0^#7g36g35*
8&p|!++!%9#2g+7g10\*!-g38g10!-g37:g00!!*<>3^
443>:!#v_>>1-::3%1-:53g+00p\3/1-:63g+01p^
^>^>>$#<"#"53g63g7+p41g53g-43g63g-+!#^_

Try it online!
As @flawr mentioned in their MATLAB answer, this may take some time if the field size is of any non-trivial size. In fact it's quite easy to get into a situation where it's really not worth trying to wait for it to finish, because you're quite likely to be waiting until the end of time.
To understand why this happens, it helpful to view the program as it's executing in one of Befunge's many "visual debuggers". Since data and code are the same thing in Befunge, you'll get to view the path as it changes over time. For example, here is a short animation showing what a part of a run on a slow path might look like.

Once the algorithm decides to make that fateful turn to the left at the bottom of the field boundary, it has essentially condemned itself to a lifetime of aimless wandering. From that point on it has to follow every single possible path in that fenced off area before it can back out and try the turn to the right. And the number of potential paths in these cases can easily become astronomical.
Bottom line: If it seems to be taking a long time, it's probably a good idea to just abort the execution and start again.
Explanation
This is basically a recursive algorithm, trying every possible path through the field, and then unwinding steps that have already been followed whenever it gets stuck. Since Befunge doesn't have the concept of functions, a recursive function is out of the question, but we can emulate the process by tracking the state on the stack.
This works by populating the stack with potential coordinates that we may want to follow. Then we pull one set from the stack and check whether it is suitable (i.e. in range and not overlapping with an existing path). Once we've got a good spot, we write a # into the playfield at that location, and add those details to the stack in case we need to backtrack later.
We then push an additional four sets of coordinates onto the stack (in random order) indicating the potential paths we can take from this new location, and jump back to the start of the loop. If none of the potential paths are feasible, we'll get to the point on the stack where we saved the location of the # we wrote out, so we'll undo that step and continue trying potential coordinates from one step prior.
This is what the code looks like with the various component parts highlighted:

 Read the width and height of the field, and push the start coordinates along with a 0 type marker to indicate a potential path rather than a backtracking location.
 Check for backtracking locations (indicated by a 1 type marker) which are reverted with a simple p command, since they're stored in the exact format needed to write a space back into the playfield.
 Check if the coordinates are still inside the playfield. If they're out of range, drop them from the stack and loop back to try the next potential coordinates.
 If they are in range, get the next two values from the stack, which is the location of the previous step (required in the test that follows this).
 Check if the coordinates are going to come into contact with an existing segment of the path. The location of the previous step is obviously ignored from this check.
 If all test are successful, write a # into the playfield, and check if we've reached the destination location.
 If we have, write out the final path,  and exit.
 Otherwise save the coordinates onto the stack with a 1 type marker for later backtracking.
 This is interrupted with a random number calculation which we're going to need soon.
 Push four potential destinations that can be reached from the current location. The random number determines the order in which they're pushed and thus the order that they will be followed.
 Wrap back to the start of the main loop and process the next values on the stack.


Magic the Gathering: Friends or Foes? In the card game Magic: the Gathering there are five different colours, which represent loose affiliations of cards, White (W), Blue (U), Black (B), Red (R) and Green (G). These are often arranged in a pentagon as follows:
  W
G   U
 R B

Both in the lore of MtG as well as in many card mechanics, adjacent colours in this pentagon are usually considered allies, and non-adjacent (sort of opposite) colours are considered enemies.
In this challenge, you'll be given two colours and should determine their relationship.
The Challenge
You're given any two distinct characters from the set BGRUW. You may take these as a two-character string, a string with a delimiter between the characters, two separate character values, two singleton strings, two integers representing their code points, or a list or set type containing two characters/strings/integers.
Your output should be one of two distinct and consistent values of your choice, one which indicates that the two colours are allies and one which indicates that they are enemies. One of those two values may be no output at all.
You may write a program or a function and use any of the our standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Test Cases
There are only 20 possible inputs, so I'll list them all.
Friends:
WU   UB   BR   RG   GW   UW   BU   RB   GR   WG

Foes:
WB   UR   BG   RW   GU   BW   RU   GB   WR   UG


Toilet Paper Mysteries Today you need to solve a very practical problem: How many loops do you need to have a certain number of sheets on your toilet paper roll? Let's look at some facts:

The diameter of a bare toilet paper cylinder is 3.8cm
The length of one sheet of toilet paper is 10cm.
The thickness of one sheet of toilet paper is 1mm.

Before you wrap around the cylinder the first time, it has a circumference in cm of 3.8*pi. Every time you wrap a sheet around the cylinder its radius increases by .1, therefore its circumference increases by .2*PI. Use this information to find out how many loops it takes to fit n sheets of toilet paper. (Note: Use an approximation of Pi that is at least as accurate as 3.14159).

Test Cases:

n=1:

10/(3.8*pi) = .838 loops

n=2:

(How many full loops can we make?) 1 full loop = 3.8*pi = 11.938.
(How much do we have left after the 1st loop?) 20 - 11.938 = 8.062
(How much of a 2nd loop does the remaining piece make?) 8.062/(4*pi) = .642 loops
Answer: 1.642 loops

n=3:

1st full loop = 3.8*pi = 11.938, 2nd full loop = 4*pi = 12.566
30 - 11.938 - 12.566 = 5.496
5.496/(4.2*pi) = .417
Answer: 2.417 loops

n=100 => 40.874

Pyth, 27 23 bytes

+fg0=-QJc*.n0+18T50)cQJ

Try it online. Test suite.

Explanation

                            Q = input number (implicit)
 f                 )        increment T from 1, for each T:
             +18T             add 18 to T, get radius
         *.n0                 multiply by pi to, get half the circumference
        c        50           divide by 50, get circumference in sheets
       J                      save it to J
    =-Q                       decrement Q by it
  g0                          use this T if Q is now <= 0
+                           add
                     Q        Q (now <= 0)
                    c J       divided by J (the last circumference)
                            and print (implicit)


Compute the Kolakoski sequence This is a repost of an old challenge, in order to adjust the I/O requirements to our recent standards. This is done in an effort to allow more languages to participate in a challenge about this popular sequence. See this meta post for a discussion of the repost.

The Kolakoski sequence is a fun self-referential sequence, which has the honour of being OEIS sequence A000002 (and it's much easier to understand and implement than A000001). The sequence starts with 1, consists only of 1s and 2s and the sequence element a(n) describes the length of the nth run of 1s or 2s in the sequence. This uniquely defines the sequence to be (with a visualisation of the runs underneath):
1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1,2,1,1,2,1,2,2,1,1,2,1,1,2,...
= === === = = === = === === = === === = = === = = === === = === =
1, 2,  2, 1,1, 2, 1, 2,  2, 1, 2,  2, 1,1, 2, 1,1, 2,  2, 1, 2, 1,...

Your task is, of course, to implement this sequence. You may choose one of three formats to do so:

Take an input n and output the nth term of the sequence, where n starts either from 0 or 1.
Take an input n and output the terms up to and including the nth term of the sequence, where n starts either from 0 or 1 (i.e. either print the first n or the first n+1 terms).
Output values from the sequence indefinitely.

In the second and third case, you may choose any reasonable, unambiguous list format. It's fine if there is no separator between the elements, since they're always a single digit by definition.
In the third case, if your submission is a function, you can also return an infinite list or a generator in languages that support them.
You may write a program or a function and use any of our standard methods of receiving input and providing output. Note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.

Jelly, 7 bytes

2Rṁxṁµ¡

This is a full program that prints the first n terms.

Try it online!

How it works

2Rṁxṁµ¡  Main link. Argument: n (integer)

     µ   Combine the preceding links into a monadic chain.
      ¡  Set t = n.  Call the chain n times, updating t with the return value after
         each call. Yield the last value of t.
2R           Set the return value to 2 and take its range. Yields [1, 2].
  ṁ          Mold; cyclically repeat 1 and 2 to match t's length.
             In the first run, ṁ promotes t = n to [1, ..., n].
   x         Repeat the k-th element of the result t[k] times.
             In the first run, x repeats each element t = n times.
    ṁ        Mold; truncate the result to match the length of t.
             In the first run, ṁ promotes t = n to [1, ..., n].

Example run

Let n = 5.

The first invocation of the chain repeats 1, 2 cyclically to reach length 5, then each element 5 times, and finally truncates the result to length 5.

  1         2         1         2         1
x 5         5         5         5         5
---------------------------------------------------
  1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1

  1 1 1 1 1

This yields a list of length 5. The first element is the first element of the Kolakoski sequence.

The second invocation of the chain repeats 1, 2 cyclically to reach length 5, then repeats the kth element j times, where j is the kth element of the previous list, and finally truncates the result to length 5.

   1 2 1 2 1
x  1 1 1 1 1
------------
   1 2 1 2 1

   1 2 1 2 1

This yields another list of length 5. The first two elements are the first two elements of the Kolakoski sequence.

The process continues for three more iterations.

   1 2   1 2   1
x  1 2   1 2   1
----------------
   1 2 2 1 2 2 1

   1 2 2 1 2

   1 2   1   2 1
x  1 2   2   1 2
------------------
   1 2 2 1 1 2 1 1

   1 2 2 1 1

   1 2   1   2 1
x  1 2   2   1 1
----------------
   1 2 2 1 1 2 1

   1 2 2 1 1

These are the first five elements of the Kolakoski sequence.


Implement bit-wise matrix multiplication The MMIX architecture is a fairly simple big-endian RISC design. It has a couple of interesting features, one of them is the MXOR instruction, which is what you should implement.

The MXOR instruction interprets its arguments (two 64-bit registers) as two 8×8 matrices of bits and performs a matrix multiplication where exclusive-or is used for addition and logical and is used for multiplication.

An argument in binary representation where the leftmost digit is most significant

  a0 a1 a2 … a63

is interpreted as a matrix like this:

  a0 a1 … a7
  a8 a9 … a15
  …
  a56 a57 … a63

Your task is to write a function, subroutine or similar in a language of choice which can be evoked from a single-letter name (i.e. f(x,y)) that implements this function. The two arguments of the function shall be of equal implementation-defined unsigned 64 bit integer type, the function shall return a value of the same type.

he winner of this competition is the shortest submission (measured in bytes or characters if the language you use uses a meaningful character encoding). You are encouraged to post a readable commented version of your code in addition to the golfed solution so other's can understand how it works.

APL, 28 characters
f←{2⊥,↑≠.×/{8 8⍴(64⍴2)⊤⍵}¨⍵}

Usage:
> f 12345678 87654321
3977539

You can read it almost literally if you go right-to-left. (64⍴2)⊤ transforms each argument into 64 bit representation and 8 8⍴ makes an 8x8 matrix out of the results. ≠.×/ then applies the inner product to both arguments, where multiplication × and xor ≠ is used. The matrix is then transformed back to vector form ,↑, before 2⊥ undoes the basis transformation.


Keep Decoding This Number! This challenge posed an algorithm for encoding an integer n as another integer r. What follows is a succinct explanation of that algorithm, using n=60 as an example.

The original algorithm

First, we encode the number as a string of brackets.

If n = 1, return an empty string.
Otherwise, we take n's prime decomposition sorted ascending and replace each element with its prime index (1-indexed) in brackets. 60 = 2*2*3*5 => [1][1][2][3]
Do this recursively until all we have are brackets. [1][1][2][3] => [][][[1]][[2]] => [][][[]][[[1]]] => [][][[]][[[]]]

Once we have our string of brackets, we convert that into an integer with the following process.

Convert each opening bracket to a 1 and each closing bracket to a 0. [][][[]][[[]]] => 10101100111000
Remove all trailing 0s and the final 1. 10101100111000 => 1010110011
Convert the final string of 0s and 1s from binary to an integer. 1010110011 => 691

Decoding this encoding

An interesting property of this algorithm is that it is not surjective. Not every integer can be the result of this encoding.

Firstly, the binary representation of the result r, must be balance-able in that the number of 0s must never exceed the number of 1s. A short falsey test case is 4, which is 100 in binary.
Secondly, the brackets in the binary representation must be sorted ascending when the final 1 and trailing 0s are appended once more. A short falsey test case is 12 <= 1100 <= 110010 <= (())().

However, just determining if a number is decode-able in this way would make for a short challenge. Instead, the challenge is to repeatedly decode a given input until either an un-decode-able number or a cycle is reached, and returning the resulting sequence of numbers.

The challenge

Given a number 1 <= r <= 2**20 = 1048576, return the sequence of numbers that r successively decodes into, starting with r itself and ending with an un-decode-able number or a cycle.
If an un-decode-able number is given as input, such as 4 or 12, will return a list containing only the input.
A sequence ending in a cycle should be indicated in some way, either by appending or prepending a marker (pick any non-positive integer, string, list, etc. as a marker, but keep it consistent), or by repeating the cycle in some way (repeating the first element, repeating the whole cycle, repeating infinitely, etc.).
On the off chance that any of the sequences are infinite (by increasing forever, for example), consider it undefined behavior.
This is code golf. Smallest number of bytes wins.

A worked example of decoding

   1 -> 1 -> 1100 -> [[]] -> [2] -> 3
-> 3 -> 11 -> 111000 -> [[[]]] -> [[2]] -> [3] -> 5
-> 5 -> 101 -> 101100 -> [][[]] -> 2*[2] -> 2*3 -> 6
-> 6 -> 110 -> 110100 -> [[][]] -> [2*2] -> [4] -> 7
-> 7 -> 111 -> 11110000 -> [[[[]]]] -> [[[2]]] -> [[3]] -> [5] -> 11
-> 11 -> 1011 -> 10111000 -> [][[[]]] -> 2*[[2]] -> 2*[3] -> 2*5 -> 10
-> 10 -> 1010 -> 101010 -> [][][] -> 2*2*2 -> 8
-> 8 -> 1000  ERROR: Unbalanced string

Test cases

4 -> [4]
12 -> [12]
1 -> [1, 3, 5, 6, 7, 11, 10, 8]
2 -> [2, 4]
13 -> [13, 13]    # cycle is repeated once
23 -> [23, 22, 14, 17]
51 -> [51, 15, 31, 127, 5381]
691 -> [691, 60]
126 -> [126, 1787, 90907]
1019 -> [1019, 506683, 359087867, 560390368728]

Suggestions and feedback for this challenge are most welcome. Good luck and good golfing!

Python 3, 379 358 339 337 327 310 304 bytes

Conjecture: Is 13 the only number that will lead to a cycle? (There are no exceptions smaller than 106.)

Fixed a bug and -7 bytes thanks to Sherlock9.-3 byte thanks to Jonathan Frech.-16 bytes thanks to ovs.-6 bytes thanks to Mr. Xcoder.

If there is a cycle, it will repeat the whole cycle.

def p(a,x=0,n=1):
 while a:x+=1;a-=n%x;n*=x*x
 return x
def g(a):
 c=i=0
 for v in a:
  c+=int(v)*2-1
  if c<0:return 0,0
  if c<1:break
  i+=1
 if a:x=p(g(a[1:i])[0]);b,c=g(a[i+1:]);return(x>c>0)*(0,0)or(x*b,x)
 return 1,0
def f(a):
 x=a,
 while(x.count(a)<3)*a:a,t=g(bin(a-~a)[2:]);x+=a,
 return x[:-1]

Try it online!

Explanation:

def p(a,x=0,n=1):     # return the a-th prime
 while a:             # magical way to enumerate primes
  x+=1
  a-=n%x
  n*=x*x
 return x

def g(a):             # decode a 0/1 string
 c=i=0
 for v in a:
  c+=int(v)*2-1       # +1 if 1, -1 if 0
  if c<0: return(0,0) # c<0: unbalanced parentheses
  if c<1: break       # first outermost parentheses
  i+=1
 if a:
   x=p(g(a[1:i])[0])  # recursive solve those inside the parentheses ...
   b,c=g(a[i+1:])     # and the remaining
   if x>c and c:      # if not ascending
    return (0,0)
   return (x*b,x)     # return (result, value of first closed parentheses)
 return (1,0)         # empty string

def f(a):
 x=a,
 while a and x.count(a)<3: # detect non-decodable or cycle
  a,t=g(bin(a-~a)[2:])     # a-~a is a*2+1
  x+=a,
 return x[:-1]


Write two single line functions to encode and decode base64 Write two functions of one line each that can encode and decode base64.

Use any language you want, but if the language can naturally be converted to a single line (e.g. javascript) then any block of code separated by an end-of-line character is counted as a line.
The functions must be self-contained. They cannot reference outside variables or imported libraries, with the exception of a single input argument.
Expanding on the previous point, you cannot define constants or variables for use inside the function. For instance, if your function references alphabet as the collection of base64 symbols, replace every instance of alphabet with a literal of the same value.
The functions must be one line each, not counting the function definition itself. For example, in languages like Visual Basic, functions are a minimum of three lines due to the beginning and end lines being a required part of the function definition. This is acceptable as long as the code that does the base64 conversion is only one line.
Do not use built in functions such as javascript's atob or btoa.

Here's my functions written in python. I can't find a way to make these smaller.

def tobase64(m):
    return ''.join(['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[int(z[::-1].zfill(6)[::-1],2)] for z in [''.join([bin(ord(x))[2:].zfill(8)for x in m])[y:y+6] for y in range(0,len(m)*8,6)]])+''.join(['=' for x in range(-len(m)%3)])

and the decoder

def fromb64(m):
    return ''.join([chr(int(w,2)) for w in [(''.join([''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])[y:y+8] for y in range(0,len(''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])),8)])+'a')[:-(len(m)-len(m.replace('=','')))*2-1][z:z+8] for z in range(0,len(''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])),8)] if len(w) == 8])

Python 2, 437 characters

As a first improvement to your Python solution, you can cut down on the references to the long string of characters 'abc...ABC...0123456789+/':

def fromb64(m):
    return (lambda A:''.join([chr(int(w,2)) for w in [(''.join([''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])[y:y+8] for y in range(0,len(''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])),8)])+'a')[:-(len(m)-len(m.replace('=','')))*2-1][z:z+8] for z in range(0,len(''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])),8)] if len(w)==8]))('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')

This is just (lambda A: {{what you did, but with that string replaced by A}})(that string).


Stop walking into walls! Some text-based rogue-likes don't let you walk into walls, and give you your move back if you try to. Why do that when you can make the player move in the closest valid direction?

The challenge

Write a program of function that, given a direction and a 3 by 3 grid of characters, outputs the same grid after the player has taken a step.

For example,

9
#..
.@#
#.#

becomes

#.@
..#
#.#

Input

The direction is given by a single digit from 1 to 9, each corresponding to 8 cardinal directions and standing still. This is derived from the relative locations of the numbers on a keypad:

NW   N   NE
..\  |  /
...7 8 9
W- 4 5 6 -E
...1 2 3
../  |  \
SW   S   SE
However, you may also use the numbers 123, 456, 789 instead of 789, 456, 123. In other words, you may swap the top and bottom 2 rows or numbers if you so choose. These are the only 2 acceptable index combinations.
The 3 by 3 grid will consist of 3 distinct, printable ASCII characters representing walkable floor, walls, and the player. (In the test cases, . is used for floor, #s are walls, and @ is the player)
You may choose what characters your program uses, but you must state them in your answer and they must be consistent over multiple trials.
The character representing the character will always be in the middle of the 3 by  3 grid, and the direction will always be between 1 and 9 (incl.)
You may take input in any order
The 3 by 3 grid can be input as a char array, a string array, a 9 length string, or another reasonable alternative.

Output

Return from a function, or output to StdOut or closest alternative
Trailing spaces and newlines are allowed
You must use the same character representations as the input
The same formats allowed for inputs are allowed for outputs

How the player moves

If the specified direction is blocked by a wall (e.g. if the above example had direction 6), then look at the 2 closest directions:

If one (and only one) direction is free, move the player in that direction.
If no directions are free, look at the next closest 2 directions (excluding direction 5). If you have wrapped all the way around and found no open direction (player surrounded by walls), do not move the player
If both of the directions are open, pick one to move to at random (although not necessarily uniformly).

If the given direction is a 5, do not move the player

Test cases

(# = wall, . = floor, @ = player)

Input:

9
#..
.@#
#.#

Output:

#.@
..#
#.#

Input:

3
#..
.@#
#.#

Output:

#..
..#
#@#

Input:

7
##.
#@#
..#

Output:

##@      ##.
#.#  or  #.#
..#      @.#

Input:

5
...
.@.
...

Output:

...
.@.
...

Input:

2
###
#@#
###

Output:

###
#@#
###

Scoring

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

JavaScript (ES6), 192 163 bytes

a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a)

Notes

This function uses a special input format. The first input is an array of integers (0 for floor, 1 for wall and 2 for player) representing the map. The second input is the (flipped) direction: 1 is north-west, 2 is north, 3 is north-east, 4 is west etc. The inputs should be given through currying syntax (Z(a)(b)).

Test cases

The maps and directions have been modified to suit my input format.

Z=
a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a)

testcases = [
    [[1,0,0,0,2,1,1,0,1], 3],
    [[1,0,0,0,2,1,1,0,1], 9],
    [[1,1,0,1,2,1,0,0,1], 1],
    [[0,0,0,0,2,0,0,0,0], 5],
    [[1,1,1,1,2,1,1,1,1], 2]
]
for (test of testcases) {
    console.log(Z(test[0])(test[1]))
}


Un-de-duplicating strings Introduction

Let's observe the following string:

AABBCCDDEFFGG

You can see that every letter has been duplicated, except for the letter E. That means that the letter E has been de-duplicated. So, the only thing we need to do here is to reverse that process, which gives us the following un-de-duplicated string:

AABBCCDDEEFFGG

Let's take a harder example:

AAAABBBCCCCDD

You can see that there is an uneven number of consecutive B's, so that means that one of the BB was de-duplicated from the original string. We only need to un-de-duplicate this letter, which gives us:

AAAABBBBCCCCDD

The challenge

Given a non-empty de-duplicated string, consisting of only alphabetic characters (either only uppercase or only lowercase), return the un-de-duplicated string. You can assume that there will always be at least one de-duplicated character in the string.

Test cases

AAABBBCCCCDDDD    -->    AAAABBBBCCCCDDDD
HEY               -->    HHEEYY
AAAAAAA           -->    AAAAAAAA
N                 -->    NN
OOQQO             -->    OOQQOO
ABBB              -->    AABBBB
ABBA              -->    AABBAA

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

MATL, 7 bytes

Y'to+Y"

Try it online! Or verify all test cases.

Let's take 'ABBA' as example input.

Y'   % Implicit input. Run-length decoding
     % STACK: 'ABA', [1 2 1]
t    % Duplicate top of the stack
     % STACK: 'ABA', [1 2 1], [1 2 1]
o    % Modulo 2
     % STACK: 'ABA', [1 2 1], [1 0 1]
+    % Add, element-wise
     % STACK: 'ABA', [2 2 2]
Y"   % Run-length encoding. Implicit display
     % STACK: 'AABBAA'


Count All Possible Unique Combinations of Letters in a Word You are given a string, which will contain ordinary a-z characters.  (You can assume this will always be the case in any test, and assume that all letters will be lowercase as well).  You must determine how many unique combinations can be made of the individual characters in the string, and print that number.

However, duplicate letters can be ignored in counting the possible combinations.  In other words, if the string given is "hello", then simply switching the positions of the two ls does not count as a unique phrase, and therefore cannot be counted towards the total.

Shortest byte count wins, looking forward to seeing some creative solutions in non-golfing languages!

Examples:

hello -> 60
aaaaa -> 1
abcde -> 120

Python 2, 50 48 bytes

f=lambda s:s==''or len(s)*f(s[1:])/s.count(s[0])

Try it online!

No boring built-ins! To my surprise, this is even shorter than the brute force approach, calculating all of the permutations with itertools and taking the length.

This function uses the formula

\$\text{# of unique permutations} = \frac{\text{(# of elements)!}}{\prod_{\text{unique elements}}{\text{(# of occurences of that element)!}}}\$

and computes it on the fly. The factorial in the numerator is calculated by multiplying by len(s) in each function call. The denominator is a bit more subtle; in each call, we divide by the number of occurences of that element in what's left of the string, ensuring that for every character c, all numbers between 1 and the amount of occurences of c (inclusive) will be divided by exactly once. Since we divide only at the very end, we're guaranteed not to have any problems with Python 2's default floor division.


Largest number in ten bytes of code Your goal is to print (to the standard output) the largest number possible, using just ten characters of code.

You may use any features of your language, except built-in exponentiation functions.

Similarly, you may not use scientific notation to enter a number. (Thus, no 9e+99.)

The program must print the number without any input from the user. Similarly, no reading from other files, or from the Web, and so on.
Your program must calculate a single number and print it. You can not print a string, nor can you print the same digit thousands of times.
You may exclude from the 10-character limit any code necessary to print anything. For example, in Python 2 which uses the print x syntax, you can use up to 16 characters for your program.
The program must actually succeed in the output. If it takes longer than an hour to run on the fastest computer in the world, it's invalid.
The output may be in any format (so you can print 999, 5e+100, etc.)
Infinity is an abstract concept, not a number. So it's not a valid output.

Perl, >1.96835797883262e+18

time*time

Might not be the largest answer... today! But wait enough millennia and it will be!

Edit:

To address some of the comments, by "enough millenia," I do in fact mean n100s of years.

To be fair, if the big freeze/heat death of the universe is how the universe will end (estimated to occur ~10100 years), the "final" value would be ~10214, which is certainly much less than some of the other responses (though, "random quantum fluctuations or quantum tunneling can produce another Big Bang in 101056 years"). If we take a more optimistic approach (e.g. a cyclic or multiverse model), then time will go on infinitely, and so some day in some universe, on some high-bit architecture, the answer would exceed some of the others.

On the other hand, as pointed out, time is indeed limited by the size of integer/long, so in reality something like ~0 would always produce a larger number than time (i.e. the max time supported by the architecture).

This wasn't the most serious answer, but I hope you guys enjoyed it!


Calculate the value of \$\zeta(s)\$ Challenge

Given an integer, \$s\$, as input where \$s\geq 1\$ output the value of \$\zeta(s)\$ (Where \$\zeta(x)\$ represents the Riemann Zeta Function).

Further information

\$\zeta(s)\$ is defined as:

$$\zeta(s) = \sum\limits^\infty_{n=1}\frac{1}{n^s}$$

You should output your answer to 5 decimal places (no more, no less). If the answer comes out to be infinity, you should output \$\infty\$ or equivalent in your language.

Riemann Zeta built-ins are allowed, but it's less fun to do it that way ;)

Examples

Outputs must be exactly as shown below

Input -> Output
1 -> ∞ or inf etc.
2 -> 1.64493
3 -> 1.20206
4 -> 1.08232
8 -> 1.00408
19 -> 1.00000

Bounty

As consolation for allowing built-ins, I will offer a 100-rep bounty to the shortest answer which does not use built-in zeta functions. (The green checkmark will still go to the shortest solution overall)

Winning

The shortest code in bytes wins.

Mathematica, 9 7 11 bytes

Zeta@#~N~6&

Explanation:

Zeta@#       (* Zeta performed on input *)
      ~N     (* Piped into the N function *)
        ~6   (* With 6 digits (5 decimals) *)
          &  (* Make into function *)

Without builtin:

Mathematica, 23 UTF-8 bytes

Sum[1/n^#,{n,∞}]~N~6&

Thanks to Kelly Lowder


Run the Monty Hall Problem There’s already been a question about simulating the Monty Hall Problem. This one is different. The user will play the Monty Hall Problem. Your program will play the role of the host. Montybot, if you like.

Here are the steps:

Pick (randomly) which of the three doors hides the prize.
Output a visual display of three doors. A simple ABC will do. Or three squares. Or whatever.
Receive input choosing one of the doors. This could be a mouse click on the chosen door, or a single letter input (B) or whatever.
Open another door. You do not open the chosen door. You do not open the door hiding the main prize. That may mean you have no choice, or it may mean that you have a choice of two. If you have a choice of two, pick one at random. Visually indicate that the door has been opened and that no prize was hidden behind it. For a program text-based input/output, this could be as simple as outputting AB0, to show that door C has been opened. Feel free to be more inventive. If you’re doing a GUI program, your choice of display is up to you.
Accept input from the user. The user may input stick or switch (or, for a GUI program, click on buttons, or use a select input, or whatever). If the user enters anything other than stick or switch, the implementation is undefined. Do whatever you want.
Output the text You won! or You lost.
Terminate the progam.

Rules:

When you have to choose something at random, don’t worry about cryptographic randomness. Any rand() function will do.
The program must not cheat. The prize must be in place before the game starts. That is to say that the steps must be performed in the order given: First choose a door behind which to hide your prize, then ask the player to choose. The choice of which door to open in step 4 must happen in step 4: it is not selected in advance.
The output in step 6 must be honest.
This is code golf. Shortest code wins.

APL, 77

p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]

Needs ⎕IO←0. Tested on Dyalog.

Explanation

p←?3                       ⍝ p(rize) is a random number between 1 and 3
⎕←d←3↑⎕A                   ⍝ d(oors) is the string 'ABC'; output it
c←d⍳⍞                      ⍝ ask for one of the letters; c(hoice) is its position
o←e[?⍴e←(⍳3)~p,c]          ⍝ o(pen) is a random position except for p and c
d[o]←'_'                   ⍝ replace the o position in the d string with a '_'
⎕←d                        ⍝ output the modified d string
w←(c=p)=5=⍴⍞               ⍝ get choice, if it's stick (5 chars) and c=p, or neither, (w)in
⎕←'You','lost' 'won!'[w]   ⍝ print the result

Examples

      p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You lost
      p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You won!


Build me a castle Stairway! You will be given a String consisting of printable ASCII (without newlines). Your task is to build a nice Stairway for my Castle.

How to build a nice Stairway?

First off, you should get all the rotations of the String. For example, the String abcd has the following rotations: abcd, bcda, cdab, dabc (each character is moved to the end until we reach the last character).
We now place each rotation on top of each other:

abcd
bcda
cdab
dabc

We can't really climb on a straight wall, so we must build stairs. That means you should add a number of spaces before each rotation corresponding to its index in the rotation list:

abcd
 bcda
  cdab
   dabc

You also need a Stairway that links to the other side of my castle, so you should build one like below, reversing each rotation and adding some spacing:

abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

This is code-golf, hence the shortest code in bytes wins and standard rules for the tag apply.

Test Cases

Input: abcd, Output:

abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

Input: aaaa, Output:

aaaa      aaaa
 aaaa    aaaa
  aaaa  aaaa
   aaaaaaaa

Input: Code golf, Output (Notice the spaces):

Code golf                flog edoC
 ode golfC              Cflog edo
  de golfCo            oCflog ed
   e golfCod          doCflog e
     golfCode        edoCflog
     golfCode        edoCflog
      olfCode g    g edoCflo
       lfCode go  og edoCfl
        fCode gollog edoCf

05AB1E, 12 bytes
Code:
vDNúsÀ}\».B∞

Uses the 05AB1E encoding. Try it online!
Explanation:
v     }        # Length input times, do.. (N = iteration count)
 DNú           #   Duplicate and prepend N spaces
    sÀ         #   Swap and rotate one to the left
       \       # Discard the top of the stack
        »      # Join the stack by newlines
         .B    # Pad with spaces into a rectangle
           ∞   # Mirror the string


Perfect powers in more than one way? Challenge
Your task is to write a program or function which, given a positive integer \$N\$, finds all positive integers less than or equal to \$N\$ that can be expressed as a perfect power in more than one way.
Definition
A perfect power is defined as a number \$i\$ found by \$m^k\$, where:

\$m\$ and \$i\$ are positive integers
\$m \ne k\$

Test Cases

input -> output
1000 ->  16, 64, 81, 256, 512, 625, 729
56 -> 16
999 -> 16, 64, 81, 256, 512, 625, 729
81 -> 16, 64, 81
1500 -> 16, 64, 81, 256, 512, 625, 729, 1024, 1296

Please provided a readable, commented version as well.

Mathematica: 103 chars

Spaces can be removed

Select[Flatten@
       Table[
        Solve[Log@#/Log@b == k, k, Integers] /. k -> #, {b, 2, #}] & /@ Range@#,
Length@# > 2 &][[All, 1, 1]] &

Usage:

%[81]
{16, 64, 81}