text:
Transform 7-segment display pattern into number
Given A and B, where A is the scale of a Digital LED Pattern B. Parse pattern B and print the number.
input:
1
 _  _  _  _     _     _     _  _  _  _  _     _
 _| _| _|| ||_||_   ||_ |_|| |  ||_||_||_   ||_|
|_  _||_ |_|  | _|  ||_|  ||_|  |  |  | _|  ||_|

output:
2320451640799518

input:
2
 __  __
   |   |
 __| __|
|      |
|__  __|

output:
23

Rules:

Use STDIN/STDOUT for input/output
I tried to mimic this question as much as possible, but I think code-golf suits this one better.
Shortest code (in bytes) wins

Shouldn't that be "Given a number A and 2*A+1 lines of input…"?

@reima You are right, the pattern will be 2*A+1 lines. I wanted the style of the question to be as similar to its original as possible, so I changed it so that it doesn't mention the number of lines at all.

Ruby, 151 characters
s,*r=*$<;c=r[s=s.to_i]
i=0;(n=(r[0][i+1]+c[i]+c[i+s,2]+r[-1][i]).tr(" |_","01").to_i 2
$><<(0..9).find{|j|0x3df9778eb5c5b>>5*j&31==n};i+=s+2)while b[i]

Leaves out digits it cannot recognise, but some invalid digits are recognised nevertheless.
Assumes the lines are padded with spaces to their full length.


text:
Wireless Keyboard Inteference
Initech are setting up an office of 36 employees in a soul-crushingly efficient square of cubicles, 6 desks long and 6 desks deep.  Management has bought wireless keyboards in bulk from a cheap, international wholesaler.  IT are quickly discovering that the wireless keyboards only operate on 3 different radio frequencies, and each individual keyboard is hardwired to a particular frequency.  When two keyboards on the same frequency are too close to each other, they interfere with each other.  The only identifying mark on the keyboards is a unique serial number which gives no clues as to the keyboard's radio frequency.  Thankfully there are an equal number of keyboards operating on each frequency.
A keyboard can be defined by the following class.
sealed class WirelessKeyboard
{
    private int frequency;
    private int serialNum;

    public WirelessKeyboard(int frequency, int serialNum)
    {
        this.frequency = frequency;
        this.serialNum = serialNum;
    }

    public bool InteferesWith(WirelessKeyboard other)
    {
        return this.frequency == other.frequency;
    }

    public int getSerialNum()
    {
        return serialNum;
    }
}

Your function must accept an array of 36 WirelessKeyboard objects.  Each is predefined with a unique serial number and one of the three frequencies (12 keyboards of each frequency).  The array is in random order.  The only way to determine a keyboard's frequency is to test if it interferes with another keyboard.
Your function must:

Not modify or extend the WirelessKeyboard class beyond translating it into your programming language of choice.
Accept an input array of WirelessKeyboard objects.
Not create or alter any WirelessKeyboard objects.  Only those in the input may be used.
Not use any means (eg. reflection) to read a keyboard's frequency.
Output a 6x6 array (or equivalent) populated with WirelessKeyboard objects, which:

Contains all 36 unique keyboards.
InteferesWith(other) must return false for all horizontally and vertically adjacent keyboards.

For the sake of code golf, the WirelessKeyboard class may be aliased as K and code may be written as a function.  For example, in C/Java, ungolfed and golfed:
WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection) { ... }

K[,]F(K[]c){ ... }

The shortest code in a week gets the points.  Please post your implementation of the WirelessKeyboard class if it differs significantly from the sample above, but do not count it towards your score.  The function and any dependant declarations (eg. library imports) count towards your score.

I'm expecting functions, similar to the signature in the question's last code block.  I see how I made that confusing now.

Julia, 97 chars
s(k)=while any([k[j]>k[j-1]||j>6&&k[j]>k[j-6] for j=2:36]);i,j=rand(1:36,2);k[[i,j]]=k[[j,i]];end

Checks if the array is in an acceptable final state state, if not, randomly flips two entries. It's super slow, which I find highly amusing. Does an in place alteration on the input array k. InterferesWith is implemented as >.
As I said, it's really slow.  I tested it with more frequencies and smaller boards with 3 frequencies, but it hasn't returned in over 30 mins on the actual problem. I suspect that it won't return overnight, but I'll update if it does. Update: Yes it did finish in less than 12 hours, and yielded an answer that I added to the gist.
Gist with commented code, and includes 3x3 test case that finishes fast: https://gist.github.com/ggggggggg/8679916

Ruby, 108
Here's my WirelessKeyboard class, similar to @gggg I have used a shorter alias for the InterferesWith method.
class K
    attr_reader :freq, :serial
    protected :freq

    def initialize freq, serial
        @freq, @serial = freq, serial
    end

    def interferes_with other
        self.freq == other.freq
    end

    alias :i :interferes_with

    def inspect
        '%3i:%i' % [serial, freq]
    end
end

My actual code:
f=->k{r=k.group_by{|e|e.i(a=k[0])?0:e.i(k.find{|e|!e.i a})?1:2}
(v=0..5).map{|y|v.map{|x|r[(x+y%2)%3].pop}}}

Test run:
keyboards = (0..35).map { |i| K.new(i%3, i) }.shuffle
puts f[keyboards].map { |r| r.map { |c| c.inspect }*' ' }

Result:
 23:2  34:1  33:0   8:2  25:1  24:0
 19:1  12:0  20:2   4:1  21:0  29:2
  2:2  16:1  18:0  35:2   7:1  27:0
 28:1   0:0  17:2  13:1  15:0   5:2
 26:2  22:1   6:0  32:2  10:1   3:0
  1:1  30:0  11:2  31:1   9:0  14:2

PHP 200
<? function O($K){$O=[[],[],[]];foreach($K as$v){foreach($O as&$d){if(!$d||$v->I($d[0])){$d[]=$v;break;}}}$i=6;while($i--){$j=6;while($j--){$v=$j%3+$i%3;$v>2&&$v-=3;echo array_pop($O[$v]);}echo"\n";}}

sample result
10-1 32-2  6-0  1-1 20-2 15-0
 2-2 24-0 19-1 11-2 30-0 28-1
18-0 25-1 29-2 21-0  4-1  5-2
16-1 35-2  3-0 22-1 14-2 12-0
 8-2  9-0  7-1 17-2 33-0 13-1
 0-0 31-1 23-2 27-0 34-1 26-2

testcase+class http://codepad.org/UtjNt7qV
(the class has a __toString to be echoable

C#, 269 bytes
using System.Linq;

WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection)
{
    var list = collection.ToList();
    var map = new WirelessKeyboard[6, 6];
    map[0, 0] = list[0];
    list.Remove(map[0, 0]);
    map[1, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0]));
    list.Remove(map[1, 0]);
    map[2, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0]) && !keyboard.InteferesWith(map[1, 0]));
    list.Remove(map[2, 0]);
    for (int y = 0; y < 6; y++)
    {
        int x = y == 0 ? 3 : 0;
        for (; x < 6; x++)
        {
            map[x, y] = list.First(keyboard => keyboard.InteferesWith(map[(x + y) % 3, 0]));
            list.Remove(map[x, y]);
        }
    }
    return map;
}

The golfed code with InterferesWith defined as I:
using System.Linq;
K[,]F(K[]c)
{
    var l=c.ToList();
    var m=new K[6,6];
    l.Remove(m[0,0]=l[0]);
    l.Remove(m[1,0]=l.First(k=>!k.I(m[0,0])));
    l.Remove(m[2,0]=l.First(k=>!k.I(m[0,0])&&!k.I(m[1,0])));
    for(int x=2;++x<36;){
        l.Remove(m[x%6,x/6]=l.First(k=>k.I(m[(x+x/6)%3,0])));
    }
    return m;
}

It populates the first three cubicles with keyboards with different frequencies, then fills the rest with a diagonal-stripe pattern using the first three as a template:
11-2  13-1  33-0   5-2   7-1  12-0
16-1  15-0  20-2  22-1   0-0  17-2
18-0  35-2  10-1  27-0  32-2  28-1
14-2  31-1   9-0  29-2   4-1   3-0
25-1  30-0   2-2   1-1  21-0  26-2
24-0  23-2  34-1   6-0   8-2  19-1

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Count the words in a text and display them
The code should take input a text (not mandatory can be anything file, stdin, string for JavaScript, etc):
This is a text and a number: 31.

The output should contain the words with their number of occurrence, sorted by the number of occurrences in descending order:
a:2
and:1
is:1
number:1
This:1
text:1
31:1

Notice that 31 is a word, so a word is anything alpha-numeric, number are not acting as separators so for example 0xAF qualifies as a word. Separators will be anything that is not alpha-numeric including .(dot) and -(hyphen) thus i.e. or pick-me-up would result in 2 respectively 3 words. Should be case sensitive, This and this would be two different words,  ' would also be separator so wouldnand t will be 2 different words from wouldn't.
Write the shortest code in your language of choice.
Shortest correct answer so far:

grep and coreutils - 42 bytes

Does case matter (ie is This the same as this and tHIs)?

If anything non-alphanumeric counts as a separator, is wouldn't 2 words (wouldn and t)?

@Gareth Should be case sensitive, This and this would be indeed two different words,  same wouldnand t.

If Wouldn't are 2 words, shouldn't it be "Would" and "nt" since its short for Would not, or is that to much grammer nazi-ish?

@TeunPronk I try to keep it simple, putting a few rules will encourage exceptions to be in order with grammar , and there are a lot of exceptions out there.Ex in English i.e. is a word but if we let the dot all the dots at the end of phrases will be taken, same with quotes or single quotes, etc.

Should words that have the same count be sorted by ascending alpha? or by some other sort?

@KevinFegan That is not one of requirements.

Is the formatting of the output important - i.e. do you have to output word:count - or are other formats ok, e.g. (word, count)?

Vaguely realted old questions from Stack Overflow: http://stackoverflow.com/questions/3169051/code-golf-word-frequency-chart/

Is *&%@!#! a word ?
(I assume no , since they would all be counted as seperators)

@TejasKale you are right  *&%@!#! for that reason is not a word.

grep and coreutils  44  42
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Test:
printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Results in:
  2 a
  1 This
  1 text
  1 number
  1 is
  1 and
  1 31

Update

Use case-insensitive option and shorter regex. Thanks Tomas.

This being almost exactly McEllroy's response to Knuth's book Literate Programming. The only difference being that this does not include a pipe into head at the end.

This was pretty much my first thought too.

Wouldn't '\w+' work as well?

@Sylwester: The \w character group consists of [:alnum:] and _, which, I think, has the same status as the hyphen.

+1 Pretty straightforward, exactly what I was about to write :)

41 characters: grep -io \[A-Z0-9]*|sort|uniq -c|sort -nr

@Tomas: Added this to the answer, thanks. I left in protection for the asterisk, because it was expanding file names in some shells.

Is there a reason not to use -o \[a-Z0-9]*

