title: An Affinity for Ciphers

text:
# Question
Title: An Affinity for Ciphers
# Description

You, an armchair cryptanalyst, have noticed that the first letters of each word in your neighbor's mail (yes, you read it -- how else would you know if he's plotting something?) look very suspicious put together. To make sure that his mail is safe to send to its destination, you need to first decode these messages. You could check one or two, but your neighbor has many correspondences, and so you determine the best solution is to write a program to do the decoding for you.

Because you're sure that this neighbor is up to no good, you make your program assuming that most of the encoded words are actual words in English. You know that the backups of your backups of your backups are taking up a lot of room on your single drive (paranoia doesn't necessitate intelligence), and so you want to write this program in as little space as possible to minimize the space it takes up when you back it up thrice (it is important, after all).

---

# Description

You are to output what you think is the solution to a given Affine Cipher. In short, Affine ciphers are encoded by the following formula for each character in the plaintext: `C ≡ aP + b (mod 26)` where `a` and `b` are constants, `C` is the ciphertext letter, and `P` is the plaintext letter. In this case, the letter "a" has the value of 0, "b" 1, and so on and so forth.

# Rules

1. With reference to my previous equation, in the ciphers you will be decoding `a` will *only* be a number coprime with 26.
2. For testing the validity of decoded words, you may use a dictionary of your choosing (note that "i" and "a" should be words listed; the validity of the other letters do not matter, but I recommend making only "i" and "a" valid).
3. If you choose to use a dictionary, you must be able to read from a text file and use it as a dictionary (i.e. you shouldn't be restricted to one dictionary). You may accomplish this by taking input of a filename and reading that file or hard-coding in a filename. This is so that every program can use the same dictionary for the test cases. This dictionary will be a text file with a word on each newline, all in lowercase.
4. In each message, if you are using a dictionary, you should account for **three** words not matching a word in English; any more and the decoding is wrong. If you are not using a dictionary, this number should be constant but may be different (so long as you obtain correct answers for the test cases). If there is no output with fewer than three wrong words, you are not to give an output.
5. When you output your decoding, you should output the one you think is most correct (i.e. the one that has the most English words).
6. If you do **not** use a dictionary, claim a `-100 byte` bonus on your submission.
7. When testing words to see if they are valid, check only contiguous alphabetical characters (e.g. you'd test `#affineciphers` as one word but `pa$$word` as two: `pa` and `word`). Words will not necessarily be of one case.
8. Your program must work for all of the test cases, but not be hardcoded for them. In theory, if I add another test case (one within reason), your program should be able to decode it.
9. Though it would be nice if you did so, optimizing for speed is unnecessary and will net you no bonuses.
10. Although I would like to test your program, it does not have to have a free or online interpreter.
11. If you do not use a dictionary, you may not read external files (i.e. the logic used to determine whether a word is a word in the English language or not must be contained within the program).

## Sample encoding

Here's a sample of encoding, done with simple numbers (`a = 3, b = 2`)

`foobar`

First, we express our input numerically

`6, 15, 15, 2, 0, 18`

Then we multiply by `a`

`18, 45, 45, 12, 0, 54`

Optionally reduce to least positive residue

`18, 19, 19, 12, 0, 2`

Add `b`

`20, 21, 21, 18, 2, 4`

Now we reduce to least positive residue (there is no reduction to do for this case, though) and convert to text

`tyyrbd`

## Input

You should be able to handle any characters, but the only encoded characters will be alphabetical ones (both capital and lowercase).

## Output

You should output what your program thinks to be the decoded cipher, with the case matching that of the input and any non-alphabetical character remaining (i.e. don't change the case and strip the input of non-alphabetical characters when you output)

---

## Test Cases

Input followed by expected output. Here is the dictionary you are to use (if you are using one). Save it as `dictionary.txt` (or whatever you want, really), and input its name for testing. This dictionary should have almost all the words in the test cases, with some left out intentionally to test if your program will still output.

**Test Case 1:**

```
@nLWc@ wc! m neCN.

@tHIs@ is! a teST.

```

**Test Case 2:**

```
Yeq lkcv bdk xcgk ez bdk uexlv'm qplqgwskmb.

You lead the race of the world's unluckiest.

```

**Test Case 3:**

```
Ugifc ism ozsmvd kpync g fssw st ryceco sb estbcnny.

Maybe you should write a book on pieces of confetti.

```

**Test Case 4:**

```
Nh wrteq tfwrx, tgy t yezvxh gjnmgrxx stpgx / Nh xrgxr, tx qwzjdw zk wrnuzfb p wty yejgb, / Ze rnsqpry xznr yjuu zsptqr qz qwr yetpgx / Zgr npgjqr stxq, tgy Urqwr-vteyx wty xjgb.

My heart aches, and a drowsy numbness pains / My sense, as though of hemlock I had drunk, / Or emptied some dull opiate to the drains / One minute past, and Lethe-wards had sunk.

```

---

# Notes

The `-100 byte` bonus is subject to increase (i.e. more bytes will be subtracted) if I deem it to be too low. If it's not low enough (i.e. it's too much of a bonus), I will not change it provided that there are answers that have claimed it already.

I will add an ungolfed reference solution (to show how I would attempt the problem) if this question doesn't get any answers soon or if there is popular demand (let me know if you would like a reference solution).

# Answer
# Java 8, 608

```
import java.nio.file.*;import java.util.*;import java.util.function.*;s->{try{List<String>d=Files.readAllLines(Paths.get("d"));int v=java.util.stream.IntStream.range(0,676).mapToObj(I->new int[]{I,(int)Arrays.stream(s.toLowerCase().split("[^a-z]+")).map(u->{char[]x=new char[u.length()];for(int i=x.length;i-->0;)x[i]=(char)(((u.charAt(i)-'a')*(I%26)+I/26)%26+'a');return new String(x);}).filter(d::contains).count()}).max((m,n)->m[1]-n[1]).get()[0],a=v%26,b=v/26;s.chars().forEach(h->System.out.print((char)(h>='a'&&h<='z'?((h-'a')*a+b)%26+'a':h>='A'&&h<='Z'?((h-'A')*a+b)%26+'A':h)));}catch(Exception e){}}

```

This is a bunch of imports, and then a lambda expression. Runnable, readable code follows:

```
import java.nio.file.*;
import java.util.*;
import java.util.function.*;

public class C {

    static final Consumer<String> f = s -> {
        try {
            List<String> d = Files.readAllLines(Paths.get("d"));
            int v = java.util.stream.IntStream.range(0, 676).mapToObj(I -> new int[]{I, (int) Arrays.stream(s.toLowerCase().split("[^a-z]+")).map(u -> {
                char[] x = new char[u.length()];
                for (int i = x.length; i-- > 0;) {
                    x[i] = (char) (((u.charAt(i) - 'a') * (I % 26) + I / 26) % 26 + 'a');
                }
                return new String(x);
            }).filter(d::contains).count()}).max((m, n) -> m[1] - n[1]).get()[0],
                a = v % 26,
                b = v / 26;
            s.chars().forEach(h -> System.out.print((char) (h >= 'a' && h <= 'z' ? ((h - 'a') * a + b) % 26 + 'a' : h >= 'A' && h <= 'Z' ? ((h - 'A') * a + b) % 26 + 'A' : h)));
        } catch (Exception e) {
        }
    };

    public static void main(String[] args) {
        f.accept("@nLWc@ wc! m neCN.");
    }
}

```

The dictionary should be stored in a file named "d", with no extension. One word per line.
> 1 votes

---
Tags: code-golf, cryptography
---


title: Why? To please the rich programmer!

text:
# Question
Title: Why? To please the rich programmer!
Have you ever wanted to ask the compiler "Why?" Most of us have been frustrated when the code isn't working as it should. Mathworks has therefore implemented a nice little function, `why`, that answers the question. To give a few examples from MATLAB:

```
why
The programmer suggested it.

why
To fool the tall good and smart system manager.

why(2)
You insisted on it.

why(46)
Bill insisted on it.

```

Your task is to implement the `why` function in your language. The function should work with and without an input argument (alternatively use input `0` or `-1`). The function must be named `why` (or, writing `why(n)` in STDIN should result in the appropriate string being printed).

If no argument is given, or the argument is zero or negative, the output string should be a random, valid phrase. So, there should be a function `why`, `why()`, `why(0)` or `why(-1)` that returns a random sentence.

If an input argument, `n` is given (function argument, not STDIN), the output should be the n'th string (defined below). So, `why(1)` should always output (print/display) the same result.

The sentences are built up as follows (Type 1, Type 2 and Special). All sentences end with `!`.

```
"Person" "ending" !
"Verb" "adjective" "Person" !
A list of special cases

```

The list of persons:

```
Stewie
Peter
Homer
The programmer
The system manager
You

```

The list of endings:

```
suggested it
insisted on it
did it

```

The list of verbs are:

```
To fool
To satisfy
To please

```

The list of adjectives:

```
the smart
the bald
the tall
the rich
the stupid

```

The list of special cases:

```
How should I know?
Stop asking!
Don't ask!

```

The way to select a numbered one is:

**Type of sentences:**

```
Odd number => Type 1
Even number => Type 2
n % 7 = 0 => Type 3 (% is the modulus operator)

```

**Names:** The nth name is defined using modulus (%).

```
n = 1:   1 % 7  => Stewie
n = 2:   2 % 7  => Peter
...
n = 6:   6 % 7  => You
n = 7:   7 % 7  => How should I know?
n = 11:  11 % 7 => The programmer
n = 14:  14 % 7 => Stop asking!
n = 21:  21 % 7 => Don't ask!

```

**Endings:** The nth ending is also defined using the modulus. Assume the endings (1, 2 and 3) are listed like `(1 2 2 3)`. As the numbers are always odd, use `((n+1)/2 % 4)`

```
n = 1:    ((1+1)/2 % 4)  => suggested it
n = 3:    ((3+1)/2 % 4)  => insisted on it
n = 13:   ((13+1)/2 % 4) => did it

```

**Adjectives:** The nth adjective is defined using the modulus. As the numbers are always even, use: `(n % 10)/2`

```
n = 2:   (2 % 10)/2 => Smart
n = 6:   (6 % 10)/2 => The tall
...

```

**Verbs:** The nth verb is also defined using the modulus. Assume the verbs (1, 2 and 3) are listed like `(1 2 2 3)` As the numbers are always even for verbs, use `(n % 8) / 2`

```
n = 2:   (2 % 8)/2 => To fool
n = 4:   (4 % 8)/2 => To satisfy
n = 6:   (6 % 8)/2 => To satisfy
n = 8:   (8 % 8)/2 => To please

```

Now, the way to create a random one should be fairly simple, simply select a random `n`.

Some examples:

```
why
You suggested it!

why
To fool the tall Homer!

why
Don't ask!

why(1)
Stewie suggested it!

why(14)
Stop asking!

why(8)
To please the rich Stewie!

```

Standard code golf rules apply. A winner will be selected one week from the day the challenge was posted.

# Answer
> 5 votes
# JavaScript (ES6) 345

Not sure about the numbers, but here is my attempt.

Test running the snippet below in an EcmaScript compliant browser.

```
why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])

for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o

function test() { R.innerHTML=why(+I.value) }

// Less golfed

WHY=n=>(
  n=n<1?Math.random()*999|0:n,
  s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
     "stupid", "smart", "bald", "tall", "rich",
     "Don't ask!", "How should I know?", "Stop asking!",
     "Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
  n%7
    ? ( p=s[n%7+13],
        n&1
        ? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
        : `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
    : s[11+n%3]
)
```

```
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
```

```
Why(<input id=I>)<button onclick=test()>-></button><span id=R></span>
<pre id=O>
```

# Answer
> 3 votes
# C#, 502 bytes

This project needs to have the **AssemblyName** set to **why** which will produce an executable with the correct name.

Fully golfed:

```
using System;class W{static void Main(string[]i)int n=i.Length>0?int.Parse(i[0]):new Random().Next();string[]s={"Don't ask!","How should I know?","Stop asking!"},v={"To please ","To fool ","To satisfy ",null},a={"the stupid","the smart","the bald","the tall","the rich"},p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},e={"suggested it!","insisted on it!",null,"did it!"};Console.Write(n%7<1?s[n%3]:n%2<1?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!":"{0} "+(e[n/2%4]??e[1]),p[n%7]);}}

```

Indentation and new lines for clarity:

```
using System;
class W{
    static void Main(string[]i)
        int n=i.Length>0
            ?int.Parse(i[0])
            :new Random().Next();
        string[]
            s={"Don't ask!","How should I know?","Stop asking!"},
            v={"To please ","To fool ","To satisfy ",null},
            a={"the stupid","the smart","the bald","the tall","the rich"},
            p={"","Stewie","Peter","Homer","The programmer","The system manager","You"},
            e={"suggested it!","insisted on it!",null,"did it!"};
        Console.Write(
            n%7<1
                ?s[n%3]
                :n%2<1
                    ?(v[n%8/2]??v[2])+a[n%10/2]+" {0}!"
                    :"{0} "+(e[n/2%4]??e[1]),
            p[n%7]
        );
    }
}

```

Example input/output:

```
>Why
To fool the bald Homer!
>Why 1
Stewie suggested it!

```

# Answer
> 2 votes
# Powershell ~~437~~ ~~461~~ 453 Bytes

Edit: Missed the duplicated verbs

Splitting between the corpus and the calculations for byte-count

* 267 Bytes = Pre-coded text (excluding `to`,`the`,`it` and `!` since they have fixed places).
* 186 Bytes = calculation

Sets default argument to 0 if not specified. If argument is `<1` then it gets a random number `<99` `fn:1` and reruns. Technically this means `-50` will work as well, being treated as a random case.

```
function why{param($b=0)$p=@('Stewie','Peter','Homer','The programmer','The system manager','You');$e=@('did','suggested','insisted on','insisted on');$v=@('please','fool','satisfy','satisfy');$a=@('stupid','smart','bald','tall','rich');$s=@("Don't ask!",'How should I know?','Stop asking!');if($b-le0){why(Get-Random 99)}elseif(!($b%7)){$s[$b/7%3]}else{$n=$p[$b%7-1];if($b%2){"$n $($e[($b+1)/2%4]) it!"}else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"}}}

```

Explanation:

```
# Any -1 in calculations is to account for arrays starting at index 0
# Final key placed in position 0 for indexing (4%4 = 0)
# Powershell 1 = True, 0 = False
if($b-le0){why(Get-Random 99)}          # If not positive, choose random number
elseif(!($b%7))                         # $b%7 means special so use that
  {$s[$b/7%3]}                          # Divide by 7 and find modulo, use that phrase.
else{$n=$p[$b%7-1]                      # Get the correct person (Used in both types). 6 max
if($b%2){"$n $($e[($b+1)/2%4]) it!"}    # Create type 1 sentence
else{"To $($v[$b%8/2]) the $($a[$b%10/2]) $n!"} # Type 2

```

`fn:1` 99 Chosen to save a byte. If there are more than 99 possible sentences above (did not calculate) increase to 999 or 9999 as applicable (+1/2 bytes)

# Answer
> 2 votes
# MUMPS, 379 bytes

```
f(s,i) s:'i i=$L(s,"^") q $P(s,"^",i)
why(n) s:'n n=$R(840) s p="Stewie^Peter^Homer^The programmer^The system manager^You",e="suggested^insisted on^did",v="fool^satisfy^please",a="smart^bald^tall^rich^stupid",s="How should I know?^Stop asking!^Don't ask!" q:n#7=0 $$f(s,n#3) q:n#2 $$f(p,n#7)_" "_$$f(e,n+1/2#4)_" it!" q "To "_$$f(v,n#8/2)_" the "_$$f(a,n#10/2)_" "_$$f(p,n#7)_"!"

```

When no input is given, a random number in 0..839 is generated.

Usage:

```
>w $$why(15)
Stewie did it!
>w $$why()
Don't ask!

```

MUMPS's left-to-right evaluation strategy saves a good few bytes on parentheses here.

Side note: see those strings that look like `"foo^bar^baz^qux"`? Those are so-called "delimited strings", and are the standard way of storing lists that fit within the maximum string size limit, since MUMPS does not actually have lists/arrays (or, indeed, any data structures besides trees). For lists too large to fit in a single string, we instead use trees of depth 1 and put the values on the leaves of the tree. Fun!

# Answer
> 1 votes
# Emacs Lisp 473 Bytes

```
(defun why(n)(if(and n(> n 0))(let*((p'(t"Stewie""Peter""Homer""The programmer""The system manager""You"))(e'("did""suggested""insisted on""insisted on"))(v'("please""fool""satisfy""satisfy"))(a'("stupid""smart""bald""tall""rich"))(s'("Don't ask!""How should I know?""Stop asking!"))(q(nth(% n 7)p)))(cond((=(% n 7)0)(nth(%(/ n 7)3)s))((=(% n 2)1)(format"%s %s it!"q(nth(%(/(1+ n)2)4)e)))(t(format"To %s the %s %s!"(nth(/(% n 8)2)v)(nth(/(% n 10)2)a)q))))(why(random 99))))

```

Largest 'waste' is probably the `format`,`%s`... sections. If variables could be inlined into the strings without the specification it would save 10 bytes on `%s` and another 12 on `format`

# Answer
> 1 votes
# Ruby ~~396~~ ~~378~~ 372 bytes

I'm sure this is not golfed to the max.

```
p=%w[a Stewie Peter Homer The\ programmer The\ system\ manager You]
why=->n{n<1 ? why[rand(99)+1]:n%7<1 ? $><<%w[a How\ should\ I\ know? Stop\ asking! Don't\ ask!][n/7]:n%2<1 ? $><<'To '+%w[fool satisfy satisfy please][n%8/2-1]+' the '+%w[smart bald tall rich stupid][n%10/2-1]+' '+p[n%7]+?!:$><<p[n%7]+' '+%w[a suggested insisted\ on insisted\ on did][(n+1)/2%4]+' it!'}

```

Edit: I've just realized that I don't know operator precedence. Oh well..

# Answer
> 1 votes
## CJam, 281 bytes

```
99mrqi_])0>=i:A7md{;A2%{S["suggested""insisted on""did"]A2/=+" it"+}{"To "["fool""satisfy"_"please"]A(2/:B=" the "["smart""bald""tall""rich""stupid"]B=SM}?[M"Stewie""Peter""Homer""The programmer""The system manager""You"]A=\'!}{["How should I know?""Stop asking!""Don't ask!"]\(=}?

```

Permalink

Haven't used CJam before, so I'll take any tips. I'm sure there's a lot of tricks I don't know!

(I couldn't figure out how to name this as a function called "why" - it appears that functions don't exist in CJam - so I'm not sure if a CJam answer is okay or not...)

# Answer
> 1 votes
# Lua 5.3.0, 452 460 446 bytes

This is my first attempt at a code golf, so please correct me if I did something wrong!

```
a={"Stewie","Peter","Homer","The Programmer","The system manager","You"}b={"fool ","satisfy ",n,"please "}b[3]=b[2]why=function(n)pcall(math.randomseed,n and n>0 and n)n=math.random(1e9)q=n>>4r=n>>8return 1>n&7 and({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]or 0<n%2 and a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"or"To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]end

```

Ungolfed:

```
a={
    "Stewie",
    "Peter",
    "Homer",
    "The Programmer",
    "The system manager",
    "You"
}
b={
    "fool ",
    "satisfy ",
    n,
    "please "
}
b[3]=b[2]
why=function(n)
    pcall(math.randomseed,n and n>0 and n)
    n=math.random(1e9)
    q=n>>4
    r=n>>8
    return
            1>n&7 and
                ({"How should I Know?","Stop asking!","Don't ask!"})[q%3+1]
            or 0<n%2 and
                a[q%6+1]..({" suggested"," insisted on"," did"})[r%3+1].." it"
            or
                "To "..b[q%4+1].."the "..({"smart ","bald ","tall ","rich ","stupid "})[r%5+1]..a[(r>>4)%6+1]
end

```

# Answer
> 0 votes
# Python (2), 692 bytes

I’m still learning, so please be gentle! :)

```
from sys import argv,maxint
import random
def why(*O):
 P=["You","Stewie","Peter","Homer","programmer","system manager"];E=["did","suggested","insisted on","insisted on"];I=["please","fool","satisfy","satisfy"];Q=["stupid","smart","bald","tall","rich"];S=["Don't ask!","How should I know?","Stop asking!"]
 if len(argv)>1:A=O[0]
 else:A=random.randint(-maxint-1,maxint)
 if A%7==0:print S[A%3]
 else:
  M=P[A%6]
  if A%11==0:
   M=P[4]
  if A%2==0:
   if M==P[0]:M="you"
   U=I[(A%8)/2];Z=Q[(A%10)/2];print"To %s the %s %s!"%(U,Z,M)
  if A%2==1:
   if M==P[4]:M="The %s"%P[4]
   if M==P[5]:M="The %s"%P[5]
   C=E[((A+1)/2)%4];print"%s %s it!"%(M,C)
if len(argv)>1:why(int(argv[1]))
else:why()

```

Works with or without an int as a command line argument.

I tried to emphasise code correctness as much as possible, as with generating random numbers from `-sys.maxint - 1` to `sys.maxint` and displaying sentences in the right case.

The code relies very heavily of if-statements that I’m sure could be replaced with something more place efficient.

Feedback is very welcome!

### Ungolfed (1341 bytes)

```
from sys import argv, maxint
import random

def Why(*Optional):
    Persons = ["You", "Stewie", "Peter", "Homer", "programmer", "system manager"]
    Endings = ["did it", "suggested it", "insisted on it", "insisted on it"]
    Verbs = ["please", "fool", "satisfy", "satisfy"]
    Adjectives = ["stupid", "smart", "bald", "tall", "rich"]
    SpecialCases = ["Don't ask!", "How should I know?", "Stop asking!"]

    if len(argv) > 1:
        Argument = Optional[0]
    else:
        Argument = random.randint(-maxint - 1, maxint)

    if Argument % 7 is 0:
        print SpecialCases[Argument % 3]
    else:
        Person = Persons[(Argument) % 6]
        if Argument % 11 is 0:
            Person = "programmer"
        if Argument % 2 is 0:
            if Person is "You":
                Person = "you"
            Verb = Verbs[(Argument % 8) / 2]
            Adjective = Adjectives[(Argument % 10) / 2]
            print "To %s the %s %s!" % (Verb, Adjective, Person)
        if Argument % 2 is 1:
            if Person is "programmer":
                Person = "The programmer"
            if Person is "system manager":
                Person = "The system manager"
            Ending = Endings[((Argument + 1) / 2) % 4]
            print "%s %s!" % (Person, Ending)

if len(argv) > 1:
    Why(int(argv[1]))
else:
    Why()

```

---
Tags: code-golf
---


title: Code me a Jam!!

text:
# Question
Title: Code me a Jam!!
On occasion I get a little blue and need a little music to cheer me up, but clicking the start button and finding my media player takes *sooooooo* long. I want a faster way to play a song.

**The challenge:**

Write a program that:

* Choose a song from my home directory *(so you don’t mix-up program sound files with music)* *(this includes sub folders of the home directory)*.
* This song should be a random choice from all the media in my home folder. This doesn't need to be a perfect random, but I don't want to hear the same song multiple times. *(unless that's my only song ;)*
* To make it simple you should only look for files ending in `.mp3`.
* In the event that you find no music in my home dir, you should print `Sorry Joe, no Jams!` to stdout or closest equivalent *(btw my name isn't Joe ;)*
* The layout of my home folder will contain no infinite loops
* You should use system to play the song instead of using built in media playing APIs in your language *(i.e. I want the song to play in the default player for my system)*.
* I should be able to place this file anywhere on my computer *(e.g. my desktop or start folder)*
* Your answer should work on windows, multi-platform is a *(un-scored)* bonus

This is code golf so the shortest program in bytes wins!!

# Answer
### PowerShell, 59 52 bytes

```
ii(ls -r./*.mp4|random);(,"Sorry Joe, no Jams!")[$?]

```

-7 byte golf improvements, thanks to Jaykul:

* Use `ii` (`Invoke-Item`) instead of `saps`
* No need to use `Get-` in `Get-noun` commandlet names, it will be searched by default.
* No space needed after `-r`

---

Previously at 59 bytes

```
saps(ls -R ~/*.mp3|Get-Random);(,"Sorry Joe, no Jams!")[$?]

```

It will throw an error if there are no files, but it will print the message too.

Explanation:

* `saps` is an alias for Start-Process
* `ls` is an alias for Get-ChildItem
* `~` maps to the home directory, and `-R` is -Recurse
* Get-Random selects a random item from the pipeline.
* After trying to launch it, it uses the previous command exit value as an index into a two-item array which either does nothing, or returns the apology message.
> 3 votes

# Answer
# Dyalog APL, ~~78~~ ~~75~~ 73

```
{0::'Sorry Joe, no Jams!'⋄⎕SH⍵,{⍵⊃⍨?≢⍵}⎕SH∊'dir/b '⍵'*.mp3'}'%HOMEPATH%\'

```

**Explanation**:

`{`...`}` unnamed function, wherein  represents whatever is to the right of the `}`
APL statements (separated by ) are executed leftmost first, but each statement is evaluated from right to left (no precedence rules), so each function gets whatever is to its right as argument
`0::` sets a trap for all errors to return the string instead
`∊'dir/b '⍵'*.mp3'` makes the three strings into a single string
`⎕SH` passes its argument to *cmd.exe*
`?≢⍵` random 1 ≤ integer ≤ count (or 0 \< float \< 1 if count is 0)
`⍵⊃⍨` pick that element (floats are invalid indices, so an error is triggered here if count was 0)
`⍵,` prepends the home dir
`⎕SH` passes its argument to *cmd.exe*
> 3 votes

# Answer
# Python 2, 178 bytes

```
import glob,os,random
try:os.startfile(random.choice([y for x in os.walk(os.getenv('HOMEPATH'))for y in glob.glob(os.path.join(x[0],'*.mp3'))]))
except:print"Sorry Joe, no Jams!"

```

Works on Windows, as per the spec.
> 1 votes

# Answer
# Linux shell utilities, 74

Ok, so this one's not going to work on windows, but in case you decide to use a real OS (), here's what you could do in Linux:

```
find ~ -name \*.mp3|shuf|(read l&&xdg-open "$l"||echo Sorry Joe, no Jams!)

```
> 1 votes

---
Tags: code-golf, music
---


title: Generate Some Secure PINs

text:
# Question
Title: Generate Some Secure PINs
*Inspired by this badly received migrated post.*

The head of security at your company is concerned about your PIN generating system after it gave him `12345`. He also didn't really appreciate the Spaceballs joke you made at his expense, so you've been delegated to re-write the PIN generator. Since it has to fit on some special hardware, you have to make it as small as possible.

# Your Task

* You take two inputs - # of PINs, and PIN size in digits.
* Generate the specified number of PINs of the specified size **randomly** and print it out.
* All valid PIN's of the size must be possible to be printed out, even if they aren't uniformly probable.
* However, there are some restrictions on the PINs - here are the invalid ones:

1. If all the pairs are the same digit: `114422` (Note: this will obviously include all same digit PINs).
    2. Increasingly linear PINs (mod 10): `246802`.
    3. All groups of 3 are physical lines on the keypad of `1 2 3;4 5 6;7 8 9;bksp 0 enter;`: `147369`.
    4. The PIN can be entirely split up into groups from rule 1 and rule 3.

* This is , so shortest code in **bytes** wins!

# Answer
# Pyth, 120 bytes

```
Arz7VGJ1WJK%"%0*d",HO-^TH1=J|q1l{m%-F_vMcd1T.:K2u|GHmu|GHm?qlk2:k"(.)\\1"0?qlk3}k+++=bcS"123456789"3_Mb.Tb_M.TbZdZ./K0)K

```

Figured I should add a real implementation then. Generates random numbers until one is found that meets all requirements. Can probably be improved a lot!

Online version
> 1 votes

# Answer
# Perl 5, 244

Starts with generating random numbers for the given size.
And only prints those that don't meet the restrictions.

Finding a solution for the keypad lines (without hardcoding combinations) was kinda fun.

```
($k,$l)=@ARGV;$m=10**$l-1;while($n<$k){$_=sprintf("%0".$l."d",int(rand($m)));@N=split//,$_;pop@N;$i=$d=0;while(++$i<@N&&$d<1){$d=$N[$i-1]<=>$N[$i]}$b=$_;$b=~s|\d|@A=split//,$';2*$A[0]-$&-$A[1]==0|eg;if((!m/(\d)\1/)&$b>0&$d>=0){$n++;print$_.$/}}

```

# Test

```
$ perl gen_pins.pl 10 5
98121
15931
69042
93730
83458
25312
24601
49468
49490
67012

```
> 0 votes

---
Tags: code-golf, number, random
---


title: Harmonious "Convergence"

text:
# Question
Title: Harmonious "Convergence"
The Alternating Harmonic Series is a well known convergent series.

"Clearly", it is obvious that it converges to the natural log of 2. Or does it?

Since the series is not absolutely convergent, by simply rearranging the terms, I can make it approach anything I want. Suppose I want the series to converge to . All I'd have to do is this:

If you didn't catch the pattern, there isn't an obvious one. Here's how it works:

1. Consider the terms of the alternating harmonic series in terms of positive and negative terms.
2. Add together just enough positive terms to exceed our target (e). (aka `sum > target`)
3. Subtract the next negative term.
4. Go back to 2.

Note that at step 2, if our `sum == target`, you should add another positive term.

From this we can define a sequence associated with each number as follows:

* Follow the algorithm above
* For each positive term, output 1.
* For each negative term, output 0.

Let's call this sequence the "Harmonious Bit Pattern" of a number. For example, the HBP of e begins as:

```
1, 1, 1, 1, <32 times>, 0, 1, 1, <54 times>, 0, 1, 1, ...

```

## Your challenge:

You will be given:

* a rational input *target* in the range \[-10, 10\] (note: even reaching 10 via the harmonic series takes many millions of terms). This may be a decimal (aka `1.1`) or you may take a rational directly (aka `12/100`)
* a positive `int` *n* input, specifying the number of terms of the Harmonious Bit Pattern to output.

You are expected to output the exact Harmonious Bit Pattern of the *target* to the specified number of terms. You may output space separated values, comma separated, no separation, etc; just as long as the pattern of 0s and 1s is clearly visible and is read left to right with consistent separation.

## Test Cases

```
>>> 0, 1
1
>>> 0, 2
10
>>> 0, 7
1000010
>>> 1, 10
1101011011
>>> 1.01, 3
110
>>> 1.01, 24
110101101101101101101101
>>> 2.71, 32
11111111111111111111111111111111
>>> 2.71, 144
111111111111111111111111111111110111111111111111111111111111111111111111111111111111111101111111111111111111111111111111111111111111111111111111
>>> -9.8, 100
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

Note that since `-9.8` is so large, the first `1` that would be output is somewhere around the `149496620`th term (that was computed via floats, so the value might not be exact).

# Answer
> 3 votes
# Perl, 69 bytes

```
use bigrat;$s+=.5/($s>$ARGV[$_=0]?-++$n:++$p-++$_/2),print for 1..pop

```

Takes inputs as command line arguments.

**Explanation**: `bigrat` enables fractions everywhere for accurate calculations. `$s` is the current sum of terms, `$ARGV[0]` is the target value, `pop` (same as `$ARGV[1]`) represents the number of terms, `$p` and `$n` represent the positive and negative term counts. `$_` is either `1` or `0` depending on whether a positive or negative term was added.

# Answer
> 3 votes
# Haskell, ~~92~~ ~~91~~ 90 bytes

```
import Data.Ratio
f=(.h 0 1 2).take
h a p q z|a>z=0:h(a-1%q)p(q+2)z|1<2=1:h(a+1%p)(p+2)q z

```

Usage example: `f 24 1.01` -\> `[1,1,0,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1]`.

`h` builds the infinite bit pattern by carrying four parameters around: `a` is the current sum. `p` is the denominator of the next positive term, `q` for negative terms. `z` is the target number. `f` starts everything up and truncates the result to length `n`.

Edit: @Zgarb found a byte to save. Thanks!

# Answer
> 1 votes
# Python 3, ~~128~~ 124 bytes

```
from fractions import*
F=Fraction
*c,s=2,1,0
t=F(input())
for i in'x'*int(input()):w=s<=t;s+=F(w*2-1,c[w]);c[w]+=2;print(+w)

```

This makes use of Python's `Fraction` class.

```
from fractions import*
F=Fraction
*c,s=2,1,0                # c = [2, 1]. s = 0
                          # c is my positive/negative term counter, s is the sum
t=F(input())              # input a fraction
for i in'x'*int(input()): # Do this for for the chosen number of terms, as per the spec
  w=s<=t;                 # "w" or which one do we choose? Positive or negative?
  s+=F(w*2-1,c[w]);       # w*2-1 gives 1 if w else -1. Gives 1 if we need to add, else -1
  c[w]+=2;                # Increment the coefficient we chose
  print(+w)               # Output that. The +w coerces the bool to an int.

```

---
Tags: code-golf, sequence
---


title: Can I Slide Apart The Puzzle?

text:
# Question
Title: Can I Slide Apart The Puzzle?
Write a program or function that takes in a rectangular grid of text where every cell is either an `A` or a `B`. All the `A` cells will form a simply-connected shape, i.e. they will all be orthogonally connected with no holes (diagonally neighboring letters do not count as connected). Likewise, all the `B` cells will form another simply-connected shape. The grid will always contain at least one `A` and at least one `B`.

Imagine the grid is actually two blocky-shaped pieces of thin plastic, represented by the `A` and `B` portions. If it were placed flat on a table, could the two pieces be slid apart while keeping both completely flat on the table?

Print or return a truthy value if the two `A` and `B` shapes could be separated like this by simply pulling them apart. If not, print or return a falsy value.

For example, the input

```
AAA
ABB
AAA

```

is truthy because the `BB` section can be slid to the right, separating it from the `A`'s:

```
AAA
A    BB
AAA

```

However, the input

```
AAAA
ABBA
ABAA

```

is falsy because there's no way to slide the `A` and `B` portions apart without having them overlap.

The shortest code in bytes wins. If desired, you may use any two distict printable ASCII characters in place of `A` and `B`.

**Truthy Examples (separated by empty lines)**

```
BBB
BAA
BBB

BA

A
B

AB
AB

AAA
BBB

AAAAB
ABBBB

ABBA
ABBA
AAAA

AAAAAABBBBBBBBB
AABBBBBBBBBBBBB
AAAAAAAAAABBBBB
AABBBBBBBBBBBBB
AAAAAAAAAAAAAAB

AAAAAAAAAAAA
ABABABABABAB
BBBBBBBBBBBB

BAAAAABB
BBAAABBB
BBBABBBB
BBBABBBB
BBBABBBB
BBBBBBBB
BBBBBBBB

AAA
BAA
AAA

```

**Falsy Examples**

```
BBBB
BAAB
BABB

BBBB
BAAB
AABB

BBBBBBB
BBBBBAB
AAAAAAB
BBBBBBB

BAAA
BABA
BBBA
AABA
AAAA

AAAAAAA
ABBBBBA
AAAAABA
BBBBBBA

BAAAAABB
BBAAABBB
BBBABBBB
BBBABBBB
BBBAABBB
BBBBBBBB
BBBBBBBB

AAA
ABA
BBA
ABA
AAA

```

# Answer
# Snails, 14

```
o(t\B+~)+!(t\B

```

If the puzzle can be slid apart, it prints the area of the input. Otherwise, it prints 0.

It's a bit slow for the larger examples, as it takes time factorial in the area of the grid.

```
         ,, the program will print the number of starting cells matching this pattern
o        ,, pick a cardinal direction
(
    t    ,, teleport to any cell on the grid
    \B+  ,, match "B" 1 or more times, moving in the direction set by 'o'.
         ,, when a cell is matched, it gets slimed and can't be matched again.
    ~    ,, match an out-of-bounds cell
)+       ,, do parenthesized instructions 1 or more times
!(       ,, the following must not match:
    t\B  ,, teleport to some cell and match 'B'

```
> 9 votes

# Answer
# CJam, ~~33~~ ~~32~~ ~~20~~ ~~19~~ 17 bytes

Revised version, with massive support from @Sp3000 and @MartinBüttner:

```
qN/_z]{:e`z,3<}/|

```

Try it online

### Contributions

* @Sp3000 suggested a critical simplification to my original algorithm.
* @MartinBüttner applied his mad golfing skills to the revised approach, which almost certainly resulted in shorter code than I would have come up with even after considering the simplification.

### Algorithm and Proof

The following explains the criteria for the puzzle sliding apart horizontally. The vertical case can be determined by looking at columns instead of rows, or transposing the character matrix and looking at the rows again.

I'll use the term "stretch" for a maximum sequence of the same letters. For example, the following rows have 1, 2, and 3 stretches respectively:

```
AAAAAAAA
BBBAAAAA
AABBBAAA

```

I'll also use the term "interlocked" for a row/puzzle that cannot slide apart.

The key observation is that **the puzzle can slide apart if and only if all rows have at most 2 stretches**. Or reversed, it is **interlocked if and only if there is any row with more than 2 stretches**.

The following might not qualify as a strict mathematical proof, but I believe that it makes for a convincing explanation why this has to be the case.

It is easy to see that the puzzle is interlocked if it has rows of more than 2 stretches. Looking at a row with 3 stretches:

```
BBBAAB

```

it is clear that it prevents the puzzle from sliding apart because the `A` stretch is locked between the `B` stretches. This means that the row is interlocked, which in turn makes the whole puzzle interlocked.

The opposite direction of the proof is not quite as obvious. We need to show that there are no interlocked puzzles where all rows have only 1 or 2 stretches. Starting with a couple of observations:

* Rows with only 1 stretch do not contribute to a puzzle being interlocked, since they can slide in either direction without any collisions.
* If all rows with 2 stretches have the same order of `A` and `B`, the puzzle is clearly not interlocked. In this case, all `A` cells are left of all `B` cells, or vice versa, and there are no collisions when sliding the two pieces apart.

The only tricky case would be puzzles where we have rows with 2 stretches of different order. I'm going to show that such puzzles **do not exist** under the given specifications. To show this, let's look at a partial puzzle that does have this configuration, where `.` are wildcards:

```
.......
AAABBBB
.......
BBAAAAA
.......

```

Now, the specification says that both the `A` and `B` cells are simply connected in all valid puzzles. To make the `A` cells connected in the partial puzzle above, we have two options:

1. We loop around one of the stretches of `B`, for example:

```
..AAAAAA
AAABBBBA
.......A
BBAAAAAA
........

```

To do this, we unavoidably extend one of the rows to have 3 stretches, so this will never give us a valid puzzle where all rows have at most 2 stretches.
2. We connect them on a direct path:

```
.......
AAABBBB
..A....
BBAAAAA
.......

```

The `A` cells are now simply connected, and there are still no rows with more than 2 stretches. However, the `B` cells also need to be simply connected. The direct path is now blocked by the connected `A` cells, and the only way to connect the `B` cells is to loop around one of the stretches of `A` cells. This leads back to case 1, where we can't do that without creating rows of 3 stretches.

To count the stretches, the implementation uses the CJam RLE operator.

### Explanation of Code

```
qN/     Get input and split at newlines.
_z      Make a transposed copy.
]       Wrap the original and transposed puzzle in an array so that we can
        loop over the two.
{       Start of loop over original and transposed puzzle.
  :e`     Apply RLE to all rows.
  z,      Transpose the matrix with the RLE rows, and take the element count of the
          result. Or in other words, take the column count. This will be the length
          of the longest row after RLE.
  3<      Check the length for less than 3.
}/      End of loop over original and transposed puzzle.
|       Or the results of the two.

```
> 21 votes

# Answer
# JavaScript (ES6), ~~108~~ ~~107~~ ~~98~~ ~~91~~ 82 bytes

```
a=>!(T=[],R=/AB+A|BA+B/).test([...a].map((c,i)=>T[i%-~a.search`
`]+=c))|!R.test(a)

```

Live demo. Tested in Firefox. Takes input as a newline-delimited string.

Edits:

* Saved 1 byte by changing `\n` to a literal newline.
* Saved 9 bytes by doing the RegExp test directly on the multi-line string instead of converting to an array.
* Eliminated another 9 bytes by using array comprehensions to split string, moving ! into `g` function and calling RegExp directly on array instead of using `find`.
* Continued the arthmetic sequence by saving another 9 bytes. Did a modulus on the index instead of splitting the array by newlines before taking the transpose.

### How it works

Previous version:

```
a=>(T=[],a.split`
`.map(s=>s.split``.map((c,i)=>T[i]+=c)),!T.find(g=s=>/AB+A|BA+B/.test(s)))|!g(a)

```
1. Take the input `a` and split it by newlines into an array of strings.
2. Transpose `a` and store it in `T`. Use `map` to iterate over each element of `a`, split the string into a character array, and use `map` again to append the `i`th character in the line to the `i`th line of `T`. Since each element of `T` is uninitialized, it will end up looking something like `"undefinedAAABBA"`, but this won't matter.
3. Create a RegExp based testing function `g` that matches the pattern `/AB+A|BA+B/`. If it matches, the pieces are locked in the given direction because then there are a set of `B`s sandwiched between two or more `A`s or vice-versa.
4. Use the testing function `g` to test all elements of the block `a` and its transpose `T` for a match using `find`. If both match, then the pieces are locked in both directions, so output a falsy value, otherwise a truthy one.
> 9 votes

# Answer
# Javascript (ES6), 118

```
slidey=
// code
a=>!a.match(R=/AB+A|BA+B/)||!(a=a.split`
`.map(b=>b.split``))[0].map((_,c)=>a.map(d=>d[c])).some(e=>e.join``.match(R))

// IO
var S =document.getElementById('S');
S.onkeyup = _=> document.getElementById('P').innerText = slidey(S.value);

document.getElementById('P').innerText = slidey(S.value);
```

```
<textarea id='S'>BAAAAABB
BBAAABBB
BBBABBBB
BBBABBBB
BBBABBBB
BBBBBBBB
BBBBBBBB</textarea>
<p id='P'></p>
```

Explanation:

```
a=> !/* check string horizontally */ || !/* check string vertically by transposing it and
                                            running the same horizontal check */

a=> !a.match(R=/AB+A|BA+B/) || !/* ... */
// check for lines containing something like BAAAAAB or ABBBBBBBA
// this is the only way something can get blocked horizontally
// eg AAAAAAA
//    AAABAAA <<< note the B in the middle of As here
//    AAABBBB <<< blocked from being pulled out horizontally
//    AAAAAAA

a=> /* ... */ ||!( a = a.split('\n').map(b=> b.split('')) ) // split a into 2D array
    [0].map((_,c)=>a.map(d=>d[c])) // transpose it
    .some(e=>e.join``.match(R)) // run the check again using `some` to go line by line
                                // which is shorter than .join().match() outside

a=> !/* returns null if no horizontal obstacles and an array if there are */
    || !/* same thing */
// negate both to cast to a boolean (false if obstacles, true if not)
// an input can only be unslidable if both directions are blocked
// so (no obstacles vertically? || no obstacles horizontally?) gives the answer

```
> 5 votes

# Answer
# JavaScript (ES6) 72 ~~74~~

**Edit** 2 bytes saved thx @NotthatCharles

I have the intuitive understanding that if one piece can slide just a fraction of step, then it's free. The current test cases confirm this.

So I check just one step in each direction.

Characters used: 1 and 0
2 bytes more to use any 2 printable characters like A and B

Test running the snippet below in an EcmaScript 6 compliant browser (supporting the spread operator - IE Firefox)

```
f=s=>[w=~s.search`
`,-w,-1,1].some(o=>![...s].some((x,p)=>x+s[p+o]==10))

// 4 bytes more- for any symbol, not just 1 and 0 (for instance A and B):
g=s=>[w=~s.search`
`,-w,-1,1].some(o=>![...s].some((x,p)=>x+s[p+o]=='AB'))

//TEST
console.log=x=>O.innerHTML+=x+'\n'

testOk = [
 '111\n100\n111',
 '10',
 '0\n1',
 '01\n01',
 '000\n111',
 '00001\n01111',
 '0110\n0110\n0000',
 '000000111111111\n001111111111111\n000000000011111\n001111111111111\n000000000000001',
 '000000000000\n010101010101\n111111111111',
 '10000011\n11000111\n11101111\n11101111\n11101111\n11111111\n11111111',
 '000\n100\n000'
]

testKo = [
 '1111\n1001\n1011',
 '1111\n1001\n0011',
 '1111111\n1111101\n0000001\n1111111',
 '1000\n1010\n1110\n0010\n0000',
 '0000000\n0111110\n0000010\n1111110',
 '10000011\n11000111\n11101111\n11101111\n11100111\n11111111\n11111111',
 '000\n010\n110\n010\n000'
]

console.log('Expecting true')
testOk.forEach(t=>console.log(t+'\n'+f(t)+'\n'))
console.log('Expecting false')
testKo.forEach(t=>console.log(t+'\n'+f(t)+'\n'))
```

```
<pre id=O></pre>
```
> 5 votes

# Answer
# Mathematica ~~100~~ 69 bytes

With a massive 31 bytes saved, thanks to @Martin Buttner,

```
g=Max[Length/@Split/@#]<3&;g[c=Characters@StringSplit@#]||g@Thread@c&

```

Formats the input as a matrix of characters; it also makes a transpose of the matrix. If either the matrix or its transpose has no more than 2 runs per row then the puzzle is can slide.

`{a,a,b,b,b}` has 2 runs of letters.

`{a,a,b,a,a}` has 3 runs of letters.

`{a,a,b,a,a,a,b,b,b,b,b,b,b,b}` has 4 runs of letters.
> 3 votes

# Answer
## Dyalog APL, 22 bytes

```
(∨/{∧/2>+/2≠/⍵}¨)⊂∘⍉,⊂

```

Try it here. This is a function that takes in a 2D array of characters, and returns `1` for sliding instances and `0` for non-sliding ones. The algorithm is similar to most other answers: check for the matrix and its transpose that no row contains more than one adjacent pair of different letters. For the 4x3 input matrix

```
AAAA
ABBB
AAAB

```

the function can be invoked as

```
f ← (∨/{∧/2>+/2≠/⍵}¨)⊂∘⍉,⊂
f 4 3 ⍴ 'AAAAABBBAAAB'

```

which results in `1`.

## Explanation

```
⊂∘⍉,⊂   The matrix and its transpose.
{...}¨   For each of them:
  2≠/⍵   On each row, replace each adjacent pair with 1 if they differ, with 0 otherwise
  2>+/    Take the sum on each row and check that it's less than 2
  ∧/     AND over all rows
∨/      OR over the resulting two values

```
> 2 votes

# Answer
# JavaScript (ES6), 94 bytes

```
x=>!(y=/AB+A|BA+B/).test(x)|(z=[],x.split`
`.map(b=>b.split``.map((c,i)=>z[i]+=c)),!y.test(z))

```

Same-size alternate method:

```
x=>(t=s=>!/AB+A|BA+B/.test(s),z=[],x.split`
`.map(b=>b.split``.map((c,i)=>z[i]+=c)),t(x)|t(z))

```

This returns `1` for a truthy input and `0` for falsy. I started work on this before any other answers had been posted. I also originally tried using ES7's array comprehensions, but that ended up about 10 chars longer than this method.

Try it out:

```
a=x=>!(y=/AB+A|BA+B/).test(x)|(z=[],x.split`
`.map(b=>b.split``.map((c,i)=>z[i]+=c)),!y.test(z))

P.onclick=_=>Q.innerHTML='Result: '+a(O.value)
```

```
<textarea id=O cols="20" rows="8">AAAAAABBBBBBBBB
AABBBBBBBBBBBBB
AAAAAAAAAABBBBB
AABBBBBBBBBBBBB
AAAAAAAAAAAAAAB</textarea>
<button id=P>Test</button>
<p id=Q>Result: </p>
```

Suggestions welcome!
> 1 votes

---
Tags: code-golf, geometry, grid
---


title: How are you doing?

text:
# Question
Title: How are you doing?
Martin has created a nice snippet that can be used to keep track of the score for answers to challenges. That's great and all, but wouldn't it be better if you could keep track of it yourself?

Create a program that compares the byte counts in itself with the rest of the answers to this question, and returns "I'm answer number n".

Rules:

* The byte count in your own answer can be hardcoded in the code
* The function can take the url as input, or it can be hardcoded. The chars for the url will not count toward the byte count, so it's not necessary to use a url-shortener.
* url-addresses to answers cannot be hardcoded
* The score for the answers can be found from the header, (the same way Martin's snippet does).
* The answer header must have the correct format (described below).
* If it's possible to run the program online, please share a link to an online compiler (or a code snippet that can be executed from the answer). If it's not possible, please show how to call the function, and show the output from your own compiler (at the time you posted the answer. You don't need to update it unless you want to of course).
* You have to actually compare the answer with the other answers to this question. Simply writing a script `I'm answer number 1.` in some language is not legal.
* If other answers have the same number of bytes as your own, you can choose if you want to be best or worse of them.

The header must be formatted:

```
# Language Name, N bytes

```

Strike-through etc cannot be used, so if the code size is changed, show it in bold text below the header or indicate it in some other way.

The output must be `I'm answer number n.`, where the number `n` is the position (trailing newline/spaces are OK). So, the shortest answer will output: "I'm answer number 1.", the second will be "I'm answer number 2." etc.

This is code golf, so the shortest answer in bytes will win.

# Answer
> 2 votes
# Perl, 107 bytes

```
use LWP;print"I'm answer number ",1+grep($_<107,LWP::UserAgent->new->get('http://codegolf.stackexchange.com/q/60204')->content=~/<h1>.+, (\d+)/g),'.';

```

Slightly less golfed:

```
use LWP;
$agent = new LWP::UserAgent();
$response = $agent->get('http://codegolf.stackexchange.com/q/60204');
@answers = $response->content =~ m/<h1>.+, (\d+)/g;
print "I'm answer number ", 1+grep($_<107, @answers), '.';

```

---

**Sample Usage**

```
$ perl my_rank.pl
I'm answer number 1.

```

# Answer
> 7 votes
# Python 2, 145 bytes

```
from requests import*
print"I'm answer number %s."%(sorted([int(a["body"].split(",")[1].split()[0])for a in get('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=activity&site=codegolf&filter=!SWJ_BpAceOT6L*G2Qa').json()["items"]]).index(145)+1)

```

Output from 2015-10-10 17:30:00 UTC:

```
I'm answer number 1.

```

I didn't count any of the URL for my score, if I should please comment on how much I should add to it. Has own score hardcoded in it, assumes that it's already posted. Will break if ever more than 99 answers are posted.

# Answer
> 6 votes
# AutoIt, 175 bytes

(202 bytes - 27 for the URL)

```
#include<String.au3>
$0=_StringBetween
$1=1
For $2 In $0(BinaryToString(InetRead("http://q.codegolf.xyz/60204")),'<h1>',' b')
$1+=$0($2,', ','')[0]<175?1:0
Next
ConsoleWrite("I'm answer number "&$1&".")

```

Output from 2015-10-09 17:47:00 UTC:

```
I'm answer number 1.

```

# Answer
> 4 votes
# JavaScript (ES7), 149 bytes

283 bytes - 134 for the URL. I've never use HTTP requests before, but here goes...

```
x=z=>alert(`I'm answer number ${[for(y of z.items)y.body.match(/, (\d+)/)[1]].sort().indexOf("149")+1}.`);document.write('<script src="//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T&callback=x">\x3C/script>')
```

Tested successfully in Firefox 41.

First it looks through the headers of all the answers to find their byte-counts, then it finds the first position with byte-count ~~243~~ 149. It's currently set up to check only the first 100 answers, and will break if someone gets under 100 bytes, but it works for now. ;)

Thanks to @GeorgeReith for the much shorter technique. Old version using AJAX (243 bytes):

```
x=new XMLHttpRequest,x.onreadystatechange=_=>{if(x.readyState==4&&x.status==200)alert(`I'm answer number ${[for(y of JSON.parse(x.responseText).items)y.body.match(/, (\d+)/)[1]].sort((a,b)=>a-b).indexOf("243")+1}.`)},x.open("GET","//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T",!0),x.send()

```

# Answer
> 4 votes
# PHP, 158 ~~159~~ ~~164~~ bytes

```
I'm answer number <?for(;$h[]=json_decode(fread(gzopen('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r),1e4),1)[items][+$i++][body];);echo array_sum(preg_filter(~„ÑÕß×£›ÔÖß†‹šŒÃÐ—ÎÑÕ‚Œš,~ÛÎÃÎÊÇ,$h)),~Ñ;

```

127 bytes from `'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T'` not counted

### Formatted version with ungolfed strings:

```
<?
for(;
    $h[]=json_decode(
        fread(
            gzopen(
                'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r
            ), 1e4
        ), 1
    )[items][+$i++][body];
);
echo"I'm answer number ",
    array_sum(
        preg_filter('{.* (\d+) bytes</h1.*}se','$1<159', $h)
    ),
    ".";

```
* Loads the JSON response (one time per answer actually to save 5 bytes, thanks to @Blackhole)
* Collects answer bodies in `$h`
* replaces whole text with "1" (true) if the byte count is \<=159, or "" (false) otherwise
* sums the results

The character sequences like `¶Ø’ßž‘Œˆšß‘Š’šß` are valid constant names in PHP, but because the constants do not exist are treated as string literal. `~` inverts them, this one to `"I'm answer number "` (saving a byte for one quotation mark each)

### Usage

```
php -derror_reporting=0 howareyou.php

```

> I'm answer number 1.

# Answer
> 3 votes
# Javascript (ES6), 186 bytes

(335 - 149 bytes for the URL)

```
a=d=>alert(`I'm answer number ${d.items.map(q=>(y=[q.body.match(/, (\d+)/)[1],(x=q.owner.user_id==11182)])&&x?z=y:y).sort().indexOf(z)+1}.`)
document.write(`<script src="https://api.stackexchange.com/questions/60204/answers?pagesize=100&order=desc&sort=activity&site=codegolf&filter=!)Q2B_A19OPkd2j8JforD00f5&callback=a">\x3C/script>`)
```

# Answer
> 1 votes
# Awk, 153 bytes

```
BEGIN{if(u){print"I\047m answer number "system("curl -s "u"|awk -f a")".";exit}FS="1>.*,|es<\/h"}NF==3{r+=($2+0)<153?1:0}END{exit(r<1?1:r)}

```

This should be saved to a file `a` and run like:

```
awk -v u=http://codegolf.stackexchange.com/questions/60204/how-are-you-doing -f a

```

I'm subtracting the 68 bytes for `http://codegolf.stackexchange.com/questions/60204/how-are-you-doing` and adding 13 to the code for the bootstrapping `awk -v u=` and `-f a`.

Less golfed, this can be even shorter:

```
curl -s http://codegolf.stackexchange.com/questions/60204/how-are-you-doing | awk -F"1>.*,|es<\/h" 'NF==3{r+=(0+$2)<103?1:0}END{print"I\047m answer number "(r<1?1:0)"."}'

```

It always prefers itself in ties. The byte count is hard coded in each.

The more golfy version has the script calling itself and outputting the exit value via system. In each case only counts lower than the hard-coded value increment `r`, which then has to be adjusted back to `1` if it's leading.

This will fail to correctly find bytes if there's whitespace between `bytes` and `</h1>` and probably a number of other cases I haven't considered.

As of `Sun Oct 11 05:17:51 UTC 2015`, this gives:

```
I'm answer number 3.

```

# Answer
> 1 votes
# GNU Awk, 156 bytes

(Inspired by n0741337's Awk solution.)

This one does it all itself, without running external command.

```
BEGIN{d="/inet/tcp/0/"h"/80"
print"GET "p" HTTP/1.1\nHost:"h"\n"|&d
while(d|&getline)n+=match($0,/1>.*, ([0-9]+)/,m)&&m[1]<156
print"I'm answer number",n+1}

```

Expects hostname and path as separate values. Given they are available for free, hopefully this not breaks the rules.

Sample run:

```
bash-4.3$ awk -v h=codegolf.stackexchange.com -v p=/questions/60204/how-are-you-doing -f number.awk
I'm answer number 4

```

---
Tags: code-golf, internet
---


title: Regular Polygrams

text:
# Question
Title: Regular Polygrams
Given the number of vertices `n ≥ 3` and the "step size" `1 ≤ m < n/2` (indicating the distance between two connected vertices), output a graphical representation of the corresponding regular polygram. If the polygram consist of multiple closed loops, each loop must be rendered in a different line colour. (If this sounds confusing, the examples below should hopefully clear things up.)

## Rules

Any reasonable solution to the problem will likely satisfy these rules automatically - they are just there to put some constraints on the parameters of the output in order to prevent answers like "This black block is totally a polygram, but you can't see it because I set the line width to over 9000."

* You can render the polygram either to a file (which may be written to disc or to the standard output stream) or display it on the screen.
* You may use either vector or raster graphics. If your output is rasterised, your image must have dimensions of 400x400 pixels or more, and the polygram's *radius* (the distance from the centre to each vertex) must be between 35% and 50% of the side length.
* The aspect ratio of the polygram must be 1 (so that its vertices lie on a proper circle) - the canvas of the image may be rectangular.
* The lines of the polygram must be no thicker than 5% of the radius (and of course, they must have non-zero thickness to be visible).
* You may render axes or a frame in addition to the polygram, but nothing else.
* You may choose any (solid) background colour.
* For polygrams consisting of multiple closed loops, you must support at least 6 *visually distinct* colours, all of which must be different from the background. (Grey-scale is fine, provided the shades are sufficiently spread out through the spectrum.) Your code must still work for more than 6 loops, but the colours don't have to be distinguishable for any additional loops (i.e. you may also reuse colours from previous loops at that point).

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

## Examples

Here are all the outputs up to `n = 16` (where the column corresponds to `n` and the row to `m`):

Click for larger version.

As examples for larger `n`, here are `(n, m) = (29, 11)` and `(30, 12)`:

# Answer
# Mathematica, 70 bytes

```
ListPolarPlot[Table[{2Pi(i+j#2)/#,1},{i,GCD@##},{j,#+1}],Joined->1>0]&

```

Well... this is my reference implementation which beats both submissions so far. I'm not intent on winning my own challenge, so I'm hoping someone will beat this.

The output is like the plots in the challenge itself, except I'm not removing the axes here:
> 1 votes

# Answer
# MATLAB, ~~85~~ 81

The function displays a plot on the screen.

```
function f(n,m)
hold all
axis equal
for k=1:gcd(m,n)
plot(i.^(4*(k:m:n^2)/n))
end

```

Result for n=30, m=12:
> 5 votes

# Answer
# CJam, 114

```
"P2"N400:ASAN6N0aA*aA*q~:M;:K{:CK,f{M*+K%P*2*K/_[mc)\ms)]199f*}_+2ew{~1$.-Af/A,\ff*\f.+{:mo~_3$=@C6%)tt}/}/}/Sf*N*

```

It outputs the image in ASCII PGM format.

You can try it online, but the output is pretty long. You can change `400` and `199` to smaller numbers to reduce the image size.

CJam has no concept of images, drawing, lines or shapes, so I generated the image in a square matrix, pixel by pixel (one number representing a grey shade for each pixel).

This is what the result looks like for `30 12`:
> 3 votes

---
Tags: code-golf, graphical-output, geometry, trigonometry
---


title: Counting Abelian groups of a given size

text:
# Question
Title: Counting Abelian groups of a given size
### Background

Last time, we counted groups of a given size, which is a non-trivial problem.

This time, we'll only count *Abelian groups*, i.e., groups with a commutative operation. Formally, a group **(G, ∗)** is Abelian if **x ∗ y = y ∗ x** for for all **x, y** in **G**.

The problem becomes much simpler this way, so we're going to count them efficiently.

### Task

Write a program or function that accepts a non-negative integer **n** as input and prints or returns the number of non-isomorphic Abelian groups of order **n**.

One way of calculating the number of groups – which we'll denote by **A(n)** – is by observing the following:

* **A(0) = 0**
* If **p** is a prime, **A(pk)** is equal to the number of integer partitions of **k**. (cfr. OEIS A000041)
* If **n = mk**, and **m** and **k** are co-prime, **A(n) = A(m)A(k)**.

You may use this or any other method of calculating **A(n)**.

### Test cases

```
Input               Output
0                   0
1                   1
2                   1
3                   1
4                   2
5                   1
6                   1
7                   1
8                   3
9                   2
10                  1
11                  1
12                  2
13                  1
14                  1
15                  1
16                  5
17                  1
18                  2
19                  1
20                  2
4611686018427387904 1300156
5587736968198167552 155232
9223371994482243049 2

```

(taken from OEIS A000688)

### Additional rules

* Given enough time, RAM and a register size that can hold the input, your code should work (in theory) for arbitrarily large integers.
* Your code must work for all integers between **0** and **263 \- 1** and finish in under 10 minutes on my machine (Intel i7-3770, 16 GiB RAM, Fedora 21).

*Please make sure you time your code for the last three test cases before submitting your answer.*
* Built-ins that trivialize this task, such as Mathematica's `FiniteAbelianGroupCount`, are not allowed.
* Built-ins that return or count the integer partitions of a number or the partitions of a list are not allowed.
* Standard rules apply.

# Answer
## CJam (39 38 bytes)

```
qimF{~M\{_ee{~\)<1b}%1+a\+}*0=1be&}%:*

```

Online demo

This follows the suggested line of finding a prime factorisation (`mF`) and then calculating the partitions of each power and taking their product.

There are two special cases for `mF`: it factors `0` as `0^1` and `1` as `1^1`. The latter doesn't require special treatment: there is one Abelian group of size 1, and one partition of 1. However, zero does require a special case.

The partition counting uses a recurrence for `A008284(n, k)`, the number of partitions of `n` into `k` parts. In OEIS it is given as

```
T(n, k) = Sum_{i=1..k} T(n-k, i), for 1<=k<=n-1; T(n, n) = 1 for n >= 1.

```

but I think it's more useful to think of the sum as ranging from `1` to `min(k, n-k)`.

### Dissection

```
q~              e# Parse input into an integer
mF              e# Factorise it
{               e# For each factor p^a
  ~             e#   Split the array [p a]
                e#   The following lines count partitions of a
                e#   (Note: they would be buggy if a were ever 0, but it isn't)
  M\{           e#   Starting with a table of zero rows, repeat a times
    _ee         e#     Copy table and pair each row with its index
    {~\)<1b}%   e#     Extract that prepended index and use it to sum for each j
                e#     the first jth items of row j
    1+          e#     Append a 1 for P(i, i)
    a\+         e#     Prepend the new row to the table (which is stored in reverse)
  }*
  0=1b          e#   Sum the elements in the latest (first) row

  e&            e#   If p was 0 then replace with 0
}%
:*              e# Take the product

```
> 4 votes

# Answer
# CJam, ~~50~~ ~~49~~ ~~47~~ 43 bytes

```
ri_mF{1=_L{1$0>{,f{):X-Xj}:+}{;!}?}2j}%:*e&

```

Uses CJam's builtin `mF` factorisation and a memoised port of this Python partition number function:

```
p=lambda n,x:n==0 or n>0and sum(p(n+~a,a+1)for a in range(x))

```

or ungolfed:

```
def p(n, x): # Call like p(n, n). n is number remaining, x is max part size
  if n > 0:
    return sum(p(n-a-1,a+1)for a in range(x))
  else:
    return (n==0)

```

Like @RetoKoradi's answer, the last case takes about 17 seconds on the offline interpreter because that's how long it takes CJam to factorise the number. Hence I've left it out of this online test suite.

### Full explanation

```
[Main body]
ri                                Read input and convert to int
  _          e&                   Logical AND input with final result to special case 0
   mF                             Factorise input into [base, exponent] pairs
     {...}%                       Map, converting each pair to a partition number
           :*                     Take product

[Pair -> partition]
1=_                               Get exponent and copy (n,x in above Python)
   L                              Initialise empty cache
    {                       }2j   Memoise with 2 arguments
     1$0>                         Check if n > 0
         {            }{  }?      Execute first block if yes, else second block
                        ;!        Return (n == 0)
          ,f{      }              For each a in range(x) ...
             ):X-Xj               Call p(n-a-1,a+1) recursively
                    :+            Sum the results

```
> 6 votes

# Answer
# Mathematica, ~~96~~ ~~94~~ 88 bytes

```
f=1##&@@#&;f[SeriesCoefficient[1/f[1-x^Range@#],{x,0,#}]&/@Last/@FactorInteger@#]Sign@#&

```

I'm not that proficient with Mathematica, but I thought I'd give it a try. Thanks to @MartinBüttner for -6 bytes.

This uses the generating function formula for integer partitions.
> 4 votes

# Answer
# CJam, 58 bytes

```
li_mF{1=_L{_1>{_2$<{\;_j}{\,f{)_@\-j}:+}?}{;;1}?}2j}%:*\g*

```

Try it online

The very last test example takes forever (or at least longer than I was willing to wait) in the online interpreter, but finishes in 17 seconds with the offline version of CJam on my laptop. All other test examples are pretty much instantaneous.

This uses the CJam `mF` operator, which gives the prime factorization with exponents. The result is then the product of the partition counts for each exponent.

The main part of the code is calculating the partition counts. I implemented the recursive algorithm on the wikipedia page, using the `j` operator that supports recursion with memoization.

Explanation:

```
li    Get input and convert to int.
_     Make a copy to handle 0 special case at the end.
mF    Factorization with exponents.
{     Loop over factors.
  1=    Take exponent from [factor exponent] pair.
  _     Repeat it, recursive calls are initiated with p(n, n).
  L     Empty list as start point of memoization state.
  {     Start recursive block. Argument order is (m, n), opposite of Wikipedia.
    _1>   Check for n > 1.
    {     Start n > 1 case.
      _2$   Copy both m and n.
      <     Check for n < m.
      {     n < m case.
        \;    Pop m.
        _     Copy n.
        j     Make the p(n, n) recursive call.
      }     End n < m case.
      {     Main part of algorithm that makes recursive calls in loop.
        \,    Generate [0 1 ... m-1] range for k.
        f{    Start loop over k.
          )     Increment, since k goes from 1 to m.
          _     Copy k.
          @\    Rotate n to top, and swap. Now have k n k at top of stack.
          -     Subtract, now have k n-k at top of stack.
          j     Make the p(n-k, k) recursive call.
        }     End loop over k.
        :+    Sum up all the values.
      }?    Ternaray operator for n < m condition.
    }     End n > 1 case.
    {     n <= 1 case.
      ;;1   Pop m, n values, and produce 1 as result.
    }?    Ternary operator for n > 1 condition.
  }2j   Recursive call with memoization, using 2 values.
}%    End loop over factors.
:*    Multiply all values.
\     Swap original input to top.
g     Signum.
*     Multiply to get 0 output for 0 input.

```
> 4 votes

---
Tags: code-golf, math, abstract-algebra
---


# Question
Title: Convert ciphered Roman numerals to Arabic decimals
Write an algorithm to interpret a sequence of letters as a Roman numeral. (see roman numeral rules below)

Each distinct letter has a matching Arabic decimal value, no maximum. But you don't have the key beforehand, so `{A=10, I=1, X=5, ... Z=1000000}` is decided by your interpretation.

# Challenge

1. Read input via `STDIN` or equivalent and write output via `STDOUT` or equivalent
2. Valid inputs are combinations of uppercase and lowercase letters i.e. matching `\[a-zA-Z]+\`
3. Input should be validated to see if the letter sequence can be interpreted as valid Roman numeral
4. If the input passes validation, valid output should be the lowest Arabic decimal interpretation and the key used i.e. `Aa` is interpreted as `4 {a=5, A=1}` **not** `6 {A=5, a=1}` **or** `9 {a=10, a=1}`

**Roman Numeral Rules**

1. Only letters representing powers of ten can be repeated, maximum of three times successively and four times in total e.g. `II` `III` `XXXIX`
2. If one or more letters are placed after another letter of greater value, add that amount

```
AAaa   => 22 {A=10, a=1}          (20 + 2 = 22)
bbAAaa => 222 {b=100, A=10, a=1}  (200 + 20 + 2 = 222)

```
3. If a letter is placed before another letter of greater value, subtract that amount

```
Aa    => 4 {a=5, A=1}                 (5 – 1 = 4)
AaA   => 19 {A=10, a=1}               (10 + 10 – 1 = 19)
BbBaA => 194 {B=100, b=10, A=5, a=1}  (100 + 100 - 10 + 5 - 1 = 194)

```

Several rules apply for subtracting amounts from Roman numerals:

* Only subtract powers of ten i.e. `1, 10, 100...` **not** `5, 50, 500...`
    * No double subtraction therefore `18` is written as `XVIII` **not** `IIXX (10 + 10 - 1 - 1)`
    * Do not subtract a number from one that is more than ten times greater.
    You can subtract `1` from `5` **or** `10` but **not** from `50, 100, 500...`

# Example

**`Input:`**

```
Aa
BAa
CCCXLVII
MMMCDVII
ABADDF
XVVX
FAASGSH
DXCCDA
AaBbcDEf

```

**`Output:`**

```
4 {a=5, A=1}
14 {B=10, a=5, A=1}
347 {C=100, L=50, X=10, V=5, I=1}
347 {M=100, D=50, C=10, V=5, I=1}
1921 {A=1000, B=100, D=10, F=1}
'XVVX' failed Roman numeral test
7191 {F=5000, A=1000, S=100, G=10, H=1}
'DXCCDA' failed Roman numeral test
4444 {a=5000, A=1000, b=500, B=100, D=50, c=10, f=5, E=1}

```

# Answer
# Python 2, ~~415~~ ~~444~~ ~~440~~ ~~419~~ 416 bytes

There aren't all that many Roman numerals, after all. This script creates all of them and checks all permutations of the input, then returns the smallest match.

```
a=raw_input()
g=range
b=list(set(a))+[' ']*9
from itertools import*
c=[]
s={}
u=1000
for i in g(10*u):
 t,f=(10*u,9*u,5*u,4*u,u,900,500,400,100,90,50,40,10,9,5,4,1),i;r=""
 for j in g(17):k=i/t[j];r+=('W MW Q MQ M CM D CD C XC L XL X IX V IV I').split()[j]*k;i-=t[j]*k
 s[r]=f
for i in permutations(b[:9]):
 r=''
 for j in a:r+='IVXLCMQWE'[i.index(j)]
 if r in s:c+=[s[r]]
print c and min(c)or'%s failed Roman numeral test'%a

```
> 1 votes

---
Tags: code-golf, cryptography, roman-numerals
---


title: Print a Symbolic Negative of your Code

text:
# Question
Title: Print a Symbolic Negative of your Code
(This is a variation on Print a Negative of your Code, which I enjoyed a lot! Thanks to Martin Büttner♦ \- almost all of this text is his.)

Let's consider the *symbols* to be the following printable ASCII characters (note that space is included):

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

```

And the *alphanumerics* to be these:

```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

```

Consider a square of printable ASCII characters for side length N, like the following:

```
ONE,
{two}
&3,+=
!four
f|ve.

```

We also require each row and each column to contain at least one symbol and one alphanumeric. (The above example satisfies this.)

We define the *symbolic negative* of such a square to be a square of the same size where each symbol is replaced with an alphanumeric and vice versa. For example, the following would be a valid symbolic negative of the above example:

```
[&]OK
a...b
1/100
i@#$%
(R) z

```

The choice of specific characters is irrelevant as long as they are in the categories above.

### The Challenge

Your task is to write a program with square source code with side length N \> 1, which prints a symbolic negative of its source code to STDOUT. Trailing spaces must be printed. You may or may not print a single trailing newline.

The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment which automatically prints the value of each entered expression.

The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest *symbols* in the source code wins. If there's still a tie, the earliest answer wins.

# Answer
> 11 votes
# GolfScript, 3 × 3 (4 symbols)

```
4,m
`3/
n*o

```

Try it online on Web GolfScript.

### Output

```
[0
1 2
 3]

```

### How it works

```
4,  # Push the array [0 1 2 3].
  m # Undefined token. Does nothing.
`   # Push the string representation of the array. Pushes "[0 1 2 3]".
 3/ # Split into chunks of length 3. Pushes ["[0 " " 1 " "2 3]"].
n*  # Join the chunks, separated by linefeeds. Pushes the output.
  o # Undefined token. Does nothing.

```

# Answer
> 11 votes
# CJam, 3 × 3 (5 symbols)

```
[5,
S*3
/N*

```

Try it online in the CJam interpreter.

### How it works

```
[   e# Unmatched [. Does nothing.
 5, e# Push [0 1 2 3 4].
S*  e# Join the integers, separating by spaces. Pushes "0 1 2 3 4".
  3 e#
/   e# Split into chunks of length 3. Pushes ["0 1" " 2 " "3 4"].
 N* e# Join the chunks, separated by linefeeds. Pushes the output.

```

### Output

```
0 1
 2
3 4

```

# Answer
> 10 votes
# Pyth, 3x3, 4 Symbols

```
S]1
.5;
S]1

```

### Output:

```
[1]
0.5
[1]

```

### Explanation:

* S sorts the one element list `]1`
* The numeric literal `.5` gets printed as `0.5`, `;` terminates the statement (does nothing in this case)

# Answer
> 6 votes
# C++, 18 x 18

"Always choose the worst tool for the job."

```
#include<cstdio>
int main(){ for  (
int line =  0lu;
1lu*line <  18l;
1lu*line++){pri\
ntf(line == 0lu *
123*line? "\x41.\\
x2e\x02e...\x2e\\
x42\x02e...\x2e.\
CDE\x00a":  14l!=
1lu*line?".\x2e.\\
x46\x02e...\x47""\
HIJ\x02e..""KLM"
 /*O*/"\n":  /*The
bad code:*/"NOP.\
QRS\x054." "UVW\
XYZ\x02e" "\x2e\\
x2e\x00a"); 0lu;}}

```

Output:

```
A.......B......CDE
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM
NOP.QRST.UVWXYZ...
...F....GHIJ...KLM
...F....GHIJ...KLM
...F....GHIJ...KLM

```

---
Tags: code-golf, restricted-source, source-layout, printable-ascii
---


title: How many three-fruit pies can you make?

text:
# Question
Title: How many three-fruit pies can you make?
A three-fruit pie is made of three *different* fruits. What is the most three-fruit pies you can make from the quantities of 5 fruits you have?

For example, with

```
1 apple
1 banana
4 mangoes
2 nectarines
0 peaches

```

you can make 2 pies:

```
apple, mango, nectarine
banana, mango, nectarine

```

**Input:** Five non-negative integers, or a list of them.

**Output:** The maximum number of three-fruit pies you can make from those quantities of fruit. Fewest bytes wins.

**Test cases:**

```
1 1 4 2 0
2
2 2 2 2 2
3
0 6 0 6 0
0
12 5 3 2 1
5
1 14 14 3 2
6
0 0 1 0 50
0

```

**Leaderboard:**

```
var QUESTION_ID=59192,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 33 votes
# Pyth, ~~19~~ ~~18~~ 14 bytes

*-1 byte by @FryAmTheEggman*

*14-byte program by @isaacg*

I claim that the number of pies that can be formed from an ascending list `[x1,x2,x3,x4,x5]` is:

```
floor(min((x1+x2+x3+x4+x5)/3,(x1+x2+x3+x4)/2,x1+x2+x3))

```

Or in code:

```
JSQhS/Ls~PJ_S3

```

\[See revision history for TI-BASIC and APL programs\]

## Proof of correctness

Let

```
s3 = x1+x2+x3
s4 = x1+x2+x3+x4
s5 = x1+x2+x3+x4+x5

```

We want to show that `P(X)=floor(min(s5/3,s4/2,s3))` is always the greatest number of pies for a list `x1≤x2≤x3≤x4≤x5` of numbers of fruits 1~5.

First, we show that all three numbers are upper bounds.

* Since there are `s5` total fruits, and each pie has three fruits, `⌊s5/3⌋` is an upper bound.
* Since there are `s4` fruits that are *not* fruit 5, and at least two non-5 fruits are required in each pie, `⌊s4/2⌋` is an upper bound.
* Since there are `s3` fruits that are neither fruit 4 nor fruit 5, and at least one such fruit is required in each pie, `s3` is an upper bound.

Second, we show that the method of taking fruits from the three largest piles always satisfies the bound. We do this by induction.

**Base case:** 0 pies can obviously be formed from any valid list with `P(X)>=0`.

**Inductive step:** Given any list `X` where `P(X) > 0`, we can bake one pie, leaving behind a list `X'` with `P(X') >= P(X)-1`. We do this by taking a fruit from the largest three piles `3,4,5`, then resorting if needed. Bear with me; there's some casework.

* If `x2<x3`, then we don't need to sort the list after removing fruits. We already have a valid `X'`. We know that `P(X') = P(X)-1` because `s5'` is 3 less (because three fruits of type 1~5 were removed), `s4'` is 2 less, and `s3'` is 1 less. So `P(X')` is exactly one less than P(X).
* If `x3<x4`, then we're similarly done.
* Now we take the case where `x2=x3=x4`. We'll need to rearrange the list this time.

+ If `x5>x4`, then we rearrange the list by switching piles 4 and 2. `s5'` and `s4'` are still a decrease of 3 and 2 respectively, but `s3'=s3-2`. This isn't a problem, because if `x2=x3=x4`, then `2*x4<=s3`-\>`2*x4+s3 <= 2*s3` -\> `(x4 + s4)/2 <= s3`. We have two subcases:
    + Equality, i.e. `(x4,x3,x2,x1)=(1,1,1,0)`, in which case `P(X)` = `1` and we can clearly make a pie from piles `5,4,3`, or:
    + `(s4+1)/2 <= s3`, in which case decreasing `s4` by an extra `1` doesn't mean an extra decrease to P(X).
* Now we're left with the case where `x1<x2=x3=x4=x5`. Now `s3` will also be decreased by 1, so we need `(s5/3+1)` to be `<=s4/2`; that is, `8x5+2x1+2<=9x5+3x1`, or `x5+x1>=2`. All cases smaller than this can be checked manually.
* If every number is equal, it is clear that we can achieve the bound of `⌊s5/3⌋`, which is always less than the other two—we simply go through the numbers in sequence.

Finally we're done. Please comment if I'm missing something, and I'll be giving a small bounty for a more elegant proof.

# Answer
> 7 votes
# CJam, 34

```
q~L{J2be!\f{\.-_W#){j)7}|;}0+:e>}j

```

Try it online

**Explanation:**

```
q~          read and evaluate the input array
L{…}j       calculate with memoized recursion and no initial values
             using the input array as the argument
  J2b       convert 19 to base 2 (J=19), obtaining [1 0 0 1 1]
  e!        get permutations without duplicates
             these are all the combinations of three 1's and two 0's
             which represent the choices of fruit for one pie
  \         swap with the argument array
  f{…}      for each combination and the argument
    \       swap to bring the combination to the top
    .-      subtract from the argument array, item by item
    _       duplicate the resulting array
    W#)     does it contain the value -1? (calculate (index of W=-1) + 1)
    {…}|    if not
      j     recursively solve the problem for this array
      )7    increment the result, then push a dummy value
    ;       pop the last value (array containing -1 or dummy value)
  0+        add a 0 in case the resulting array is empty
             (if we couldn't make any pie from the argument)
  :e>       get the maximum value (best number of pies)

```

# Answer
> 7 votes
## Haskell, 62 bytes

```
f x=maximum$0:[1+f y|y<-mapM(\a->a:[a-1|a>0])x,sum y==sum x-3]

```

This defines a function `f` that takes in the fruit list `x` and returns the maximum number of pies.

### Explanation

We compute the number of pies recursively. The part `mapM(\a->a:[a-1|a>0])x` evaluates to the list of all lists obtained from `x` by decrementing any positive entries. If `x = [0,1,2]`, it results in

```
[[0,1,2],[0,1,1],[0,0,2],[0,0,1]]

```

The part between the outer `[]` is a list comprehension: we iterate through all `y` in the above list and filter out those whose sum is not equal to `sum(x)-3`, so we get all lists where 3 different fruits have been made into a pie. Then we recursively evaluate `f` on these lists, add `1` to each, and take the maximum of them and `0` (the base case, if we can't make any pies).

# Answer
> 7 votes
## **C#, 67**

Recursively make one pie per iteration with fruits you have the most until you run out.

```
int f(List<int>p){p.Sort();p[3]--;p[4]--;return p[2]-->0?1+f(p):0;}

```

Test cases here

# Answer
> 6 votes
# Pyth, 29

```
Wtt=QS-Q0=Q+tPPQtM>3.<Q1=hZ;Z

```

Test suite

Sorts the input list and removes zeroes. Then, as long as you have 3 fruits, decrement the first and two last elements, and add the remaining elements to the list, before sorting it and removing zeroes again. Then increment a counter by 1.

This is actually rather quick so long as there are only 5 fruits, it can solve for very large bins of fruits, i.e. `1000,1000,1000,1000,1000` in under a second.

# Answer
> 6 votes
# Python, general solution, ~~128~~ 92 bytes

*-36 bytes from @xnor, you da real mvp*

```
g=lambda l,k:0if k>sum(l)else-(-1in l)or-~g(map(sum,zip(sorted(l),[0]*(len(l)-k)+[-1]*k)),k))

```

~~`def g(a,k):b=[i for i in a if i];return 0if len(b)<k;c=sorted(b,reverse=True);return 1+g([c[i]-(k-1>i)for i in range(len(c))],k)`~~

This works so long as my proof is correct. If it's not, let me know why so I can try to fix it. If it's uncomprehendable, let me know, and I'll attack it after a few cups of coffee.

# Answer
> 5 votes
## Python 2, 78 bytes

### Taking 5 numbers as input: ~~91~~ ~~89~~ 88 bytes

```
s=sorted([input()for x in[0]*5])
while s[2]:s[2]-=1;s[3]-=1;s[4]-=1;s.sort();x+=1
print x

```

*Edit*: Changing `s=sorted([input()for x in[0]*5])` by `s=sorted(map(input,['']*5));x=0` saves 1 byte.

Takes 5 numbers as input and prints the number of possible pies that can be made. It takes the same approach as Reto Koradi's answer -without improving byte count- but it felt like this question was missing an answer in Python.

Thanks @ThomasKwa and @xsot for your suggestion.

**How it works**

```
 s=sorted([input()for x in[0]*5]) takes 5 numbers as input, puts them in a list
                                  and sorts it in ascending order. The result
                                  is then stored in s

 while s[2]:                      While there are more than 3 types of fruit
                                  we can still make pies. As the list is
                                  sorted this will not be true when s[2] is 0.
                                  This takes advantage of 0 being equivalent to False.

 s[2]-=1;s[3]-=1;s[4]-=1          Decrement in one unit the types of fruit
                                  that we have the most

 s.sort()                         Sort the resulting list

 x+=1                             Add one to the pie counter

 print x                          Print the result

```

Note that variable `x` is never defined, but the program takes advantge of some leakage python 2.7 has. When defining the list `s` with list comprehension the last value in the iterable (`[0]*5` in this case) is stored in the variable used to iterate.

To make things clearer:

```
>>>[x for x in range(10)]
>>>x
9

```

### Taking a list as input: 78 bytes

Thanks @xnor @xsot and @ThomasKwa for suggesting changing the input to a list.

```
s=sorted(input());x=0
while s[2]:s[2]-=1;s[3]-=1;s[4]-=1;s.sort();x+=1
print x

```

**How it works**

It works the same way the above code, but in this case the input is already a list so there is no need of creating it and variable `x` has to be defined.

Disclaimer: This is my first attempt at golfing and it feels it can still be golfed, so suggest any changes that could be made in order to reduce byte count.

# Answer
> 4 votes
# CJam, 23 bytes

```
0l~{\)\$2/~+:(+_2=)}g;(

```

Try it online

This takes fruit from the 3 largest piles in each iteration, and counts the number of iterations.

I don't have a mathematical proof that this always gives the correct result. It does for the given test examples, and I'll believe that it works for all cases until somebody gives me a counter example.

The intuitive explanation I used to convince myself: To maximize the number of pies, you need to keep as many piles non-empty as you can. That's because you lose the ability to make more pies as soon as you have 3 or more empty piles.

This is achieve by always taking fruit from the largest piles. I can't think of a case where taking fruit from a smaller pile would lead to a better situation than taking fruit from a larger pile.

I have slightly more formal reasoning in my head. I'll try to think of a way to put it into words/formula.

# Answer
> 3 votes
# \>\<\>, 76 bytes

```
0&4\/~}&?!/
@:@<\!?:}$-1@@$!?&+&:)@:@
,:&:@(?$n;/++:&+::2%-2,:&:@(?$&~+:3%-3

```

Turns out sorting in \>\<\> isn't easy! This program relies on the proof put forward by Thomas Kwa to be true, which certainly looks to be the case with the test cases.

The 5 input numbers are expected to be present on the stack at the program's start.

The first two lines sort the numbers on the stack, and the third performs the calculation `floor(min((x1+x2+x3+x4+x5)/3,(x1+x2+x3+x4)/2,x1+x2+x3))`, taken from Thomas's answer.

# Answer
> 3 votes
## Python 2, 59 bytes

```
h=lambda l,k=3:k*'_'and min(h(sorted(l)[:-1],k-1),sum(l)/k)

```

A general method that works for any `n` and `k`. The `k=3` makes the fruits per pie default to 3, but you can pass in a different value. The recursion uses the fact that strings are bigger than numbers in Python 2, letting the empty string represent the base case of infinity.

This method uses the fact that always taking the most common fruit is optimal, so we consider each possible rank of fruit as a limiting factor. I've reproven that fact below.

---

Mego's proof made me think of this more direct proof that repeatedly taking the most common fruits is optimal. This is stated with pies of `k` fruits.

**Theorem:** Repeatedly taking the `k` most common fruits gives the optimal number of pies.

**Proof:** We will show that if `N` pies are possible, then the most-common-fruit strategy produces at least `N` pies. We do this by switching fruits among the `N` pies to make them match the ones produced by this strategy, while keeping the pies valid.

Let's make it so the first pie (call it `p`) contain the most common fruits. If it doesn't yet, it must contain a fruit `i`, but not a more common fruit `j`. Then, the remaining pies have strictly more of fruit `j` than fruit `i`, and so some other pie `q` must contain `j` but not `i`. Then, we can swap fruit `i` from pie `p` with fruit `j` from pie `q`, which keeps `N` pies having distinct fruit.

Repeat this process until `p` has the `k` most common fruits.

Then, set pie `p` aside, and repeat this process for the next pie to make it have the most common remaining fruits. Keep doing this until the pies are the sequence produced by the most-common-fruit stategy.

# Answer
> 1 votes
# PowerShell, 92 Bytes

```
$a=($args|sort)-ne0;while($a.count-ge3){$a[0]--;$a[-1]--;$a[-2]--;$a=($a-ne0;$c++}($c,0)[!$c]

```

Uses the same greedy-based algorithm as FryAmTheEggman's answer ... just a lot wordier in PowerShell....

```
$a=($args|sort)-ne0  # Take input arguments, sort them, remove any 0's
while($a.count-ge3){ # So long as we have 3 or more fruit piles
  $a[0]--            # Remove one from the first element...
  $a[-1]--           # ... the last element ...
  $a[-2]--           # ... and the second-to-last.
  $a=$a-ne0          # Remove any 0's from our piles
  $c++               # Increment how many pies we've made
}                    #
($c,0)[!$c]          # Equivalent to if($c){$c}else{0}

```

---
Tags: code-golf
---


title: The Ideal Question

text:
# Question
Title: The Ideal Question
What makes the ideal question? Perhaps it is merely the abstraction of a profound thought and the initialization of a dream, a hope, a thought, a (… *5,024.2 characters omitted*). Therefore, I propose that we find such a factor to quantify questions. I propose also that this factor be called ***Q****F*, or the Q-factor. I determine a question's Q-factor as thus:

(Recall that .)

**Objective** Given a number as input, determine the respective question's Q-factor on PPCG.SE. If the question does not exist, simply output `;-;` (the crying emote).

Take, for example, . (this question):

The net votes, in this case, means .

```
views     = 23435
net votes = 33
edits     = 6
answers   = 30, answers^2 = 900
comments  = 19
charsIOPN = "Joe Z.".length = 6

```

So:

```
r_F = 6 / 6 = 1
Q_F = r_F * (23435 * 33 + 6) / (900 - 19)
    =  1  *      773361      /    881
    ~ 877.821793

```

Please provide at least 2 significant figures on ***Q****F*.

This is a , so the shortest program in bytes wins.

---

Note: Please include three examples of your program running, one of which must be this question. The other two are yours to decide. (This is just a confirmation check.) Also report the time at which you entered the query.

# Answer
# Julia, ~~411~~ ~~382~~ ~~367~~ ~~355~~ 353 bytes

It's quite long but I'm very pleased that it works!

```
using Requests
n->(R(t)=readall(get(t));G(t)=JSON.parse(R("http://api.stackexchange.com/2.2/questions/$t?site=codegolf"))["items"];j=G(n)[1];d=parse(Int,match(r"<span \S+n (\d+)",R("http://codegolf.xyz/posts/$n/revisions")).captures[1]);d/length(j["owner"]["display_name"])*(j["view_count"]*j["score"]+d)/(j["answer_count"]^2-length(G("$n/comments"))))

```

This creates an unnamed function that takes an integer as input and returns a float.

It requires the `Requests` package, which can be installed using `Pkg.add("Requests")`. That package provides methods for `Base.get()` for submitting HTTP requests. It also imports the `JSON` package (on which it depends, so that doesn't need to be installed separately) which we use to parse the JSON output in the response.

Ungolfed:

```
using Requests

function f(n::Int)
    # Define a function to submit an HTTP request and read
    # the response, returning a string
    R(t) = readall(get(t))

    # Define a function that submits a request, reads all text
    # as JSON, parses it, and extracts the items field
    G(t) = begin
        api = "http://api.stackexchange.com/questions"
        JSON.parse(R("$api/$t?site=codegolf"))["items"]
    end

    # Get the data for the question using the API
    j = G(n)[1]

    # Scrape the number of edits from the revision history HTML
    # using minxomat's handy shortened PPCG URL
    h = R("http://codegolf.xyz/posts/$n/revisions")
    d = parse(Int, match(r"<span \S+n (\d+)", h).captures[1])

    # Compute the coefficient r_F
    r = d / length(j["owner"]["display_name"])

    # Compute the Q-factor
    Q = r * (j["view_count"] * j["score"] + d) /
        (j["answer_count"]^2 - length(G("$n/comments")))

    return Q
end

```

Thanks to Dennis and Martin Büttner for golfing help!
> 11 votes

# Answer
# Mathematica 10, 381 bytes

f=(a=StringTemplate["http://api.stackexchange.com/``````?site=codegolf"];j=Import[a["questions/",#,""],"JSON"];c=Import[a["questions/",#,"/comments"],"JSON"];r=Import[a["posts/",#,"/revisions"],"JSON"];N[#5/#6*(#1*#2+#5)/(#3^2-#4)]&@@j[[3,2,1,{5,2,12},2]]~Join~{Length@c[[3,2]],Length@DeleteCases[r[[3,2]],_?(("revision_type"/.#)=="vote_based"&)],StringLength@j[[3,2,1,3,2,6,2]]})&

Just three API queries and a lot of indexing, really. Hardest part was trying to understand how to get `edits` from the available `revisions`, hopefully I got it right.
> 3 votes

# Answer
# Python 2, 392 Bytes

Well, I gave it a shot.

```
from requests import*;from re import*;l=len
def i(n):
 try:s,r="http://api.stackexchange.com/2.2/questions/%s?site=codegolf","http://codegolf.xyz/posts/%i/revisions"%n;q,c=s%n,s%('%i/comments'%n);i=get(q).json()['items'][0];m=float(l(findall("<span \S+n (\d+)",get(r).text)));r=m/l(i["owner"]["display_name"]);print r*(i["view_count"]*i["score"]+m)/(i["answer_count"]**2-m)
 except:print';-;'

```

Very similar logic to Alex's Julia answer. I'd like to loop through this to see which question is the most ideal but I'd rather not continually call the api for hours on end.
> 2 votes

# Answer
# Groovy, ~~459~~ 457 bytes

Pretty much like the rest of the answers.

```
import groovy.json.JsonSlurper
import java.util.zip.GZIPInputStream
def f={n->def j,d,u={p->new JsonSlurper().parseText(new GZIPInputStream("http://api.stackexchange.com/2.2/questions/$p?site=codegolf".toURL().getContent()).getText()).items}
j=u(n)[0]
d=("http://codegolf.xyz/posts/$n/revisions".toURL().text=~/<span \S+n (\d+)/).getCount()
println((d/j.owner.display_name.length())*(j.view_count*j.score+d)/(j.answer_count**2-u("$n/comments").size()))}

```

Saved 2 bytes thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ!

Ungolfed:

```
import groovy.json.JsonSlurper
import java.util.zip.GZIPInputStream

def f = { n->

    def stackApi = "http://api.stackexchange.com/2.2"

    // Fetch json from stackexchange rest api
    def getItems = { pathParam ->
        //Stackexchange compresses data, decompress before parsing json
        def httpData = "$stackApi/questions/$pathParam?site=codegolf".toURL().getContent()
        def deCompressedData = new GZIPInputStream(httpData).getText()
        def json = new JsonSlurper().parseText(deCompressedData)
        return json.items
    }

    // Get the edit count from the html page
    def htmlPage = "http://codegolf.xyz/posts/$n/revisions".toURL()
    def editCount = (htmlPage.text=~/<span \S+n (\d+)/).getCount()

    // apply formula
    def json = getItems(n)[0]
    def r = editCount/json.owner.display_name.length()
    def Q = r * ( json.view_count * json.score + editCount) /
                (json.answer_count**2 - getItems("$n/comments").size())
    println(Q)
}

f(16327)

```
> 2 votes

---
Tags: code-golf, math, number
---