Draw a ladder and slide Your task is to create a program or function that takes, as input, a natural number (n) between 1 and 25 (inclusive) and prints an isometric representation of a slide and ladder with n number of rungs.

Ladder and slide specifications

The ladder is always oriented on the left and the slide on the right. We're viewing it from the ladder side, so part of the slide is obscured at the top three levels. The rungs are represented by four dashes (----) and the sides of the ladder and slide by slashes (/ and \). The following is a diagram to represent the patterns of spaces needed for a slide with five rungs.

Slide              Blank space count
    /----/\        1234/----/\
   /----/  \       123/----/12\
  /----/    \      12/----/1234\
 /----/ \    \     1/----/1\1234\
/----/   \    \    /----/123\1234\

Examples

>>1
/----/\

>>3
  /----/\
 /----/  \
/----/    \

>>4
   /----/\
  /----/  \
 /----/    \
/----/ \    \

>>10
         /----/\
        /----/  \
       /----/    \
      /----/ \    \
     /----/   \    \
    /----/     \    \
   /----/       \    \
  /----/         \    \
 /----/           \    \
/----/             \    \

This is code-golf, so the answer with the lowest byte count wins.

Note: trailing white space is acceptable in the output, as long as it doesn't exceed the length of the line.

Retina, 81 72 52 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$* /\    \
^.

+` /(.+)$
$&¶$%`/  $1
/.{5}
/----/

Try it online!

Explanation

The program consists of four stages, all of which are regex substitutions (with a couple of Retina-specific features). I'll use input 5 as an example for the explanation.

Stage 1

.+
$* /\    \

This turns the input n into n spaces followed by /\    \ which will become the top of the ladder/slide:

     /\    \

For now, we'll just show the slide in full and represent the ladder only by its left-hand /.

Stage 2

^.

Unfortunately, n spaces are one more than we need, so we remove the first character again. We've now got:

    /\    \

Stage 3

+` /(.+)$
$&¶$%`/  $1

Time to expand the complete structure. Knowing where the top is, is sufficient to build the entire thing, because we can simply extend it one line at a time, moving the ladder and the slide apart by two spaces.

The + tells Retina to repeat this stage in a loop until the output stops changing (in this case, because the regex stops matching). As for the regex itself, we simply match the / on the last line and everything after it and we also match one space in front of it, which means this can no longer match once / has reached the first column.

Here's what we replace this with:

 $&    The match itself. We don't want to remove the line we already have.
 ¶     A linefeed, because we want to append a new line.
 $%`   This is a very recent addition to Retina: it's like the normal $` but
      is bounded by linefeeds. That means this inserts everything in front
      of the match which is on the same line. In particular this one space
      less than the indentation of the matched line, hence we are shifting
      the / one column left.
 /     A literal /, representing the left edge of the ladder.
>  <   Two spaces, so that we can shift the slide one column right.
 $1    Capturing group 1 which contains the slide and its separation from
      the ladder.

So at each iteration, this adds one line to the string, until we end up with this:

    /\    \
   /  \    \
  /    \    \
 /      \    \
/        \    \

Stage 4

/.{5}
/----/

All that's left is getting the ladder right. That's really simple, we just match the / and the next 5 characters and insert the correct ladder representation, thereby overriding the slide or spaces that are already there:

    /----/\
   /----/  \
  /----/    \
 /----/ \    \
/----/   \    \


Create an ABACABA city Here is the 3rd ABACABA city:
  _
A|_|
B|__|
A|_|_
C|___|
A|_|
B|__|
A|_|

It is made out of the ABACABA sequence, which is basically:

A (1st iteration)
place B - AB
repeat A - ABA (2nd iteration)
Place C - ABAC
Repeat ABA - ABACABA (3rd iteration)

and you get the idea.
The buildings have a height (corresponded by no. of underscores) equal to the letters converted to numbers as A = 1, B = 2 e.t.c.
Input
An iteration number 1<=n<=26.
Output
The ABACABA city of order n, including the letters at the start of the lines.

Python 2, 82 bytes

f=lambda n,s=1:n*"'"and"  _"*s+f(n-1,0)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1,0)

I noticed no one had posted the binary recursion method and decided to give it a shot...and now with a trick borrowed from Sherlock9, it is the shortest python answer! (Also, thanks to xnor for one more shortening.) (And then Dennis who shaved a handful more...)

Ungolfed:

def f(n,s=1):
    if n>0:
        strsofar = "  _" if s==1 else ""        #prepend overhang for top-level call
        strsofar += f(n-1,0)                    #build the city above the current line
        strsofar += "_"*(n-2)                   #add the overhang to reach the current tower
        strsofar += "\n%c|%s|" % (64+n, "_"*n)  #write the current (center) line
        strsofar += f(n-1,0)                    #build the city below the current line
        return strsofar
    else:
        return ""                               #only this line will be executed when n==0 (base case)

print "  _"+f(input())


Bacon's cipher: An Intro to Steganography This little piggy went to market, this little piggy wrote some code...

Ah wait, we're not talking about that bacon, we're talking about Sir Francis Bacon! Specifically, the cipher Bacon devised in the late 1500s, as a method of hiding a message within another message, a method of steganography.

The cipher works by concealing the message in the presentation of text, rather than its content. First, the letters of your message are encoded into binary (from 0 to 25) as follows:

Note: Please use the following encoding in your code and do not worry about numbers, spaces, or other symbols in the input, though I may devise some bonus for those who include these characters in their encoding. If you do include other symbols, the letters must still occupy spaces 0-25 in the encoding.

Letter  Encoding
A       AAAAA
B       AAAAB
C       AAABA
D       AAABB
E       AABAA
F       AABAB
G       AABBA
H       AABBB
I       ABAAA
J       ABAAB
K       ABABA
L       ABABB
M       ABBAA
N       ABBAB
O       ABBBA
P       ABBBB
Q       BAAAA
R       BAAAB
S       BAABA
T       BAABB
U       BABAA
V       BABAB
W       BABBA
X       BABBB
Y       BBAAA
Z       BBAAB

Having encoded all of the letters in your message into the As and Bs above, you must now select two typefaces for your code. For this example, I will use normal text for typeface A and bold text for typeface B.

So the message

HELLOWORLD

is encoded to

AABBB AABAA ABABB ABABB ABBBA BABBA ABBBA BAAAB ABABB AAABB

And now we conceal this binary with a carrier text.

  The quick brown fox jumps over the lazy dogs, gamboling in the fields where the shepherds keep watch.

It is alright if the carrier message is longer than the actual encoded message, though it cannot be shorter. Now we turn the carrier text into bold according to where the Bs are in the encoded message,

  The quick brown fox jumps over the lazy dogs, gamboling in the fields where the shepherds keeps watch.

Which without Markdown reads as

Th**e** **qu**ic**k** bro**w**n **fo**x **j**u**mp**s **ove**r **t**h**e** **l**az**y**
**do**g**s**, gam**b**o**l**i**ng** in t**he** fields where the shepherds keeps watch.

Note that I did not use the punctuation in the carrier message to encode the message, but whether the punctuation is encoded or not is up to you/.

Rules

Your input will be the message you to be encoded and a carrier message. If the carrier message is too short, return some sort of error message.
You must select two typefaces for encoding A and B, such as UPPERCASE, lowercase, italic, bold, bold italic, strikethrough, in code format and so on. You must use Stack Exchange's form of Markdown to encode these typefaces, i.e.

UPPERCASE, lowercase, *italic*, **bold**,
***bold italic***, <s>strikethrough</s>, `in code format`

Your output must be your now-encoded carrier message, either shown with Markdown or shown without, as seen in the above example.
You are only required to make an encoding algorithm. Any decoding algorithms you wish to provide are welcome, but at time of writing will not help or hinder your score.
Your code must be a program or a function.
This is code golf, so the smallest number of bytes wins.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Python 3, 216 211 231 225 207 bytes

This is a solution that uses normal text and Markdown-style italics for its two typefaces. And it encodes everything in the carrier message except the spaces.
Edit: Had to fix the code so that the result would print correctly and added examples below the code.
Edit: Edited the code to previously worse uppercase/lowercase solution, due to problems in printing the italics correctly.
def g(s,c):
 c=c.lower();w=[h.upper()for h in s if h.isalpha()];t=''.join("{:05b}".format(ord(i)-65)for i in w);r='';j=m=0
 while t[j:]:a=c[m];x=a!=" ";r+=[a,a.upper()][x*int(t[j])];j+=x;m+=1
 return r+c[m:]

Examples
>>> g('HELLOWORLD', 'The quick brown fox jumps over the lazy dogs, gamboling in the fields
where the shepherds keep watch')
'thE QUicK broWn FOx JuMPs OVEr ThE LazY DOgS, gaMbOlINg in THe fields where the shepherds keep watch'

Ungolfed:
def bacon(message, carrier):
    # Lowers the case of the carrier message
    carrier = carrier.lower()
    # Removing all non-alphabetic characters and making the rest uppercase
    words = ""
    for char in message:
        if char.isalpha():
            words += char.upper()
    # Encoding the message
    binary = ""
    for letter in words:
        encode = ord(letter) - 65
        binary += "{:05b}".format(encode)
    # Encoding the carrier message
    result = ""
    bin_index = 0
    char_index = 0
    while bin_index < len(binary):
        letter = carrier[char_index]
        # If letter isn't a space and it needs to be encoded
        if letter != " " and int(binary[bin_index]):
            letter = letter.upper()
        result += type + letter + type
        # The encoding only proceeds if letter wasn't a space
        bin_index += letter != " "
        # char_index increments whether or not letter was alphabetical
        char_index += 1
    # Return the encoded text and any leftover characters from the carrier message
    return result + carrier[char_index : ]


Generate basis elements of the Steenrod algebra The Steenrod algebra is an important algebra that comes up in algebraic topology. The Steenrod algebra is generated by operators called "Steenrod squares," one exists for each positive integer i. There is a basis for the Steenrod algebra consisting of "admissible monomials" in the squaring operations. It is our goal to generate this basis.

A sequence of positive integers is called admissible if each integer is at least twice the next one. So for instance [7,2,1] is admissible because \$7 \geq 2*2\$ and \$2 \geq 2*1\$. On the other hand, [3,2] is not admissible because \$3 < 2*2\$. (In topology we would write \$\mathrm{Sq}^7 \mathrm{Sq}^2\mathrm{Sq}^1\$ for the sequence [7,2,1]).

The degree of a sequence is the total of it's entries. So for instance, the degree of [7,2,1] is \$7 + 2 + 1 = 10\$. The excess of an admissible sequence is the first element minus the total of the remaining elements, so [7,2,1] has excess \$7 - 2 - 1 = 4\$.

Task

Write a program that takes a pair of positive integers (d,e) and outputs the set of all admissible sequences of degree d and excess less than or equal to e. The output is a set so the order of the admissible sequences doesn't matter.

Examples:

 Input: 3,1
 Output: [[2,1]]

Here we are looking for admissible sequences with total 3. There are two options, [3] and [2,1]. ([1,1,1] and [1,2] have sum 3 but are not admissible). The excess of [3] is 3 and the excess of [2,1] is \$2-1 = 1\$. Thus, the only sequence with excess \$\leq1\$ is [2,1].

Input: 6, 6
Output: [[6], [5, 1], [4, 2]] (or any reordering, e.g., [[5,1],[4,2],[6]])

Since excess is always less than or equal to degree, we have no excess condition. Thus, we're just trying to find all admissible sequences of degree 6. The options are [6], [5, 1], and [4, 2]. (These have excess \$6\$, \$5-1 = 4\$, and \$4-2=2\$.)

Input: 10, 5
Output: [[7,3], [7,2,1], [6,3,1]]

The admissible sequences of degree 10 are:

[[10], [9,1], [8,2], [7,3], [7,2,1], [6,3,1]]

These have excess \$10\$, \$9-1 = 8\$, \$8-2 = 6\$, \$7-3 = 4\$, \$7-2-1 = 4\$, and \$6-3-1=2\$ respectively, so the last three all work.

Scoring

This is code golf: Shortest solution in bytes wins.

Test cases:

Any reordering of the output is equally good, so for input (3, 3), outputs [[3],[2,1]] or [[2,1],[3]] are equally acceptable (however [[1,2],[3]] isn't).

Input: 1, 1
Output: [[1]]

Input: 3, 3
Output: [[2,1], [3]]

Input: 3, 1
Output: [[2,1]]

Input: 6, 6
Output: [[6], [5, 1], [4, 2]]

Input: 6, 4
Output: [[5,1], [4,2]]

Input: 6, 1
Output: []

Input: 7, 7
Output: [[7], [6,1], [4,2,1], [5,2]]

Input: 7,1
Output: [[4,2,1]]

Input: 10, 10
Output: [[10], [9,1], [7,2,1], [6,3,1], [8,2], [7,3]]

Input: 10, 5
Output: [[7,3], [7,2,1], [6,3,1]]

Input: 26, 4
Output: [15, 7, 3, 1]

Input: 26, 6
Output: [[16, 7, 2, 1], [16, 6, 3, 1], [15, 7, 3, 1], [16, 8, 2], [16, 7, 3]]

05AB1E, 16 12 bytes

Saved 4 bytes thanks to Grimy

Åœíʒx¦@P}ʒÆ@

Try it online!

Explanation

Åœ              # integer partitions
  í             # reverse each
   ʒ    }       # filter, keep only elements true under:
    x           # each element doubled
     ¦          # remove the first element in the doubled list
      @         # compare with greater than or equal with the non-doubled
       P        # product
         ʒ      # filter, keep only elements true under:
          Æ     # reduce by subtraction
           @    # compare with greater than or equal to second input