Java 8: 289
Which is pretty good, since java is a very non-golfy language.
import java.util.stream.*;class C{static void main(String[]a){Stream.of(a).flatMap(s->of(s.split("[\\W_]+"))).collect(Collectors.groupingBy(x->x,Collectors.counting())).entrySet().stream().sorted(x,y->x.getValue()-y.getValue()).forEach(e->System.out.println(e.getKey()+":"+e.getValue()));}

Ungolfed:
import java.util.stream.*;
class C {
    static void main(String [] args){
        Stream.of(args).flatMap(arg->Stream.of(arg.split("[\\W_]+")))
            .collect(Collectors.groupingBy(word->word,Collectors.counting()))
            .entrySet().stream().sorted(x,y->x.getValue()-y.getValue())
            .forEach(entry->System.out.println(entry.getKey()+":"+entry.getValue()));
    }
}

Run from the command line:
java -jar wordCounter.jar This is a text and a number: 31.

Wrong regex for splitting. It should be "[^\\W_]"

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, the String.split(String regex) method takes a pattern that matches the delimiter to split on. So, for instance, "aababba".split("b") would yield the array {"aa", "a", "", "a"}. My regex [^\\w\\d] means 'a character in neither the word character nor digit character classes'. [^\\W_] is instead 'a character that is neither an underscore nor is in the non-word-character class' and would match any word character except the underscore.

Sorry, my previous comment was incorrect. \w includes \d, so \d is redundant. \w includes underscore, which should be considered a separator according to the question. So the correct regex for splitting should be "[\\W_]+".

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ ok, thanks; I've fixed the problem.

APL (57)
⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]

e.g.
      ⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]
This is a text and a number: 31.
 a       2
 This    1
 is      1
 text    1
 and     1
 number  1
 31      1

Explanation:

⎕D,⎕A,⎕UCS 96+⍳26: numbers, uppercase letters, lowercase letters
(I←⍞)∊: read input, store in I, see which ones are alphanumeric
Z←I⊂⍨: split I in groups of alphanumeric characters, store in Z
+⌿∘.≡⍨Z: for each element in Z, see how often it occurs
Z,⍪: match each element in Z pairwise with how many times it occurs
G←⊃∪↓: select only the unique pairs, store in G
⍒,1↓⍉G: get sorted indices for the occurrences
G[...;]: reorder the lines of G by the given indices

what... the... f.....

This is why I have nightmares.

@Thebluefish: APL was designed from a notation, with the intention that much like maths, a concise notation frees you to think clearly. Again like maths, when you first see that notation, you tend to think it's not clear at all, but languages always seem complex to begin with. It would be easier if it wasn't all on one line, though...

whatever you come up with in APL I only see some unicode garbage, arrows pointing in directions and an upside down pine tree. that is worse than J

