Ruby 161 145

Reads the tabstop specification on the first line of input.

i=t=[]
gets.scan(/(\+)?(\d+)/){t<<i=$2.to_i+($1?i:0)}
81.times{|j|t<<j*i}
while gets
$_.sub!$&," "*(t.find{|s|s>i=$`.size}-i)while~/\t/
print
end

edit: Added two lines that makes the last read tabstop repeat so that tabstop specifications of a single number also works correctly

i is a temporary variable for holding the last parsed tabstop. t is the list of tabstobs, parsed from the gets.scan line. For good measure we add 81 multiples of the last parsed tabstop. the while gets loop keeps going until there is no more input. For each line of input we substitute tabs for spaces, one tab at the time because the string moves as we add the spaces and we must recalculate the correct tabstop.


Recover boolean cells from windowed sums

Jelly, 23 18 bytes
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€

Try it online!
-5 bytes thanks to @Jonathan Allan
Uses [0,1] as ?, [0] as 0, and [1] as 1.
How?
Brute force of all possible boolean matrices.
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€
   Ø.               # [0,1]
     ṗ              # Cartesian power:
L+’                 # Length of answer = length of sums + k - 1
           Ƈ          # Filter by:
      +⁴\⁼¥             # n-wise overlapping sums are equal to
            ⁸           # the given sums
             Z      # Get the lists of all possibilities for each position (some binary list)
              Ṣ€    # Sort each possibility list (0s then 1s)
                Q€  # Take unique entries from every possibility ([0],[1],or [0,1])


Build a program that creates a minimal one-ohm resistor diagram for a given resistance

For series-parallel circuits with few resistors, the resistances which can be created with n resistors but not with fewer are the numbers on the nth level of the Stern-Brocot tree. (This breaks later on, with 5/6 = 1/2 + 1/3 apparently a minimal counterexample).

Instead of mapping from position in the Stern-Brocot tree to an S-P expression, it turns out to be much more convenient to use the Calkin-Wilf tree; its nodes at a given depth are permutations of the Stern-Brocot tree's nodes at that depth, but it has a different parent-child relationship: the left child of m/n is m/(m+n) = (1^-1 + (m/n)^-1)^-1 = P(1, m/n), and the right child of m/n is (m+n)/n = 1 + m/n = S(1, m/n).

GolfScript

# Parse input
'/'/' '*~
# Stack: numerator denominator
{
    # numerator denominator
    1$1$<{
        # n/d is less than 1, so parent is n/(d − n) and we're looking at Parallel
        ', P('@@.2$/@@1$%
        # ', P(' d/n n d%n
    }{
        # n/d >= 1, so parent is (n - d)/d and we're looking at Series
        ', S('@@1$1$/@2$%@
        # ', S(' n/d n%d d
    }if
    # Loop until we get to 0/1 or 1/0
    1$1$*
}do;;
# Stringify
]''*
# Trim leading ', '
2>.
# Close the parentheses
'('/,(')'*+
# Add the boilerplate
'1
0 1 '\'
0 1'


C (gcc), 172 bytes

So, I shaved off a whopping 6 bytes off of this thing with some quite ridiculous trickery. Compile with -DK=!sleep(2)-putchar(rand()%2?33:46)/46. Depends on the sleep() function being defined in the system standard libraries.
Does not loop or recurse.

p(n){puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");printf("\nSuccess rate is %i percent (%i/5)",n*20,n=K+K+K+K+K);}

Try it online!

Explanation

This solution depends on three critical implementation/runtime details. First, the sleep() must not be interrupted, via e.g. a signal. Second, the additions and subtractions being resolved in order from left-to-right. Third, the arguments to printf() must be resolved right-to-left.

With that out of the way, let's sort through this thing.

p(n){ // Unfortunately, I need a variable to store the RNG result.
    // This is straight-forward printing of a line.
    puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");
    // So, resolving right-to-left, we have a) the K preprocessor macros,
    // b) the assigment of their sum to n, c) the percentage equivalent of
    // the fraction n/5 and d) a constant format string.
    // The summation of the K's is where the magic happens.
    printf("\nSuccess rate is %i percent (%i/5)",n*20,n=K+K+K+K+K);
}

The compiler argument

-DK=!sleep(2)-putchar(rand()%2?33:46)/46

So, starting from the left (i.e. like it should resolve), we have sleep().
sleep() returns the number of seconds left when it returns,
so we expect the user (and other processes) to be kind and to not interrupt our sleep. We take the logical complement, and because
in our case sleep() will always return 0, the result is 1. More on the
significance later.

Next, we enter putchar(). putchar() prints a single 1-byte character,
and returns the value of the byte. So, we get a random value inside,
compute modulo-2 for a nice 50-50 split (albeit with horrible entropy),
and then ternary-conditional it into our desired characters - ! (33)
and . (46). Then we divide the return value of putchar() with 46.

Now, that division will return 0 for ! and 1 for . - so we take 1 (from !sleep()) and subtract the result of the division from that. Presto!

Okay, there's a slight problem. When you write things to a buffer in C (i.e. stdout), it doesn't necessarily write to the receiving end immediately. In fact, when I was running this on my distro of choice, I discovered that it would only print the pings after the program terminated. However, given that all the other solutions in C are letting that slide, and that there probably exists at least one machine out there somewhere does that and fulfills all the other prerequisites (and one could always just "fix" that in the kernel...), I'm not going to mess with my score by fflush()ing stdout.


Javascript 70 68

Building from @grc's answer:

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

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

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

input:

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

output:

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

Update: -2 characters, thanks @copy


Determining the continued fractions of square roots

GolfScript (66 60 chars)

~:^,{.*^>}?(:?';'[1?{^1$.*-@/?@+.2$/@@1$%?\- 1$(}do;;]','*1$

Warning: most of the ? in there are the variable representing floor(sqrt(input)) rather than the builtin. But the first one is the builtin.

Takes input on stdin and outputs to stdout.

Psuedocode of the algorithm (proof of correctness currently left as an exercise for the reader):

n := input()
m := floor(sqrt(n))
output(m)
x := 1
y := m
do
  x := (n - y * y) / x
  output((m + y) / x)
  y := m - (m + y) % x
while (x > 1)

Yet again I find myself wanting a single operator which takes a b on the stack and leaves a/b a%b on the stack.


C, 82 bytes

p(n,a,b,c,r){c=0;for(b=1;++b<n-2;c+=r==n)for(a=n,r=0;a>0;a/=b)r=r*b+a%b;return!c;}

Ideone it!

Explanation

This code reverses n in base b and stores in r:

for(a=n,r=0;a>0;a/=b)r=r*b+a%b;

The outer loop counts the number of bases from 2 to n-1 in which n is a palindrome.

If n is non-palindromic, the count would be 1 (n must be a palindrome in base n-1).


Jelly, 17 14 bytes

ċⱮ6Ḣ©+$®aĖUṀ)M

Try it online!

A monadic link that takes a list of the two lists as its argument and returns [1] for player 1 wins, [2] for player 2 wins and [1, 2] for a tie. TIO link tidies this up for display.

Thanks to @JonathanAllan for saving 3 bytes!

Explanation

            )   | For each input list (e.g. of one list 1,1,3,3,4)
ċⱮ6             | - Count each of 1..6 (e.g. 2,0,2,1,0,0)
      $         | - Following as a monad:
   Ḣ            |   - Head (number of 1s)
    ©           |   - Copy to register
     +          |   - Add (e.g. 2,4,3,0,0)
       ®a       | - Register logical and with this
         Ė      | - Enumerate (e.g. [1,2],[2,4],[3,3],[4,0],[5,0])
          U     | - Reverse each (e.g. [2,1],[4,2],[3,3],[0,4],[0,5])
            Ṁ   | - Max (e.g. 4,2)
              M | Index/indices of maximal score


Create a chain of spam generators in as many languages as possible

PHP 5.5 -> Ruby 2.0 -> Python 2.7 -> Lua -> C# -> Java -> PdfTeX -> GolfScript 855 / 8^2 = 13.359375

The main ideas were:

Instead of actually creating the logic to create the n+1th language in all programming languages do this only one time, and only use the basic random and stdout writing facilities of each programming language
To shorten the template generator, just compress it with zLib. Make this generator the second language
Use PHP as the first language, as it has built-in zLib decompressor

So the initial code is:

<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\[(.*?)\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x).gzuncompress("BINARY_DATA")."__END__\n".$x;

Where BINARY_DATA is the gzcompressed version of the template generator (e.g. the result of the php code, which is the ruby version)

The complete initial code in base64 (should be 855 bytes after decoding):

PD9waHAgJHg9ZmlsZV9nZXRfY29udGVudHMoInBocDovL3N0ZGluIik7ZWNobyBw
cmVnX3JlcGxhY2VfY2FsbGJhY2soIi9cWyguKj8pXF0vIixmdW5jdGlvbigkbSl7
JHI9ZXhwbG9kZSgiLyIsJG1bMV0pO3JldHVybiAkclthcnJheV9yYW5kKCRyKV07
fSwkeCkuZ3p1bmNvbXByZXNzKCJ42o2UwXKbMBCG7zyFZj0doElV55BLiNJmmump
7aHpTA+Yg4xErA6SGCQSZ4jevZIBx3biTHywzO6y/7+fYRm5uf5zjVtOGS5XWjbY
NLWwSZzHKVx4OTa06Z/oE51iRZw6XFzV1FquXiQ/+2TEMKflKsSbViiLfFx4OTbK
puYuajpr0OUlBDmIoqrVErVUMX8I2ejWXCIvL0oejVfm0USznk0y4Fx4YWaxsUx3
Fj+0wvJkKE9mPcVCmYaX1qUpuI+wUODlgvzwjeI4XHg5NtSu8CBnOGeJNthcbsmT
NN0ToWSnHbatx1DEp3Hv/GyZ0KMyzXfaJWen4Z6aqzu7cmmRZvseknQ8c0JyT2FZ
ixKVNTUGUdRPAWOp9ce9Fgz9pEIlqc/dPhrLJf49UGqJ4g9oL1x4OTak2a79Jfl0
JXs5eiHk7AuM5d+0Mrrm+O/G/8zXVKI19hlcXAYXICqUtPgXX9sb7V15OJdzfJ72
R3uYlah2ezheG97DyTKXxQk4D1wiW+YUs64pJiRceGFm9fohFA+THM19hTd5ycDr
1nrId3mBaHtnArx/9J7izop6n99h+N0Iw4M3/JELeAlwATsIlUf4vdbUHhA8bLHP
L7R4P8FtXHhhZloNI6wJUMjeGGS0fIFgMX5EpTp5Pp9fTYGGVZ0SlW4l4/eCWn42
n8/R1qqb6oJLNLmcgpXwbtdkjU1XXHg5Ntn0RlxcvULQW17AYnsj4xWafuvG+lEc
6mf9dnD3IVQHvgjgDQxceDAwLyi8audAq3e+MR3g+O7gXHgwMJ4fxgPMR1TZ8zLc
yiDIw17YJFx4OTZPEPuBXFwMG4FiZ2GEJUJceDAw+dHiEB1cXIx1x4zAdoTlI98U
uciNR1QQ4ndQ5HdeFFZt9B9+DwFHIikuIl9fRU5EX19cbiIuJHg7

Let's go through all of the languages with the test input string [Thank you/Wow/Great], this is [awesome/wonderful].

PHP

$ cat ti2 | php a.php
Great, this is wonderful.
d=DATA.read.chomp.split('[').map{|a|a.split(']')}.flatten.map{|a|a.split('/')}
d.each{|a|print a.sample}
puts <<"DATA"

from random import choice
import sys
#{d.map{|a|"sys.stdout.write(choice(#{a.inspect}))"}*"\n"}
print
print '''math.randomseed(os.time())
#{d.map{|a|"a=#{a.inspect.tr('[]','{}')};io.write(a[math.random(1,#{a.length})]);"}*"\n"}
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
#{d.map{|a|b=->m{m.length==1?"System.Console.Write(#{m.first.inspect});":"if (r.NextDouble()<0.5){System.Console.Write(#{m.shift.inspect});}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
#{d.map{|a|b=->m{m.length==1?"System.out.print(\"#{m.first.inspect}\");":"if (r.nextFloat()<0.5){System.out.print(\"#{m.shift.inspect}\");}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.out.println();
#{x="a";d.map{|a|b=->m{m.length==1?m.first: "\\\\\\\\ifnum500>\\\\\\\\pdfuniformdeviate1000 #{m.shift}\\\\\\\\else "+b[m]+"\\\\\\\\fi"};x=x.succ;a.length>1?"System.out.println(\"\"\\\\\\\\def \\\\\\\\opt#{x} {#{b[a.dup]}}%\"\");": ""}*"\n"}
System.out.println(""#{x="a";d.map{|a|x=x.succ;a.length>1?"\\\\\\\\opt#{x}{}": a.first}*""}"");
System.out.println();
System.out.println(""#{d.map{|a|a.length>1? "[#{a.map{|b|"'#{b}'"}*""}]#{a.length}rand=" : "'#{a.first}'"}*""}"");
System.out.println(""\\\\\\\\bye"");
}
}");
}
}
]==]);
'''
DATA
__END__
[Thank you/Wow/Great], this is [awesome/wonderful].

Ruby

$ ruby a.rb
Great, this is awesome.
from random import choice
import sys
sys.stdout.write(choice(["Thank you", "Wow", "Great"]))
sys.stdout.write(choice([", this is "]))
sys.stdout.write(choice(["awesome", "wonderful"]))
sys.stdout.write(choice(["."]))
print
print '''math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\\\def \\\\optb {\\\\ifnum500>\\\\pdfuniformdeviate1000 Thank you\\\\else \\\\ifnum500>\\\\pdfuniformdeviate1000 Wow\\\\else Great\\\\fi\\\\fi}%"");

System.out.println(""\\\\def \\\\optd {\\\\ifnum500>\\\\pdfuniformdeviate1000 awesome\\\\else wonderful\\\\fi}%"");

System.out.println(""\\\\optb{}, this is \\\\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\\\bye"");
}
}");
}
}
]==]);
'''

Python

$ python a.py
Great, this is wonderful.
math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}
]==]);

Lua

$ lua a.lua
Great, this is wonderful.
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}

C#

$ mcs a.cs
$ mono a.exe
Thank you, this is wonderful.
class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print("Thank you");}else{if (r.nextFloat()<0.5){System.out.print("Wow");}else{System.out.print("Great");};};
System.out.print(", this is ");
if (r.nextFloat()<0.5){System.out.print("awesome");}else{System.out.print("wonderful");};
System.out.print(".");
System.out.println();
System.out.println("\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%");

System.out.println("\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%");

System.out.println("\\optb{}, this is \\optd{}.");
System.out.println();
System.out.println("['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'");
System.out.println("\\bye");
}
}

Java

$ javac a.java
$ java a
Wow, this is wonderful.
\def \optb {\ifnum500>\pdfuniformdeviate1000 Thank you\else \ifnum500>\pdfuniformdeviate1000 Wow\else Great\fi\fi}%
\def \optd {\ifnum500>\pdfuniformdeviate1000 awesome\else wonderful\fi}%
\optb{}, this is \optd{}.

['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'
\bye

PdfTeX

(the code will be inside a.pdf instead of the stdout. I hope this is still okay)

$ pdftex a.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012)
 restricted \write18 enabled.
entering extended mode
(./a.tex [1{/usr/local/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.ma
p}] )</usr/local/texlive/2012/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.p
fb>
Output written on a.pdf (1 page, 15967 bytes).
Transcript written on a.log.
$ open a.pdf

Result:

In text:

Great, this is wonderful.
['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'

Golfscript

$ ruby golfscript.rb a.gs
Wow, this is awesome.

Notes

It seems PHP is quite forgiving with binary data in string literals, except for hex codes AF and 96. Don't ask why.
I could've probably added perl and C++11 code as well easily (as they both support raw string literals), but 8 is a more round number than 10 :)
The distribution of values is not uniform, as the first element comes more often than later ones. According to comments this should be okay.
The initial code was actually generated using the following PHP 5.5 code. orig.rb is actually the same as the Ruby code without the footer (__END__ and the appended data afterwards)

generator.php:

<?php
$d=file_get_contents('orig.rb');
$dc = gzcompress($d,9);
echo '<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\\[(.*?)\\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x)';
?><?php
echo ".gzuncompress(\"";
for ($i=0;$i<strlen($dc);$i++) {
  switch($dc[$i]) {
  case '"':
    echo "\\\"";break;
  case "\n":
    echo "\\n";break;
  case '\\':
    echo "\\\\";break;
  case "\x00":case "\xaf":case "\x96":
    echo sprintf("\\x%02x",ord($dc[$i]));
    break;
  default:
    echo $dc[$i];
  }
}
echo "\").\"__END__\\n\".\$x;";

(you can potentially use this code to zLib encompress PHP solutions for other challenges)


Jelly, 25 bytes
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h

Try it online! or Try it without #
Jelly, 25 bytes
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K

Try it online! or Try it without ~
How they work
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h - Main link. No arguments
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»     - Pair of compressed strings ["Stack Exchange Chat", " - The Nineteenth Byte"]
                      Ƈ   - Keep those for which the following is True:
                     i ”h - They contain "h"; ["Stack Exchange Chat", " - The Nineteenth Byte"]
                            Smash together and output

“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK»iƇ”h  - Main link. No arguments
“¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK»      - Pair of compressed strings ["Stack Exchange Chat", "^Backets reamyappenzell"]
                     Ƈ    - Keep those for which the following is True:
                    i ”h  - They contain "h"; ["Stack Exchange Chat"]
                            Smash together and output

And the second one:
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K - Main link. No arguments
“¡TƑ9ı2ṆR“¡TḟKY=ɱø~»      - Pair of compressed strings ["Stack Exchange Chat", "- The Nineteenth Byte"]
                     ƑƇ   - Keep those where the following has no effect:
                    t  ⁶  -   Removing spaces from the front and end; ["Stack Exchange Chat", "- The Nineteenth Byte"]
                        K - Join with spaces; "Stack Exchange Chat - The Nineteenth Byte"

“¡TƑ9ı2ṆR“¡TḟKY=ɱø»tƑƇ⁶K  - Main link. No arguments
“¡TƑ9ı2ṆR“¡TḟKY=ɱø»       - Pair of compressed strings ["Stack Exchange Chat", " Backets reamyappenzell"]
                    ƑƇ    - Keep those where the following has no effect:
                   t  ⁶   -   Removing spaces from the front and end; ["Stack Exchange Chat"]
                       K  - Join with spaces; "Stack Exchange Chat"


Python 3, 157 bytes

t=i=0
p=o='PLEASE'
for c in input():i+=1;k=int(f'{ord(c):08b}'[::-1],2);o+=i%4//3*p+f'DO,1SUB#{i}<-#{t-k&255}';t=k
print(f'DO,1<-#{i}{o}DOREADOUT,1DOGIVEUP')

Try it online!
This prints \$n+3\$ instructions, of which \$\left\lfloor \frac{n+5}{4} \right\rfloor\$ are polite. That ratio just barely fits in the \$[1/5, 1/3]\$ politeness interval for all \$n \geq 1\$.
-1 byte thanks to Neil.


JavaScript (Node.js),  55 ... 46  45 bytes
Saved 1 byte thanks to @KevinCruijssen
s=>Buffer(s).map(c=>c^(c^~68174912>>c)&32)+''

Try it online!
How?
The constant \$68174912\$ is a bitmask describing the positions of the vowels:
00000100000100000100010001000000
     v     v     v   v   v
zyxwvutsrqponmlkjihgfedcba`_^]\[

As per the ECMAScript specification, the following expression:
~68174912 >> c & 32

is equivalent to:
~68174912 >> (c % 32) & 32

and therefore evaluates to \$32\$ for a consonant or \$0\$ for a vowel, no matter the case of \$c\$.
Commented
s =>                   // s = input string
  Buffer(s)            // turn s into a buffer
  .map(c =>            // for each ASCII code c:
    c ^                //   change the case if:
      ( c              //     c is not in lower case
        ^              //     XOR
        ~68174912 >> c //     c is a consonant
      ) & 32           //
  ) + ''               // end of map(); coerce back to a string


CJam, 58 bytes

q{As#)},:~4/2fb{(:X8<"><+-.,[]"X={XA<{("+-"X=*}"[-]"?}?o}h

Try it online.

Explanation

q               "Read the input.";
{As#)},         "Remove any extraneous characters (not '0' or '1').";
:~              "Evaluate each character ('0' -> 0, '1' -> 1).";
4/2fb           "Split into groups of 4 (Nameless commands) and numerically
                 evaluate each group as an array of binary digits.";
{               "While command values remain:";
  (:X             "Grab the next command value.";
  8<              "If the command value is less than 8:";
  "><+-.,[]"X=    "Then: It maps directly to a BF command. Look it up.";
  {               "Else:";
    XA<             "If the command value is less than 10:";
    {("+-"X=*}      "Then: It is 8 or 9. Grab the next command value and
                     produce a string of that many copies of '+' if the former
                     command value is 8, or '-' if it is 9.";
    "[-]"?          "Else: It is 11. Produce its translation, '[-]'.";
  }?
  o               "Output the BF translation.";
}h


Find the number of n-by-n (-1, 0, 1) matrices with zero permanent as quickly as possible

Rust, \$A(5) = 186481694371\$ in 0.2 s, \$A(6) = 19733690332538577\$ in 580 s

(Unofficial times on a Core i7-10710U with 6 cores/12 threads.)

src/main.rs

use itertools::Itertools;
use num_integer::gcd;
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::sync::Mutex;

type Count = u64;
type Coeff = i32;

fn sort_scols(n: u32, i: u32, sets: &[u32], state: &[Coeff]) -> Vec<u32> {
    let mut scol_ranks: Vec<u32> = (0..2 * n).map(|scol| (scol >> 1 > i) as u32).collect();
    let mut sorted_scols: Vec<u32> = (0..2 * n).collect();
    let mut scol_descs = vec![vec![]; 2 * n as usize];
    for (set_index, (&set, &coeff)) in sets.iter().zip(state).enumerate() {
        if coeff != 0 {
            for col in 0..n {
                if set & 1 << col != 0 {
                    scol_descs[(col as usize) << 1].push(set_index);
                    scol_descs[(col as usize) << 1 | 1].push(set_index);
                }
            }
        }
    }
    let mut sorted_set_indexes: Vec<_> = (0..sets.len()).collect();
    let mut set_ranks: Vec<u32> = vec![!0; sets.len()];
    let mut set_descs = vec![(0, vec![]); sets.len()];

    while {
        for (&coeff, set_desc) in state.iter().zip(&mut set_descs) {
            set_desc.0 = coeff;
            set_desc.1.clear();
        }
        let mut seen = 0;
        for &scol in &sorted_scols {
            if seen & 1 << (scol >> 1) == 0 {
                seen |= 1 << (scol >> 1);
                if scol & 1 == 0 {
                    for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
                        if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
                            set_desc.1.push(scol_ranks[scol as usize]);
                        }
                    }
                } else {
                    for (&set, set_desc) in sets.iter().zip(&mut set_descs) {
                        if set_desc.0 != 0 && set & 1 << (scol >> 1) != 0 {
                            set_desc.0 = -set_desc.0;
                            set_desc.1.push(scol_ranks[scol as usize]);
                        }
                    }
                }
            }
        }

        let set_index_key =
            |&set_index: &usize| (set_descs[set_index].0.abs(), &set_descs[set_index].1);
        sorted_set_indexes.sort_by_key(set_index_key);
        if sets.len() != 0 {
            let mut next_set_rank = 0;
            set_ranks[sorted_set_indexes[0]] = next_set_rank;
            for (&set_index0, &set_index1) in sorted_set_indexes.iter().tuple_windows() {
                if set_index_key(&set_index0) < set_index_key(&set_index1) {
                    next_set_rank += 1;
                }
                set_ranks[set_index1] = next_set_rank;
            }
        }

        let scol_set_index_key = |scol: u32| {
            let sign = 1 - 2 * (scol & 1) as Coeff;
            let set_ranks = &set_ranks[..];
            let set_descs = &set_descs[..];
            move |&set_index: &usize| (set_ranks[set_index], set_descs[set_index].0 * sign)
        };
        for (scol, scol_desc) in scol_descs.iter_mut().enumerate() {
            scol_desc.sort_by_key(scol_set_index_key(scol as u32));
        }
        let scol_cmp = |&scol0: &u32, &scol1: &u32| {
            scol_ranks[scol0 as usize]
                .cmp(&scol_ranks[scol1 as usize])
                .then_with(|| {
                    scol_descs[scol0 as usize]
                        .iter()
                        .map(scol_set_index_key(scol0))
                        .cmp(
                            scol_descs[scol1 as usize]
                                .iter()
                                .map(scol_set_index_key(scol1)),
                        )
                })
        };
        sorted_scols.sort_by(scol_cmp);

        let mut new_scol_ranks = vec![!0; 2 * n as usize];
        let mut next_rank = 0;
        let mut changed = false;
        new_scol_ranks[sorted_scols[0] as usize] = next_rank;
        for (&scol0, &scol1) in sorted_scols.iter().tuple_windows() {
            if scol_ranks[scol0 as usize] < scol_ranks[scol1 as usize] {
                next_rank += 1;
            } else if scol_cmp(&scol0, &scol1) == Ordering::Less {
                changed = true;
                next_rank += 1;
            }
            new_scol_ranks[scol1 as usize] = next_rank;
        }
        scol_ranks = new_scol_ranks;

        changed
    } {}

    let mut seen = 0;
    sorted_scols.retain(|scol| {
        seen & 1 << (scol >> 1) == 0 && {
            seen |= 1 << (scol >> 1);
            true
        }
    });
    assert_eq!(seen, !(!0 << n));

    sorted_scols
}

fn count(n: u32) -> Count {
    static ERR: &str = "n is too large";
    Count::checked_pow(3, TryFrom::try_from(n * n).expect(ERR)).expect(ERR);
    (1..=Coeff::try_from(n).expect(ERR)).fold(1, |x: Coeff, y| x.checked_mul(y).expect(ERR));

    let mut cur_sets = vec![0];
    let mut cur_set_indexes = vec![0];

    let mut cur_states = HashMap::new();
    cur_states.insert(vec![1], 1);

    for k in 0..n {
        for i in 0..n {
            let keep_set = |&set: &u32| {
                if set.count_ones() == k {
                    !set & !1 << i & !(!0 << n) != 0
                } else {
                    set & 1 << i == 0
                }
            };
            let enlarge_set = |&set: &u32| set.count_ones() == k && set & 1 << i == 0;
            let new_sets: Vec<u32> = cur_sets
                .iter()
                .copied()
                .filter(keep_set)
                .chain(
                    cur_sets
                        .iter()
                        .copied()
                        .filter(enlarge_set)
                        .map(|set| set | 1 << i),
                )
                .collect();
            let mut new_set_indexes = vec![!0; 1 << n];
            for (set_index, &set) in new_sets.iter().enumerate() {
                new_set_indexes[set as usize] = set_index;
            }

            let new_states = Mutex::new(HashMap::new());
            cur_states.into_par_iter().for_each(|(cur_state, count)| {
                for elt in -1..=1 {
                    let mut new_state: Vec<Coeff> = cur_sets
                        .iter()
                        .copied()
                        .zip(&cur_state)
                        .filter(|(set, _)| keep_set(set))
                        .map(|(_, &coeff)| coeff)
                        .chain(
                            cur_sets
                                .iter()
                                .copied()
                                .zip(&cur_state)
                                .filter(|(set, _)| enlarge_set(set))
                                .map(|(set, &coeff)| {
                                    let mut new_coeff = coeff * elt;
                                    if set & !(!0 << i) != 0 {
                                        new_coeff +=
                                            cur_state[cur_set_indexes[set as usize | 1 << i]];
                                    }
                                    new_coeff
                                }),
                        )
                        .collect();

                    let factor = new_state.iter().copied().fold(0, gcd);
                    if factor > 1 {
                        for coeff in &mut new_state {
                            *coeff /= factor;
                        }
                    }

                    let sorted_scols = sort_scols(n, i, &new_sets, &new_state);

                    let new_state: Vec<Coeff> = new_sets
                        .iter()
                        .map(|&set| {
                            let mut permuted_set = 0;
                            let mut sign = 0;
                            for (col, &permuted_scol) in sorted_scols.iter().enumerate() {
                                sign ^= set >> col & permuted_scol & 1;
                                permuted_set |= (set >> col & 1) << (permuted_scol >> 1);
                            }
                            (1 - 2 * sign as Coeff)
                                * new_state[new_set_indexes[permuted_set as usize] as usize]
                        })
                        .collect();

                    *new_states.lock().unwrap().entry(new_state).or_insert(0) += count;
                }
            });

            cur_sets = new_sets;
            cur_set_indexes = new_set_indexes;
            cur_states = new_states.into_inner().unwrap();
        }
    }

    *cur_states.get(&vec![0]).unwrap_or(&0)
}

fn main() {
    for n in 1..=6 {
        println!("{} {}", n, count(n));
    }
}

Cargo.toml

[package]
name = "permanent"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]
edition = "2018"

[dependencies]
num-integer = "0.1.41"
rayon = "1.2.1"
itertools = "0.8.2"

Building and running

$ cargo build --release
$ time target/release/permanent
1 1
2 33
3 7555
4 13482049
5 186481694371
6 19733690332538577
5995.30user 282.67system 9:42.97elapsed 1076%CPU (0avgtext+0avgdata 6479028maxresident)k
0inputs+0outputs (0major+3259222minor)pagefaults 0swaps

How it works

This counts matrices using dynamic programming so we don’t need to enumerate all of them directly.  Basically, the state of a partially filled matrix is represented by the coefficients of an expression for the permanent as a polynomial in the remaining unfilled elements.  Specifically, it corresponds to a partial execution of the following algorithm for calculating the permanent:

\$\operatorname{perm} A = c_{\{0, 1, \dotsc, n - 1\}}\$, where \$c_\varnothing = 1\$, \$c_S = \sum_{i \in S} c_{S \smallsetminus \{i\}}a_{|S| - 1, i}\$ for \$S \ne \varnothing\$.

For example, here’s the \$n = 4\$ calculation written out explicitly:

c = 1

c0 = c * a00
c1 = c * a01
c2 = c * a02
c3 = c * a03

c01  = c1 * a10; c02  = c2 * a10; c03  = c3 * a10
c01 += c0 * a11; c12  = c2 * a11; c13  = c3 * a11
c02 += c0 * a12; c12 += c1 * a12; c23  = c3 * a12
c03 += c0 * a13; c13 += c1 * a13; c23 += c2 * a13

c012  = c12 * a20; c013  = c13 * a20; c023  = c23 * a20
c012 += c02 * a21; c013 += c03 * a21; c123  = c23 * a21
c012 += c01 * a22; c023 += c03 * a22; c123 += c13 * a22
c013 += c01 * a23; c023 += c02 * a23; c123 += c12 * a23

c0123  = c123 * a30
c0123 += c023 * a31
c0123 += c013 * a32
c0123 += c012 * a33

return c0123

After executing each line, we can forget the filled elements a… and represent the current state with just the c… variables that are still live.  This representation collapses many different partially filled matrices into the same coefficient vector.  For example, swapping any two filled rows results in the same coefficient vector.

The sort_scols function further collapses the state space by using the symmetries of column permutations and column sign flipping to try to find a canonical representation for each state.  It doesn’t do a perfect job, but this imperfection only impacts performance, not correctness.


Mathematica, 72 bytes

{1}//.{r___,x_}:>{r,x,n=1;Check[RandomChoice[#[[x]]->(n++&/@#)],##&[]]}&

This is a function takes the matrix as an argument and returns a list, and it uses 1-indexing.

The basic idea is to start with

{1}//.

which repeatedly applies the rule that follows to the list {1} until it stops changing. The rule matches the pattern

{r___,x_}:>

which means "a list with zero or more elements called r followed by an element called x." This gives x as the last element in the current list, and we replace the list with

{r,x,<stuff>}

which is the original list with <stuff> appended. The stuff in question is

RandomChoice[#[[x]]->(n++&/@#)]

which takes #[[x]] (the xth element of the input matrix) as a list of weights and maps them to n++&/@#, which is short for Range@Length@# (i.e. {1,2,3,...} with the appropriate length). This will throw an error if the weights are all zero, which is why it's wrapped in a

Check[...,##&[]]

which will return ##&[] if an error message is generated. This is just a fancy way of writing Sequence[], which acts as a "nothing" element ({1,2,Sequence[],3} evaluates to {1,2,3}) and therefore leaves the list unchanged, causing the //. to stop replacing.


CJam, 119 91 bytes

q~:M;),>:R;(:L{{R{ML)d/-Y#)mr}$L/L<2{{M1$:+-+}%z}*:U:+__O|=R*-}gU{:s_:,:e>f{Se[}}%zSf*N*}M?

This is a provably correct, non-deterministic approach.

On my desktop, the second test case generally finishes in less than 10 minutes.

The first case finishes instantly. Try it online in the CJam interpreter.

Sample run

$ cjam grid.cjam <<< '8 1 300 500'
77  66  37 47  56  46 86  85
63 102  70 72  49  54 81   9
62  69  58 57  71  17 48 118
64  65  67 87  53  44 80  40
73  60  55 89  51  76 84  12
68  59  28 78  74  38 50 105
61  75  52 43 125  83 42  19
32   4 133 27  21 142 29 112

Idea

Without time limits, we could just randomly generate squares until finding a valid square. This approach builds on that idea, adding two optimizations:

Instead of pseudo-randomly generating square of side length N, we generate squares of side length N-1, add one column to form a N × (N-1) rectangle whose rows have sum S, then one row to form a square of side length N whose columns have sum S.

Since the sum of the elements of all columns will be NS and the sum of the elements of the first N-1 rows is (N-1)S, the last row will also have sum S.

However, this process may generate an invalid matrix, since there's no guarantee that all elements of the last row and column will be unique or fall in the range [A ... B].
Picking a square of unique integers in [A ... B] and side length N-1 uniformly at random would take way too long. We somehow have to prioritize squares that have a higher chance of resulting in a valid square of side length N after applying the process detailed in the previous bullet point.

Given that each row and column has to have a sum of S, its elements have an average of S/N. Thus, picking more elements close to that average should increase our chances.

For each I in [A ... B], we pseudo-randomly pick a float between 0 and (I - S/N)2 + 1 and sort the elements of [A ... B] by the picked floats. We keep the first N2 numbers and place them in reading order in a square.

Assuming a perfectly uniform distribution of all real numbers between 0 and (I - S/N)2 + 1 in each step, all squares have a non-zero probability of being picked, meaning that the process will finish eventually.

Code

q~          e# Read all input from STDIN and evaluate it.
:M;         e# Save "S" in M and discard it from the stack.
),>:R;      e# Transform "A B" into [A ... B], save in R and discard.
(:L         e# Save "N - 1" in L and keep it on the stack.
{           e# If L is non-zero:
  {         e#   Do:
    R{      e#     For each I in R:
      ML)d/ e#       Compute M/Double(L+1).
      -Y#   e#       Subtract the result from I and square the difference.
      )mr   e#       Add 1 and pick a non-negative Double below the result.
    }$      e#     Sort the values of I according to the picks.
    L/      e#     Split the shuffled R into chunks of length L.
    L<      e#     Keep only the first L chunks.
    2{      e#     Do twice:
      {     e#       For each row of the  L x L array.
        M1$ e#       Push M and a copy of the row.
        :+- e#       Add the integers of the row and subtract their sum from M.
        +   e#       Append the difference to the row.
      }%    e#
      z     e#       Transpose rows and columns.
    }*      e#
    :U:+    e#     Save the result in U and concatenate its rows.
    __O|    e#     Push two copies. Deduplicate the second copy.
    =R*     e#     Push R if all elements are unique, an empty array otherwise.
    -       e#     Remove the result's elements from U's elements.
  }g        e#   If the resulting array is non-empty, repeat the loop.
  U{        e#   For each row in U:
    :s      e#     Convert its integers into strings.
    _:,     e#     Copy and replace each string with its length.
    :e>     e#     Compute the maximum length.
    f{      e#     For each integer, push the maximum length; then
      Se[   e#       Left-pad the integer with spaces to that length.
    }       e#
  }%        e#
  z         e#   Transpose rows with columns.
  Sf*N*     e#   Join columns by spaces, rows by linefeeds.
}M?         e# Else, push M.


58 : -20 bytes(25%) from OP

for(b=[],j=2;j<136;j+=j==14||j==94?29:j==55?27:2)b.push(j)

This should do the same thing as your code, but without all the ugly parentheses and explicit assignments. Since all you're really doing is adding each time, all you have to do is check how much to add.

I should note that I have no idea where you got the numbers from in the original code. Since it doesn't seem to match the pattern you gave, I assume the pattern is just an example (and the actual lines are longer), or there's something going on in your other code (not shown here). Either way, I matched up my positions with yours.

For a fixed pattern like this, though, it  might be shorter to just encode it in a bitmap-style string or bitmasked integer. Doing it loop-style allows you to vary it a bit easier, but if your pattern is constant it's something to be aware of. For instance, your shown pattern has 51 positions, which are either "on" or "off". This means it needs 51 bits for a straight bitmask, which can fit in a single number:

000101010101010000010101010101010000010101010101000 = 0xAAA0AAA82AA8

So, if you can unpack that into an array efficiently, you may be able to score some more bytes. Unfortunately, I'm no Javascript whiz, so I couldn't get it shorter this way, leaving it at 61 bytes. Others may be able to improve upon this:

for(b=[],j=0,m=0xAAA0AAA82AA8;m>0;m>>>=1,j++)if(m&1)b.push(j)

So for this exact pattern, the first method is shorter (for me). If the pattern wasn't so evenly spaced (allowing simple additions), the second would most likely end up shorter.


///, 37 bytes

Greetings, Planet!/!tenalP ,sgniteerG


Ruby, 8618 correct (91.1%), 53 bytes, 8618 - 10 * 53 = 8088 score

->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}

This is an anonymous Ruby function which uses regexes to count syllables.

The function adds a syllable for every instance of:

A run of non-e vowels, followed by zero of more es
An e which is not part of a trailing ed or ely, with the exception of trailing ted or deds
A trailing le

Analysis

The basic idea is to count runs of vowels, but this by itself isn't very accurate ([aeiouy]+ gets 74% correct). The main reason for this is because of the silent e, which modifies the previous vowel sound while not being pronounced itself. For example, the word slate has two vowels but only one syllable.

To deal with this, we take e out of the first part of the regex and treat it separately. Detecting silent es is hard, but I found two cases where they occur often:

As part of a trailing ed (unless it's a ted or ded like settled or saddled),
As part of a trailing evy (e.g. lovely)

These cases are specifically excluded in what would otherwise be e..

The reason for the . in e(?!d$|ly). is to consume the next char if there is a double vowel (e.g. ea or ee), and so that e at the end of the word are not counted. However a trailing le is usually pronounced, so that is added back in.

Finally, vowel runs are counted as one syllable. While this may not always be the case (e.g. curious), it's often difficult to work out whether there are multiple syllables. Take the ia of celestial and spatial, as an example.

Test program

I don't really know Ruby so I'm not sure how well it can be golfed. I did manage to scrape together a test program by consulting a lot of SO though:

cases = 0
correct = 0

s = "->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}"

f = eval s

for i in 1 ... 8
    filepath = i.to_s + "-syllable-words.txt"
    file = File.open(filepath)

    while (line = file.gets)
        word = line.strip
        cases += 1
        if f.call(word) == i
            correct += 1
        end
    end
end

p "Correct: #{correct}/#{cases}, Length: #{s.length}, Score: #{correct - s.length*10}"


Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2

Python 3.5, 160 141 126 124 121 109 bytes

This is a simple implementation of the sequence's definition. Golfing suggestions welcome.

Edit: -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5.

import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1)

Ungolfing:

import math
def f(n, r=[2,1], c=3):
    if n<2:
        return r[1]
    elif (c in r) + math.gcd(c,r[0]*r[1]) < 2:
        return f(n-1, [c]+r)
    else:
        return f(n, r, c+1)


Create a function for transposing musical chords

OK, within the limitations of the question as asked and not catering for a lot of things you'd need to allow for if using with real music (flats being the most obvious):

function t(c,a) {
  var s=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],i;
  return c.replace(/[A-G]#?/g,function(m){return s[(i=(s.indexOf(m)+a)%s.length)<0?i+s.length:i];});
}

This is my first attempt at code-golf, so I hope I've taken the right approach. Following is the readable version that I originally posted at stackoverflow.com:

function transposeChord(chord, amount) {
  var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
  return chord.replace(/[CDEFGAB]#?/g,
                       function(match) {
                         var i = (scale.indexOf(match) + amount) % scale.length;
                         return scale[ i < 0 ? i + scale.length : i ];
                       });
}


Python 2, 270 bytes

from random import*
e=lambda s,n:all(sum(map(ord,l))!=n*65for l in s)
R,C,d=randint,choice,[-1,1]
def w(a):
 print a;n=len(a);
 while e(a,n)and e(zip(*a),n):
    if n==2:x,y,w,z=0,0,0,1
    else:x,y=R(1,n-2),R(1,n-2);w,z=x+C(d),y+C(d)
    a[y][x],a[z][w]=a[z][w],a[y][x]
 print a

Always chooses A as character to complete a row/col. Performs random swaps until goal is reached.
Accepts the matrix as list of lists, usage for testing:
A="""ADCD
BBBA
DACC
ACDB"""
a=[[c for c in l] for l in A.split('\n')]
w(a)


J, 40 39 34 bytes

3 :'(o.1)<(>./-<./)12 o.y*+{.y'@:-

An anonymous dyadic function, taking a point, p, as one of its arguments, and a list of points, P, as the other argument (it doesn't matter which argument is which), and returning 0 or 1, if p is outside or inside the convex hull of P, respectively.
The point p, and the points in P, are taken as complex numbers.

Example

  is_inside =: 3 :'(o.1)<(>./-<./)12 o.y*+{.y'@:-

  0.5j0.5  is_inside  0j0 0j1 1j0 1j1
1
  1.5j0.5  is_inside  0j0 0j1 1j0 1j1
0

or...

Python 2, function, 121 103, full program, 162

Python 3, 149 bytes

import sys,cmath as C
p,q,*P=[complex(*eval(l.replace(*";,")))for l in sys.stdin]
A=[C.phase((r-p)/(q-p+(q==p)))for r in P]
print(max(A)-min(A)>C.pi)

Takes input, in the same format as the original post, through STDIN, and prints a boolean value indicating whether p is in the convex hull of P

Explanation

The program tests whether the difference between the maximum and minimum (signed) angles between any point r in P, p, and a fixed arbitrary point q in P (we just use the first point in P), is less than 180°.
In other words, it tests whether all the points in P are contained in an angle of 180° or less, around p.
p is in the convex hull of P if and only if this condition is false.

At the cost of a few more bytes, we can use a similar method that doesn't require us to explicitly calculate angles:
Note that the above condition is equivalent to saying that p is outside the convex hull of P if and only if there exists a line l through p, such that all the points in P are on the same side of l.
If such a line exists, then there's also such a line that is incident to one (or more) of the points in P (we can rotate l until it touches one of the points in P.)

To (tentatively) find this line, we start by letting l be the line through p and the first point in P.
We then iterate over the rest of the points in P; if one of the points is to the left of l (we assume some directionality throughout, left or right doesn't really matter,) we replace l with the line passing through p and that point, and continue.
After we iterated over all of P, if (and only if) p is outside the convex hull, then all the points in P should be to the right of (or on) l.
We check that using a second pass over the points in P.

Python 2, 172 bytes

import sys
P=[eval(l.replace(*";,"))for l in sys.stdin]
x,y=P.pop(0)
C=lambda(a,b),(c,d):(a-x)*(d-y)-(b-y)*(c-x)>0
l=reduce(lambda*x:x[C(*x)],P)
print any(C(l,q)for q in P)

Alternatively, to do the same thing in a single pass, let to-the-left-of be a realtion between any two points, q and r, in P, such that q is to the left of r if q is to the left of the line passing through p and r.
Note that to-the-left-of is an order relation on P if and only if all the points in P are on the same side of some line passing through p, that is, if p is outside the convex hull of P.
The procedure described above finds the minimum point in P w.r.t. this order, i.e., the "leftmost" point in P.
Instead of performing two passes, we can find the maximum (i.e., the "rightmost" point), as well as the minimum, points in P w.r.t. the same order in a single pass, and verify that the minimum is to the left of the maximum, i.e., effectively, that to-the-left-of is transitive.

This would work well if p is outside the convex hull of P, in which case to-the-left-of is actually an order relation, but may break when p is inside the convex hull (for example, try to figure out what will happen if we ran this algorithm where the points in P are the vertices of a regular pentagon, running counter-clockwise, and p is its center.)
To accommodate, we slightly alter the algorithm:
We select a point q in P, and bisect P along the line passing through p and q (i.e., we partition P around q w.r.t. to-the-left-of.)
We now have a "left part" and a "right part" of P, each contained in a halfplane, so that to-the-left-of is an order relation on each; we find the minimum of the left part, and the maximum of the right part, and compare them as described above.
Of course, we don't have to physically bisect P, we can simply classify each point in P as we look for the minimum and maximum, in a single pass.

Python 2, 194 bytes

import sys
P=[eval(l.replace(*";,"))for l in sys.stdin]
x,y=P.pop(0)
C=lambda(a,b),(c,d):(a-x)*(d-y)-(b-y)*(c-x)>0
l=r=P[0]
for q in P:
 if C(P[0],q):l=q*C(l,q)or l
 elif C(q,r):r=q
print C(l,r)


Put the line in the code you nut and shake it all up

CJam, 120 valid permutations, 334 299 290 bytes
"She put the lime in the coconut, she drank them both up"N+
"Brother bought a coconut, he bought it for a dime"N+]$~
"She put the lime in the coconut, she drank them both up"N+
"His sister had another one, she paid it for a lime"N+]$~
"She put the lime in the coconut, she drank them both up"N+

Pretty simple logic:

Put each line of the song in each of the 5 programs
Wrap everything on stack in an array
Sort the array
Unwrap the array so that the next program can use the same logic
In each step, we have the partial lyrics in an array. Luckily, sorting the array gives the correct order of the lyrics.

UPDATE: Turns out that you don't need the wrap-sort-unwrap cycle after the 3 similar and appearing at the end lines of the song. I can explain why if its not that apparent :)


Write a program that reverses the name of its source file

Bash + common linux utils, 13 bytes

My method is similar to @DigitalTrauma's but a bit shorter due to the pipe with ls:

mv * `ls|rev`


C++

What i will present here is an algorithm, illustrated with an example for a 3x3 case. It could theoretically be extended to the NxN case, but that would need a much more powerful computer and/or some ingenious tweaks. I will mention some improvements as I go through.

Before going further, let's note the symmetries of the Sudoku grid, i.e. the transformations which lead to another grid in a trivial way. For block size 3, the symmetries are as follows:

Horizontal symmetry

**The N=3 sudoku is said to consist of 3 "bands" of 3 "rows" each**
permute the three bands: 3! permutations = 6
permute the rows in each band: 3 bands, 3! permutations each =(3!)^3=216

Vertical symmetry

**The N=3 sudoku is said to consist of 3 "stacks" of 3 "columns" each.**
the count is the same as for horizontal.

Note that horizontal and vertical reflections of the grid can be achieved by a combination of these, so they do not need to be counted.
There is one more spatial symmetry to be considered, which is transposing, which is a factor of 2. This gives the total spatial symmetry of

2*(N!*(N!)^N)^2 = 2*(6*216)^2=3359232 spatial symmetries for the case N=3.

Then there is another, very important symmetry, called relabelling.

Relabelling gives a further (N^2)!=9!=362880 symmetries for the case N=3. So the total
number of symmetries is 362880*3359232=1218998108160.

The total number of solutions cannot be found simply by multiplying the number of symmetry-unique solutions by this number, because there are a number (less than 1%) of automorphic solutions. That means that for these special solutions there is a symmetry operation that maps them to themselves, or multiple symmetry operations that map them to the same other solution.

To estimate the number of solutions, I approach the problem in 4 steps:

1.Fill an array r[362880][12]with all possible permutations of the numbers 0 to 8. (this is programming, and it is in C, so we are not going to use 1 to 9.) If you are astute you will notice that the second subscript is 12 not 9. This is because, while doing this, bearing in mind that we are going to consider this to be a "row" we also calculate three more integers r[9,10,11] == 1<<a | 1<<b | 1<<c where 9,10,11 refer to the first, second and third stack and a,b,c are the three numbers present in each stack for that row.

2.Fill an array b with all possible solutions of a band of 3 rows. To keep this reasonably small, only include those solutions where the top row is 012,345,678. I do this by brute force, by generating all possible middle rows and ANDing r[0][10,11,12] with r[i][10,11,12]. Any positive value means there are two identical numbers in the same square and the band is invalid. When there is a valid combination for the first two rows, I search the 3rd (bottom) row with the same technique.

I dimensioned the array as b[2000000][9] but the program only finds 1306368 solutions. I did not know how many there were, so I left the array dimension like that. This is actually only half the possible solutions for a single band (verified on wikipedia), because I only scan the 3rd row from the current value for i upwards. The remaining half of the solutions can be found trivially by exchanging the 2nd and 3rd rows.

The way the information is stored in array b is a little confusing at first. instead of using each integer to store the numbers 0..8 found in a given position, here each integer considers one of the numbers 0..8 and indicates in which columns it can be found. thus b[x][7]==100100001 would indicate that for solution x the number 7 is found in columns 0,5 and 8 (from right to left.) The reason for this representation is that we need to generate the rest of the possibilities for the band by relabelling, and this representation makes it convenient to do this.

The two steps above comprise the setup and take about a minute (possibly less if I removed the unnecessary data output. The two steps below are the actual search.)

3 Search randomly for solutions for the first two bands that do not clash (i.e. do not have the same number twice in a given column. We pick a random solution for band 1, assuming always permutation 0, and a random solution for band 2 with a random permutation. A result is normally found in less than 9999 tries (first stage hit rate in the thousands range) and takes a fraction of a second. By permutation, I mean that for the second band we take a solution from b[][] where the first row is always 012,345,678 and relabel it so that any possible sequence of numbers on the first row is possible.

4 When a hit is found in step 3, search for a solution for the third band which does not clash with the other two. We do not want to make just one try, otherwise the processing time for step 3 would be wasted. On the other hand we do not want to put an inordinate amount of effort into this.

Just for fun, last night I did it the dumbest way possible, but it was still interesting (because it nothing for ages, then found large numbers of solutions in bursts.) It took all night to get one datapoint, even with the little hack (!z) I did to abort the last k loop as soon as we know this is not a valid solution (which makes it run nearly 9 times faster.) It found 1186585 solutions for the complete grid
after searching all 362880 relabellings of all 1306368 canonical solutions for the last block, a total of 474054819840 possibilities. That's a hit rate of 1 in 400000 for the second stage. I will try again soon with a random search rather than a scan. It should give a reasonable answer in just a few million tries, which should take only a few seconds.

The overall answer should be (362880*(1306368*2))^3*hit rate=8.5E35*hit rate. By back calculating from the number in the question, I expect a hit rate of 1/1.2E14. What I've got so far with my single datapoint is 1/(400000*1000) which is out by a factor of about a million. This could be an anomaly of chance, an error in my program, or an error in my math. I won't know which it is until I run a few more tests.

I'll leave this here for tonight. The text is a bit scrappy, I will tidy it up soon and hopefully add some more results, and maybe a few words on how to make it faster and how to extend the concept to  N=4. I don't think I'll be making too many more changes to my program, though :-)

Ah.. the program:

#include "stdafx.h"
#define _CRT_RAND_S
#include <algorithm>
#include <time.h>

unsigned int n[] = { 0,1,2,3,4,5,6,7,8 }, r[362880][12], b[2000000][9],i,j,k,l,u,v,w,x,y,z;

int main () {

  //Run through all possible permutations of n[] and load them into r[][]
  i=0;
  do {
      r[i][9] = r[i][10] = r[i][11]=0;
      for (l = 0; l < 9; l++){
          r[i][l] = n[l];
          r[i][9 + l / 3] |= 1 << n[l];
      }
      if((i+1)%5040==0) printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
          ,r[i][0],r[i][1],r[i][2],r[i][3],r[i][4],r[i][5],r[i][6],r[i][7],r[i][8],r[i][9],r[i][10],r[i][11],r[i][9]+r[i][10]+r[i][11]);
      i++;
  } while ( std::next_permutation(n,n+9) );

  //Initialise b[][]
  for (l = 0; l<2000000; l++) for (k = 0; k<9; k++) b[l][k]=0;
  //fill b[][] with all solutions of the first band, where row0 ={0,1,2,3,4,5,6,7,8} and row1<row2
  l=0;
  for (i = 0; i<362880; i++)
  if (!(r[0][9] & r[i][9] | r[0][10] & r[i][10] | r[0][11] & r[i][11])){printf("%d %d \n",i,l);
     for (j=i; j<362880;j++)
       if(!(r[0][9]&r[j][9] | r[0][10]&r[j][10] | r[0][11]&r[j][11] | r[j][9]&r[i][9] | r[j][10]&r[i][10] | r[j][11]&r[i][11] )){
           for (k = 0; k < 9; k++){
               b[l][r[0][k]]|=1<<k;
               b[l][r[i][k]]|=1<<k;
               b[l][r[j][k]]|=1<<k;
            }
            l++;
       }
//        printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
//        ,r[i][0],r[i][1],r[i][2],r[i][3],r[i][4],r[i][5],r[i][6],r[i][7],r[i][8],r[i][9],r[i][10],r[i][11],r[i][9]+r[i][10]+r[i][11]);
//        printf("%d%d%d %d%d%d %d%d%d %o %o %o %o \n"
//        ,r[j][0],r[j][1],r[j][2],r[j][3],r[j][4],r[j][5],r[j][6],r[j][7],r[j][8],r[j][9],r[j][10],r[j][11],r[j][9]+r[j][10]+r[j][11]);
//        printf("%d %d %o %o %o %o %o %o %o %o %o \n",i,l,b[l][0],b[l][1],b[l][2],b[l][3],b[l][4],b[l][5],b[l][6],b[l][7],b[l][8]);
  }

  // find a random solution for the first 2 bands
  l=0;
  do{
      rand_s(&u); u /= INT_MIN / -653184; //1st band selection
      rand_s(&v); v /= INT_MIN / -181440; //2nd band permutation
      rand_s(&w); w /= INT_MIN / -653184; //2nd band selection
      z = 0;
      for (k = 0; k < 9; k++) z |= b[u][k] & b[w][r[v][k]];
      l++;
  } while (z);
  printf("finished random after %d tries \n",l);
  printf("found solution with top band %d permutation 0, and middle band %d permutation %d \n",u,w,v);
  getchar();

  // scan all possibilities for the last band
  l=0;
  for (i = 0; i < 362880; i++) for (j = 0; j < 1306368; j++){
              z=0;
              for(k=0;(k<9)&&(!z);k++) z|= b[u][k] & b[j][r[i][k]] | b[j][r[i][k]] & b[w][r[v][k]];
              if (!z){ l++; printf("solution %d : i= %d j=%d",l,i,j); }
  }
  printf("finished bottom band scan at %d millisec \n", clock()); getchar();
}


><> and Gol><>, 18 bytes + 3 + 6 = 27

'3d*:5-0@o~r{?H>o<

Try it online!

and

"3d*:5-0@o~r{?H>o<

Try it online!

Both output the same program, but with the first character flipped between ' and ". Neither program is equivalent to itself in the other language, since the behaviour of @ differs.


Give the smallest number that has N divisors

APL, 25 24 23 characters
f←{({+/⍵=⍵∧⍳⍵}¨⍳2*⍵)⍳⍵}

Defines a function f which can then be used to calculate the numbers:
> f 13
4096

> f 14
192

The solution utilizes the fact that LCM(n,x)==n iff x divides n. Thus, the block {+/⍵=⍵∧⍳⍵} simply calculates the number of divisors. This function is applied to all numbers from 1 to 2^d ¨⍳2*⍵. The resulting list is then searched for d itself (⍳⍵) which is the desired function f(d).


My favorite solution for GHC:

data Bad a = C (Bad a -> a)

xx :: Bad a -> a
xx (x@(C x')) = x' x

omega :: a
omega = xx (C xx)

main = omega

For GHC 6.12.1 both ghci Bad.hs and ghc Bad.hs loop infinitely.
GHC 7.4.1 loops infinitely when ghc -O2 Bad.hs is executed.

Explanation: omega is defined using an infinite recursion (the only way it can inhabit any type). Compiler's inliner sees xx as a simple, non-recursive function, so it tries to inline it in the definition of omega. It results in (\x@(C x') -> x' x) (C xx). Seeing a pattern match on a constructor the compiler tries to reduce it, getting xx (C xx) again and loops. The trick is that xx is actually recursive, but the recursion is hidden within the data type.

Note: While writing the puzzle, I forgot I left GHC running in the infinite loop. It took all my memory, crashed Firefox and I barely managed to kill it without hard reset.


Многочлены Чебышёва (Chebyshev Polynomials)

Mathematica, 15 bytes
#~ChebyshevT~x&

Of course, Mathematica has a builtin.
If an alternative input form is allowed (10 bytes):
ChebyshevT

takes an integer n and a variable.


Bash (OSX), 33 27 23 18 Bytes

You heard the man, any way we like.

open http:yon.se/q

I am aware that this is a popularity contest. But hey, when you can code golf it, why not?

It is now a code golf. \o/ This was valid at the time of posting.

There was even an exception made for me at some point! But, as @AlexA. pointed out...

  "You can use whatever methods you want (except loading the image, with the exception of VoteToClose's response)" It isn't fair to allow exceptions for specific users/answers. - Alex A.

I agree with this, and, as of such, do not wish this to be picked as the answer. Doesn't mean I won't still try to golf it down more. ;)

Thanks to @ΚριτικσιΛίθος for shaving off 6 bytes with a fancy short URL!

Thanks to @ev3commander for shaving off ANOTHER 5 bytes with an even fancier, shorter URL!

Thanks to @kennytm for pointing out that I can reduce the protocol size and remove the quotes, saving me another 4 bytes!


Jelly, 2 bytes

*2

Try it online!

Note that the main entry for a Jelly program is its last link, where any newline character will split links), neither of the two-line programs actually access their top link.

The four full programs, all of which implicitly print their result, are:

North:

*2   -> (implicit) zero raised to the power of 2 = 0

East:

*
2    -> literal 2 = 2

South:

2*   -> two raised to the power of (implicit) 2 = 4

West:

2
*    -> (implicit) zero raised to the power of (implicit) zero = 1


Which Numbers Would Crash this Function?

-2147483648 (INT_MIN) and -1

#include <stdio.h>
#include <limits.h>
int f(int x, int y) {
    return (y==0) ? 0 : (x/y);
}
int main() {
    int r = f(INT_MIN, -1);
    printf("%d\n", r);
    return 0;
}

$ gcc -Wall division.c && ./a.out # => zsh: floating point exception  ./a.out


Retina, 201 197 191

\d+
$0$*1
G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$
+`\b((1+)\D*)¶(\2.+)
$3¶$1
+s`1+(\D+)¶(.*\1)
$2
1+

Try it online!

6 bytes saved thanks to Martin!

Whee, bubble sort with regex. Note that ten bytes are spent doing decimal to unary conversion at the beginning, if unary input is OK then that isn't needed. Also, if numbers can't be in people's names, then a couple more bytes can be saved by moving the line that removes non-Bond actors to the end and removing the 1+ (untested with \D version).

Explanation:

A Retina program is made up of several stages, so I will explain each stage separately.

Stage 1:

\d+
$0$*1

Replaces the numbers in the input with unary. This uses Retina's special replacement token: $* which repeats the character after a number of times equal to the preceding token's base 10 value.

Stage 2:

G`^1+ (Barry Nelson|Bob Simmons|Sean Connery|Roger Moore|David Niven|George Lazenby|Timothy Dalton|Pierce Brosnan|Daniel Craig)$

The stuff before a ` in a stage changes the mode being used. This turns on grep mode, which means that each line that doesn't match the regex is discarded. The anchors are necessary to prevent near matches from slipping by.

Stage 3:

+`\b((1+)\D*)¶(\2.+)
$3¶$1

This is the sorting stage. The + in the mode signifies that this stage should be repeated until the replacement makes no change when applied (i.e. we reach a fixed point). The regex finds a word boundry, followed by some number of 1s and then all the rest of the line up to the newline. Then, if the next line has more 1s than it, the regex will match and we swap the lines.

Stage 4:

+s`1+(\D+)¶(.*\1)
$2

This stage uses the + mode again, but also uses s to make the . meta-character also match newlines. This removes duplicate lines, by matching for exact duplicates after the 1s and capturing the stuff after the first duplicate to replace the whole match with it. This will work without needing to consider the order of tie breaking, because the names are already sorted appropriately, with the larger numbers above, therefore we will always keep the smaller values.

Stage 5:

1+

Really simple one here, everything is in order, except we have a bunch of 1s in front of our Bonds, so we replace them and the space after them with nothing.


Bash + GNU utilities, 204

fold -$1|sed 2~2{s/.\\+/printf\ %$1's "`echo "&"|rev`"/e
y/'`printf %s {A..Z} {a..z}`"&_?!\"'.,/∀qƆpƎℲפHIſʞ˥WNOԀQɹS┴∩ΛMX⅄Zɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz⅋‾¿¡„,˙'/
}"

N is given on the command line and S is given via STDIN:

$ echo "The quick brown fox jumps over the lazy dog." | ./boustrophedon.sh 30
The quick brown fox jumps over
                ˙ƃop ʎzɐl ǝɥʇ
$

Explanation

fold -N splits the input into lines of length N.
The rest of the processing is done by sed, line-by-line:

2~2 matches every other line, starting at line 2
s/.+/printf %'N's "`echo "&"|rev`"/e uses GNU Sed's exec feature to call a shell to reverse the line and left-pad it with up to N spaces
y/ABC.../∀qƆ.../ transform characters

Note ABC... is generated using a bash expansion and printf.  Also some fancy quoting for all the different characters.


C, 452
A good hash function helps. There may be better ones. (Improvements suggested by @ugoren et al.)
h;main(c){char*p="Sn)Cu&V$U#Mo#Rf#Sg&Cs#Y+FTa%Rb)S'Nd#GaK&Mg'Zr$PtPm%ReUuo#SmDy(Ac$Lu%W&CaRa(Cf)EuB#Ds%Md$Uus*NpIn$H&YbIr*BeEs*Tc#I(FlRuC#ThSrBh/NaCoLrKr&Nb$CePb$Ne'Am)At*PdLa#Tl%HgMt,CrTbBk$Rh&Rn4TeZn$HfAg%Fm)Xe$AlScFePo$As'HeO#LvN&DbGe#Ho&Mn$Cd+Ni$Rg$HsBr$AuSi#Pr&Uup#Se*Ti#Tm$Er$Sb&PPu&Cm$GdBa'Cn&UutLiFr#Ar#Bi#NoOs%Pa4Cl";while((c=getchar())>64)h=(h+c%32+74)*311%441;while(h)if(*p<65?h-=*p++-34,0:1)for(h--;*++p>96;);do putchar(*p++);while(*p>96);}

Ungolfed with comments:
int h;
main(c) {

  /* Hashed element symbols. Characters #$% etc. are used as padding: */
  char *p="Sn)Cu&V$U#Mo#Rf#Sg&Cs#Y+FTa%Rb)S'Nd#GaK&Mg'Zr$PtPm%ReUuo#SmDy(Ac$Lu%W&C"
          "aRa(Cf)EuB#Ds%Md$Uus*NpIn$H&YbIr*BeEs*Tc#I(FlRuC#ThSrBh/NaCoLrKr&Nb$CeP"
          "b$Ne'Am)At*PdLa#Tl%HgMt,CrTbBk$Rh&Rn4TeZn$HfAg%Fm)Xe$AlScFePo$As'HeO#Lv"
          "N&DbGe#Ho&Mn$Cd+Ni$Rg$HsBr$AuSi#Pr&Uup#Se*Ti#Tm$Er$Sb&PPu&Cm$GdBa'Cn&Uu"
          "tLiFr#Ar#Bi#NoOs%Pa4Cl";

  /* This hash function gives a unique result for each element: */
  while((c=getchar())>64) h=(h+c%32+74)*311%441;

  /* Find the corresponding position in the hashed data */
  while(h) {
    if(*p<65?h-=*p++-34,0:1) {      /* Step over an abbreviation */
      for(h--;*++p>96;);            /* Skip padding */
    }
  }

  /* Output first uppercase character and all following lowercase characters: */
  do {
    putchar(*p++);
  } while(*p>96);
}

I used brute force to find this hash; This was the only one with a hash size of ≤512 that had no collisions. I didn't check alternative spellings though, and there might be better functions with different algorithms (e.g. using XOR instead of addition).
The hash function maps text strings to values from 0 to 440. "Tin" hashes to zero, so "Sn" is at the start of the table. The next 7 positions are empty. To keep the code compact, this is indicated by the ASCII value 34+7=41 (")"). Next comes "Copper" (8), four empty cells (34+4=38="&"), and "Vanadium" (13). After calculating a hash, the program steps through the table, subtracting 1 for every capital letter followed by 0 or more lowercase letters, and subtracting (ASCII VALUE)-34 for every non-alphabet character. When the value reaches zero, we have found the correct result.


JavaScript (ES6), 87 83 bytes

Saved 4 bytes thanks to @l4m2

Takes input as a string. Returns either 0 or a 2-element array.

t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]

Test cases

let f =

t=>[i=0,83,588,83,588,83,15].every(d=>(k=t-(t/25>>2)*40)>(j=i,i+=d))|i-k&&[k-j,i-k]

console.log(f('0000')) // YAY!!!
console.log(f('0020')) // 20 63
console.log(f('0105')) // 65 18
console.log(f('0122')) // 82 1
console.log(f('0123')) // YAY!!!
console.log(f('0124')) // 1 587
console.log(f('0852')) // 449 139
console.log(f('1111')) // YAY!!!
console.log(f('1113')) // 2 81
console.log(f('1200')) // 49 34
console.log(f('1234')) // YAY!!!
console.log(f('1357')) // 83 505
console.log(f('1759')) // 325 263
console.log(f('1800')) // 326 262
console.log(f('1801')) // 327 261
console.log(f('2222')) // YAY!!!
console.log(f('2244')) // 22 61
console.log(f('2345')) // YAY!!!
console.log(f('2351')) // 6 9

How?

We do not care about the result of the .every() loop. Provided that the input is valid, it will always be falsy. What we're really interested in is when we exit this loop.

We exit as soon as we find a favorite time i (expressed in minutes) which is greater than or equal to the reference time k (the input time t converted in minutes). We then return 0 if i == k or the 2 delays otherwise.


CJam, 78 68 61 45 42 39 31 30 bytes
l$:L{L\/,~}${:DM+:MD/,LD/,d/}$

Takes the input string via STDIN
Inspired by recursive's approach, but a little different. No need of transpose or rectangle at all!.
How it works:
l$:L                              "Sort the input line and store it in L";
    {     }$                      "Sort the string based on this code block output";
     L\/,~                        "Sort based on number of occurrences of each";
                                  "character in the full string";
            {               }$    "Sort the sorted string again";
             :DM+:M               "Store each character in D, add to M and update M";
                   D/,            "Count occurrences of D in M";
                      LD/,        "Count occurrences of D in L";
                          d/      "Sort string based on the ratio of two occurrences";

(Sad that CJam can no longer complete with Pyth due to need of so much bloat as syntax)
Try it here


Python 2, 151 149 bytes

from random import*
W,H,N=input()
L='x'*W
exec"M='';exec'M+=sample(set(map(chr,range(65,65+N)))-{L[len(M)],M[-1:]},1)[0];'*W;L=M;print' '.join(L);"*H

Takes input comma-separated via STDIN, e.g. 10, 10, 2.


Jelly, 6 bytes

½Ċ|1c3

Try it online! or verify all test cases.

Background

For all positive integers k, we have 1² + 3² + ⋯ + (2k - 1)² = k(2k - 1)(2k +1) ÷ 3.

Since there are m C r = m! ÷ ((m-r)!r!) r-combinations of a set of m elements, the above can be calculated as (2k + 1) C 3 = (2k + 1)2k(2k - 1) ÷ 6 = k(2k - 1)(2k + 1) ÷ 3.

To apply the formula, we must find the highest 2k + 1 such that (2k - 1)² < n. Ignoring the parity for a moment, we can compute the highest m such that (m - 1)² < n as m = ceil(srqt(n)). To conditionally increment m if it is even, simply compute m | 1 (bitwise OR with 1).

How it works

½Ċ|1c3  Main link. Argument: n

½       Compute the square root of n.
 Ċ      Round it up to the nearest integer.
  |1    Bitwise OR with 1 to get an odd number.
    c3  Compute (2k + 1) C 3 (combinations).


5. Retina 0.8.2 -m, 8 available bytes
The code is given as three separate files. Here are their hexdumps:
00000000: 002a 0f2a 062a 092a 042a 142a            .*.*.*.*.*.*
00000000: 4545 4545 4545                           EEEEEE
00000000: 45                                       E

This outputs 6. Try it online!
The first file uses bytes 0, 15, 6, 9, 4, 20, and 42, and the other two files consist entirely of E (byte 69), covering the list specified by the previous answer.

Normally, Retina takes patterns and replacements in a single file separated by newlines, but we don't have newlines available. Fortunately, Retina 0.8.2 still makes available the language's original multi-file code format.* This program has two stages, a replacement stage and a count stage:

Find all regex matches of _*_*_*_*_*_* in the input, where _ represents the various unprintable characters. Since the input is empty, this matches once. Replace that match with EEEEEE.
In the resulting string, count the number of matches of E (six).

* IIRC, Retina was originally designed this way to take advantage of a PPCG scoring loophole. Now I'm using it to take advantage of a different kind of loophole. Seems appropriate.

The next answer may use the 54 bytes whose codepoints are prime numbers:
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251


Find the number of subgroups of a finite group

Mathematica, 62 48 bytes

Count[Subsets@First@#,x_/;Union@@#[[x,x]]==x]-1&

Pure function expecting a 1-indexed 2D array. Counts the number of Subsets of the First row of the input array that are  closed under the group operation. Since this will include the empty set, we subtract 1. Note that a nonempty subset of a finite group that is closed under the group operation is in fact a subgroup, (and vice versa, by definition).

Strictly speaking I don't check that the subset x is closed under the group operation, I restrict the multiplication table to the subset x and check that it contains precisely the elements of x. Clearly this implies that x is closed with respect to the group operation. Conversely, any subgroup x will contain 1 and thus x will be a subset of the elements appearing in the restricted multiplication table, and since x is closed under the group operation, it must equal x.


Shortest program that throws StackOverflow Error

Befunge, 1

I don't know Befunge, but...

1

from Stack overflow code golf


Write biSp in point-free form using as few terms as possible

7 terms

We again define a helper combinator BBQ = B B (C B), which has reduction rule

BBQ w x y z = x y (w z)

Then biSp = BBQ BBQ BBQ

  BBQ BBQ BBQ g h f x y
= BBQ g (BBQ h) f x y
= BBQ h f (g x) y
= f (g x) (h y)

Online demo

By brute force, this is the only 7-term solution and there is no smaller solution.

8 terms

There are a handful of 8-term solutions. Firstly, the obvious

C BBQ BBQ BBQ

which reduces in one step to BBQ BBQ BBQ.

Then there are three solutions of the form X X X with a five-term X:

X = B (B B) C B which reduces in one step to BBQ
X = C B (C B) B which reduces in one step to BBQ and allows the further extraction, for no net gain or loss, of a helper combinator Q = C B
X = C (B C (B B))

There is one solution of the form X X with a six-term X:

X = C B (B B (C B)) (again, with an equivalent version which extracts Q = C B)

And there is one solution which can only be written in 8 terms with two helper combinators:

Q = C B
X = Q (Q Q B)
biSp = X X


Processing,  425 bytes (259 bytes + 1 +165 byte file)

Code:

size(959,593);String[]a=loadStrings("a"),b=loadStrings("b");PShape m=loadShape("M.svg");m.disableStyle();for(int i=0;i<51;i++){fill(255);int r=0;for(String j:a){if(j.isEmpty())r++;if(j.contains(b[i]))fill(r>0?#0000FF:#FF0000);}shape(m.getChild(i));}save("m");

Blank map should be named "M.svg" and stored in a folder called /data (all other files are in the same folder as the program.)

Input File ("a"):

Mississippi
California
Connecticut

Delaware
Florida
Wyoming
Hawaii

Key File ("b"): http://pastebin.com/0pNufAH9

Output ("m.tif"):

Ok, here is my try at my own challenge. Some notes:

The output map looks different from the input map in the following ways

The input map had grey filling on a transparent background. The output has white filling on a gray background. I think this should be allowed, because white, gray, and transparency are all neutral.
The output map is missing the lines around Hawaii and Alaska that the input had. Once again, I think this is ok because the lines are not a significant part of the map.

The program uses an external file to hold keys. According to this meta post, I just need to add 1 byte for one additional file.

If anyone has any discrepancies with my self-adjudication of my code, feel free to leave a comment.

Also, if anyone is curious about trying this challenge in Processing, it supports both reading SVG files into PShape's, as well as parsing SVG files as XML.


Python 2, 118 96 - 50% = 48 bytes

Takes input in the form ['abc','def','ghi']. Note that this solution returns the list reversed if the input is sorted, as per a previous spec.

def f(n):m=n[1:];S=sorted;a=S(n);return[a.pop(a.index(n[0])-1)]+a[::-1]if m==S(m)else[n[0]]+f(m)

Try it Online!

Seems to be the O(n) solution more efficient than computing all permutations.

Explanation: Recursively checks if everything after the current element is in sorted order. If so, returns the string immediately lexicographically before (a.index(n[0])-1)) the first element + the rest of the list reversed (a[::-1]).

Runtime: O(n^2 logn) In the worst case (list is reversed), the function will call sorted, which has a runtime of nlogn, for each element in the list (n times).


20 languages

Using  ()-#*.05;=>^Vefikloqrst (24 characters) so far:

let f l=floor(l**0.5);;       OCaml
let f l=floor(l**0.5)         F#
f(l)=floor(l^.5)              Julia
f(o)=floor(o^.5)              PARI/GP
s^+>5 0>5 0*.5l               Pyth
(* **.5).floor                Perl 6
floor.(**0.5)                 Haskell
flr.(tt ^.5)                  Wonder
l=>l**.5^0                    JavaScript
l->l**.5^0                    Cheddar
.5^5*5f                       Pyke
(isqrt)                       Maple
ri.5#i                        CJam
isqrt                         Common Lisp
0.5^k                         MATL
*.5^0                         Jelly
*.^0                          M
t0^                           05AB1E
q f                           Japt
r#                            Pushy
V-                            gs2


CJam, 62 53 bytes

This is too long for now. Will add explanations once I am done golfing.

qS%2/{{el__"aeiou"&0=#_2$<@@>}%(a+2/Wf%~}%{s(eu\+}%S*

Try it online here


JavaScript, 297 277 262 235 223 chars

No carriage returns in the golfed version are significant; they are there only to make the answer readable. Semicolons are significant.

Edit: Replaced the outer map with a while loop and other edits. Finally inside of 2× the size of the Golfscript version (for now)!

Edit: Replaced the indexOf with math, broke down the lookup table, other small improvements.

Edit: Another map to for and put in a final \n I had been unnecessarily eating. Finally inside of Jules's Python version.

i=prompt(o='').split(' ');for(r=6;o+=' EADGBe'[r]+' ',r--;o+='\n')
for(j=0;n=i[j++];o+=(([84,13,52,5][2*/m/.test(n)+x]*8>>2*r&3)+y-7*x)+'---')
y=n.charCodeAt(0),y=(2*y-(y>66)-(y>69)+(n[1]<'$')-(n[1]=='b')+2)%12,x=y>6;alert(o)

Output no longer takes advantage of the trailing --- being optional as:

e 2---2---0---0---3---5---0---2---
B 3---2---2---0---3---7---0---2---
G 4---3---2---1---4---7---0---3---
D 4---4---2---2---5---7---2---4---
A 2---4---0---2---5---5---2---4---
E 2---2---0---0---3---5---0---2---


Python 2, 714 737 821 bytes

-23 bytes thanks to Kevin Cruijssen

M=input()
m=''.join(M)
def P(L):
 if len(L)<2:yield[L];return
 for p in P(L[1:]):
	for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:]
	yield[[L[0]]]+p
h,w,R,C=len(M),len(M[0]),0,[-1,0,1]
K=[(i,j)for i in range(h)for j in range(w)]
Z=[(i,j)for i,j in K if' '==M[i][j]]
from networkx import*
for l in set(m):
 G,S=[],[]
 if l in'oO0':R+=m.count(l);continue
 for I in K:
  i,j=I
  for p in C:
	for q in C:
	 X=x,y=i+p,j+q
	 if X in K and X!=I and set(M[i][j]+M[x][y])<=set(' '+l):G+=[(I,X)];S+=[I,X]
 B=0
 for L in P(list(set(S))):
  b=0
  for p in L:
	for i,j in p:
	 if' '!=M[i][j]:
		try:find_cycle(from_edgelist([(I,X)for I,X in G if I in p+Z and X in p+Z]));b+=1
		except:1
		break
	if b>B:B=b
 R+=B
print R

Try it online!

For each letter A (except  o, O, and 0) the code build a graph representing the adjacency of the different occurrences of letter A and space in the initial given matrix. Then it computes the set of semi-separated cycles covering the graph when maximizing the number of cycles (separation is based only on the letter A, the same space can be used for several cycles).
The code passes all tests.
Input: the list of lines of the matrix.
More explanation and golfing coming soon.


Python 3, 262 ... 170 bytes
This program outputs the result via Stderr.
I'm a bit out of practice at golfing, since I have not been too active lately, so I'm sure it can be golfed more.

L=[[c,int(c)]for c in input()]
while 1:i=L.index(min([x for x in L if x[1]]or exit(str(int("".join(x[0]for x in L))))));L[i][1]-=1;q=i+1<len(L)and-~i;L.insert(q,L.pop(i))

Try it online
Ungolfed
# Index to shift, Times remaining
def Shift(i, t):
    if t<1:
        L[i][1]=0
        return
    if i+1<len(L):
        L[i],L[i+1]=L[i+1],L[i]
        Shift(i+1,t-1)
    else:
        L.insert(0,L.pop())
        Shift(0,t-1)
L=[[c,1]for c in input()]
while 1:
    t=[x for x in L if x[1]]or exit("".join(x[0]for x in L).lstrip('0'))
    i=L.index(min(t,key=lambda x:x[0]))
    Shift(i,int(L[i][0]))


JavaScript (ES6), 219 bytes
A slower but significantly shorter version using bitmasks instead of strings.

f=(D,P=[511],e=m=0)=>P.map((X,r)=>[...Array(-~X)].map((_,p)=>D.map(([d,s,t],j)=>(N=(g=(n,k)=>n&&n%2+g(n>>1,++k,x+=n%2*k))(p&=X,x=0))<3|N>5|r-s|x%9^d%9||f(D.filter(_=>j--),A=[...P],e+!~t*N,A[r]^=p,A[t]^=p))),m=m>e?m:e)|m

Try it online!
NB: The reason why it's slower is that we do not compute the powersets of the players. Given a bitmask of players \$X\$, we iterate on all \$(X \operatorname{AND} p)\$ for \$0\le p\le X\$ without deduplicating.

JavaScript (ES7),  293 272  271 bytes
Takes input in the format described in the challenge. This is a brute force search.

f=(D,P=[17**6+'8'],e=m=0)=>P.map((X,r)=>X&&[...X].reduce((a,x)=>[...a,...a.map(y=>y+x)],['']).map(p=>D.map(([d,s,t],j)=>p<99|p[5]|r-s|eval([...p].join`+`)%9^d%9||f(D.filter(_=>j--),A=[...P],e+!~t*p.length,A[r]=X.replace(eval(`/[${p}]/g`),''),A[t]=[A[t]]+p))),m=m>e?m:e)|m

Try it online! (the first test case times out on TIO)
How?
The array P[] holds a list of strings describing the players in each room.
We start with P=['241375698'] (using \$17^6=24137569\$), which means that all players are initially located in room \$0\$.
For each room X at position r, we compute the powerset of X:
[...X].reduce((a, x) => [...a, ...a.map(y => y + x)], [''])

For each group of players p in there and for each door [d,s,t] at index j, we test if the group is unable to pass through the door:
                         // we can't pass if:
p < 99 |                 // there are less than 3 players
p[5] |                   // or there are more than 5 players
r - s |                  // or the source room s is not equal to the current room
eval([...p].join`+`) % 9 // or the sum of the players modulo 9
^ d % 9                  // does not match the ID of the door modulo 9

If the group can pass, we do a recursive call:
f(                       //
  D.filter(_ => j--),    // remove the door that has just been used from D[]
  A = [...P],            // use a copy A[] of P[]
  e + !~t * p.length,    // if t = -1, add the length of p to e (number of escaped guys)
  A[r] = X.replace(      // remove the players from the source room A[r]
    eval(`/[${p}]/g`),   //
    ''                   //
  ),                     //
  A[t] = [A[t]] + p      // and append them to the target room A[t]
)                        //

We keep track of the maximum number of escaped players in m and eventually return it.


Perl, 345 334 318 293 263 245B

$_='$_=$i=pop;$c=y///c-1;sub f{say if$c&&$i==eval pop=~s/\^/**/gr}A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;map{f$_}glob joinO,/./g';s!O!"{+,-,*,/,^}"!g;s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;s!d!D!;eval

Call with perl -M5.10.0 scratch.pl 736

Results

The first few results that I found are:

^+343
736^+
7+3^6
^+/3125
^+^3125
/^+-11664
/^--11664
1-1+6^6/4
/^++14641
^^++14641
1+5^6/1-8
1+5^6^1-8
1+5^6-2-2
1+5^6-2^2
1+5^6+2-4
1+5^6+4^2
-^+^16377
-^-+16377
/^+^16384
/^-+16384

Explanation

Fully ungolfed

I tried to repeat myself as much as possible to make the later golfing easier.

#!perl
use 5.10.0;

$_ = $input = pop;

# y///c counts characters in $_
$count = y///c - 1;

sub f {
    say if $count && $input == eval pop =~ s/\^/**/gr
}

# PREFIX
map {
    m{                            # Parses *^+1234
        (\D)                      # $1 = first symbol
        (
            (?R)                  # RECURSE
        |
            (\d)(?{               # $3 = first digit
                $match=$3
            })
        )
        (.)(?{                    # $4 = last digit
            $match="$match)$1$4"
        })
    }x;
    f "(" x $count . $match
}
    # glob expands '{0,1}{0,1}' into 00,01,10,11
    glob "{+,-,*,/,^}" x $count . $input;

# POSTFIX
map {
    m{(\d)((?R)|(\d)(?{$match=$3}))(.)(?{$match="$1$4($match"})};
    f $match. ")" x $count
}
    glob $input . "{+,-,*,/,^}" x $count;

# INFIX
# /./g splits $_ into characters
map { f $_} glob join "{+,-,*,/,^}", /./g

How it's golfed

Remove whitespace & comments and replace all vars with 1-character version
Wrap program in $_=q! ... !;eval
Extract strings and substitute them in afterwards.

This gives something like this, from which you can remove the line breaks for the result:

$_='
    $_=$i=pop;
    $c=y///c-1;
    sub f{say if$c&&$i==eval pop=~s/\^/**/gr}
    A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;
    A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;
    map{f$_}glob joinO,/./g
';
s!O!"{+,-,*,/,^}"!g;
s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;
s!d!D!;
eval


Deadfish, 18

This was actually the first language I tried before I considered infix operators. I'm posting it now for the sheer hilarity of the idea that Deadfish could be useful for something.

iii
ios
sii

For those who don't know Deadfish, i is increment, s is square and o is output, with the accumulator starting at 0 (there's also a 4th instruction d for decrement not used here). The fact that we don't have automatic printing and need to use o is a major drawback, but surprisingly Deadfish doesn't do too terribly here, all things considered. It turns out that the optimal placement of the output operator is in the middle.

iiisoisii 9
iiisiiois 11
iiisiisio 122
iioisiisi 2
iioiisiis 2
iisioiisi 5
iisiisiio 38
iisiisoii 36
iiiiosiis 4
iiiisiosi 17
iiiisiiso 324
isoiiisii 1
isiioiiis 3
isiisiiio 12
oiiiisiis 0
osiiiisii 0
oisiiiisi 0
oiisiiiis 0
siiiisoii 16
sioiiiisi 1
iisiosiii 5
sioiisiii 1
oisiisiii 0
isiisioii 10
siisiioii 6
isiioisii 3
oiisiisii 0
iiosiisii 2
siisoiiii 4
isoisiiii 1
osiisiiii 0
iisiiiosi 7
siiioiisi 3
oiiisiisi 0
siisiiiio 8
iisiiiiso 64
isiiiisio 26
siiiisiio 18
iiosiiiis 2
isiiiiois 5


Counting triangles with integer perimeter

Jelly, 3 bytes

«Ḥ’

Try it online!

Explanation

«   min(a,b)
 Ḥ          *2
  ’           -1

(Not quite rigorous) proof of correctness:

Let x = min(a,b) and y = max(a,b), and let z be a potential third side.
We can't have z ≤ y-x, because for z < y-x the triangle can't be closed and for z = y-x it would be degenerate. See triangle inequality.
We can't have z ≥ y+x, for the same reasons.
Every integer z in between is valid and gives a different triangle. That means we've got (y+x) - (y-x) - 1 = 2x - 1 different triangles.


CJam, 73 70 bytes

q~:Q,mQ:Le!{QL/.{1$W$W*t_:+W*t}:Te_$Q$=Tz{W%_L,.=a\}2*++::+)-!*}=&T"%02d "ffe%N*

The above code is 80 bytes long and qualifies for the bonus.

Time complexity is O(n!) for n×n squares. For 9×9, this translates to 7 seconds on my machine.

Try it online: permalink for Chrome | permalink for Firefox


Jelly,  8  7 bytes

ḊżṖVÆPS

A monadic link taking a sequence member and returning its index in the sequence.

Try it online!

How?

ḊżṖVÆPS - Link: number, n
Ḋ       - dequeue (implicit range) = [ 2   , 3   , 4   ,... ,              n         ]
  Ṗ     - pop (implicit range)     = [   1 ,   2 ,   3 ,... ,                  n-1   ]
 ż      - zip                      = [[2,1],[3,2],[4,3],... ,             [n , n-1]  ]
   V    - evaluate as Jelly code   = [ 21  , 32  , 43  ,... ,         int("n"+"n-1") ]
    ÆP  - is prime? (vectorises)   = [  0  ,  0  ,  1  ,... , isPrime(int("n"+"n-1"))]
      S - sum


Jelly, 12 11 10 bytes

ḟẋLṭ+
0;ç/

Try it online! or generate all permutations of length 4.

How it works

0;ç/   Main link. Argument: B (bit array)

0;     Prepend a 0 to B.
  ç/   Reduce [0] + B by the helper link.

ḟẋLṭ+  Helper link. Left argument: A (array or 0). Right argument: b (bit)

 ẋ     Repeat A b times, yielding A or [].
ḟ      Filter false; remove the elements of A or [] from A.
  L    Get the length of the resulting array.
       This yield len(A) if b = 0 and 0 if b = 1.
    +  Add b to all elements of A.
   ṭ   Tack; append the result to the left to the result to the right.


string ... s="?,!;." ... var x=s.IndexOf(c);

s is used only once, so could be inlined.

var x=s.IndexOf(c); ... &&x>-1&& ... c+" "+(x%2>0?" "+w.ToLower():w):"")+c;

Change "?,!;." to ",;?!." and the test x%2>0 can be simplified to x<2.

Where in the spec does it require double-space after sentence-terminating punctuation? IMO you could lose the " "+ inside the parentheses.

Given the IMO ridiculous interpretation which they're allowing of "random", I don't see why you do such complicated stuff with z. Just use the character index modulo 3. A direct change to

string p(string i){int n=i.Length,j,x;string w="Um|Literally|You know|Er|Okay|Right|Ah|Like".Split('|')[n%8],o="";for(j=0;j<n;j++){var c=i[j];x=",;.?!".IndexOf(c);o+=(x>-1&&j%3<1?c+" "+(x<2?" "+w.ToLower():w):"")+c;}return o;}

gives a further nice saving. An alternative using Linq also saves a lot by exploiting fat arrow syntax, and would be cheaper if they give you free using statements:

using System.Linq;string p(string s)=>string.Join("",s.Select((c,i)=>{var w="Um|Literally|You know|Er|Okay|Right|Ah|Like".Split('|')[s.Length%8];var x=",;.?!".IndexOf(c);return(x>=0&&i%3<1?c+" "+(x<2?" "+w.ToLower():w):"")+c;}));


Pyth, 5 bytes

s.T.g

Test suite

Very straightforward: Group and sort, transpose, concatenate.

s.T.g
s.T.gkQ    Implicit variables
   .gkQ    Group the input input lists of elements whose values match when the
           identity function is applied, sorted by the output value.
 .T        Transpose, skipping empty values. This puts all first characters into
           a list, then all second, etc.
s          Concatenate.


Golfscript - 29 chars

6666,-2%{2+.2/@*\/9)499?2*+}*

I will post analysis later


C#, 1.052 × 1010

The idea is to do the hash function in reverse to get all possible un-hashed strings from the given number. Integer overflow of the 32-bit hash value is also emulated in reverse by incrementing the given hash value by 2^32 on each iteration.

UPDATE: I've made several micro-optimisations that significantly improved the performance of my program. The new version produced 10.52 billion results in 15 minutes (compared to 9.05 billion in 1 hour for the previous version).

Futher improvement may be difficult since the output file was 117GB in size and that's about how much free space I have on my SSD. Writing results to the screen doesn't seem to be a viable option since it's almost a thousand times slower than writing to a file.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Unhash
{
    class Program
    {
        const int minChar = 32;

        const int maxChar = 126;

        // limit maxStrLength to make sure that max hash value does not exceed long.MaxValue (2^63 - 1)
        const int maxStrLength = 12;

        static long[] minHashValues;

        static long[] maxHashValues;

        static Program()
        {
            minHashValues = new long[maxStrLength + 1];
            for (int strLength = 0; strLength <= maxStrLength; strLength++)
                minHashValues[strLength] = Pow(31, strLength) / (31 - 1) * minChar;

            maxHashValues = new long[maxStrLength + 1];
            for (int strLength = 0; strLength <= maxStrLength; strLength++)
                maxHashValues[strLength] = Pow(31, strLength) / (31 - 1) * maxChar;
        }

        static void GuessHash(int hash, int maxLength = 256)
        {
            Stopwatch sw = Stopwatch.StartNew();
            var timeLimit = new TimeSpan(0, 15, 0);

            if (maxLength > maxStrLength)
                maxLength = maxStrLength;

            long currentHash = (uint)hash;
            long step = 1L << 32;

            const int bufferSize = 32 * 1024;
            using (var writer = new StreamWriter("output.txt", false, new UTF8Encoding(false), bufferSize))
            {
                for (int strLength = 0; strLength <= maxLength; strLength++)
                {
                    long maxHash = maxHashValues[strLength];
                    if (currentHash > maxHash)
                        continue;

                    long minHash = minHashValues[strLength];
                    while (currentHash < minHash)
                        currentHash += step;

                    while ((currentHash <= maxHash) && (sw.Elapsed < timeLimit))
                    {
                        GuessLongHash(writer, currentHash, new char[strLength], strLength - 1);
                        currentHash += step;
                    }
                }
            }
        }

        static void GuessLongHash(StreamWriter writer, long hash, char[] chars, int charPos)
        {
            if (hash <= maxChar)
            {
                char ch = (char)hash;
                if (ch >= minChar)
                {
                    chars[charPos] = ch;
                    writer.WriteLine(new string(chars));
                }
                return;
            }

            char c = (char)(hash % 31);
            while (c < minChar)
                c += (char)31;

            while (c <= maxChar)
            {
                chars[charPos] = c;
                GuessLongHash(writer, (hash - c) / 31, chars, charPos - 1);

                c += (char)31;
            }
        }

        static long Pow(int value, int exponent)
        {
            long result = 1;
            for (int i = 0; i < exponent; i++)
                result *= value;
            return result;
        }

        static void Main(string[] args)
        {
            const int hash = 69066349;
            GuessHash(hash);
        }
    }
}