Print all Country Codes ISO 3166-1 is the standard that defines all the country codes. The well-known two-letter codes (US, GB, JP, etc.) are called Alpha-2 codes.

With two letters, there are only 262 = 676 possible codes, which can be nicely arranged in a grid. This table can be useful as an overview, to see which codes are actually in use, reserved, etc.

This challenge is simple: you're to print all assigned codes of this grid to STDOUT, using plain ASCII, exactly as shown below:

AA    AC AD AE AF AG    AI       AL AM AN AO AP AQ AR AS AT AU    AW AX    AZ
BA BB    BD BE BF BG BH BI BJ    BL BM BN BO    BQ BR BS BT BU BV BW BX BY BZ
CA    CC CD    CF CG CH CI    CK CL CM CN CO CP    CR CS    CU CV CW CX CY CZ
            DE    DG       DJ DK    DM    DO                            DY DZ
EA    EC    EE EF EG EH             EM       EP    ER ES ET EU EV EW
                        FI FJ FK FL FM    FO       FR                FX
GA GB GC GD GE GF GG GH GI       GL GM GN    GP GQ GR GS GT GU    GW    GY
                              HK    HM HN          HR    HT HU
   IB IC ID IE                   IL IM IN IO    IQ IR IS IT IU IV IW IX IY IZ
JA          JE                      JM    JO JP
            KE    KG KH KI          KM KN    KP    KR             KW    KY KZ
LA LB LC       LF       LI    LK                   LR LS LT LU LV       LY
MA    MC MD ME MF MG MH       MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA    NC    NE NF NG    NI       NL       NO NP    NR    NT NU             NZ
OA                                  OM
PA          PE PF PG PH PI    PK PL PM PN          PR PS PT       PW    PY
QA                                  QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ
RA RB RC    RE       RH RI       RL RM RN RO RP       RS    RU    RW
SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO       SR SS ST SU SV    SX SY SZ
TA    TC TD    TF TG TH    TJ TK TL TM TN TO TP    TR    TT    TV TW       TZ
UA                UG          UK    UM                US                UY UZ
VA    VC    VE    VG    VI             VN                   VU
               WF                WL       WO          WS       WV
XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ
            YE                                           YT YU YV
ZA                                  ZM             ZR             ZW       ZZ

(If I made any mistakes copying it down, the table here in this post is normative for the challenge, not the one on Wikipedia.)

You may or may not use trailing whitespace in each line which doesn't contain the *Z code, but not beyond the 77th character in that line (i.e., at most, you can make it a rectangular block, ending in Zs and spaces). Also, you may or may not use a single trailing new line at the end.

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

Python 2, 240 bytes

Straightforward binary encoding implementation.

R=range(26)
print"\n".join(" ".join(chr(65+r)+chr(65+c)if int("8hfxckgq1olihfa47x3rrdkojzkklec7qk1hp4ht6avmzxfg7c4uv14xe0pzvvg93x81ag2bf88v2w0p3p08g8nwtuktbwosj9dytset3qmhdl72v5u62nepapgabdqqu7x",36)&1<<c+r*26 else"  "for c in R)for r in R)

The script for generating the integer is quick and dirty:

codes="""AA    AC AD AE AF AG    AI       AL AM AN AO AP AQ AR AS AT AU    AW AX    AZ
BA BB    BD BE BF BG BH BI BJ    BL BM BN BO    BQ BR BS BT BU BV BW BX BY BZ
CA    CC CD    CF CG CH CI    CK CL CM CN CO CP    CR CS    CU CV CW CX CY CZ
            DE    DG       DJ DK    DM    DO                            DY DZ
EA    EC    EE EF EG EH             EM       EP    ER ES ET EU EV EW
                        FI FJ FK FL FM    FO       FR                FX
GA GB GC GD GE GF GG GH GI       GL GM GN    GP GQ GR GS GT GU    GW    GY
                              HK    HM HN          HR    HT HU
   IB IC ID IE                   IL IM IN IO    IQ IR IS IT IU IV IW IX IY IZ
JA          JE                      JM    JO JP
            KE    KG KH KI          KM KN    KP    KR             KW    KY KZ
LA LB LC       LF       LI    LK                   LR LS LT LU LV       LY
MA    MC MD ME MF MG MH       MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA    NC    NE NF NG    NI       NL       NO NP    NR    NT NU             NZ
OA                                  OM
PA          PE PF PG PH PI    PK PL PM PN          PR PS PT       PW    PY
QA                                  QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ
RA RB RC    RE       RH RI       RL RM RN RO RP       RS    RU    RW
SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO       SR SS ST SU SV    SX SY SZ
TA    TC TD    TF TG TH    TJ TK TL TM TN TO TP    TR    TT    TV TW       TZ
UA                UG          UK    UM                US                UY UZ
VA    VC    VE    VG    VI             VN                   VU
               WF                WL       WO          WS       WV
XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ
            YE                                           YT YU YV
ZA                                  ZM             ZR             ZW       ZZ
"""
n = sum(1 << (x/3) for x in range(0, len(codes), 3) if codes[x] != " ")
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
print baseN(n, 36)


Four weights to produce integer scale differences from 0 through 40 pounds Just-in-time edit: I decided to reveal part of the answer and highlight a single aspect of the challenge.

Show how 4 weights, of 1, 3,  9, and 27 lbs. can be used to produce "weight differences" from 0 to 40 lbs.

You have a two - pan balance scale.

We define the difference in pan weights as the total weight placed on the left pan minus the total weight on the right pan.

The difference in pan weights for the empty scale is 0 lbs.

You have 4 rocks, a,b,c, and d, weighing 1, 3, 9 and 27 lbs respectively

Show how you can produce all integer weight differences from 0 to 40 lbs.

Simpler example:

Problem: With weights of 1 and 3 lbs. show how you can generate all weight differences from 0 to 4 lbs.

Output: for a=1, b=3;

For the 4 weight, 40 pound version, your output should consist of
a table with columns displaying the weight difference, the symbolic amounts in each pan, and the absolute weights in each pan.

You may format the table in a way congenial to the language you are coding in.

Scoring: Shortest code wins

Bonus: 50% of your score if the same code can present the results for the case where 3, 4, and 5 weights are used (for 13, 40, and 121 lbs.)

APL 198 * 50% = 99
z←W n
l←⍉(n⍴3)⊤w←0,⍳+/b←3*0,⍳n-1
r←(⍴l)⍴0
:while 0≠+/+/l>1
    r←r+l>1
    l←((l≤1)×l)+1⌽l>1
:end
a←' ',⌽⎕av[97+⍳n]
c←(⍴l)⍴⍳n
b←0,⌽b
z←l≠r
l←z×l
r←z×r
l←1+l×c
r←1+r×c
z←w,'{',a[l],'}','{',a[r],'}','{',b[l],'}','{',b[r],'}'

As we are effectively working in base three the arithmetic is fairly trivial and is complete by the end of the while loop where the arrays l and r are the contents of the left and right scale pans respectively in base three. This takes about 80 characters. The rest is formatting the output which I am sure can be improved.
To run simply type W followed by the number of weights you want to use. Below is a sample output for n=3:
 W 3
 0 {   }{   }{ 0 0 0 }{ 0 0 0 }
 1 {  a}{   }{ 0 0 1 }{ 0 0 0 }
 2 { b }{  a}{ 0 3 0 }{ 0 0 1 }
 3 { b }{   }{ 0 3 0 }{ 0 0 0 }
 4 { ba}{   }{ 0 3 1 }{ 0 0 0 }
 5 {c  }{ ba}{ 9 0 0 }{ 0 3 1 }
 6 {c  }{ b }{ 9 0 0 }{ 0 3 0 }
 7 {c a}{ b }{ 9 0 1 }{ 0 3 0 }
 8 {c  }{  a}{ 9 0 0 }{ 0 0 1 }
 9 {c  }{   }{ 9 0 0 }{ 0 0 0 }
10 {c a}{   }{ 9 0 1 }{ 0 0 0 }
11 {cb }{  a}{ 9 3 0 }{ 0 0 1 }
12 {cb }{   }{ 9 3 0 }{ 0 0 0 }
13 {cba}{   }{ 9 3 1 }{ 0 0 0 }


Proportion of strings with ascending letters Challenge

Construct n strings, each with three distinct letters, chosen randomly with equal probability.
Print the proportion k/n where k is the number of strings such that all three characters are in ascending order. Print also those k strings.

Input

The only input is n (and thus it must be a positive integer).

Outputs

The proportion k/n must be truncated to two decimal places.
The strings that are in ascending order of letters.

Requirements

The letters must come from the English alphabet.
You cannot print the value of k.

Examples

Input: 6, Output: 0.16 agh
Input: 1, Output: 1.00 suv
Input: 9, Output: 0.22 hls jqr

How to Win

Fewest number of bytes wins.

Jelly, 31 bytes

13 bytes to cater for the truncation requirement!

ØaẊ⁸Ð¡Ḋḣ€3ṢƑƇðL÷+⁵×ȷ2ḞṾs2j”.Ḋṭ⁸

A monadic link which, given an integer, yields a list.

Try it online! (footer joins the list with spaces)