Could be shorter with ⎕s (http://help.dyalog.com/latest/Content/Language/System%20Functions/r.htm) and the new key operator (http://help.dyalog.com/latest/Content/Language/Primitive%20Operators/Key.htm):
g⌷⍨⊂⍒2⌷⍉g←{⍺,≢⍵}⌸('\w+'⎕s'\0')⍞

C#: 153c 144c 142c 111c 115c 118c 114c 113c
(via LINQPad in "C# Statements" mode, not including input string)
Version 1: 142c
var s = "This is a text and a number: 31."; // <- line not included in count
s.Split(s.Where(c=>!Char.IsLetterOrDigit(c)).ToArray(),(StringSplitOptions)1).GroupBy(x=>x,(k,e)=>new{s,c=e.Count()}).OrderBy(x=>-x.c).Dump();

Ungolfed:
var s = "This is a text and a number: 31.";
s.Split(                                                     // split string on multiple separators
    s.Where(c => !Char.IsLetterOrDigit(c))                   // get list of non-alphanumeric characters in string
     .ToArray(),                                             // (would love to get rid of this but needed to match the correct Split signature)
    (StringSplitOptions)1                                    // integer equivalent of StringSplitOptions.RemoveEmptyEntries
).GroupBy(x => x, (k, e) => new{ s = k, c = e.Count() })     // count by word
 .OrderBy(x => -x.c)                                         // order ascending by negative count (i.e. OrderByDescending)
 .Dump();                                                    // output to LINQPad results panel

Results:

Version 2: 114c
([\w] includes _, which is incorrect!; [A-z] includes [ \ ] ^ _ `; settling on [^_\W]+)
var s = "This is a text and a number: 31."; // <- line not included in count
Regex.Matches(s, @"[^_\W]+").Cast<Match>().GroupBy(m=>m.Value,(m,e)=>new{m,c=e.Count()}).OrderBy(g=>-g.c).Dump();

Ungolfed:
Regex.Matches(s, @"[^_\W]+")                                   // get all matches for one-or-more alphanumeric characters
     .Cast<Match>()                                            // why weren't .NET 1 collections retrofitted with IEnumerable<T>??
     .GroupBy(m => m.Value, (m,e) => new{ m, c = e.Count() })  // count by word
     .OrderBy(g => -g.c)                                       // order ascending by negative count (i.e. OrderByDescending)
     .Dump();                                                  // output to LINQPad results panel

Results:
(as Version 1)

By the way, for version 2, your ungolfed version does not match your golfed version. And since you are using literal string, you can write @"[^_\W]"

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ - fixed the typo and removed the extra \ for a 1-char saving -- thanks!!

R, 58 char
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)

Usage:
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)
1: This is a text and a number: 31.
9:
Read 8 items

     a     31    and     is number   text   This
     2      1      1      1      1      1      1

This is shorter (49 chars) sort(table(gsub("[[:punct:]]","",scan(,""))),d=T). Unfortunately both solutions doesn't work correctly for wouldn't.

Python 101 97
import re
a=re.split('[_\W]+',input())
f=a.count
for w in sorted(set(a),key=f)[::-1]:print w,f(w)

Now works with newline:
$ python countword.py <<< '"This is    a text and a number: 31, and a\nnewline"'
a 3
and 2
31 1
number 1
newline 1
is 1
text 1
This 1

This doesn't work when there are newlines or more than one consecutive space in text.

@klingt.net fixed.

PHP - 84 bytes
<?$a=array_count_values(preg_split('/[_\W]+/',$argv[1],0,1));arsort($a);print_r($a);

Input is accepted as a command line argument, e.g.:
$ php count-words.php "This is a text and a number: 31."

Output for the sample string:
Array
(
    [a] => 2
    [number] => 1
    [31] => 1
    [and] => 1
    [text] => 1
    [is] => 1
    [This] => 1
)

it says input is what you want. so you can get it as command line parameter using $argv[1]

@Einacio good call.

-1. Underscore _ should not be included in a word.

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ fixed.

perl6: 49 characters
.say for get.comb(/\w+/).Bag.pairs.sort(-*.value)

Comb input for stuff matching \w+, put resulting list of words in a Bag, ask for their pairs and sort them by negative value. (The * is a Whatever star, it's not multiplication here)
output:
"a" => 2
"This" => 1
"is" => 1
"text" => 1
"and" => 1
"number" => 1
"31" => 1

Perl 6 scares me.

Every time I think of a cool language feature, I look for it and it's in Perl6 somewhere. That's why it's taking a long time...

You can trim 6 characters by using .words instead of .comb(/\w+/) :)

@Mouq: unfortunately .words doesn't strip the : or . from the input as required :(

-1. _ should not be included in a word under the problem statement.

PowerShell (40)
$s -split"\W+"|group -ca|sort count -des

$s is a variable that contains the input string.

[\W] isn't good enough - it is matching a space in my test.  And it is not ordered by descending count...

$s -split"[\W]"|group -ca|where{$_.Name -ne ""}|sort{-$_.Count} gets you closer (with costs, of course)

Ooops I missed the sorting part.  Will fix my answer shortly.

alternatively:
$s -split"\W+"|group -ca |sort count -des

-split"\W+" is matching an empty string between the last . and the end of the string; also \W+ matches _ which is technically not allowed

GNU awk + coreutils: 71 69
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr

Although gawk asort works on associative arrays, it apparently does not preserve the index values, necessitating the external sort
printf "This is a text and a number: 31." |
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr
2 a
1 This
1 text
1 number
1 is
1 and
1 31

GNU awk 4.x: 100 93
A slightly larger but pure gawk solution using PROCINFO to set the default sort order for the associative array (appears to require a relatively recent gawk - > 4.x?)
BEGIN{RS="\\W+";PROCINFO["sorted_in"]="@val_num_desc"}
{c[$0]++}
END{for(w in c)print c[w],w}

Oooooh. I didn't know about PROCINFO. As if I needed another excuse to use awk in my life. Curse you!

@dmckee TBH I didn't know about PROCINFO until I started poking around - I was convinced there had to be a way to do the sort natively - just a pity the identifiers are so long ;)

In the bad old days there simply wasn't a way. Which leads to things like this old answer of mine.

-1. Underscore _ should not be included in a word.

Perl 69
$h{$_}++for<>=~/\w+/g;print"$_: $h{$_}
"for sort{$h{$b}-$h{$a}}keys%h

Added recommendations from @primo and @protist

What about sorting?

@daniero, excellent point! This now sorts!

I think that's about as terse as it can get. If you don't mind a deprecation warning, no space is required between ge and for. Also, the <=> operator can be replaced by -.

@primo Ahhh - instead of <=> is genius, not sure that's on the golfing tips for Perl thread. I'll update this later, thanks!

you forgot digits...i wrote $h{$_}++for<>=~m/\w++|\d++/g;print"$_:$h{$_}\n"for sort{$h{$a}>=$h{$b}}keys%h then started looking around...then decided it was too similar to bear repeating :)...i like the sorting method in yours

Hey @protist, \w includes numbers too (perl -e 'print for"a 1 2 3 4 b"=~/\w/g' prints a1234b), but your mechanism for iterating the words saves another character so I'll update. Thank you!

-1. Underscore _ should not be included in a word.

Powershell: 57 55 53 62 57
(not including input string)
$s = "This is a text and a number: 31."    # <-- not counting this line...
[Regex]::Matches($s,"[^_\W]+")|group -ca|sort{-$_.Count}

returns:
Count Name                      Group
----- ----                      -----
    2 a                         {a, a}
    1 and                       {and}
    1 31                        {31}
    1 number                    {number}
    1 This                      {This}
    1 is                        {is}
    1 text                      {text}

(with props to @microbian for group -ca)

Groovy 77 82
changed regex from [^\w]+ to [^\d\p{L}]+ in order to solve problem with underscore
String s = 'This is a text and a number: 31'

def a=s.split(/[^\d\p{L}]+/)
a.collectEntries{[it, a.count(it)]}.sort{-it.value}

without first line, 82 characters
output:
[a:2, This:1, is:1, text:1, and:1, number:1, 31:1]

nu_ber is not alphanumeric. This shouls be 2 words

Why use nu_ber instead of number?

I was mislead by some other posts ;) now I removed the "_" from the input, but fixed the regex to handle it

EcmaScript 6
Version 1 (108 characters)
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&console.log(x+':'+_[x]))

Version 2 (102 characters)
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&alert(x+':'+_[x]))

Version 3 (105 characters)
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);alert(keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x]).join('\n'))

Version 4 (94 characters)
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>alert(x+':'+_[x]))

Version 5 (without alert; 87 characters)
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x])

Version 6 (100 characters)
keys(_,s.match(_=/\w+/g).map(x=>_[x]=-~_[x])).sort((a,b)=>_[a]<_[b]).map(x=>console.log(x+':'+_[x]))

Output:
a:2
31:1
This:1
is:1
text:1
and:1
number:1

You can change _[a] and _[b] to _.a and _.b. Also changing /\w+/g,_={} to _=/\w+/g will produce the same result.

@eithedog Thank you! However, I can't change _[a] to be _.a because it tries to access the property "a" of _, not the property a.

ah, correct - the order won't be kept. Carry on :)

Oh, I didn't notice your answer.. nice. But.. is Object.keys becoming a global in ES6? Your answer seems to assume this, but I don't recall seeing that as scheduled for ES6.

@FireFly I can't find any documentation, but it works fine in Firefox. I haven't tested it in Chrome/Opera/IE.

Underscore _ should not be included in a word. Version 3-6 violates this rule.

Javascript - 132 126 chars !
(Shortest JS code)
o={},a=[]
for(i in s=s.split(/[\W_]+/))o[z=s[i]]=o[z]+1||1
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

Improved the regex and some edits.

Ungolfed
s = s.split(/[\W_]+/), o={}, a=[]; // split along non-char letters, declare object and array

for (i in s) { n = s[i]; o[n] = o[n] + 1 || 1 } // go through each char and store it's occurence

for (j in o) a.push( [j, o[j]] ); // store in array for sorting

a.sort(function (b, c){ return c[1] - b[1]; }); // sort !

<= // make s = "How shiny is this day is isn't is"
=>
      [ [ 'is', 3 ],
        [ 'How', 1 ],
        [ 'shiny', 1 ],
        [ 'this', 1 ],
        [ 'day', 1 ],
        [ 'isn', 1 ],
        [ 't', 1 ] ]

Old - 156 143 141 140 132 chars
s=s.split(/[^\w]+/g),o={}
for(i in s){n=s[i];o[n]=o[n]+1||1}a=[]
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

Gave a first try at golfing. Feedback appreciated.

Ruby 58 82 65
h=Hash.new 0
gets.scan(/[\d\w]+/){h[$&]+=1}
p *h.sort_by{|k,v|-v}

Test run:
$ ruby counttext.rb <<< "This is a text and a number: 31."
["a", 2]
["text", 1]
["This", 1]
["is", 1]
["and", 1]
["number", 1]
["31", 1]

Edit 58->80: Ok, I was way off. I forgot to sort the words by occurrences. Also, Array#uniq is not an enumerator, but uses a given block to compare elements, so passing puts to it didn't filter out duplicates (not that it says that we should).

Maybe split(/\W+/) instead of scan (untested)?

@Howard Thanks. \W excludes _ so that had to be fixed, but it still saved 2 characters (then I added 20 to fix the sorting that I had neglected).

Shouldn't be sorted in reverse (a=gets.split(/[_\W]+/)).uniq.map{|w|[w,a.count(w)]}.sort_by(&:last).reverse.map{|x|p x}

@EduardFlorinescu Nah. reverse is way too verbose ;) Btw, it's not fair changing the question.

If you see in the output sample it was sorted descended only that I forgot to specify it.

@EduardFlorinescu Yea, that was a sample! Could've been completely random that the output was like that ;)

@danier No, could not, not if sorted, I mentioned sorted but not descending, but if you see 2 first, and 1 second, and is sorted it cannot be random it descending.

@EduardFlorinescu Unless one uses a sorting function that randomizes the direction before it starts :D Ok, that's a stretch, but you never know...

Python - 95 ( now  87  thanks to @primo)
d=__import__('re').findall(r'\w+',raw_input())
print sorted(map(lambda y:(y,d.count(y)),d))

Sample input :
'This is a text and a number: 31'

Sample output :
[('This', 1),('is', 1), ('a', 2),('text', 1),('and', 1),('a', 2),('number', 1),('31', 1)]

Any improvement sugestion would be appreciated

The solution is nice but the output is not sorted.

What do you mean by sorted? Thanks for the comment.

\w matches [a-zA-Z0-9_]. Your entire regex can be replaced by r'\w+'. Also, the x variable is not needed, just use raw_input() as the second parameter to findall.

By sorted, the OP means that the words that appear most often need to be listed first. Also, your program should include a print statement (i.e. print map(...), otherwise it's not a complete program.

I don't have time to sort it right now :( I'm in a hurry , thanks for the suggestions and comments.

I suggest using sorted, and then reversing with [::-1]. I really want to +1 this, because I've never seen __import__() before.

Can someone explain to me or provide good tutorials and documentation of the sorted function? I have never used it before.

@Azwr try starting here: Python built-in functions. You'll likely need to switch the order of y and d.count(y) to get it to sort by occurrence.

JavaScript 160 144 (Edited: to meet requirements)
f=Function;o={};s.replace(/\w+/g,f('a','o[a]=++o[a]||1'));Object.keys(o).sort(f('b,c','return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

Unminified:
f=Function;
o = {};
s.replace(/\w+/g, f('a','o[a]=++o[a]||1'));
Object.keys(o).sort(f('b,c', 'return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

Logs each word to console in order, passing the following string:
s="This is sam}}ple text 31to test the effectiveness of this code, you can clearly see that this is working-as-intended, but you didn't doubt it did you?.";
Outputs:
you 3
this 2
is 2
can 1
text 1
31to 1
test 1
the 1
effectiveness 1
of 1
This 1
code 1
sam 1
ple 1
clearly 1
see 1
that 1
working 1
as 1
intended 1
but 1
didn 1
t 1
doubt 1
it 1
did 1

I don't have the heart to use alert().

The sort should be by the number. of occurrences so you should be first.

@EduardFlorinescu Silly me... I'll fix it later.

@EduardFlorinescu fixed

-1. Underscore _ should not be included in a word.

++o[a]||1 => -~o[a]

Merge f and o

EcmaScript 6, 115 100 87 (without prompt&alert)
Thanks to @eithedog:
s.match(/\w+/g,a={}).map(w=>a[w]=-~a[w]),keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1])

With prompt and alert (100):
prompt(a={}).match(/\w+/g).map(w=>a[w]=-~a[w]);alert(keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1]))

Run it in Firefox.

You don't need var . Also, you can move a={} inside prompt - prompt(a={}). You can also drop Object. and change w=>a[w]=a[w]+1||1 to w=>a[w]=-~a[w]

Very nice. Beats the working Python one now :)

Same as for @toothbrush's answer - moving the declaration of a from prompt to regexp will spare two more chars.

It's nice and clean. Good job!

-1. Underscore _ should not be included in a word.

F# - 169
let f s=(s+"").Split(set s-set(['a'..'z']@['A'..'Z']@['0'..'9'])|>Set.toArray)|>Seq.where((<>)"")|>Seq.countBy id|>Seq.sortBy((~-)<<snd)|>Seq.iter((<||)(printfn"%s:%d"))

Degolfed:
let count (s : string) =
    s.Split (set s - set (['a'..'z']@['A'..'Z']@['0'..'9']) |> Set.toArray)
 |> Seq.where ((<>) "")
 |> Seq.countBy id
 |> Seq.sortBy ((~-) << snd)
 |> Seq.iter ((<||) (printfn "%s:%d"))

Output when called from fsi:
> "This is a text and a number: 31." |> f
a:2
This:1
is:1
text:1
and:1
number:1
31:1
val it : unit = ()

Update: Some explanation as requested in the comments.
Uses set functions to generate an array of non alphanumeric characters in the input to pass to String.Split, then uses sequence functions to filter out empty strings, generate word counts and print the result.
Some golfing tricks: Adds an empty string to the function argument s to force type inference of the argument as a string rather than explicitly declaring the type. Uses Seq.where rather than Seq.filter to save a few characters (they are synonyms). Mixes forward pipe and ordinary function application in an attempt to minimize characters. Uses currying and (op) syntax to treat <> ~- and <|| operators as regular functions to avoid declaring lambdas to filter empty strings, sort by descending count and print tuples.

You should definitely insert some sort of explanation; that way we can understand your code.

Added a degolfed version and some explanation.

Pure Bash (no external programs), 164
This is longer than I'd hoped, but I wanted to see if the necessary counting and sorting (in the right direction) could be done purely with bash arrays (associative and non-associative):
declare -A c
for w in ${@//[[:punct:]]/ };{ ((c[$w]++));}
for w in ${!c[@]};{ i=${c[$w]};((m=i>m?i:m));s[$i]+=$w:;}
for((i=m;i>0;i--));{ printf "${s[i]//:/:$i
}";}

Save as a script file, chmod +x, and run:

$ ./countoccur This is a text and a number: 31.
a:2
and:1
number:1
text:1
31:1
is:1
This:1
$

q (50)
desc count each group" "vs ssr[;"[^0-9A-Za-z]";" "]

ssr replaces non alphanumeric
" "vs splits the result into a symbol list
count each group counts creates a dict matching distinct elements of the list with the number of occurances
desc sorts the dict by descending values

edit: fixed accidentally matching ascii 58-64 and 91-96

I've no knowledge of q but is the regex [0-z] ASCII-based?  If it is, wouldn't it also include ASCII chars 58-64?  Because those are : ; < = > ? @.

Great catch jimbob, thanks

You're welcome; only spotted because I found the same in C#.  Sadly, same with [A-z], which matches ASCII 91-96, which are `[ \ ] ^ _ ``

ah right you are, nice little ascii lesson right there!

I just discovered [^_\W]+ for mine, which should be "exclude non-word characters and underscore", if your syntax supports the \W class...

k [71 chars]
f:{s:" ",x;`_k!m@k:|(!m)@<.:m:#:'=`$1_'(&~((),/:s)like"[a-zA-Z0-9]")_s}

Any other character except alphanumeric chars will be considered as delimiter.
example
f "This is a text and a number: 31."
a     | 2
31    | 1
number| 1
and   | 1
text  | 1
is    | 1
This  | 1

example
f "won't won won-won"
won| 4
t  | 1

Javascript (135)
u=/\w+/g
for(i=s.length;i--;)for(w in a=s.match(u))u[w=a[w]]=u[w]||a.reduce(function(p,c){return p+=w==c},0)==i&&!console.log(w+":"+i)

Unminified:
u=/\w+/g;for (i=s.length;i--;)
    for(w in a=s.match(u))
        u[w=a[w]] = u[w] ||
           a.reduce(function(p,c){return p+=w==c},0)==i && !console.log(w+":"+i)

Loops over every possible number of matches in descending order, and outputs words with that number of occurrences. Just to be horrible.
Notes: Alert would have reduced the length some. Strictly speaking alphanumeric should be [^\W_]

Haskell (153 = 104 code + 49 import)
Pretty straight-forward, totally composed function... no argument even necessary! This is my first golf, so go easy, maybe? :)
import Data.Char
import Data.List
import Data.Ord
so=reverse.(sortBy$comparing snd).(map(\t@(x:_)->(x,length t))).group.sort.(map$filter isAlphaNum).words

Output:
*Main> so "This is a text and a number: 31."
[("a",2),("text",1),("number",1),("is",1),("and",1),("This",1),("31",1)]

AWK
awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'

Does the job without gawkish extensions:
$ echo 'This is a text and a number: 31.' | awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'
a: 2
This: 1
text: 1
number: 1
is: 1
and: 1
31: 1

If printing "count: word" instead, it would be a bit shorter but I wanted to mimic the given example output...

Tcl, 99 bytes
proc C s {lmap w [split [regsub -all \[^\\w|\ \] $s {}]] {dict inc D $w}
lsort -s 2 -inde 1 -de $D}

Try it online!

Python 2.X (108 - Characters)
print'\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(raw_input().split()).items())

Python 3.X (106 - Characters)
print('\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(input().split()).items())

Separators will be anything that is not alpha-numeric - You only split on whitespace.

Python 3 - 76
The requirement of splitting on non-alphanumeric chars unfortunately extends the code by 19 chars. The output of the following is shown correctly. If you are not sure, add a .most_common() after the .Counter(...).
i=__import__
print(i('collections').Counter(i('re').findall('\w+',input())))

In/Output
Given the input of This is a text and a number: 31. you get following output:
Counter({'a': 2, 'is': 1, 'This': 1, 'and': 1, '31': 1, 'number': 1, 'text': 1})

I tried it with other values like
1 2 3 4 5 6 7 8 2 1 5 3 4 6 8 1 3 2 4 6 1 2 8 4 3 1 3 2 5 6 5 4  2 2 4 2 1 3 6

to ensure, the output-order does not rely on the key's value/hash. This example produces:
Counter({'2': 8, '3': 6, '1': 6, '4': 6, '6': 5, '5': 4, '8': 3, '7': 1})

But as I said, print(i('collections').Counter(i('re').findall('\w+',input())).most_common()) would return the results as an definitly ordered list of tuples.

Python 3 - 57 (if a space would be enough for splitting :P)
print(__import__('collections').Counter(input().split()))

If you assumed the string was in some variable s, as some other answers do, you could lose 6 characters by replacing input().

@PhilH well. you are right, but I would never read that out of the requirements. sure the "string for JavaScript"-part might suggest it, but I cannot, with a clear conscience, interpret a string-variable as a valid "input". But you are right. that would shorten it even more. :P

-1. Underscore _ should not be included in a word.

Well this depends on the definition of alpha-numeric. In Python,  "\w" is defined for accepting alpha-numeric chars. You might be correct but a with this kind of interpretation of the rules,  my solution keeps being correct. :)

Haskell - 137
import Data.List
count text=let textS=(words(text\\".-\':")) in (sortBy (\(_,n) (_,m) -> compare m n)).nub$map(\t->(t,(length.(filter(==t)))textS)) textS

Doesn't fulfill the condition that non-alphanumeric should be separator.

J, 35+?
(~.(([\:]);]\:]),.@(+/"1@=))@(>@;:)

Doesn't fully work though. Problem is that the splitting into words ';:' monad doesn't handle non-alplanumeric characters in quite the right way. Any suggestions?
Here's how you use it:
(~.(([\:]);]\:]),.@(+/"1@=))@(>@;:) 'This is a text and a number: 31.'
┌───────┬─┐
│a      │2│
│This   │1│
│is     │1│
│text   │1│
│and    │1│
│number:│1│
│31.    │1│
└───────┴─┘

LiveScript - 74 (translation of ECMA one)
s.match(/[^_\W]+/g,a={})map (->-~=a[it]),keys(a)map(->[it,a[it]])sort (.1-&1.1)

Then it's a problem of the ECMA one :)

Clojure
(defn wc [s]
  (let [mc #(assoc % %2 (inc (get % %2 0)))]
    (sort-by #(- (val %))
             (reduce mc {} (re-seq #"\w+" (.toLowerCase s))))))

example:
(wc "hi mom hi dad hello peter hello dad hi")
;; (["hi" 3] ["hello" 2] ["dad" 2] ["peter" 1] ["mom" 1])

Smalltalk, 91 78
input in s

(s allRegexMatches:'\w+')asBag valuesAndCountsDo:[:c :n|(c,$:)print.n printNL]

input:

pick-me-up This is a text and a number: 31.

output:
31:1
pick:1
text:1
me:1
number:1
up:1
is:1
a:2
and:1
This:1

Python (95):
a=sorted(raw_input().split(__import__("string").punctuation))
for i in set(a):print i,a.count(i)

Pretty straightforward, I'd say.

Mathematica, 56 bytes
What, no Mathematica answer yet? This one is not quite a winner, but it's both concise and quite expressive:
f=SortBy[Tally@StringCases[#,WordCharacter..],-Last@#&]&

Calling f["This is a text and a number: 31."] yields
{
 {"a", 2},
 {"31", 1},
 {"and", 1},
 {"is", 1},
 {"number", 1},
 {"text", 1},
 {"This", 1}
}

shell utils, also 42 characters
tr -sc [:alnum:] \\n|sort|uniq -c|sort -rn

Another approach that equals Thor's answer.

Python 2 - 61
Assuming the input is in variable s, which is more realistic in real programming than user input anyway.
import re,collections as c
print c.Counter(re.split('\W+',s))

output
Counter({'a': 2, 'and': 1, '': 1, 'This': 1, 'text': 1, 'is': 1, 'number': 1, '31': 1})

This isn't really good output me thinks. It has an empty word and isn't readable. Here's a version with neat output (90):
Python 2 (neat) - 90
import re,collections as c
d=c.Counter(re.split('\W+',s))
for w in d:
  if w:print w+':'+`d[w]`

output
a:2
and:1
This:1
text:1
is:1
number:1
31:1

Will never win but wanted to try anyway...
C# (118)
var i = "This is a text and a number: 31.";
//The above line is not counted
Regex.Split(i,@"[\W_]").Where(w=>w!="").GroupBy(g=>g).OrderBy(o=>-o.Count()).Select(s=>new{s.Key,V=s.Count()}).Dump();

Ungolfed:
Regex.Split(i, @"[\W_]")                         //split by special chars
     .Where(w => w != "")                        //remove empty
     .GroupBy(g => g)                            //group by word
     .OrderBy(o => -o.Count())                   //order by reversed count
     .Select( s => new { s.Key, V = s.Count() }) //select value and count
     .Dump();                                    //write to screen (LinQPad)

@m.buettner Thanks for the tip on the epxression! :)

Actually, \W|_ is another byte shorter. I was wondering if you could save the Where call if you used a slightly more advanced expression, but I can't seem to find a way to deal with a leading or trailing "", if the string doesn't start with an alphanumeric character.

J 69
Should handle corner-cases like ' - etc, at the huge cost of including all alphanumeric characters (u:62$,65 97 48+/i.26):
(>@~.,.':',.":@#/.~)(#~*@#&>)(<;._1~-.@e.&(u:62$,65 97 48+/i.26))'.',

Usage: just append whatever string to be counted bewteen single quotes (mind that you need to double single quotes in the string).
Example:
   (>@~.,.':',.":@#/.~)(#~*@#&>)(<;._1~-.@e.&(u:62$,65 97 48+/i.26))'.','This is a text and a number: 31. More-tests wouldn''t be bad'
This  :1
is    :1
a     :2
text  :1
and   :1
number:1
31    :1
More  :1
tests :1
wouldn:1
t     :1
be    :1
bad   :1

Clojure
(defn count-words [string]
  (as-> string s
        (clojure.string/replace s #"[^a-zA-Z0-9 ]" "")
        (clojure.string/split s #"\W")
        (frequencies s)
        (sort-by val s)
        (reverse s)))

(clojure.pprint/pprint (count-words "This is a text and a number: 31."))

;; => (["a" 2] ["31" 1] ["number" 1] ["and" 1] ["text" 1] ["is" 1] ["This" 1])

I thought I would beat markw's concision with this approach, but I didn't.

Perl 6, 53 39 bytes
{.comb(/<-[_\W]>+/).Bag.sort:{-.value}}

I use .comb to find every word matching the regexp <-[_\W]>+. In Perl 6, character classes are written <[]> instead of [], and negative character classes <-[]> instead of [^].
We then transform the list of words to a Bag (a set that keeps the number of occurences), and we sort said bag by their value.

C# (332)
This is my original program after excluding white spaces. Please pardon me if I did mistake in counting
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    static void Main(String[] A)
    {
        Dictionary<string,int> D=new Dictionary<string,int>();
        foreach(string s in A)
        {
            if(!D.ContainsKey(s))
                D.Add(s,1);
            else D[s]+= 1;
        }
        foreach(KeyValuePair<string,int> i in D.OrderByDescending(k=>k.Value))
            Console.WriteLine(i.Key+":" + i.Value);
    }
}

This is program with lots of character saving after suggestions from my dear friend jimbobmcgee
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    static void Main(string[] A)
    {
       var D = new Dictionary<string, int>();
       foreach (var v in A)
       {
          if (!D.ContainsKey(v))
            D[v] = 1;
          else D[v] += 1;
       }
     foreach (var v in D.OrderBy(k=>-k.Value))
     {
        Console.WriteLine(v.Key+": "+v.Value);
     }
   }
}

Output

Assuming you are ripping out all whitespace, I make it 332: using System;using System.Collections.Generic;using System.Linq;class P{static void Main(String[]A){Dictionary<string,int>D=new Dictionary<string,int>();foreach(string s in A){if(!D.ContainsKey(s))D.Add(s,1);else D[s]+=1;}foreach(KeyValuePair<string,int> i in D.OrderByDescending(k=>k.Value))Console.WriteLine(i.Key+":"+i.Value);}}

Thanks. I will edit it. How can we do it without manually deleting spaces?

remove 19c if Dictionary<string,int> D=... becomes var D=...; same with foreach(string s... becoming (foreach(var s...for 3c;D.Add(s,1);can becomeD[s]=1for a 5c saving; same withforeach(KeyValuePair...becomingforeach(var...` for 21c...

What's wrong with manually deleting spaces?

15c saving for replacing the entire if(!D... block with D[s]=D.ContainsKey(s)?D[s]+1:1;; also D.OrderByDescending(k=>k.Value) can become D.OrderBy(k=>-k.Value) for 9c.

That said, yours doesn't handle the : in the input, which should be treated as a separator

@jimbobmcgee Another 34 chars saved by using a SortedList, allowing you to remove using System.Linq; (-8) and swap the foreach with for(int i=0;i<D.Count;i++) (-34) but with a penalty when you use Console.WriteLine(D.Keys[i]+":"+D.Values[i]); (+8). Another 14 saved by getting rid of the two remaining using statements and just using the fully qualified names.

If you remove the using System, it'll complain about String[], but just use the string keyword instead (string[]). You can trim off two more characters by removing the braces in the second for/foreach statement - they're not required when you have a single statement in the loop. Ah, I didn't see the KeyValuePair => var change in @jimbobmcgee's first comment - so the for saving with the SortedList is only 14 chars, not 34.

JavaScript (ES5),  146
 F=Function;a={};r="return ";b="b";x=prompt().match(/\w+/g);alert(""+x.filter(F(b,r+"!~(a[b]=~-a[b])")).map(F(b,r+"-a[b]+':'+b")).sort().reverse())

=>|  This is a text and a number: 31.
  <=|  2:a,1:text,1:number,1:is,1:and,1:This,1:31

-1. Underscore _ should not be included in a word.

JAVA CODE
 String s="This is a text and a number: 31";
                String[] stringArray = s.split(" ");
                final Map<String, Integer> counter = new HashMap<String, Integer>();
                for (String str : stringArray)
                    counter.put(str, 1 + (counter.containsKey(str)counter.get(str): 0));
                List<String> list = new ArrayList<String>(counter.keySet());
                Collections.sort(list, new Comparator<String>() {
                    @Override
                    public int compare(String x, String y) {
                        return counter.get(y) - counter.get(x);
                    }
                });
                list.toArray(new String[list.size()]);
                for (String str : list) {
                    int frequency = counter.get(str);
                    System.out.println(str + ":" + frequency);
                }

OUTPUT
 a:2
 text:1
 is:1
 31:1
 number::1
 This:1
 and:1

This is a code-golf question. At the very least you could remove all unnecessary spaces (like between ) and {) and shorten all variable names to 1 character.

-1. : should not be part of a word

Python3 (244 bytes)
import re, collections as c, sys
t=''
with open(sys.argv[1]) as f:
    t+=f.read()
d=c.Counter([s for s in (re.sub('[\s\W]','\n',t).split('\n')) if s])
for x in sorted(d.items(), key=lambda x: x[1])[::-1]:
    print('{}:{}'.format(x[0],x[1]))

Works also with newlines, tabs etc. in the sample text.
Output
> $ python3 wc.py test.txt
a:2
text:1
is:1
This:1
and:1
number:1
31:1

Just split along [^_\W]+

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Underhanded code contest: Not-so-quick sort
The Task
Write a program, in the language of your choice, that reads lines of input from standard input until EOF, and then writes them to standard output in ASCIIbetical order, similar to the sort command-line program.  A short, non-underhanded example in Python is:
import sys

for line in sorted(sys.stdin):
    print(line.rstrip('\n'))

The underhanded part
Similar to The OS War, your goal is to prove that your favored platform is “better”, by having your program deliberately run much more slowly on a competing platform.  For the sake of this contest, a “platform” consists of any combination of:

Processor

Architecture (x86, Alpha, ARM, MIPS, PowerPC, etc.)
Bitness (64-bit vs. 32-bit vs. 16-bit)
Big- versus little-endian

Operating System

Windows vs. Linux vs. Mac OS, etc.
Different versions of the same operating system

Language implementation

Different compiler/interpreter vendors (e.g., MSVC++ vs. GCC)
Different versions of the same compiler/interpreter

Although you could meet the requirements by writing code like:
#ifndef _WIN32
    Sleep(1000);
#endif

Such an answer should not be upvoted.  The goal is to be subtle.  Ideally, your code should look like it's not platform-dependent at all.  If you do have any #ifdef statements (or conditions based on os.name or System.Environment.OSVersion or whatever), they should have a plausible justification (based on a lie, of course).
Include in your answer

The code
Your “favorite” and “unfavorite” platforms.
An input with which to test your program.
The running time on each platform, for the same input.
A description of why the program runs so slowly on the unfavorite platform.

This is harder than I thought. The only answers I can come up with are either very long and a bit obvious, or very short and extremely obvious :-(

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

C
CleverSort
CleverSort is a state-of-the-art (i. e. over-engineered and sub-optimal) two-step string sorting algorithm.
In step 1, it starts by pre-sorting the input lines using radix sort and the first two bytes of each line. Radix sort is non-comparative and works very well for strings.
In step 2, it uses insertion sort on the pre-sorted list of strings. Since the list is almost sorted after step 1, insertion sort is quite efficient for this task.
Code
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Convert first two bytes of Nth line into integer

#define FIRSTSHORT(N) *((uint16_t *) input[N])

int main()
{
    char **input = 0, **output, *ptemp;
    int first_index[65536], i, j, lines = 0, occurrences[65536];
    size_t temp;

    // Read lines from STDIN

    while(1)
    {
        if(lines % 1000 == 0)
            input = realloc(input, 1000 * (lines / 1000 + 1) * sizeof(char*));

        if(getline(&input[lines], &temp, stdin) != -1)
            lines++;
        else
            break;
    }

    output = malloc(lines * sizeof(char*));

    // Radix sort

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++) occurrences[FIRSTSHORT(i)]++;

    first_index[0] = 0;

    for(i = 0; i < 65536 - 1; i++)
        first_index[i + 1] = first_index[i] + occurrences[i];

    memset(occurrences, 0, 65536 * sizeof(int));

    for(i = 0; i < lines; i++)
    {
        temp = FIRSTSHORT(i), output[first_index[temp] + occurrences[temp]++] = input[i];
    }

    // Insertion sort

    for(i = 1; i < lines; i++)
    {
        j = i;

        while(j > 0 && strcmp(output[j - 1], output[j]) > 0)
            ptemp = output[j - 1], output[j - 1] = output[j], output[j] = ptemp, j--;
    }

    // Write sorted lines to STDOUT

    for(i = 0; i < lines; i++)
        printf("%s", output[i]);
}

Platforms
We all know that big-endian machines are much more efficient than their little-endian counterparts. For benchmarking, we'll compile CleverSort with optimizations turned on and create randomly a huge list (just over 100,000 strings) of 4-byte lines:
$ gcc -o cleversort -Ofast cleversort.c
$ head -c 300000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input
$ wc -l input
100011 input

Big-endian benchmark
$ time ./cleversort < input > /dev/null

real    0m0.185s
user    0m0.181s
sys     0m0.003s

Not too shabby.
Little-endian bechmark
$ time ./cleversort < input > /dev/null

real    0m27.598s
user    0m27.559s
sys     0m0.003s

Boo, little Endian! Boo!
Description
Insertion sort is really rather efficient for almost-sorted lists, but it is horribly inefficient for randomly sorted ones.
CleverSort's underhanded part is the FIRSTSHORT macro:
#define FIRSTSHORT(N) *((uint16_t *) input[N])

On big-endian machines, ordering a string of two 8-bit integers lexicographically or converting them to 16-bit integers and ordering them afterwards yields the same results.
Naturally, this is possible on little-endian machines as well, but the macro should have been
#define FIRSTSHORT(N) (input[N][0] | (input[N][1] >> 8))

which works as expected on all platforms.
The "big-endian benchmark" above is actually the result of using the proper macro.
With the wrong macro and a little-endian machine, the list is pre-sorted by the second character of every line, resulting in a random ordering from the lexicographical point of view. Insertion sort behaves very poorly in this case.

Python 2 vs. Python 3
Obviously, Python 3 is several orders of magnitude faster than Python 2. Let's take this implementation of the Shellsort algorithm as an example:
Code
import sys
from math import log

def shellsort(lst):

    ciura_sequence = [1, 4, 10, 23, 57, 132, 301, 701]  # best known gap sequence (Ciura, 2001)

    # check if we have to extend the sequence using the formula h_k = int(2.25h_k-1)
    max_sequence_element = 1/2*len(lst)
    if ciura_sequence[-1] <= max_sequence_element:
        n_additional_elements = int((log(max_sequence_element)-log(701)) / log(2.25))
        ciura_sequence += [int(701*2.25**k) for k in range(1,n_additional_elements+1)]
    else:
        # shorten the sequence if necessary
        while ciura_sequence[-1] >= max_sequence_element and len(ciura_sequence)>1:
            ciura_sequence.pop()

    # reverse the sequence so we start sorting using the largest gap
    ciura_sequence.reverse()

    # shellsort from http://sortvis.org/algorithms/shellsort.html
    for h in ciura_sequence:
        for j in range(h, len(lst)):
            i = j - h
            r = lst[j]
            flag = 0
            while i > -1:
                if r < lst[i]:
                    flag = 1
                    lst[i+h], lst[i] = lst[i], lst[i+h]
                    i -= h
                else:
                    break
            lst[i+h] = r

    return lst

# read from stdin, sort and print
input_list = [line.strip() for line in sys.stdin]
for line in shellsort(input_list):
    print(line)

assert(input_list==sorted(input_list))

Benchmark
Prepare a test input. This is taken from Dennis answer but with fewer words - Python 2 is sooo slow...
$ head -c 100000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input

Python 2
$ time python2 underhanded2.py < input > /dev/null

real    1m55.267s
user    1m55.020s
sys     0m0.284s

Python 3
$ time python3 underhanded2.py < input > /dev/null

real    0m0.426s
user    0m0.420s
sys     0m0.006s

Where is the underhanded code?
I assume some readers may want to hunt down the trickster themselves, so I hide the answer with a spoiler tag.

 The trick is the integer division in the calculation of the max_sequence_element. In Python 2 1/2 evaluates to zero and hence the expression is always zero. However, the behavior of the operator changed to floating point division in Python 3. As this variable controls the length of the gap sequence, which is a critical parameter of Shellsort, Python 2 ends up using a sequence which contains only the number one while Python 3 uses the correct sequence. This results in a quadratic run time for Python 2.

Bonus 1:

 You can fix the code by simply adding a dot after the 1 or the 2 in the calculation.

Bonus 2:

 At least on my machine Python 2 is a bit faster than Python 3 when running the fixed code...

Well played!  Nitpix time: flag looks write-only, couldn't you remove it?  Also, r seems superfluous if you do if lst[i+h] < lst[i]: ....  On the other hand, if you keep r why do the swap?  Couldn't you just do lst[i+h] = lst[i]?  Is all of this an intentional distraction?


text:
UTF-8 Reduce Ascii art
This challenge is a cut'n paste from Enlarge ASCII art, but reversed, using PetSCII based half-block chars:
string=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"

There, PetSCII is emulated by using UTF-8 characters, you may found between U+2580 UPPER HALF BLOCK and U+259F QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT.
So the goal is to reduce by 1/2 submited ascii-art.
You have to group 2 char from 2 lines to obtain one 2x2 pattern for one character:
|XX|         |X |         |X |         |  |
|XX| -> '█'  |XX| -> '▙'  | X| -> '▚'  | X| -> '▗'  and so on...

Some samples: From
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

you have to render:
▟▀▀▘▟▀▀▙▐▛▀▙▐▛▀▀  ▗▛▀▀ ▟▀▀▙▐▌  ▐▛▀▀
█   █  █▐▌ █▐▛▀   ▐▌ ▜▌█  █▐▌  ▐▛▀
▝▀▀▘▝▀▀▘▝▀▀▘▝▀▀▀   ▀▀▀ ▝▀▀▘▝▀▀▀▝▘

And from:
  OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
 OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
 OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
 OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
  OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

Where 1st column hold spaces you may render:
▗▛▀▀▗▛▀▜▖█▀▜▖█▀▀▘  ▟▀▀▘▗▛▀▜▖█   █▀▀▘
▐▌  ▐▌ ▐▌█ ▐▌█▀▘   █ ▝█▐▌ ▐▌█   █▀▘
 ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▘  ▝▀▀▘ ▀▀▀ ▀▀▀▘▀

Piping:
wget -O - https://codegolf.stackexchange.com/q/19123/9424 |
    sed -ne '/
/,/<\/code><\/pre>/{//{/\//q};s/
//;p}'
   ('l2v2l6v2'+  'e1l1v3l2'+
 'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
 .replace(/[lve]\d/g,function
   (c){return Array(-~c[1]).
      join({l:' ',v:'Love'
         ,e:'\n'}[c[0
             ]])})

must give:
▗▟█████▙▟█████▄
▜█████████████▛▘
 ▝▀███▙▛█████▀
    ▝▀▜██▀▘

Other samples on my terminal:

With standard rules:

Input ASCII from STDIN or file, without special chars, tabulations or UTF-8.
Each submited chars have to be represented, only whitespaces have to stay empty.
This is code-golf too, so the lowest score win. Score is computed as:

+1 by chars, to be counted in chars, not in bytes!! Ie: s=' ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█' count for 20 chars, not 52 !!
-10 for explanation;
+20 for use of external font tool or library.

So to clarify: the input image is divided into 2x2 squares and each maps onto one character?

-0.5 for adding strange bonuses (define explanation) - after rounding still an upvote. Also this is then code-challenge and not code-golf.

Most of these chars does not renders correctly in my browser. :(

Under my linux, I use xterm -xrm 'XTerm*renderFont:false' & to open a console window able to display this properly.

I think you need to specify a) how the reduction is to be done and b)reword your bonuses(and probably remove the one for explanations)

@Razetime As this was posted in 2014, I can't change overall rule or score counting method. So I've tried to improve my request, but I won't remove -10 for explanation (without moderator aproval).

GolfScript (90 chars)
n/.,1&[""]*+.{,}%$-1=.1&+{1$,-´' '*+}+%2/{zip 2/{~+0\{32=!1$++}/" ▗▝▐▖▄▞▟▘▚▀▜▌▙▛█"3/=}%n}%

A lot of this goes to handling ragged arrays. Nasty test case:
xx
xxx
xxx
xx
x

contains a 3 different 2x2 grids with only one of the 4 cells containing any character at all.
To make things worse, the zip transposition to chop the columns into pairs gives the same output for ["xx" "xxx"]zip and ["xxx" "xx"]zip. I therefore begin by padding out to ensure that all lines are the same even length, and that there are an even number of lines.
Note that this program assumes that the interpreter will treat " ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█" as a string of length 48, even though as per instructions in the question I'm counting it as 16 chars plus delimiters.
I've tested this to the best of my ability, but I can't find a monospace font which actually renders those characters correctly.

Your code seem fail on second test, with the heart... But nice! +1 as you'r the 1st!

Hmm. I don't tend to use zip on ragged arrays, and I'm quite surprised by what it seems to do on e.g. ["##" "###"]. I'm going to have to rethink my approach.

Freemono, Unifont, Code2000, and Fixedsys Excelsior all render these characters correctly.

@primo, Unifont is nowhere near monospaced on those characters. Fixedsys Excelsior isn't quite correct either, but it's close enough.

Yes! now you have it! Little remark: there is two empty lines at end of output. This don't break any rule! (Note: scoring is a little changed, you may save 10 points;-)

APL (Dyalog Extended), 38 - 10 = 28 chars
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)≠⎕⍪0]

Try it online!
-10 bytes for an explanation? Count me in!
-14 bytes from Adám.
Takes input as a list of lines from STDIN.
Explanation
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[{2⊥∊⍵}⌺(2 2⍴2)⊢↑{2|≢⍵:⍵,0⋄⍵}' '≠⎕]
                                                   ⎕  take input
                                               ' '≠   convert spaces to 0, 1 otherwise
                                   {2|≢⍵:⍵,0⋄⍵}       if there are an odd number of rows, append a 0 to each column
                                  ⊢↑                  convert to matrix, apply the following:
                          ⌺(2 2⍴2)                    cut the matrix into 2x2 pieces, apply the following to them:
                    {2⊥∊⍵}                            enlist, decode from base 2
' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█'[                                 ] index those numbers into the box drawing characters

43 or 38 in Extended.

C++ (gcc), 257 ... 254 248 - 32 - 10 = 212 chars
#include<bits/stdc++.h>
namespace std{int f(){string a,b;for(int i:{1,3}){getline(cin,a={});b.resize(max(a.size()/2,b.size()));for(int j=a.size();j--;)b[j/2]+=(a[j]>32)<<i-j%2;}for(int i:b)cout.write(" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█"+i*3,3);cout<<endl;cin&&f();}}

Try it online!
Explained:
#include<bits/stdc++.h> // Evil hack to include all STL headers

namespace std {         // Shorter than using namespace std;

int f() {               // int is one byte shorter than void
  string a, b;          // a will hold one input line, b will hold one reduced line

  for (int i: {1, 3}) {                           // Do two iterations:
    getline(cin, a = {});                         // Read an input line, make sure it is empty first
    b.resize(max(a.size() / 2, b.size()));        // Resize b such that it is max of both inputs divided by 2
    for (int j = a.size(); j--;)                  // Loop over all characters in the input line backwards (order doesn't matter here)
      b[j/2] += (a[j] > 32) << i - j % 2;         // Set the bits in b depending on the presence of non-whitespace in a
  }

  for (int i: b)                                  // For each character in b:
    cout.write("⠀▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" + 3 * i, 3);    // Write the corresponding multibyte character

  cout << endl;                                   // Write a newline and annoy people with an unnecessary flush

  cin && f();                                     // If we didn't reach the end of the input yet:
                                                  // Tail recurse to the start of the function
}

}

Thanks to Razetime for fixing the wrong space character. I also found an issue if the input is an odd number of lines, which required three extra characters to fix. Thanks to ceilingcat for shaving off 9 bytes.

Perl 6, 159 chars (192 bytes)
(|lines.map(*~' '),'')».comb(/../).rotor(2).map:{my@d='  'xx.max(*.elems);say [~] map {"█▛▜▀▙▌▚▘▟▞▐▝▄▖▗ ".comb[:2(.trans([' ',/./]=>~⑩))]},[Z~] .map:{|$_,|@d}}

Try it online!

Fixed my solution.

143 chars

Bash (203, 197 chars)
#!/bin/bash
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=;while read -r m;do read -r n o;for((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)){
printf -ve %-2s "${n:i:2}" "${m:i:2}";e=${e//[^ ]/1};o+=${r:2#${e// /0}:1};};echo "$o";done

or
r=" ▝▘▀▗▐▚▜▖▞▌▛▄▟▙█" IFS=
while read -r m; do
    read -r n o
    for ((l=${#m}>${#n}?${#m}:${#n},i=0; i<l; i+=2)) {
        printf -ve %-2s "${n:i:2}" "${m:i:2}"
        e=${e//[^ ]/1}
        o+=${r:2#${e// /0}:1}
    }
    echo "$o"
done

Perl (192 chars)
#!/usr/bin/perl -CS
use utf8;my$r=" ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";while($v=<>){$w=<>;foreach my$i(0..length($v)/2){($x=substr($v,$i*2,2).substr($w,$i*2,2))=~s/\S/1/g;$x=~s/ /0/g;print substr($r,ord pack("b8",$x),1)}print"\n"}

or
#!/usr/bin/perl -CS
use utf8;
my $r = " ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█";
while ( $v = <> ) {
    $w = <>;
    foreach my $i ( 0 .. length($v) / 2 ) {
        ( $x = substr( $v, $i * 2, 2 ) . substr( $w, $i * 2, 2 ) ) =~ s/\S/1/g;
        $x =~ s/ /0/g;
        print substr( $r, ord pack( "b8", $x ), 1 );
    }
    print "\n";
}

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Freehand red circles
Over on http://meta.stackoverflow.com, we have a few memes of our own. One of them is Freehand Red Circles.
See this post:

So, the challenge is,
can you draw freehand red circles... with code?
Additional restrictions:

You will take an image as input, and you must output the image with freehand red circle added.
Must be predictable, i.e. same image input must result in same output. You can use randomness, but results have to be consistent for same input.
Output must be exactly the same image as input, except with circle (no other alterations).
The freehand red circle must look freehand (no perfect circles!), be red (obviously), and look generally like a circle (no random squiggly lines).

This is a popularity-contest, so the answer with the most upvotes at the beginning of March 2014 will win. There is no specific goal, other than "freehand red circles," so be as creative as possible so you get the most upvotes! (To be as unbiased as possible, I will upvote any answer that follows the rules.)

I think this needs a bit more clarification. Are we to a) draw a nothing but a circle on a plain white canvas, b) take an image containing text, and draw a circle around the text block, or c) take a text, and create an image of the text with a circle around it?

+1 to @primo. Also, there's other things to be considered: If all we need to do is draw a circle, is it the same circle every time or does the program need to be capable of drawing different circles - and are those circles to just be randomly different, or somehow specified by user input? Does the program need to be capable of handling user input at all, to determine the size or shape of the circle? Does it matter what format the image output is in, or could someone just come up with some clever ASCII art?

I think the answer is "this is a popularity contest, so impress your code-golf buddies"

I don't know what is unclear about this question. @Iszi - The key word is freehand. Open up Paint or GIMP and draw some freehand circles, do they all look the same? From the description and the link, it looks like you have to draw circles around something, which would imply X & Y and size. What does it matter what file format you use? Just run it through a converter if you want PNG, JPEG or whatever.

I believe with McKay.  If you want a lot of upvotes, draw random freehand circles.  Otherwise, hardcode your circle in.

@primo Any of them; it's your decision.

@primo Okay, I've updated the question to make it have a more concrete goal.

@Iszi (see above comments)

C — about 750 720 bytes if squeezed*
I think I came up with something that looks freehand-y enough.

starts at a random angle
draws a full circle plus or minus a bit
uses a thick squiggly line (maybe too squiggly!)
is customizable by changing a MAGIC number

Compile:
gcc -o freehand freehand.c -lm

Run:
./freehand [X center in % W] [Y center in % H] [radius in % diagonal] < [PPM file input] > [PPM file output]

Example:
./freehand 28.2 74.5 3.5 < screenshot.ppm > freehand.ppm

Before:

After:

Code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define MAGIC      42
#define UNIFORM(x) ((x) * (double)rand() / (double)RAND_MAX)

typedef struct {unsigned char r, g, b;} RGB;

int main(int argc, char **argv)
{
    int W, H, i, f, g, x, y;
    double X, Y, R, a, r;
    RGB *p;

    srand(MAGIC);

    if (argc != 4 || scanf("P6 %d %d 255\n", &W, &H) != 2)
        return 1;

    p = malloc(sizeof(RGB) * W * H);

    fread(p, sizeof(RGB), W * H, stdin);

    X = W * atof(argv[1]) / 100.0;
    Y = H * atof(argv[2]) / 100.0;
    R = hypot(W, H) * atof(argv[3]) / 100.0;

    for (a = UNIFORM(M_PI), i = 2.0 * M_PI * R + UNIFORM(R / 4.0), r = R; i > 0; i--, a += 1.0 / R)
    {
        r += UNIFORM(2.0) - 1.0;
        f = sin(a) * r + X;
        g = cos(a) * r + Y;

        for (x = f - 2; x <= f + 2; x++)
        {
            for (y = g - 2; y <= g + 2; y++)
            {
                if (x >= 0 && x < W && y >= 0 && y < H)
                {
                    RGB *s = p + y * W + x;
                    s->r = 255;
                    s->g = 0;
                    s->b = 0;
                }
            }
        }
    }

    printf("P6 %d %d 255\n", W, H);
    fwrite(p, sizeof(RGB), W * H, stdout);

    free(p);

    return 0;
}

* and using U for UNIFORM and M for MAGIC

C + GD library
Instead of just drawing circles any old where, I thought it would be fun to find something red in the picture and draw a circle around that.
Here are some examples of the results obtained with a few photos from Wikimedia Commons:

And here's the code. It's a bit messy, but not too difficult to follow, I hope:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gd.h>

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))

/* Used for image segmentation */
int floodfill(int *tmp, int i, int w, int id) {
  int np=1;
  tmp[i]=id;
  if (tmp[i-w-1]<0) np+=floodfill(tmp,i-w-1,w,id);
  if (tmp[i-w]<0) np+=floodfill(tmp,i-w,w,id);
  if (tmp[i-w+1]<0) np+=floodfill(tmp,i-w+1,w,id);
  if (tmp[i-1]<0) np+=floodfill(tmp,i-1,w,id);
  if (tmp[i+1]<0) np+=floodfill(tmp,i+1,w,id);
  if (tmp[i+w-1]<0) np+=floodfill(tmp,i+w-1,w,id);
  if (tmp[i+w]<0) np+=floodfill(tmp,i+w,w,id);
  if (tmp[i+w+1]<0) np+=floodfill(tmp,i+w+1,w,id);
  return np;
}

int main(int argv, char *argc[]) {
  FILE          *infile,*outfile;
  gdImagePtr    img;
  int           *t, *tmp;
  int           w,h,x,y,r,g,b;
  int           c,redness,rgb;
  int           i,np,max,min,thresh;
  int           xt,yt,n;
  int           areaID,size,maxID;
  double        xmin,ymin,xmax,ymax,rad,r0,th;
  gdPoint       v[33];

  /* Check command line and open source JPEG file */
  if (argv!=3) return printf("Usage: %s <in.jpg> <out.jpg>\n",argc[0]);
  if (!(infile=fopen(argc[1],"r"))) return printf("Can't open <%s>\n",argc[1]);
  if (!(img=gdImageCreateFromJpeg(infile))) return printf("Bad JPEG: <%s>\n",argc[1]);
  fclose(infile);

  /* Extract red pixels and auto-threshold */
  w=img->sx;
  h=img->sy;
  np=w*h;
  t=tmp=calloc(np,sizeof(int));
  for (max=0,min=255,y=1;y<h-1;y++) {
    for (x=1;x<w-1;x++) {
      rgb=gdImageGetTrueColorPixel(img,x,y);
      r = (rgb&0xff0000)>>16;
      g = (rgb&0xff00)>>8;
      b = rgb&0xff;
      redness = max(0,r-(max(g,b)+abs(g-b)));
      if (redness>max) max=redness;
      if (redness<min) min=redness;
      *t++ = redness;
    }
    t += 2;
  }
  thresh = (max+min)/2;
  for (t=tmp,i=0;i<np;i++,t++) *t=((*t>thresh)?-1:0);

  /* Label each area detected */
  areaID=1;
  maxID=0;
  max=-1;
  for (t=tmp,i=0;i<np;i++,t++) {
    if (*t<0) {
      size=floodfill(tmp,i,w,areaID);
      if (size>max) {
        max = size;
        maxID = areaID;
      }
      areaID++;
    }
  }

  /* Calculate centre coordinates and area */
  if (max>0) {
    xt=yt=n=xmax=ymax=0;
    xmin=w; ymin=h;
    for (t=tmp,y=0;y<h;y++) {
      for (x=0;x<w;x++) {
        if (*t++==maxID) {
          xt+=x;
          yt+=y;
          n++;
          if (x<xmin) xmin=x;
          if (y<ymin) ymin=y;
          if (x>xmax) xmax=x;
          if (y>ymax) ymax=y;
        }
      }
    }
    x = xt/(2*n) + (xmax+xmin)/4;
    y = yt/(2*n) + (ymax+ymin)/4;

    r0 = max(20,min(min(w,h),max(xmax-xmin,ymax-ymin))/2);
  }
  /* Default circle if nothing found */
  else {
    x=w/2; y=h/2; r0=min(w,h)/3;
  }

  /* Draw a red circle */
  for (th=4.0,i=0;i<33;i++) {
    rad = r0 * (1.2 + (" ,<MYZVSB>@EJIOSWZfgb^bbfgeZTOI@2"[i]-87)/160.0);
    v[i].x = x + rad * sin(th);
    v[i].y = y + rad * cos(th);
    th += 0.22;
  }
  gdImageSetThickness(img,7);
  c = gdImageColorAllocate(img,255,0,0);
  gdImageOpenPolygon(img,v,33,c);

  /* Output results to file */
  printf("Saving...\n");
  if (!(outfile=fopen(argc[2],"w"))) {
    return printf("Can't open <%s> for writing\n",argc[2]);
  }
  gdImageJpeg(img,outfile,85);
  fclose(outfile);
  gdImageDestroy(img);
  printf("Finished\n");
  return 0;
}

Note: Markdown messed up my link in the comments, so I'll just point out that the code uses segmentation to identify all the areas of red in the picture, and then draws a circle around the largest of these. For example, this image:

produces the following output:

Nice job! ;) Goes more with the theme of drawing them to emphasize something. But I'm curious about what it would do if there were two red objects...? (+1)

It converts all the red areas into different segments and chooses the largest. So for example in this photo of a red bucket and spade, the bucket wins. Here's the result

Mathematica
ClearAll[f]
f[image_,rad_, xPos_:.5,yPos_:.5,color_:Darker[Red,0.3],thick_:.01,axes_:False]:=
 Module[{i=ImageDimensions[image],rr,y=SeedRandom[2]},
 rr:=RandomReal[{-.1,.1}];
 Show[image,Graphics[{color,JoinForm["Round"],CapForm["Round"],Thickness[thick],
 Line[t=Table[{rad i[[2]] (Cos[z]+rr)+i[[1]]xPos,rad i[[2]] (Sin[z]+rr)+i[[2]] yPos},
 {z,0, 2 Pi+2Pi/12,Pi/12}]]}],Axes-> axes]]

f takes the following parameters:

image: the image that will be marked up with a circle
rad: the radius of the circle, in fraction of image width
xPos: the position of the center of the circle along x, from 0 to 1 (default=.5)
yPos: the position of the center of the circle along y, from 0 to 1 (default=.5)
color: ink color (default= dark red)
thickness: stroke thickness (default = .01)
axes: whether to display axes (default = False)

Examples
text = Import["text.png"]
f[text,.13,.58,.23]

A different radius, location, blue color, thicker stroke, displaying axes.
f[text,.22,.7,.5,Blue,.015,True]

Wow, very nice! Is this random, though? (It must produce same output for same input.)

I used randomness for the deviations from a true circle.  I thought that was ok.  If not, I can hardwire the shape.

"Must be predictable, i.e. same image input must result in same output. You can use randomness, but results have to be consistent for same input." There must be some way to get a seeded RNG in Mathematica, right?

Yes, SeedRandom seems to do the trick.

Alright, great! +1


text:
palindrome detection palindrome
Write a function with a single string parameter and a boolean return value. The function should return true iff the string is a palindrome character-wise.
Alternatively, write a program that reads a string from standard input and writes 1/0 to standard output depending on whether the string is palindrome or not.
The code itself should be a palindrome. The structure of the code visually documents what the code is about.
Since this is all about beauty of code, the code with the most votes wins.

@KendallFrey you are right... I mistakenly searched for palyndrome with y.

Would adding another constraint make the question unique enough?  I notice that most of the solutions to the other problem use comments.  I think it would be interesting to see a challenge where comments are forbidden.

@Josh good point, but I see the duplicate question already has some very nice answers without using comments.

Maybe mirroring, without using comments? - ( -> ), [ -> ], etc.


text:
Tennis scores meets Code Golf
In light of the 2014 Australian Open in Melbourne, and the win by Stanislas Wawrinka against Novak Djokovic, I propose the following code golf challenge!
Wawrinka and Djokovic are at it again for the basis of this CGC. Your challenge is to take a string consisting of 1's and 2's and determine the tennis scores based on the tennis scoring system. A "1" indicates that Wawrinka has scored a point, whereas a "2" indicates that Djokovic has scored a point.
For the sake of example: 1211222122111122111 will generate a two-line output:
Wawrinka 1 - 40
Djokovic 1 - 30

The longer the string, the further into the game the score is.
Rules:

Shortest code wins, pure and simple.
The scores when displayed must be right aligned and also column
aligned; e.g.
Sample alignment of output:
Wawrinka 7 5 3 -  0
Djokovic 6 7 4 - 15

If a game is in progress, the score must be displayed after the set scores. Game scores must follow set scores with a space-dash-space separator. If this happens to be the first game, a 0-0 set score must be displayed.
Wawrinka 0 -  0
Djokovic 0 - 15

A game will go in order of 0, 15, 30, 40, and game point. If a game reaches 40-40, a deuce is declared, and the score must display the deuce on the player row scoring the point:
Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce

If a deuce is reached, the next point will be an advantage to the player scoring the point:
Wawrinka 7 5 3 - Ad
Djokovic 6 7 4 - 40

The point after that, if scored by the advantaged player, wins the game, else the game goes back to deuce.
If more than one deuce is scored in between advantage points, the
number of the deuce will be indicated by a number in parentheses:
Wawrinka 7 5 3 - 40
Djokovic 6 7 4 - 40 Deuce (2)

A set is won if a player reaches 6 games or more and with a two game
margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's
fifth set)
Consecutive sets must be separated with a space.
There are tie breaks in the Australian Open, therefore if a 6-6 set is reached, a tie-break is established by the first player reaching seven points with a two point margin lead. Display of tie breaks are shown within square brackets as follows:
Wawrinka 7 6 [6]
Djokovic 6 6 [4]

The winner of the tie-break is said to have won the previous set 7-6.
If the fifth set reaches 6-6, play is continued without tie-break until a two game margin is reached with one player, that player being the winner of that set. There are NO tie-breaks in the fifth set.
If a player has won three sets, a third line will be displayed saying
Wawrinka wins or Djokovic wins depending on who has won and the code then terminates.
Wawrinka 2 6 6 3 9
Djokovic 6 4 2 6 7
Wawrinka wins

If the string ends such that the last point has won a game, set or
match, the game score is not displayed...
Wawrinka 7 5 3
Djokovic 6 7 4

If the string goes beyond a match being won, the rest of the string
is ignored, the score displayed and the winner declared.

I really don't think we need a new tag called [tag:sports]; [tag:game] should work just fine.

@Quincunx, good point...

What will be the result? Just the end score or every step along the way?

@TeunPronk depending on the score, the match will be finished or not. The idea seems to be: Given the string of points, what is the current score.

@TimSeguine ah okay, couldnt quite figure out if you should display just the current score or everytime a player gets points.

According to your rules "A set is won if a player reaches 6 games or more and with a two game margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's fifth set)" But it looks like the first set wasn't finished "7-6" because there wasn't a 2 game margin?

@McKay I think 7-6 is a finished set, but I agree that the description of the is problematic

Then what's the set win condition. It isn't stated?

@McKay I am not an expert in the rules of Tennis, but I think if the set comes to 6-6, then a tie break happens. Whoever wins the tie break wins the set 7-6. That is the only exception to the rule mentioned in the post. The OP did mention tie breaks but didn't specify how they work in that regard.

Then how does a score get to be 9-7?

@McKay because that is the final set. Okay, so I think it is fairly obvious that the OP needs to explain the scoring rules for tennis a bit better. There are no tiebreaks in the final set of a match.

The tie-breaker for the final set is often played as an Advantage Set, which can run on ridiculously long. The OP makes no mention of this, though.

To the OP: I think some more test cases would be helpful. Also I think you need to clarify the scoring on some of the edge cases McKay has pointed out. I think this is a good question that wasn't quite ready to come out of the sandbox.

@McKay - you shouldn't be able to reach 9-7 in the third set of the Australian Open; the tiebreak should apply in every set except the fifth.

My bad, guys, @Chowlett, you're right... I should have realized that tiebreaks should apply except in set 5... I'll update the description

you still say "•A set is won if a player reaches 6 games or more and with a two game margin in lead, e.g. 7-5, 6-4... 9-7 (In the case of last night's fifth set)" but yet have as example scoring 6-7.

@WallyWest you were correct with your previous edit; only the fifth set has no tie-breaker. I fixed your example to make this more clear.

the tie break scores still don't make sense. "The winner of the tie-break is said to have won the previous set 7-6." So, what does it look like if it is 6-6, and someone wins a set? Wouldn't that be 7-6?

@McKay the tie-break is played as a separate set altogether (denoted by square brackets). After that set is won, the previous set is marked 7-6.

You didn't directly answer the question. What does it look like if the score is 6 6, and someone wins a game?

Perl - 424 bytes
*1=a;*2=b;@1=(Wawrinka,0);@2=(Djokovic,0);
$$_++>${$o=S^$_}&&$$_>3and$1=$2=0,
$w=$w[$_]+=($$_[$.]++>$$o[$.]||(($t=$$_[$.]==$$o[$.])&&!$%&&$.<5))&&
$$_[$.]>5+$%&&!($1[$.]=$2[$.+=!$%]=$w<2&&0,$$_[$.-1]+=$%,$%=$t)for<>=~/./g;
@s=(' 0',15,30,(40)x($e=$$o<3||$$o-2),Ad);
$%and$_="[$_]"for@1[-1],@2[-1];$d[$&]=$1>2&&$1==$2&&' Deuce'.($1>3&&" ($e)");
print"@1",$w<3&&" - $s[$1]$d[1]","\n@2",$w<3&&" - $s[$2]$d[2]",$w>2&&"\n${$&}[0] wins"

Newlines have been added for readability horizontal sanity.
I believe this to be a complete solution, according to the scoring of the Australian Open:

Best of five sets (a.k.a. race to three).
Sets 1-4 are played as a 6-6 tie-breaker.
Set 5 is played as an advantage set.

Test Cases

1211222122111122111

Wawrinka 1 - 40
Djokovic 1 - 30

12112221221111221112

Wawrinka 1 - 40
Djokovic 1 - 40 Deuce

121122212211112211122

Wawrinka 1 - 40
Djokovic 1 - Ad

1211222122111122111221

Wawrinka 1 - 40 Deuce (2)
Djokovic 1 - 40

22111111212122221122111212212112121221212211221121222222112112221121121122221122221211111222121222122211212122111212112211222121211212211212211122121211112222222212211121122

Wawrinka 6 [5] - 30
Djokovic 6 [6] - 40

221111112121222211221112122121121212212122112211212222221121122211211211222211222212111112221212221222112121221112121122112221212112122112122111221212111122222222122111211222

Wawrinka 6 0 -  0
Djokovic 7 0 -  0

1122222211121211121211111121111211221222212212112221211222211222112212211121122122212122212222122212212211221111121222111221211111211112222212122122112111212121221221212211112122212211111111112111212222221112212121122212121111122111222222111212221121221111222122122222111212111111221121122111122122111222222121122221112221221122221121211212111122111121212112112121222122

Wawrinka 5 4 6 6 5 - 15
Djokovic 7 6 4 4 6 - 40

11222222111212111212111111211112112212222122121122212112222112221122122111211221222121222122221222122122112211111212221112212111112111122222121221221121112121212212212122111121222122111111111121112122222211122121211222121211111221112222221112122211212211112221221222221112121111112211211221111221221112222221211222211122212211222211212112121111221111212121121121212221222

Wawrinka 5 4 6 6 5
Djokovic 7 6 4 4 7
Djokovic wins

222221112112212212222111222211111111121111121112211221221211212121122211222112111112122122212222211112122212221111121111121211212112112112221221121122121121112221221222122122211222212121212112112111221221121112222212122222221111112222222221221122211221121111221121222222111111122221122111211121222112112122212122221121222221222121212111121221221112111212212222122212212212112111112112112121112221111221221221121222122211221212211111111222222121221112221212

Wawrinka 6 7 6 4 7 - 40
Djokovic 3 5 7 6 8 - Ad

2222211121122122122221112222111111111211111211122112212212112121211222112221121111121221222122222111121222122211111211111212112121121121122212211211221211211122212212221221222112222121212121121121112212211211122222121222222211111122222222212211222112211211112211212222221111111222211221112111212221121121222121222211212222212221212121111212212211121112122122221222122122121121111121121121211122211112212212211212221222112212122111111112222221212211122212122

Wawrinka 6 7 6 4 7
Djokovic 3 5 7 6 9
Djokovic wins

All intermediate scores for the last test case can be seen here: http://codepad.org/FzDIcf0W

Isn't 11-9 only meant to be valid as a fifth set?

@Volatility actually, you were right. I'll need to update.

ECMAScript 6 - 635 Characters
f=(p,q,C)=>{B='';T=' ';L=(x)=>(B+x).length;M=(x,y)=>x>y?x:y;E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]};E(a=[p,q]);g=[m=n=o=i=t=z=0,0];s=[0,0];S=[0,0];w=2;O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n';while(W=C[i++]){w=--W;++o;if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){g=[o=z=0,0];j=++s[w];k=s[l];t=++n>11;if(j>M(5,m>4||k<6?k+1:6)){E(s);a[0]+=T+s[0];a[1]+=T+s[1];s=[n=0,0];++m;if(++S[w]>2)break}}else if(!t&&d+e>7){--g[w];--g[l];++z}}E(s);E(g);return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B)}

With comments:
// Function f takes arguments:
//   p - Player 1 name
//   q - Player 2 name
//   C - String of 1s and 2s representing points won by players.
f=(p,q,C)=>{
    /* Empty String          */ B='';
    /* Space                 */ T=' ';
    /* String Length Func.   */ L=(x)=>(B+x).length;
    /* Max Function          */ M=(x,y)=>x>y?x:y;
    /* Equalize Length Func. */ E=(a)=>{var x=L(a[0]),y=L(a[1]),q=M(x,y);for(;x++<q;)a[0]=T+a[0];for(;y++<q;)a[1]=T+a[1]};
    /* No. of sets           */ m=0;
    /* No. games in set      */ n=0;
    /* No. points in game    */ o=0;
    /* Input Index           */ i=0;
    /* Output String         */ E(a=[p,q]);
    /* Current Game's Points */ g=[0,0];
    /* Current Set's Games   */ s=[0,0];
    /* No. sets won          */ S=[0,0];
    /* Is a tiebreaker       */ t=0;
    /* No. of deuces         */ z=0;
    /* Current match result  */ w=2;
    /* Output Fnctn  */ O=(i)=>a[i]+(n+o>0?T+s[i]:B)+(o>0?(t?' ['+g[i]+']':' - '+[' 0',15,30,40,'Ad'][g[i]]+(z>0&&g[0]+g[1]==6&&i==w?' Deuce'+(z>1?' ('+z+')':B):B)):B)+'\n';
    while(W=C[i++]){
        w=--W;
        // w - index of winner of current game
        // l - index of loser of current game
        // d - winner of current point's game score
        // e - loser of current point's game score
        ++o;
        if((d=++g[w])>M(t?6:3,(e=g[l=1-w])+1)){
            g=[0,0];  // Reset the game score.
            o=z=0;
            j=++s[w]; // j = Increment the winner's set score
            k=s[l];   // k = Loser's set score
            t=++n>11; // Is a tiebreak?
            if(j>M(5,m>4||k<6?k+1:6)){
                E(s);
                a[0]+=T+s[0]; // Add to output
                a[1]+=T+s[1]; // Add to output
                s=[n=0,0];  // Reset current set's no. of games & no. of deuces.
                ++m;        // Increment no. of sets.
                if(++S[w]>2)break;     // Increment winners no. sets won and check if match won.
            }
        }
        else if(!t&&d+e>7){--g[w];--g[l];++z}// Check if deuces increased.
    }
    E(s); // Format sets strings.
    E(g); // Format games strings.
    return O(0)+O(1)+(S[w]>2?(w?q:p)+' wins':B);
}

Testing
var tests=[
            '',
            '1',
            '2',
            '11',
            '222',
            '1111',
            '2222',
            '1112221',
            '11122212',
            '121212121',
            '1212121212',
            '1211222122111122111',
            '12112221221111221112',
            '121122212211112211122',
            '1211222122111122111221',
            '1111222211112222111122221111222211112222111122221212121212121212121',
            '11111111111111111111111111111111111111111111111111111111111111111111111',
            '111111111111111111111111111111111111111111111111111111111111111111111111',
            '1111111111111111111111111111111111111111111111111111111111111111111111111'
        ];
for(var ex in tests) console.log('Test '+ex+'\n'+tests[ex]+'\n'+f('Wawrinka','Djokovic',tests[ex]));

Test Outputs
Test 0

Wawrinka
Djokovic

Test 1
1
Wawrinka 0 - 15
Djokovic 0 -  0

Test 2
2
Wawrinka 0 -  0
Djokovic 0 - 15

Test 3
11
Wawrinka 0 - 30
Djokovic 0 -  0

Test 4
222
Wawrinka 0 -  0
Djokovic 0 - 40

Test 5
1111
Wawrinka 1
Djokovic 0

Test 6
2222
Wawrinka 0
Djokovic 1

Test 7
1112221
Wawrinka 0 - Ad
Djokovic 0 - 40

Test 8
11122212
Wawrinka 0 - 40
Djokovic 0 - 40 Deuce

Test 9
121212121
Wawrinka 0 - Ad
Djokovic 0 - 40

Test 10
1212121212
Wawrinka 0 - 40
Djokovic 0 - 40 Deuce (2)

Test 11
1211222122111122111
Wawrinka 1 - 40
Djokovic 1 - 30

Test 12
12112221221111221112
Wawrinka 1 - 40
Djokovic 1 - 40

Test 13
121122212211112211122
Wawrinka 1 - 40
Djokovic 1 - Ad

Test 14
1211222122111122111221
Wawrinka 1 - 40 Deuce
Djokovic 1 - 40

Test 15
1111222211112222111122221111222211112222111122221212121212121212121
Wawrinka 6 [10]
Djokovic 6 [ 9]

Test 16
11111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 5 - 40
Djokovic 0 0 0 -  0

Test 17
111111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 6
Djokovic 0 0 0
Wawrinka wins

Test 18
1111111111111111111111111111111111111111111111111111111111111111111111111
Wawrinka 6 6 6
Djokovic 0 0 0
Wawrinka wins

Javascript - 743 bytes
var b=process.argv[2],c=[0,0],e=[],g=[0,0],h=[0,0],k=["0","15","30","40"],l=["Wawrinka","Djokovic"];function m(a){var d="",f;for(f in e)d+=e[f][a]+" ";3<=c[0]||3<=c[1]||(d+=g[a]+" - ",f=h[a],a=h[(a+1)%2],d=n()?d+("["+f+"]"):3>f||3>a?d+k[f]:f>a?d+"Ad":d+k[3]);return d}function n(){return 6<=g[0]&&6<=g[1]}function p(){var a=q;g[a]++;h=[0,0];7<=g[a]?(e.push(g),g=[0,0],c[a]++):6<=g[a]&&g[a]>g[(a+1)%2]+1&&(e.push(g),g=[0,0],c[a]++)} for(var r in b){var q=parseInt(b[r])-1,s=++h[q];n()?7<=s&&(4>e.length?p():s>h[(q+1)%2]+1&&p()):4<=s&&s>h[(q+1)%2]+1&&p()}console.log(l[0]," ",m(0));console.log(l[1]," ",m(1),n()?"":2<h[0]&&2<h[1]&&h[0]==h[1]?"Deuce"+(3<h[0]?" ("+(h[0]-2)+")":""):"");console.log(3<=c[0]||3<=c[1]?(3<=c[0]?l[0]:l[1])+" wins":"");

Without closure compiler:
var input = process.argv[2];

var score = [0,0];
var match = [];
var set = [0,0];
var game = [0,0];
var gameScore = [ '0', '15', '30', '40' ];
var names = ['Wawrinka', 'Djokovic'];

function printScores(who)
{
    var out = '';
    for (var i in match) {
        out += match[i][who] + ' ';
    }

    if (!isDone()) {
        out += set[who] + ' - ';

        var point = game[who], otherPoint = game[(who+1)%2];

        if (isTieBreaker()) { // Tie breaker
            out += '['+point+']';
        } else {
            if (point < 3 || otherPoint < 3) {
                out += gameScore[point];
            } else if (point > otherPoint) {
                out += 'Ad';
            } else {
                out+= gameScore[3];
            }
        }
    }

    return out;
}

function printDeuce()
{
    if (isTieBreaker()) {
        return '';
    } else {
        return (game[0] > 2 && game[1] > 2 && game[0] == game[1]) ? ('Deuce' + (game[0] > 3 ? ' (' + (game[0] - 2) + ')' : '')) : '';
    }

}

function isDone()
{
    return score[0] >= 3 || score[1] >= 3;
}

function isTieBreaker()
{
    return set[0] >= 6 && set[1] >= 6;
}

function getOther(who)
{
    return (who + 1) % 2;
}

function addPoint(who)
{
    var points = ++game[who];

    if (isTieBreaker()) {
        if (points >= 7) {
            if (match.length < 4) {
                addGame(who);
            } else if (points > (game[getOther(who)]+ 1)) {
                addGame(who);
            }
        }
    } else {
        if (points >= 4 && points > (game[getOther(who)] + 1)) {
            addGame(who);
        }
    }
}

function addGame(who)
{
    set[who]++;
    game = [0,0];

    if (set[who] >= 7) { // Won Tiebreaker
        addSet(who);
    } else if (set[who] >= 6 && set[who] > (set[getOther(who)] + 1)) {
        addSet(who);
    }
}

function addSet(who)
{
    match.push(set);
    set = [0,0];
    score[who]++;
}

// Play game
for(var i in input) {
    addPoint(parseInt(input[i]) - 1);
}

console.log(names[0], ' ', printScores(0));
console.log(names[1], ' ', printScores(1), printDeuce());
console.log(isDone() ? ((score[0] >= 3 ? names[0] : names[1]) + ' wins') : '');