If (1) we remove the truncation requirement and (2) "The letters must come from the English alphabet" implies that we may choose any subset of three or more such letters then this 16 works:

“ḃ»Ẋ⁸Ð¡⁼ƇḢ$ðL÷;⁸

Try this one (only uses A, B, and C)

If we may also avoid the unobservable creation of all the strings as part of of our code. then this 15 works:

6ẋX€ỊƇ“ḃ»ẋðL÷;⁸

Try this one (only uses A, B, and C, and does not create any unordered strings)


Letters, Get Moving! Given a string you must move each letter (starting from the first letter) by its position in the alphabet. If you reach the end of the string you must wrap around. Non-letters don't need to be moved.

Example:

Dog

D is the fourth letter in the alphabet so we move it four spots to the right. After wrapping around, that changes the string to oDg. o is the 15th letter, (15 mod 3) = 0, so it does not move. g is the 7th letter - (7 mod 3) = 1, so the string becomes goD.

hi*bye

h is the 8th letter, move it 8 spots - hi*bye => i*hbye
i is the 9th letter, move it 9 spots - i*hbye => *hbiye
b is the 2nd letter, move it 2 spots - *hbiye => *hiybe
y is the 25th letter, move it 25 spots - *hiybe => *hibye
e is the 5th letter, move it 5 spots - *hibye => *hibey

Non-letters don't need to be moved, but they still take up space.

cat => tca
F.U.N => .F.NU
mississippi => msiisppssii

CJam, 44 42 40 bytes

qN+ee_{Xa/~\+XW=eu__el=!\'@-*m<Xa+}fXWf=

Output contains a trailing linefeed.

Test it here.

Explanation

Instead of moving the letters through the string, I repeatedly remove a letter, rotate the string accordingly, and then reinsert the letter. There's one catch for doing this: we need to be able to distinguish the beginning of the string from the end of the string (which we can't after a simple rotation). That's why we insert a linefeed at the end as a guard (letter before the linefeed is the end of the string, letter after it is the beginning). The bonus is that this automatically returns the final string to the correct rotation where the linefeed actually is at the end of the string.

lN+     e# Read input and append a linefeed.
ee      e# Enumerate the array, so input "bob" would become [[0 'b] [1 'o] [2 'b] [3 N]]
        e# This is so that we can distinguish repeated occurrences of one letter.
_{      e# Duplicate. Then for each element X in the copy...
  Xa/   e# Split the enumerated string around X.
  ~     e# Dump the two halves onto the stack.
  \+    e# Concatenate them in reverse order. This is equivalent to rotating the current
        e# character to the front and then removing it.
  XW=   e# Get the character from X.
  eu    e# Convert to upper case.
  _     e# Duplicate.
  _el=! e# Check that convert to lower case changes the character (to ensure we have a
        e# letter).
  \'@-  e# Swap with the other upper-case copy and subtract '@, turning letters into 1 to
        e# 26 (and everything else into junk).
  *     e# Multiply with whether it's a letter or not to turn said junk into 0 (that means
        e# everything which is not a letter will be moved by 0 places).
  m<    e# Rotate the string to the left that many times.
  Xa+   e# Append X to the rotated string.
}fX
Wf=     e# Extract the character from each pair in the enumerated array.

To see why this ends up in the right position, consider the last iteration of the hi*bye example. After we've processed the e, the enumerated string is in this position:

[[4 'y] [6 N] [2 '*] [0 'h] [1 'i] [3 'b] [5 'e]]

First, we split around the linefeed and concatenate the parts in reverse order:

[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y]]

The linefeed would now be either at the beginning or the end of this string. But since the linefeed is just a guard that marks the end of the string, this means that the characters are actually in the right order. Now the linefeed is not a letter, so that the array is not rotated at all. Thus, when we append the linefeed, it goes where it belongs, and everything is in the order we're looking for:

[[2 '*] [0 'h] [1 'i] [3 'b] [5 'e] [4 'y] [6 N]]

Some additional results if someone wants to compare longer test cases:

Hello, World!
,W oeHlo!lrld

Programming Puzzles & Code Golf
ago fgliPomomnrr elP& uC dezzsG

The quick brown fox jumps over the lazy dog
t eg chbi ko qfTounyzrj omw epx ueoahs rlvd

abcdefghijklmnopqrstuvwxyz
aqbrcdsetfguhivjwklxmnyozp

zyxwvutsrqponmlkjihgfedcba
abcdefghijklmnopqrstuvwxyz

I like that last one. :)


Triangular domino tiling of an almost regular hexagon Background

An almost regular hexagon is a hexagon where

all of its internal angles are 120 degrees, and
pairs of the opposite sides are parallel and have equal lengths (i.e. a zonogon).

The following is an example of an almost regular hexagon, with side lengths 2 (red), 4 (blue), and 3 (yellow).

A triangular domino is a domino made of two unit triangles. A triangular domino tiling is a tiling on a shape using triangular dominoes. The following is a possible triangular domino tiling of the above shape (each color represents an orientation of each triangular domino):

Challenge

Given the lengths of the three sides of an almost regular hexagon, find the number of distinct triangular domino tilings. The three sides will be always positive integers.

Alternative description

The second image shows that such a tiling can be viewed as an isometric view of stacked unit cubes. Now let's assign three directions to three axes in 3D:

x = down-right / southeast / SE (blue edges in the first image)
y = down-left / southwest / SW (red edges)
z = up / north / N (yellow edges)

Then the stacked unit cubes can be represented as an x-by-y 2D array, whose items represent the height of the stack at that position. So the above challenge is equivalent to the following:

  Given three positive integers x, y, and z, find the number of x-by-y arrays whose elements are between 0 and z inclusive and all rows and columns are in decreasing order.

It happens that this is one definition of plane partition in the form of \$ PL(x,y,z) \$, and it has a closed-form formula:

$$
PL(x,y,z) = \prod_{i=1}^x \prod_{j=1}^y \prod_{k=1}^z \frac{i+j+k-1}{i+j+k-2}
$$

Scoring and winning criterion

Standard code-golf rules apply. The shortest code in bytes wins.

Note that a submission is valid even if it suffers from integer overflows or floating-point inaccuracies, as long as the underlying algorithm is correct.

Test cases

x,y,z => output
---------------
1,1,1 => 2
1,1,2 => 3
1,2,3 => 10
2,3,1 => 10 (the order of inputs doesn't matter, since it's the same hexagon)
2,3,4 => 490
3,4,2 => 490
3,3,5 => 14112

APL (Dyalog Classic), 14 bytes

×/1+1÷1+∘,1⊥¨⍳

Try it online!

Uses 0 indexing with ⎕IO←0.

Explanation:

             ⍳     ⍝ Cartesian product of the ranges from 0 to n-1
          1⊥¨      ⍝ Sum of each element (using base 1)
         ,         ⍝ Flattened
        ∘          ⍝ Composed with
  1+1÷1+           ⍝ 1 + 1/(n+1)
×/                 ⍝ And reduced by multiplication


Sample win/loss data generator based on certain criteria Lets say we have this existing data:

Total - 10
Won   -  7
Lost  -  3
Longest Winning Streak - 5
Longest Losing Streak - 2

Now you need to write a function which generates an array of random boolean values (true representing a win and false representing a loss) which fulfills the above criteria.

So, in this case the output can be any of the following:

0011011111
1111101100
1010011111
..........

Rules:

Solution must be function which takes in Won, Lost, Longest Winning Streak and Longest Losing Streak and returns a boolean array or string formed of a boolean array like (110011001010). It can also display output instead of returning the generated data.
You can safely assume there are no ties/draws/no-results.
This is code-golf so shortest code wins.
Input format can be in any form (Standard Input/Command-Line,etc.). And the real input format should be - <Won> <Lost> <LWS> <LLS> where <..> are place-holders or they can be separate parameters for the function.. whatever you deem best for your code. The parameter Total is unnecessary. So you needn't use it.
As far as random is concerned, you can see that in the example, there are three (and more) possible outputs. Just output any one at random.
If you have any other question, ask in the comments below.

Important - Not any answer as of now is correct.

I provide another example (this one's real data) which is possible but not working with the codes in the current answers:

Total - 171
Won   - 111
Lost  -  60
Longest Winning Streak - 10
Longest Losing Streak  - 4

Real Data:

1110110100111111010000101111111100110001100110111101101011111011011011011111111110110001111011010001101011100101111101001011011110101101001100001111101010110001111110111111

Another possible output (Basically the same, just the third and fourth digits are interchanged):

1101110100111111010000101111111100110001100110111101101011111011011011011111111110110001111011010001101011100101111101001011011110101101001100001111101010110001111110111111


Smallest chess board compression Write an algorithm or program that can encode and decode a chess board. The goal is to make the smallest representation of a chessboard that could be used (once decoded) to determine all movement possibilities for a player on that turn.

The encoding must be able to show:

Whose turn it is.
Whether the player can castle on each side.
Whether the player can perform an en-passant, and if so, which of their pawns?
Positions of all pieces.

Important note on castling: If white moves their king one turn, and then moves it back the next, it must be clear that they cannot castle on either side after that. Same would go if they moved their left or right rook. Although the board is visually in the same state as it was two turns ago, the game state has changed. More info here: http://en.wikipedia.org/wiki/Chess#Castling

Important note on en-passant: This is also a turn-sensitive move. Read the rules for more info. http://en.wikipedia.org/wiki/Chess#En_passant

Determine input and output as needed. Major props to whoever can compress it the most!

Your score is determined worst-case scenario - maximum possible size in bits. Make sure you show how you calculated it that number and what you accounted for. Shoot for the smallest worst-case!

Min: 12 bitsMax: Avg:

Had and thought last night that I could possibly make it even smaller.

x   Colour to play next (0 -> Black, 1-> White)
1   Only King left?

00000 Position of White King (0 -> A1 ... 63 -> H8)
00000 Position of Black King

01 00000 11111  WK:A1, BK:H2 (Black to play)
11 00000 11111  WK:A1, BK:H2 (White to play)

The result is an impressive size of 12 bits!

So what about K +1 other type of piece?

x
 0
   0
     000  +Pawn
     001  +Rook
     010  +Knight
     011  +Bishop
     100  +Queen

There 2 possible arrangement of the sub tree.

   /\      /\
  +  K    K  +

Both result in the same bit sizes for all pieces. So it make no difference to which we use, I'll choose the first one.

x
 0
  0
   000
      1011001110000000000000000000000000000000000000000000000000000000000000
(+ 000) En-Passant (if >= 2 pawn & pawn in en-passant positions)
(+ 00 ) Castlings  (if >= 1 rook)
Min: 75 bit
Max: 109 bits

So on King +2 other piece types

x
 0
  1
   PRBNQ
   00011  +N +Q
   00101  +B +Q
   00110  +B +N
   01001  +R +Q
   01010  +R +N
   01100  +R +B
   10001  +P +Q
   10010  +P +N
   10100  +P +B
   11000  +P +R

There are 5 possible sub trees (I'll use 1 and 2 to indicate which of the pieces.)

   /\          /\       /\         /\          /\
  /  \        /  \     /  \       /  \        /  \
 K   /\      /\   2   /\   \     1   /\      /\   \
    1  2    K  1     K  2   1       K  2    1  2   K

So we'll require 3 bits to encode which sub tree to use.

x
 0
  1
   PRBNQ
         000  Sub Tree used

Min:= 11 = Header
       6 = 2 * 3
       4 = 1 * 4
       4 = 1 * 4
      60 = 60    Empty
      --
      85 bits

Max:=  11 = Header
        4 =  2 * 4 Kings
       48 = 16 * 3 Pawns
       12 =  4 * 3 Rook
       42 = 42 * 1 Empty
        3 =  1 * 3 En-Passant
        2 =  1 * 2 Castlings
      ---
      122 bits

Still doing the analysis for more pieces

+3 Other

x
 0
  1
   PRBNQ
         0000  Sub Tree used (of 14 possible)

+4 Other

x
 0
  1
   PRBNQ
         000000  Sub Tree used (of 42 possible)

+5 Other

x
 0
  1
   PRBNQ
         0000000  Sub Tree used (of 132 possible)
 (+000)
 (+00)

Max: 208?

Is it possible to encode all these sub-trees into 9bits?

If we total up all of the possible sub-trees we get 392 possible sub-trees.

 1  0
 2  2
 3  5
 4  14
 5  42
 6  132
    ---
    392  <= 2^9

Using Freq ID

Since there 164603 unique piece frequencies.

Log2( 164603) = 17.3286110452
             ~ 18 bits

0
 0000 0000 0000 0000 00  Freq ID

(+000)
   (+00)  Castling

Max:= 204 bits

rev 3

Min: 82 Max: 199 Avg: 160

Finally got around doing some analysis to find the maximum bit size.
With optimal huffman encoding for each of the unique piece frequencies.

               0   Player
              00  Castling
               0  En-Passant Possible
            ?000  En-Passant column (include if En-Passant Possible = 1
  0000 0000 0000  Tree Encoding ID
[Board Encoding]  Between 66 .. 180 bits

Note this is the worst possible size, which the En-Passant column bits if the number of pawns is greater than one. Irrespective of those pawns colours and position there is the potential for some boards to be 3 bits smaller.

Also there are only 144 different sizes(Worst case) for the size of the board.

 75 - 216 bits (v2)
v1  The minimum size is 98 bits (12.25 bytes), only the two kings on the board.

Maximum size is only 216 bits (27 bytes.) In the unlikly:-

  9 x Queens
  1 x King
  2 x Rooks
  2 x Knights
  2 x Bishops
on each side.

On average the size will be around 157 bits (19.625 bytes).

Pieces

To encode the board I'm using a binary tree encoding scheme.
An empty square is the most frequent from any where between 32 and 62 appearances.
Next are the pawns, then Rooks, Knights, Bishops and the least frequent are the Queen and King.

0 - left node
1 - righ node

     /\
    e  \    e:= Empty Square
      B/\W  B:= Black ; W:= White
      /  \
     /    \
    /      \
   /\      /\
  p  \    p  \  p:= Pawn
     /\      /\
    /  \    /  \
   /\  /\  /\  /\
  r  b n \ r b n \  r:= Rook; b:= Bishop; n:= Knight
         /\      /\
        q  k    q  k  q:= Queen ; k:= King

The starting board can be encode in just 166 bits (20.75 bytes)

  A     B     C      D      E     F     G     H
-----+-----+-----+------+------+-----+-----+------+
10100 10101 10110 101110 101111 10110 10101 10100 | 8
  100   100   100    100    100   100   100   100 | 7
    0     0     0      0      0     0     0     0 | 6
    0     0     0      0      0     0     0     0 | 5
    0     0     0      0      0     0     0     0 | 4
    0     0     0      0      0     0     0     0 | 3
  110   110   110    110    110   110   110   110 | 2
11100 11101 11110 111110 111111 11110 11101 11100 | 1

To indicate whom's move it takes only single bit

0-> Black , 1-> White

Castling can be encoded in 4 bits.

 B  W
LR LR
00 00

So I've use 171 bits (21.375 bytes)

En-Passe can be encoded into just 16 bits (2 bytes)

So in total thats 187 bit (23.375 bytes).

Layout

  bits    Encodes
 0 -  15  En-Passe
16 -  19  Castling
      20  Move
21 -  23  Unused
24 -> ..  Board

Not written any code yet.

Notice that 3 of the bits that are unused. So the max is 213bits.

Possible Improvements

1) Reduced the header block form 24 to 8 bits (with @Peter Taylor suggestion)

0 - 2 En-Passant
    3 Move
4 - 7 Castling
8 ... Board Pieces

2) Variable length header

A small 4 bit fixed header

0 0 0 0
| | | |
| | | +-> En-Passant Block Present?
| | |
| | +---> Pawns on board?
| |
| +-----> Castling still possible?
|
+-------> Who's move? 0-Black
                      1-White

Next block of additional bits (If castling is still possible)

00 00
|| ||
|| |+-> White Castle Right
|| +--> White Castle Left
||
|+----> Black Castle Right
+-----> Black Castle Left

Next block of additional bits (if pawns are present)

000--> En-Passant column Position

So now I have a variable length header 4 - 11 bits

3) Use a different encoding scheme depending on what pieces are left on the board.

By changing the tree encoding depending on what pieces are on the board and there frequency.

One possible encoding for an end game state (No Pawns)

        /\
       e /\
  Black /  \ White
       /    \
      /      \
     /        \
    /\        /\
   /  \      /  \
  /   /\    /   /\
 /\  / /\  /\  / /\
r b n q k  r b n q k

Which is about ~4 bits per piece.

Which type of pieces are present on the board?

RBNQK Permutation
11111 (11111)

Permutation is Variable length 0-5 bits.
If only one type of piece is left then don't include it.

Which permutation of those pieces to use for the tree?
This is the factorial of the number of pieces in the above example it is 5 pieces so 120 possible permutations that can be encoded.

 #    !  bit
 6  720  10  (If pawn included)
 5  120   6
 4   24   5
 3    6   3
 2    2   1  Don't include as of equal size.
 1    1   0  Don't include as its not needed.

Remember that there is addition bits for the empty squares and color.

Examples

Let's give an example of only QK left

RBNKQ
00011

  /\
 s  \
    /\
  B/  \W
  /\  /\
q  k q  k

101 100  0 x 60 110 111 ==> 60 + (2 x 6) = 60 + 12 = 72 bits for the board

0000 00011 Header ==> 9 bits

81 bits total

Let's give and example of only kings left

 RBNQK
 00001

  /\
 s  k
   / \
  B   W

 10 0 0 0 0 0 0 0   K... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 11  .... ...k

Put all together

 header  4   0 0 0 0
 pieces  5   0 0 0 0 1
 perm    0   - - - - - -
  board 66   10 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 11

So I calculate the smallest encoding for board at 75bits (9 bits 3 bit)

Still yet to calculate how this coding scheme affects the maximum size.

Improvement 4

Reduce the number of bits for castling to just 2 bits. Just castling for the player who's turn it is.

 0 Castling possible (from header block)
 LR
 00

Thinking about it, it maybe better just to include the 2 bits inside the header block.


"Hello, World!" (Cops' thread) This is the cops' thread. The robbers' thread is here.

Your challenge is to write a program or function that, with a certain input, prints the exact string Hello, World! and a newline. Capitalization, spacing and punctuation must be exact.

Input may be taken via standard input, a file, or command-line/function arguments. Output may be given via return value, writing to a file, or standard output.

Your program must print Hello, World! for at least one input. When your program is given the wrong input (i.e. the input that does not make it print Hello, World!), it can do whatever you like - crash, print random nonsense, call Chuck Norris, etc.

You may not use a hashing algorithm or any similar methods of obscuring the required input.

Submissions are preferred to be runnable & crackable on TIO. Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them.

After one week, this challenge will be closed to future cop submissions. The winner is the shortest code that is uncracked after a week of posting it ("it" being the code, not this challenge). The winner will be accepted after two weeks.

After a week has passed since posting, please mark your answer as safe and show the input (in a > ! spoiler quote). If a robber cracks your submission (before the week ends), please mark it as cracked and show the halting input (in a > ! spoiler quote).

Looking for uncracked submissions?

fetch("https://api.stackexchange.com/2.2/questions/137742/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});

Uncracked Submissions

Language	Author

TeX - 38 bytes Cracked(ish)
This is worth a shot, because I can't imagine anyone on a site about writing short pieces of code would know TeX:
\read16to\x\message{Hello, World!}\bye

To run it, you should get a hold of some form of TeX that allows interactive mode. Save this to a file, and run TeX (or pdfTeX, XeTeX, etc.) on it.
Edit: I'm currently considering this semi-cracked. The intended solution uses input from stdin, but TeXnically input from the way the program is invoked is valid. I'll be adding more devious TeX answers if someone gets the intended method.
Here's the intended solution:

 ^C Ia - The first key is control-c, which causes an error. Then, you press I (capital i) to input a command. Then you type a (or anything else to be typeset). Normally, the message that was printed to stdout would be followed by a space and then a ')'. When you typeset something, it causes the font information to be output after the message. That means that a newline is thrown in, and the ')' gets moved later.

That may be underhanded, but should still be within the rules of the game.


Cryptographic quine variant Create a program that prints the MD5 sum of its source in the form:

MD5 sum of my source is: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

No cheating - you can't just read the source file and compute its sum. The program must not read any external information.

Of course you can use a MD5 library available for your language.

Python 2, 91 bytes

s="import md5;print'MD5 sum of my source is: '+md5.new('s=%r;exec s'%s).hexdigest()";exec s

Using the Python quine variant which doesn't require repeating everything twice. Tested on ideone.


Writing rational numbers as ratio of factorials of primes Note: this challenge has been posted on the sandbox.

Introduction

This challenge is inspired by 2009 Putnam B1, a problem in an undergraduate mathematics competition. The problem is as follows:

  Show that every positive rational number can be written as a quotient of products of factorials of (not necessarily distinct) primes. For example,

Challenge

Your challenge is to take a pair of relatively prime positive integers, representing the numerator and denominator of a positive rational number (or just the rational number itself) as input, and output two lists (or arrays, etc.) of prime numbers so that the inputted rational number is equal to the ratio of the product of the factorials of the primes in the first list to the product of the factorials of the primes in the second list.

Notes

There may not be any primes that contained both in the first list and in the second list; however, a prime may appear as many times as one wishes in either list.
The inputs can be assumed to each be (nonstrictly) between 1 and 65535; however, it cannot be assumed that the factorials of the numbers you will need to output will be in this range.

Example Input and Output

Here are examples of legal inputs and outputs.

input=>output
10,9 => [2,5],[3,3,3]
2,1 => [2],[]
3,1 => [3],[2]
1,5 => [2,3,2],[5]     (elements of a list may be in any order)
3,2 => [3],[2,2]
6,1 => [3],[]

The inputs (2,2), (0,3), (3,0), (3,6) and (1,65536) are illegal inputs (i.e. your program doesn't need to behave in any particular way on them). Here are some examples of illegal outputs:

1,2 => [2],[2,2] (2 is in both returned lists)
5,2 => [5],[2,4] (4 is not prime)
2,1 => [2],[1] (1 is not prime either)
3,2 => [3],[2] (3!/2! = 3, not 3/2)

Scoring

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

Mathematica, 175 177 169 154 108 bytes

Join@@@Table[x[[1]],{s,{1,-1}},{x,r@#},x[[2]]s]&@*(If[#==1,1,{p,e}=Last@(r=FactorInteger)@#;p^e#0[p!^-e#]]&)

Try it online!

How it works

This is the composition of two functions. The first, which ungolfs to

If[# == 1,
  1,
  {p,e} = Last[FactorInteger[#]];
  p^e * #0[p!^-e * #]
]&

is a recursive function for actually computing the desired factorization. Specifically, given a rational input x, we compute the primes whose factorials should be in the numerator and denominator, and return the fraction with all of those primes multiplied together. (For example, on input 10/9 = 2!*5!/(3!*3!*3!), we return 10/27 = 2*5/(3*3*3).)

We do this by dealing with the largest prime factor at every step: if pe occurs in the factorization of x, we make sure p!e occurs in the factorial-factorization, and recurse on x divided by p!e.

(Earlier, I had a more clever strategy that avoids large numbers by looking at the previous prime number before p, but Mathematica can handle numbers as big as 65521! easily, so there's no point. The old version you can find in the history is much faster: on my computer, it took 0.05 seconds on inputs that this version handles in 1.6 seconds.)

The second function turns the output of the first function into lists of primes.

Join @@@
  Table[x[[1]],
    {s,{1,-1}},
    {x,FactorInteger[#]},
    x[[2]]*s
  ]&

For s=1 (positive powers) and s=-1 (negative powers), and for each term {prime,exponent} in the factorization r@#, we repeat the prime number prime exponent*s many times.

Noncompeting version with 109 62 bytes

If[#==1,∇1=1,{p,e}=Last@FactorInteger@#;(∇p)^e#0[p!^-e#]]&

Same as above, but instead of giving output as a list, gives output as an expression, using the ∇ operator (because it has no built-in meaning) as a stand-in for factorials. Thus, an input of 10/9 gives an output of (∇2*∇5)/(∇3)^3 to represent (2!*5!)/(3!)^3.

This is shorter because we skip the second part of the function.

+2 bytes: the assignment f=First has to be done in the right place to keep Mathematica from getting upset.

-8 bytes: fixed a bug for integer outputs, which actually made the code shorter.

-15 bytes: FactorInteger returns sorted output, which we can take advantage of.

-46 bytes: we don't actually need to be clever.


Reconstruct a Text Rectangle from Diagonal Strips This challenge is inspired by a SO question about traversing a matrix by enumerating all its diagonal strips.

Instead of a matrix, consider a block of text:

ABCD
EFGH
IJKL

Traversing this block's SW-NE diagonals from left to right, starting from the top left corner and ending in the bottom right, results in the following output:

A
EB
IFC
JGD
KH
L

Challenge

Write a program or a function that execute the reverse of the process described above. That is, given a set SW-NE diagonal strips, output the block of text that produced it.

Input and Output

Both input and output can be represented as strings with newlines, or arrays/lists of strings.

Trailing newlines are optional.

The input will consist of at least one printable character and can be assumed to be correct (there will not be inconsistent row lengths).

The output block will always have a number of columns greater than or equal to the number of rows.

Test Cases

Input:

A

Output:

A

Input:

.
LI
PO.
PV.
CE
G

Output:

.I..
LOVE
PPCG

Input:

M
DA
AIT
LAR
SGI
/OX
/N
/

Output:

MATRIX
DIAGON
ALS///

CJam, 23 20 bytes

{_z,,Nf*W%\.+zW%sN%}

Try it here.


Figure Out the Android Lock Pattern Lets say you saw your friend enter his or her password into their Android phone.  You don't remember how they made the pattern but you remember what the pattern looks like.  Being the concerned friend that you are you want to know how secure their password is.  Your job is to calculate all the ways that a particular pattern can be made.

How Android patterns work

Patterns are drawn on a 3x3 grid of nodes.  In a pattern one visits a series of nodes without ever lifting their finger from the screen.  Each node they visit is connected to the previous node by a edge. There are two rules to keep in mind.

You may not visit any one node more than once
An edge may not pass through an unvisited node

Note that, while typically very hard to perform and thus not very common in real android lock combinations, it is possible to move like a Knight.  That is, it is possible to move from one side to a non-adjacent corner or the other way around.  Here are two examples of patterns employing such a move:

Here is a an animated Gif of it being performed.

Solving a pattern

A typical pattern might look something like this:

With a simple pattern like this one it there are two ways two draw the pattern.  You can start at either of the two loose ends and traveling through the highlighted nodes to the other.  While this is true for many patterns particularly ones that human beings typically employ this is not true for all patterns.

Consider the following pattern:

There are two immediately recognizable solutions.  One starting in the upper left:

And one starting in the bottom center:

However because a line is permitted to pass through a point once it has already been selected there is an additional pattern starting in the top middle:

This particular pattern has 3 solutions but patterns can have anywhere between 1 and 4 solutions[citation needed].

Here are some examples of each:

1.

2.

3.

4.

I/O

A node can be represented as the integers from zero to nine inclusive, their string equivalents or the characters from a to i (or A to I).  Each node must have a unique representation from one of these sets.

A solution will be represented by an ordered container containing node representations.  Nodes must be ordered in the same order they are passed through.

A pattern will be represented by an unordered container of pairs of nodes. Each pair represents an edge starting connecting the two points in the pair.  Pattern representations are not unique.

You will take a pattern representation as input via standard input methods and output all the possible solutions that create the same pattern via standard output methods.

You can assume each input will have at least one solution and will connect at least 4 nodes.

You may choose to use a ordered container in place of an unordered one, if you so desire or are forced to by language selection.

Test Cases

With the nodes arranged in the following pattern:

0 1 2
3 4 5
6 7 8

Let {...} be an unordered container, [...] be a ordered container, and (...) be a pair.

The following inputs and outputs should match

{(1,4),(3,5),(5,8)} -> {[1,4,3,5,8]}
{(1,4),(3,4),(5,4),(8,5)} -> {[1,4,3,5,8]}
{(0,4),(4,5),(5,8),(7,8)} -> {[0,4,5,8,7],[7,8,5,4,0]}
{(0,2),(2,4),(4,7)} -> {[0,1,2,4,7],[1,0,2,4,7],[7,4,2,1,0]}
{(0,2),(2,6),(6,8)} -> {[0,1,2,4,6,7,8],[1,0,2,4,6,7,8],[8,7,6,4,2,1,0],[7,8,6,4,2,1,0]}
{(2,3),(3,7),(7,8)} -> {[2,3,7,8],[8,7,3,2]}
{(0,7),(1,2),(1,4),(2,7)} -> {[0,7,2,1,4],[4,1,2,7,0]}
{(0,4),(0,7),(1,3),(2,6),(2,8),(3,4),(5,7)} -> {[1,3,4,0,7,5,8,2,6]}
{(1,3),(5,8)} -> {}

An imgur album of all the test cases as pictures can be found here.  Patterns are in blue solutions in red.

Scoring

This is code golf. Fewest bytes wins.

Python 2.7, 493 430 bytes

exec("L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]IL];S=sorted;F=lambda t:''.join(str(i)It)\ndef N(x):\n s=' '.join(F(S(i))Ix)\nIL:s=s.replace(i[::2],i[:2]+' '+i[1:])\n return S(set(s.split()))\ndef P(s):\n e=0\nIL:e|=-1<s.find(i[::2])<s.find(i[1])\n return[zip(s[:-1],s[1:]),L][e]\nx=N(input());print[F(i)I__import__('itertools').permutations({iI`x`if i.isdigit()})if x==N(P(F(i)))]".replace('I',' for i in '))

The single line version wraps the program with exec("...".replace('I',' for i in ')) so that all for-loops and generators can be shorted with a single I and saves 15 bytes over this more readable version:

L=['012','345','678','036','147','258','048','246'];L+=[i[::-1]for i in L]
S=sorted;F=lambda t:''.join(str(i)for i in t)
def N(x):
 s=' '.join(F(S(i))for i in x)
 for i in L:s=s.replace(i[::2],i[:2]+' '+i[1:])
 return S(set(s.split()))
def P(s):
 e=0
 for i in L:e|=-1<s.find(i[::2])<s.find(i[1])
 return[zip(s[:-1],s[1:]),L][e]
x=N(input())
print[F(i)for i in __import__('itertools').permutations({i for i in`x`if i.isdigit()})if x==N(P(F(i)))]

The program takes the input in the manner shown (e.g. {(1,4),(3,4),(5,4),(8,5)}) or as a list of string (e.g. ['14','34','54','85']) (or in other python friendly formats) and returns the output as a list of strings. So we technically have an ordered container of ordered containers.

The function N normalizes a pattern so that two patterns can be easily compared. The normalization sorts the pairs denoting edges (so '02' instead of '20'), use string replacement to expand double edges (e.g. '02' becomes '01 12'), splits the edges into a set to remove duplicates, and sorts the result.

The function F flattens tuples of ints/strings to strings, so we can normalize paths produced in different ways.

The list L contains all lines on screen.

We then take each permutation of all digits in the normalized pattern and compute a valid path or L if invalid (which never normalizes to list of pairs like real paths would), or a list of pairs indicating the order nodes are visited if valid. If this normalizes to the same pattern then we have a valid solution and include it in the final list.

The main check needed to validate a permutation as a string s is -1<s.find(i[::2])<s.find(i[1]), which detects an error with a line i. For instance with the line '210' the code detects an error if '20' occurs (i.e. it's index is greater than -1) and '1' occurs after it. We don't have to worry about 1 not occurring because the 1 will show up in the normalized pattern when it wasn't in the input.

NOTE: I know replacing str(i)for i in t with map(str,t) and {i for i in`x`if i.isdigit()} with set('012345678')&set(`x`) would make the original code shorter, but this would still be slightly longer that substituting I.


Digitangular numbers A triangular number is a number that can be expressed as the sum of consecutive positive integers, starting at 1. They can also be expressed with the formula n(n + 1) / 2, where n is some positive integer.

A number's digitangular counterpart is calculated in the following way:

Split a number into an array of its digits e.g. 613 => [6 1 3]
For each number in the array, calculate the nth triangular number; [6 1 3] => [21 1 6]
Sum the resultant array; [21 1 6] => 28

Your task is, given an integer n, repeatedly calculate n's digitangular counterpart, until the result is equal to 1, then output all values that were calculated. You may output the values in any order, and with an optional inclusion of the original number at the start of the array. This is a code-golf so the shortest code wins.

Test cases

23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1

Husk, 6 bytes

U¡(ṁΣd

Try it online!

Explanation

U¡(ṁΣd
 ¡(       Iterate the following function on the input:
     d       Split the number into digits
   ṁΣ        Map each digit to its triangular number, then sum the results
U         Take the results of iteration until before the first repeated one


How many words are there? English is such an inefficient language. We've got enormous words when
there are plenty of two or three letter words we never used! As
computer scientists, every keystroke matters. We need to be more
efficient. Just think of how many words we could have had! In fact,
don't think about it, tell me.

Given a string (or list) of letters, I want you to output how many
words we could make using those letters. You must use every letter in the string exactly one time.

Words can't just be any old string of letters though, how would you
say "yffghtjrufhr"? To be a word, it has to satisfy the following
conditions:

It must contain at least one vowel ('y' is always a vowel).
There must be no more than 2 vowels in a row.
There must be no more than 3 consonants in row.
The combinations "ch", "sh", and "th" count as one consonant.
"s" counts as neither a consonant nor vowel ("length" is just as
valid as "lengths").

For example:

Input    -> Output
a        -> 1       (a)
b        -> 0
ab       -> 2       (ab, ba)
abbbb    -> 3       (babbb, bbabb, bbbab)
abbbbbbb -> 0
essss    -> 5       (essss, sesss, ssess, ssses, sssse)
abbbth   -> 46      (thabbb, thbabb, thbbab, bathbb, ...)

Obviously, since this challenge is all about character efficiency, I
think a code-golf challenge is in order. Standard rules apply!

(For clarification, an 's' breaks any streaks of vowels or consonants. The word "abbbsbbb" is ok, since there are no more than 3 consonants in a row".)


MATLAB, 92 90 86 83 79 74 72 bytes
x=input('');I=@(x)~imdilate(x,ones(3));[C,N]=bwlabel(I(x));nnz(I(C)-x)+N

This solution accepts the input in the form of a 2D matrix of 0's and 1's and will display the 3BV value for the provided input.
Here is slightly modified demo in Octave for those of you without MATLAB.
Explanation
The input matrix is dilated using a 3 x 3 matrix of 1's and then inverted (using ~) which identifies all of the points that do not have mines as neighbors (1) or do (0). To determine the number of connected regions, we use bwlabel to label each connected region of 1's. The first output is the label matrix (0 where the input was zero and any value in the range 1...N where there was a 1 in the input where N is the index of the connected group that it belongs to). The second output is the number of regions (the number of clicks required to open them). The result of the bwlabel is shown in the image on the left.

We expand the first output of bwlabel using imdilate (all non-zeros are expanded) using a 3 x 3 matrix of 1's. The result is shown in the image in the middle.
To determine the remaining clicks, we then count the squares that are not in this expanded region (~imdilate()) and not a mine (-x) (white squares in the image on the right) and add this to the total number of open regions (the number of different colors in the image on the left) to get the 3BV.


ASCII Tux (Linux Penguin) I once hacked upstart on my Ubuntu box so that a colored, themeable ASCII Tux displayed on the screen with the boot messages scrolling beneath him. I'm curious to see what kind of ASCII art Linux Penguins you can come up with.

It must fit in a 80 x 25 terminal, without using the bottom line (thus 80 x 24)
Compact source code
Bonus: use color
Bonus: use variations on the standard Tux

Edit: As a clarification, by "compact source code" I meant smallest source code per number of lines of output. The answers so far have been good but it would be fun to get a diversity of penguins going.

Many script languages, 6 UTF-8 bytes

It doesn't print ASCII art, but...

""

The character in the quote is the unicode character penguin (U+1F427) (if you want to see the penguin above, download the Symbola font). It looks like this (but a lot smaller):


Determine winner of Connect 4 You are given a partially filled Connect 4 grid (7x6).

O X
O X
X O X O     O
X O X O   X X
O X X X O O X
O O O X X O X

(Input can be given as a 1D or 2D array and as letters or numbers, etc.)

Assume that

X started the game.
Nobody has won yet.
Players may not have played well until now, but now onwards they will both employ optimal strategies.
Input grid is not faulty.

You must output a single value that indicates which player wins (or a draw)

Code golf challenge; so shortest code wins. Your program does not have to actual compute the output in reasonable amount of time, but you should be able to prove that the output will be obtained correctly in a finite amount of time.

Perl, 119 118 117 bytes

Includes +4 for -0p

Give rotated board padded with spaces on STDIN (gravity pulls stones to the right)

connect4.pl
  OXXX
   XOO
    OX
  OOXX
  XXXO
XXOOXO
OOXXOO
^D

connect4.pl:

#!/usr/bin/perl -p0
y/XO/OX/if$^S|y/X//>y/O//;$_=$$_||=/Z@{[map"|O".".{$_}O"x3,0,5..7]}/sx||s% (?! )%$_="$`X$'";do$0%eg?/1/?3:1+/2/:2

Prints 3 if player to move wins, 1 if player to move loses and 2 for a draw.

On older perls you can use a literal ^S to gain one byte.
If you don't mind extreme inefficiency you can leave out the $$_||= (transposition table) and gain 6 more bytes. If you leave out the $_= it will show you where to play instead of the result (play on 1 and win if there is one, play on 2 and draw if there is one or play on any 3 and lose)

Builds and evaluates a complete minimax tree. You will run out of memory and time unless the board is already reasonably well filled.


Build the busiest beaver in x86 machine code in 32 bytes or less Your task is to write a program in x86 machine language (any version you like) that will run through as many instructions as possible and then halt, using a maximum of 32 bytes of code and starting with zeroed-out registers.

You can assume anything about the random-access memory you like, as long as it's in a usable format for the x86 machine.

2524224 instructions

My program:

_start:
        mov     bl, _end
        stc
iloop:  adc     [bx], al
        inc     bx
        jnz     iloop
        jnc     _start
        a32
        loop    _start
        hlt
_end:

(Technical note: this is written for nasm. The a32 is nasm's syntax for the alternate address-size prefix byte. For masm, you would replace the a32 with defb 0x67.)

For clarity, here's the listing output:

 1                  _start:
 2 0000 B310                mov     bl, _end
 3 0002 F9                  stc
 4 0003 1007        iloop:  adc     [bx], al
 5 0005 43                  inc     bx
 6 0006 75F9                jnz     iloop
 7 0008 73F4                jnc     _start
 8 000A 67                  a32
 9 000B E2F1                loop    _start
10 000D F4                  hlt
11                  _end:

The program assumes that the processor is in real mode, and that the program is located at the bottom of a 64k segment of memory which is otherwise initialized to all-bits-zero. Its design is simple: treat the memory as a single giant unsigned integer, and increment it through all possible values, until it rolls back around to all-zeroes. Repeat this 232 times. Then halt.

The innermost loop (lines 4‒6) is responsible for incrementing the huge integer. Each iteration adds zero or one to a single byte, depending on whether there was a carry out of the previous byte. Note that every byte in the huge integer is accessed, whether or not it has changed, so this loop always iterates 216 - 14 times.

By the way, in case you were wondering, this code illustrates the reason why the x86 inc/dec instructions don't affect the carry flag: just to simplify this sort of multi-byte carry pattern. (This pattern came up more often back in the days of 8-bit microprocessors, when the original 8080 instruction set was defined.)

Line 7 causes the incrementing process to repeat until a one is carried out of the last byte, indicating that the huge integer has been reset to all-bits-zero. This takes a long time.

Lines 8‒9 mark the outermost loop, and causes this process to repeat 232 times, until the ecx register rolls around to zero. This is effectively equivalent to adding another 32 bits to the giant integer.

It would be possible to add another outer loop and do this again using (say) the edx register, and then maybe using esi and edi for even more repetitions. However, it's not worth doing. The instructions to increment and loop require four bytes. Those four bytes are taken away from the giant integer. So we lose 32 bits on the RAM counter, just to add 32 bits via a register: it ends up being a wash. The only reason ecx is an exception is that it has a specialized loop instruction that fits into only three bytes. Thus the program trades 24 bits for 32, a tiny but still positive gain of 8 bits.

It's not too hard to directly calculate the number of instructions that the program executes before it halts. However, there's a much simpler way to estimate this number. The program modifies all of its memory, less the 14 bytes that contain the program, and the bx and ecx registers. This adds up to 216 - 14 + 2 + 4 = 65528 bytes, for a total of 524224 bits. The shortcut involves realizing that, in the process of running, every single possible pattern of 524224 bits appears exactly once. For the RAM and the ecx register this is easy to see, since the program increments through every single value. For bx this is a little less obvious, since it's being changed at the same time as the value in memory is being updated. However, one can show that, given the program's structure, if a complete bit pattern were to actually appear twice, then the program would have to be in an infinite loop. Since this is not the case, each bit pattern must ultimately be visited only once. (The complete proof is left as an exercise to the reader, naturally.)

Since every possible bit pattern appears in the course of the program, the program must execute at least 2524224 instructions, which is approximately equal to 1.4 × 10157807. (The acutal number is very slightly higher, because of the jump instructions, but the difference at this magnitude is negligible.)

Obviously, this could be significantly improved by using more than 64k of RAM. I'm holding off on the next version of the code until I figure out exactly how much RAM can be accessed.


Dijkstra's Challenge Presented in honor of APL as an interactive tool turning 50 this year
Background

Ken [Iverson] presented his paper Formalism in Programming Languages in August 1963 at a Working Conference on Mechanical Language Structures, Princeton, N.J. The list of conferees is full of famous and soon-to-be famous names, and a few future Turing Award winners (Backus, Curry, Dijkstra, Floyd, Iverson, Newell, Perlis, Wilkes). The paper also records the discussion that occurred after the presentation, ending with an exchange between Ken and [Edsger] Dijkstra, in which Ken’s reply to Dijkstra’s question was a one-liner.

Challenge

How would you represent a more complex operation, for example, the sum of all elements of a matrix M which are equal to the sum of the corresponding row and column indices?

Write a snippet or expression (no need for a full program or function) to calculate the sum of each element in a given integer matrix which is equal to the sum of its indices. Or, as FryAmTheEggman puts it: given a matrix M with elements aij return the sum of each aij where aij = i + j.
You may assume the matrix already being in a variable or memory location, or you may take it as an argument or input. You may use either 0 or 1 based indices.
Test cases

0 for empty matrix
2

0 for 0 based indices or 2 for 1-based
1 5 2
9 4 2
5 9 6

2 for 0 based or 10 for 1 based
 0 3  0  4
 0 4  1  4
 4 3  1  2
-2 4 -2 -1

11
3 -1 3 3
3 -1 3 1

6 for 0 based or 3 for 1 based
Anecdote
Iverson's answer was ++/(M = ⍳¹ ⨢ ⍳¹)//M, which is neither valid in the Iverson Notation as defined in A Programming Language, nor in what eventually became APL. In Iverson notation, it would have been +/(M = ⍳¹(μ(M)) ⨢ ⍳¹(ν(M)))/M. In the very first versions of APL it was +/(,M=(⍳1↑⍴M)∘.+⍳1↓⍴M)/,M.

MATL, 15 14 10 bytes
3#fbb+y=*s

The input has rows separated by ;. For example: [1 5 2; 9 4 2; 5 9 6]. 1-based indexing is used.
Try it online! Or verify all test cases.
Explanation
I'll use the example with input [3 -1 3 3; 3 -1 3 1] in the explanation.
3#f    % Three-output find: for all nonzero values of implicit input matrix, pushes
       % three column vectors with row indices, column indices, and values
       %   Stack contains: [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4], [3;3;-1;-1;3;3;3;1]
bb     % Bubble up twice: move vectors of row and column indices to top
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4]
+      % Element-wise sum of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6]
y      % Duplicate the vector of nonzero values onto the top of the stack
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6], [3;3;-1;-1;3;3;3;1]
=      % Element-wise equality test of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [0;1;0;0;0;0;0;0]
*      % Element-wise multiply of top two arrays
       %   Stack contains: [0;3;0;0;0;0;0;0]
s      % Sum of array
       %   Stack contains: 3


The absent-minded linguist Background

Your friend, a linguist, has recorded and analyzed some simple conversation snippets in various languages.
Being quite absent-minded, they have forgotten which language each snippet was in.
You must help them by creating a program that analyzes the sentence structures and rules out impossible cases.

Input

Your input is a non-empty string containing the characters SVO, which stand for subject, verb, and object.
It represents a conversation snippet analyzed by the linguist.

Output

Your task is to break the string into sentences, and enter a period . after each sentence.
A sentence contains either a verb, OR a verb and a subject, OR a verb, a subject and an object.
However, you don't know which word order the original language uses; English uses subject-verb-object, but other languages, like Latin, use subject-object-verb.
In fact, all six permutations exist in natural languages, so you must check each of them.

Your output shall contain, in a newline-separated string, each applicable word order, a colon :, and the input string broken into sentences according to that order.
If the string cannot be parsed in some word order, the corresponding line shall be omitted.
The order of the lines does not matter, and it is guaranteed that at least one word order can be parsed.

Example

Consider the input

VSVOSV

In the VOS order, the snipped can be parsed as VS.VOS.V., and in the SVO order, it can be parsed as V.SVO.SV..
The order OSV also works, and the full output is

VOS:VS.VOS.V.
SVO:V.SVO.SV.
OSV:V.SV.OSV.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Regular expressions and all built-ins are allowed.

Test cases

Input:
V
Output:
VSO:V.
VOS:V.
SVO:V.
OVS:V.
SOV:V.
OSV:V.

Input:
SVV
Output:
SVO:SV.V.
SOV:SV.V.
OSV:SV.V.

Input:
VSVOV
Output:
SVO:V.SVO.V.

Input:
VSOVS
Output:
VSO:VSO.VS.
OVS:VS.OVS.

Input:
SVOSV
Output:
SVO:SVO.SV.
OSV:SV.OSV.

Input:
VSVOSV
Output:
VOS:VS.VOS.V.
SVO:V.SVO.SV.
OSV:V.SV.OSV.

Input:
VSVVSOVSV
Output:
VSO:VS.V.VSO.VS.V.
OVS:VS.V.VS.OVS.V.
SOV:V.SV.V.SOV.SV.

Input:
SVVSVSOVSVV
Output:
SOV:SV.V.SV.SOV.SV.V.

Input:
VSOVSVSOVSVVS
Output:
VSO:VSO.VS.VSO.VS.V.VS.
OVS:VS.OVS.VS.OVS.V.VS.

JavaScript (ES7), 172 bytes
x=>[for(i of"V(SO?)?0V(O?S)?0(SVO?|V)0(O?VS|V)0(SO?)?V0(O?S)?V".split(0))if((y=x.match(RegExp(i,"g"))).join``==x)i.match(/\w/g).slice(0,3).join``+":"+y.join`.`+"."].join`
`

Could probably be golfed further. Suggestions welcome!


Convert short month names to their longer counterparts [Ended] This challenge has ended! Congratulations Flonk!

I was sure I would get a good grade, but after turning in Flonk's my work, my professor did not believe it was mine and also could not understand why it was so complicated... I failed and my mom grounded me from Facebook and Minecraft for a month. I don't understand. :(

Thanks for all your submissions! Some great answers here. The official winner is Flonk with a score of 64. The top 5 are:

Flonk, 64 (Haskell, with efficient maths!)
DigitalTrauma, 40 (The cloud, the future is now)
primo, 38 (Python, and my personal favorite - and very professional much!)
Sylwester, 20 (Racket, although Janember is stretching it!)
ilmale, 16 (A highly optimized algorithm in Lua)

Original challenge below.

Please help me, it's very urgent!!! :(

I need to convert shortened versions of month names to their longer representations (e.g "Dec" -> "December"), case-insensitive. Right now I'm using Java; the month's name is a String and I would rather not convert it to a Date object first. Any language will do, though.

Is there an easy way to do this?? Go easy please I am a newbie to programming!

This is a code trolling popularity contest (the best kind there is!). The answer with the most upvotes on Apr 8, 2014 wins.

It's really simple with a little polynomial interpolation!

First, I looked at the list of short month names

["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]

and checked the sum of their characters ASCII values

[313,301,320,323,327,333,331,317,328,326,339,300]

then subtracted 300 from those to get a grasp of what I'm dealing with here, and prepared an Array that contains all the longer versions of the months' names.

[13,1,20,23,27,33,31,17,28,26,39,0]
mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

I guess you can see what's going on now - all I need is a function getIndex that maps 13 to 0, 1 to 1, 20 to 2, and so on, so I can simply do

getMonthName shortname = mons !! (getIndex shortname)

Luckily, Wolfram|Alpha can do this for me! The numbers get a bit large, but Haskell can handle that with grace. We just need to make sure to round the results, because floating-point-arithmetic is a little imprecise!
So there you go, fast, elegant, and idiomatic Haskell:

import Data.Char

getIndex x = round $ 11 -
    (220797068189915461*x)/11644212222720 +
    (184127469431441671621*x^2)/6982771136140800 -
    (8800438195450444577647153*x^3)/1013060436431307264000 +
    (2826703553741192361967823*x^4)/2026120872862614528000 -
    (269098602165195540339443*x^5)/2026120872862614528000 +
    (13744405529566098359*x^6)/1692665725031424000 -
    (13060656886070844161*x^7)/39727860252208128000 +
    (5939638907108115199*x^8)/675373624287538176000 -
    (303426664924585177*x^9)/2026120872862614528000 +
    (2983240583426137*x^10)/2026120872862614528000 -
    (12901227927103*x^11)/2026120872862614528000

mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
getMonthName = (mons!!).getIndex.subtract 300.fromIntegral.sum.fmap (ord.toLower)

Run it simply like this:

λ> getMonthName "DeC"
"December"

λ> getMonthName "jan"
"January"


All primes from 0 to 1000 Is it possible to make this C code smaller? It prints out all primes from 0 to 1000.

C, 89 chars

int i,p,c;for(i=2;i<1e3;i++){c=0;for(p=2;p<i;p++)if(i%p==0)c++;if(c==0)printf("%u\n",i);}

67 bytes
In C there's no real alternative to trial division, but it can certainly be golfed a bit.
for(int p=1,d;p++<999;d&&printf("%d\n",p))for(d=p;--d>1;)d=p%d?d:1;

Requires C99 initial declarations, which saves 1 byte.


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

Avoid sub literals. In many cases, you can simply use {} for code blocks. For example, don't write the following code.

sub ($a){$a*2}

Instead, use blocks syntax. This also lets you to use $_, @_, and %_ placeholder variables, if you only need a single variable. If you need more, you can use $^a, $^b variables, and so on.

{$_*2}

Also, in certain rare cases, it's possible to use whatever code (especially when you have simple expressions). The * replaces the placeholder argument.

* *2


Egg hunting in Collatz style Inspired by The Great API Easter Egg Hunt!
Summary
Your task is to search for a predetermined integer in the "Collatz space" (to be explained later) using the fewest step possible.
Introduction
This challenge is based on the famous Collatz conjecture that hopefully everyone here at least heard of. Here is a recap taken from Print the Super Collatz numbers.

The Collatz
Sequence (also
called the 3x + 1 problem) is where you start with any positive
integer, for this example we will use 10, and apply this set of steps
to it:
if n is even:
    Divide it by 2
if n is odd:
    Multiply it by 3 and add 1
repeat until n = 1

The Collatz distance C(m,n) between the two numbers m and n, for the purpose of this challenge, is the distance between two numbers in the Collatz graph(Credits to @tsh for telling me about this concept), which is defined as follows: (using 21 and 13 as examples):
Write down the Collatz sequence for m (in this case, 21):
21, 64, 32, 16, 8, 4, 2, 1

Write down the Collatz sequence for n(in this case, 13):
13, 40, 20, 10, 5, 16, 8, 4, 2, 1

Now count how many numbers appear only in one of the sequences. This is defined as the Collatz distance between m and n. In this case, 8, namely,
21, 64, 32, 13, 40, 20, 10, 5

So we have Collatz distance between 21 and 13 as C(21,13)=8.
C(m,n) have the following nice properties:
C(m,n)=C(n,m)
C(m,n)=0 iff. m=n

Hopefully the definition of C(m,n) is now clear. Let's start doing egg hunting in the Collatz space!
At the beginning of the game, a controller decides the position of an easter egg, which is expressed by its one-dimensional coordinate: An integer in the interval [p,q] (in other words, an integer between p and q, both ends inclusive).
The position of the egg remains constant throughout the game. We'll denote this coordinate as r.
You can now make an initial guess a0, and it will be recorded by the controller. This is your 0th round. If you are so lucky that you got it right at the first place (i.e. a0=r), the game ends, and your score is 0(The lower the score, the better). Otherwise, you enter the 1st round and you make a new guess a1, this goes on until you got it right, i.e. an=r, and your score will be n.
For each round after the 0th, the controller gives you one of the following feedbacks so that you can make a better guess based on the information given. Lets assume you are currently at the nth round and hence your guess is an

"You found it!" if an=r, in which case the game ends and you score n.
"You are closer :)" if C(an,r)<C(an-1,r)
"You are circling around the egg" if C(an,r)=C(an-1,r)
"You are farther away :(" if C(an,r)>C(an-1,r)

To save some bytes, I will call the responses as "Right", "Closer", "Same", "Farther", in the order presented above.
Here is an example game with p=1,q=15.

a0=10
a1=11, response: "Closer"
a2=13, response: "Farther"
a3=4, response: "Farther"
a4=3, response: "Closer"
a5=5, response: "Same"
a6=7, response: "Right"

Score: 6.
Challenge
Design a deterministic strategy to play the game for p=51, q=562 with the best score.
Answers should describe the algorithms in detail. You can attach any code that helps to elucidate the algorithm. This is not codegolf so you are encouraged to write legible code.
Answers should include the worst score they may achieve for all possible cases of r, and the one with lowest worst score wins. In the case of tie, the algorithms that has a better average score for all possible rs (which should also be included in the answers) win. There are no further tie breakers and we may have multiple winners in the end.
Specs

To reiterate, r lies in the interval [51,562].
Default loopholes apply.

Bounty (Added after the first answer is posted)
I may personally offer a bounty to an answer where all the guesses are made within the range [51,562] while still having a reasonably low worst score.

Ruby, 196

This was way harder that I initially thought. I had to handle a lot of obscure cases and ended up with a lot of ugly code. But is was a lot of fun! :)

Strategy

Every Collatz Sequence ends up with a sequence of powers of 2 (ex: [16, 8, 4, 2, 1]). As soon as a power of 2 is encountered, we divide by 2 until we reach 1. Let's call the first power of 2 in a sequence closest pow2 (as this is also the closest power of 2 to our number using Collatz Distance). For the given range (51-562), all the possible closest pow2 numbers are: [16, 64, 128, 256, 512, 1024]

Short version

The algorithm performs:

a binary search to figure out the closest power of 2 to the current number
a linear search to figure out every previous element in the sequence until the target number is discovered.

Detailed version

Given a game with the target number r, the strategy is the following:

Use binary search to figure out the power of 2 that is closest to r in as few steps as possible.
If the closest power of 2 that was found is the solution, stop. Otherwise continue to 3.
Since the power of 2 that was found is the first power of 2 occurring in the sequence, if follows that that value was reached by doing a (* 3 + 1) operation. (If it came after a /2 operation, then the previous number would also have been a power of 2). Compute the previous number in the sequence by doing the reverse operation (-1 and then /3)
If that number is the target, stop. Otherwise continue to 5.
Given the current number known from the sequence, it is needed to go back and discover the previous number in the sequence. It is not known whether the current number was arrived at by a (/2) or (*3 +1) operation, so the algorithm tries them both and sees which one yields a number that is closer (as Collatz Distance) from the target.
If the newly discovered number is the right one, stop.
Using the newly discovered number, go back to step 5.

The results

Running the algorithm for all the numbers in the 51-562 range takes around a second on a normal PC and the total score is 38665.

The code

Try it online!

require 'set'

# Utility methods
def collatz(n)
  [].tap do |results|
    crt = n
    while true
      results << crt
      break if crt == 1
      crt = crt.even? ? crt / 2 : crt * 3 + 1
    end
  end
end

def collatz_dist(m, n)
  cm = collatz(m).reverse
  cn = collatz(n).reverse
  common_length = cm.zip(cn).count{ |x, y| x == y }
  cm.size + cn.size - common_length * 2
end

GuessResult = Struct.new :response, :score
# Class that can "play" a game, responding
# :right, :closer, :farther or :same when
# presented with a guess
class Game

  def initialize(target_value)
    @r = target_value
    @score = -1
    @dist = nil
    @won = false
  end
  attr_reader :score

  def guess(n)
    # just a logging decorator over the real method
    result = internal_guess(n)
    p [n, result] if LOGGING
    result
  end

  private

  def internal_guess(n)
    raise 'Game already won!' if @won
    @score += 1
    dist = collatz_dist(n, @r)
    if n == @r
      @won = true
      return GuessResult.new(:right, @score)
    end
    response = nil
    if @dist
      response = [:same, :closer, :farther][@dist <=> dist]
    end
    @dist = dist
    GuessResult.new(response)
  end

end

# Main solver code

def solve(game)
  pow2, won = find_closest_power_of_2(game)
  puts "Closest pow2: #{pow2}" if LOGGING

  return pow2 if won
  # Since this is the first power of 2 in the series, it follows that
  # this element must have been arrived at by doing *3+1...
  prev = (pow2 - 1) / 3
  guess = game.guess(prev)
  return prev if guess.response == :right

  solve_backward(game, prev, 300)
end

def solve_backward(game, n, left)
  return 0 if left == 0
  puts "***      Arrived at  ** #{n} **" if LOGGING
  # try to see whether this point was reached by dividing by 2
  double = n * 2
  guess = game.guess(double)
  return double if guess.response == :right

  if guess.response == :farther && (n - 1) % 3 == 0
    # try to see whether this point was reached by *3+1
    third = (n-1) / 3
    guess = game.guess(third)
    return third if guess.response == :right
    if guess.response == :closer
      return solve_backward(game, third, left-1)
    else
      game.guess(n) # reset to n...
    end
  end
  return solve_backward(game, double, left-1)
end

# Every Collatz Sequence ends with a sequence of powers of 2.
# Let's call the first occurring power of 2 in such a sequence
# POW2
#
# Let's iterate through the whole range and find the POW2_CANDIDATES
#
RANGE = [*51..562]
POWERS = Set.new([*0..15].map{ |n| 2 ** n })

POW2_CANDIDATES =
  RANGE.map{ |n| collatz(n).find{ |x| POWERS.include? x} }.uniq.sort
# Turns out that the candidates are [16, 64, 128, 256, 512, 1024]

def find_closest_power_of_2(game)
  min = old_guess = 0
  max = new_guess = POW2_CANDIDATES.size - 1
  guess = game.guess(POW2_CANDIDATES[old_guess])
  return POW2_CANDIDATES[old_guess], true if guess.response == :right
  guess = game.guess(POW2_CANDIDATES[new_guess])
  return POW2_CANDIDATES[new_guess], true if guess.response == :right
  pow2 = nil

  while pow2.nil?

    avg = (old_guess + new_guess) / 2.0

    case guess.response
    when :same
      # at equal distance from the two ends
      pow2 = POW2_CANDIDATES[avg.floor]
      # still need to test if this is correct
      guess = game.guess(pow2)
      return pow2, guess.response == :right
    when :closer
      if old_guess < new_guess
        min = avg.ceil
      else
        max = avg.floor
      end
    when :farther
      if old_guess < new_guess
        max = avg.floor
      else
        min = avg.ceil
      end
    end

    old_guess = new_guess
    new_guess = (min + max) / 2
    new_guess = new_guess + 1 if new_guess == old_guess
    # so we get next result relative to the closer one
    # game.guess(POW2_CANDIDATES[old_guess]) if guess.response == :farther
    guess = game.guess(POW2_CANDIDATES[new_guess])

    if guess.response == :right
      pow2 = POW2_CANDIDATES[new_guess]
      break
    end

    if min == max
      pow2 = POW2_CANDIDATES[min]
      break
    end

  end

  [pow2, guess.response == :right]

end

LOGGING = false

total_score = 0
51.upto(562) do |n|
  game = Game.new(n)
  result = solve(game)
  raise "Incorrect result for #{n} !!!" unless result == n
  total_score += game.score
end
puts "Total score: #{total_score}"


Multiples of 67 in a constructed array of arrays? A triangle-shaped table is constructed such the first row is "1, 3, 5, 7, ..., 99"

Each subsequent row has the following properties:

One less element than the row above
Each element is the sum of the two elements above it

Like so:

1   3   5    7    9    11 ....
  4   8   12   16   20 ....
    ...............

This continues until the last row with one element.

How many elements are divisible by 67?

Fewest lines, chars, or whatever may win.  Depends on ingenuity.

EDIT: the answer is 17 but you have to prove it.

ADDENDUM:
I have three-line python code for this but try to beat it:

a = [[2*i+1 for i in range(50)]]
while len(a[-1])>1:a.append([a[-1][i]+a[-1][i+1] for i in range(len(a[-1])-1)])
print len([i for b in a for i in b if i%67==0])

Haskell - 86 chars

98 → 92: Use list comprehensions and sum instead of filter and length.

92 → 86: Convert nested list comprehensions into one, and change ==0 to <1 (thanks st0le).

f s=zipWith(+)s$tail s
main=print$sum[1|r<-take 50$iterate f[1,3..99],n<-r,n`mod`67<1]

Ungolfed:

initialRow :: [Integer]
initialRow = [1,3..99]

nextRow :: (Num a) => [a] -> [a]
nextRow xs = zipWith (+) xs (tail xs)

triangle :: [[Integer]]
triangle = takeWhile (not . null) $ iterate nextRow initialRow

main = print $ length $ filter ((== 0) . (`mod` 67)) $ concat triangle


Print a letter Fibonacci Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

a
b

Next, add the two lines.

a
b
ab

Keep adding the last two lines.

a
b
ab
bab

Keep going...

a
b
ab
bab
abbab

And we're done.

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

Python 2, 41 bytes

Saved 3 bytes thanks to @xnor

a,b="ab";exec"print a;a,b=b,a+b;"*input()

Test on Ideone

Simply follows the recursive definition.


Fridge magnet substitution When writing a message with fridge magnets, you'll often find yourself substituting a 1 for an I. In this challenge, your goal is to find out if a message can be written using the letters of another message. The allowed substitutions are:

A = 4
B = 8
C = U
E = M = W = 3
G = 6 = 9
I = 1
L = 7
N = Z
O = 0
R = 2
S = 5

For example, the message CIRCA 333 can be rearranged to spell ICE CREAM, where the first two 3s are rotated 180 degrees to make two Es, and the last 3 is rotated 90 degrees counterclockwise to make an M. Whitespaces can be included in the messages, but they should not be accounted for in your solution, as they're made by placing the magnets on the fridge.

Input

Two strings (or character arrays). All messages will match ^[A-Z0-9 ]+$

Output

Truthy if the two input strings are valid rearrangements of each other, falsey otherwise.

Examples

["CIRCA 333", "ICE CREAM"] => true
["DCLV 00133", "I LOVE CODE"] => true
["WE ARE EMISSARIES", "33   423    3315542135"] => true
["WE WANT ICE CREAM", "MET CIRCA 334 MEN"] => true
["I HAVE ICE CREAM", "HAVE 2 ICE CREAMS"] => false

More thruthy examples

These are all the 15+ letter words that map to another word. Some are trivial substitutions, but I included all that I found.

["ANTHROPOMORPHISE","ANTHROPOMORPHISM"]
["ANTIPHILOSOPHIES","ANTIPHILOSOPHISM"]
["CIRCUMSTANTIALLY","ULTRAMASCULINITY"]
["DECENTRALIZATION","DENEUTRALIZATION"]
["DIMETHYLNITROSAMINE","THREEDIMENSIONALITY"]
["INSTITUTIONALISE","INSTITUTIONALISM"]
["INTERCRYSTALLINE","INTERCRYSTALLIZE"]
["INTERNATIONALISE","INTERNATIONALISM"]
["OVERCENTRALIZATION","OVERNEUTRALIZATION"]
["OVERCENTRALIZING","OVERNEUTRALIZING"]
["PREMILLENNIALISE","PREMILLENNIALISM"]
["TRANSCENDENTALIZE","TRANSCENDENTALIZM"]

As this is a code golf challenge, the shortest solution wins! I will accept the shortest solution in 7 days from posting. Happy golfing!

Sample solution, non-golfed

Related

My daughter's alphabet
Foam bath letters

EDIT: Made an error in the substitutions, had G = 6 and 6 = 9 as separate substitutions, merged them into one.

Python 2, 145 131 130 129 125 bytes

lambda*a:all(len({sum(map(w.count,x))for w in a})<2for x in'A4 B8 CU EMW3 G69 I1 L7 NZ O0 R2 S5'.split()+list('DFHJKPQTVXY'))

Try it online!

Alt:

Python 2, 125 bytes

lambda*a:len({(x,sum(map(w.count,x)))for x in'A4 B8 CU EMW3 G69 I1 L7 NZ O0 R2 S5'.split()+list('DFHJKPQTVXY')for w in a})<23

Try it online!


Quine multiple times Your task is make program that do following:

You should take number. (Positive, negative, fraction is possible input)
If it is negative, you reverse the quine. and negate that number (Become positive)
Then you repeat <integer part of the input number> times and print first <floor(fraction part of the input number*length)> from your source program. If it is integer, then the fraction part is zero.

-10% bonus if your program isn't palindrome.

Example

If your program is "ABCDEFG", then

1.

5
ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFG

Explanation

  ABCDEFG five times

2.

-2
GFEDCBAGFEDCBA

Explanation

  GFEDCBA (reversed ABCDEFG) 2 times

3.

7.5
ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABC

Explanation

  ABCDEFG 7 times followed by ABC (first 3(floor(0.5*7)=floor(3.5)=3) letter on ABCDEFG)

4.

-0.3
GF

Explanation

  GFEDCBA (reversed ABCDEFG) 0 times followed by GF (first 2(floor(0.3*7)=floor(2.1)=2) letter on GFEDCBA(reversed ABCDEFG))

5.

0
<empty>

Explanation:

  <empty> here means that your program doesn't output. It is ABCDEFG zero times that is defined as empty string.

CJam, 28 26 bytes * 0.9 = 23.4

Thanks to Sp3000 for saving 2 bytes.

{`"_~"+rd_z26*,\g1|@%f=}_~

Test it here.

Explanation

{`"_~"+ e# Generalised quine framework. Leaves the source code on the stack.
  rd    e# Read input and parse as double.
  _z    e# Copy and get absolute value.
  26*   e# Multiply by 26, the length of the quine to get length N of the output.
  ,     e# Get a range [0 1 ... floor(N-1)].
  \g    e# Swap with other copy and computer signum to determine direction of string.
  1|    e# This might be zero though, so take bitwise OR with 1 to avoid an error.
  @%    e# Pull up source string. Reverse it if the signum was -1 (no-op otherwise).
  f=    e# The range we pushed earlier corresponds to the (cyclic) indices of the source
        e# which make up the desired result, so we map each index to the corresponding
        e# character to get the final result.
}_~