text:
Jolly Jumper Sequence
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1.
So the sequence [4,1,2,4] has absolute differences [3,1,2] which is equivalent to the set [1,2,3] (1 to n-1 where n is the length of original sequence) so it is therefore a jolly jumper.
Sequences have length n>0.
Assume n=1 is a jolly jumper.
Easy mode: Don't worry about stdin/stdout. Just a function that accepts arguments however and returns something that indicates jolly or not
Hard mode: Input on stdin (space separated), and output is "Jolly" / "Not jolly". Capitalization matters.
This is code golf.
EDIT: Sequences can contain negative integers and input on stdin is space separated.
$ jolly 2 -1 0 2
Jolly

$ jolly 19 22 24 25
Jolly

$ jolly 19 22 24 21
Not jolly

How is the sequence given?  As a string? "4124"?

I think space-separated would be the most common convention, so I'll say that.

You say input is on stdin, but your examples take input as command line arguments. Which should we expect?

Haskell
Easy 4 characters
Returns a list of jolly integers if and only if a list of jolly integers is given as input. This is legal based on "Just a function that accepts arguments however and returns something that indicates jolly or not".
j=id

Alternative easy solution with 61 characters:
Takes in a list and returns the empty list if the sequence is jolly.
import List
j n=zipWith(\x->abs.(x-))n(tail n)\\[1..length n]

+1 Good rules lawyering. Although I should point out that in GolfScript the empty program would suffice...

The alternative solution seems to give wrong result. [1,3] is not jolly, is it? I guess you must iterate to length n-1 instead.

Golfscript, easy mode, 21 18 chars
{.@-abs\}*;0]$.,,=

Accepts arguments as an array of ints on the stack, with nothing else on the stack; leaves 1 on the stack if it's jolly and 0 otherwise. To take input on stdin as a space-separated list of ints, prepend
~]

and to output "Jolly" / "Not jolly" (assuming that we're turning this into a program) postpend
"Not jJ"5/="olly"

I was wondering how this could possibly work -- it took me a moment to realize that when you write "a list of ints on the stack", you really do mean a list of ints (i.e. [4 1 2 4], not 4 1 2 4).

@IlmariKaronen, not sure now why I wrote "list". I've edited to "array" to make it clearer.

Scala, easy mode, 123 characters
def j(s:String)={var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
for(c<-1 to a.size)
if(!a.contains(c))false
true}

To run or test on ideone.com:
object Main
{
   def main(args:Array[String])
   {
      def j(s:String):Boolean=
      {
         var a=s.sliding(2,1).map(x=>math.abs(x(0)-x(1))).toList
         for(c<-1 to a.size)
            if(!a.contains(c)) false
         true
      }
      println(j("4124"))
   }
}

The name could be j instead of jump.

@user unknown Yes, I know. I realised about half an hour after I posted it that a) I could shorten the method name, and b) I need to use a List instead of a Set, or it won't work properly. :-S

And the updated rules expect the numbers to be divided by space, 4124 could be one, two, three or 4 numbers.

@user unknown Oh great. Another person posting a question and then changing the rules half way through.

I removed return type Boolean, a literal 'return' before `false' and changed Math to math. Saving from 137 to 123.

Ruby, 92 93 characters
The hard version with input on STDIN.
f=gets.split.each_cons(2).map{|a|eval(a*?-).abs}.sort
$><<(f==[*1..f.size]??J:"Not j")+"olly"

If you start it with -pa (counts as 4) you can save 5 chars:
f=$F.each_cons(2).map{|a|eval(a*?-).abs}.sort
$_=(f==[*1..f.size]??J:"Not j")+"olly"

Ah, nice improvement. Didn't realize there was an each_cons method.

I just realized that this fails when the sequence is a single digit. You'd have to stick with f.size instead f[-1].

Oh, you can also save 5 characters if you run it with options -pa .

Java (Hard)
Assumes that input is given through stdin. (not through command line arguments as per example)
Golfed - 325
class JollyJumper {
public static void main(String[] args) {
String[] in = new Scanner(System.in).nextLine().split(" ");
int[] j=new int[in.length-1],k=j.clone();
for(int i=0;i<in.length-1;i++){j[i]=Math.abs(Integer.parseInt(in[i])-Integer.parseInt(in[i+1]));k[i]=i+1;}
Arrays.sort(j);System.out.println(Arrays.equals(j, k)?"Jolly":"Not jolly");
}
}

Un-Golfed
public class JollyJumper {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int[] jolly;
    String[] in;

    in = sc.nextLine().split(" ");
    jolly = new int[in.length-1];

    for (int i = 0; i < in.length-1; i++)
        jolly[i] = Math.abs(Integer.parseInt(in[i]) - Integer.parseInt(in[i+1]));

    Arrays.sort(jolly);

    for (int i = 1; i <= in.length-1; i++) {
        if (jolly[i-1] != i) {
            System.out.println("Not jolly");
            return;
        }
    }
    System.out.println("Jolly");
}
}

J (easy), 18
(i.@#-:<:/:])|2-/\

   (i.@#-:<:/:])|2-/\2 _1 0 2
1
   (i.@#-:<:/:])|2-/\19 22 24 25
1
   (i.@#-:<:/:])|2-/\19 22 24 21
0

J (hard), 68
2!:55]1!:2&2'olly',~>('Not j';'J'){~(i.@#-:<:/:])|2-/\".@>2}.ARGV_j_

$ jconsole jumper.ijs 2 -1 0 2
Jolly
$ jconsole jumper.ijs 19 22 24 25
Jolly
$ jconsole jumper.ijs 2 19 22 24 21
Not jolly

Brachylog, 11 bytes (easy)
s₂ᶠ-ᵐȧᵐo~⟦₁

Try it online!
s₂ᶠ-ᵐ - Consecutive differences
ȧᵐ - Absolute values
o - Sort
~⟦₁ - Is the result the range 1 to something?

D
easy (103 83 chars)
returns sum of 1..i.length on Jolly some other number if not (a bit of rules laywering here)
import std.math;auto jolly(I)(I i){int t,l;foreach(r;i){t+=abs(l-r);l=r;}return t;}

hard (142 chars)
input is whitespace delimited and ends on EOF
import std.stdio;import std.math; void main(){int i,j,l,t;while(readf("%d ",&i)>0){t+=abs(l-i);l=i;j++;}write(t==j*++j/2?"J":"Not j","olly");}

J, 30 26 easy mode, 81 76 hard mode
edit: handle lists shorter than 3, fix stdin reading
First line takes care of easy mode, second adds hard mode.
j=:[:*/[:(>:@i.@#=/:~)[:|2-/\]
exit('olly',~[:>('Not j';'J'){~[:j 0".}:)&.stdin''

J reads generally right-to-left:
2-/\ : for every two successive numbers in the list, take the difference
| : absolute value
/:~ : sort in ascending order
>:@i.@# : 1 to n, for a list of n numbers
= : compare the sorted differences with the sequence (using a J "fork")
*/ : multiply all the element-wise booleans; if all the comparisons were 1, their product is 1, so it's jolly

Consider input 1 3.

Thanks, @Peter.  Fixed...and still not competitive with your Golfscript. Well done.

Scala easy:138  153, 170 (was errornous, improved later)
def j(i:String)={
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
a(a(i.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1}

ungolfed:
def jolly (input: String) = {
      val list = input.split (" ").map (_.toInt)

      def stepsize (s: Seq[Int]) =
        (s zip s.tail).map (x=> (x._2 - x._1))

      val first = stepsize (input.split (" ").map (_.toInt))
      val pos = first.map (math.abs)
      val unique = stepsize (pos.sorted).toSet
      (unique.size) == 1
}

The idea is, that we build the second derivation:
Original: 4 1 2 4
Stepsize:  -3 1 2 (first)
     abs:   3 1 2
  sorted:   1 2 3
Stepsize:     1 1
  to Set:       1
    size:       1

Scala hard 172  182,  205 (was errornous/improved):
def j{
def a(s:Seq[Int])=(s zip s.tail).map(x=>(x._2-x._1))
println((if(a(a(readLine.split(" ").map(_.toInt)).map(math.abs).sorted).toSet.size==1)"J"else"Not j")+"olly")}
j

more or less the same as above.

Input 4 1 2 5 returns true. Still haven't managed to get my head around that left fold though...

Oh yes, I found my error. Need to correct it.

readLine takes input from the console, not the stdin... (but you can use args instead)

And j("1") throws UnsupportedOperationException: empty.max

Pardon - how do you define the difference between stdin and "input from the console"?

What I meant was, if you run your script with scala jolly.scala 19 22 24 25 then it won't work, but I suppose you could pipe it in from a file with scala jolly.scala < numbers.txt and readLine would work. In any case your hard version doesn't work as given above - try pasting in REPL

echo "19 22 24 25" | scala -i jolly.scala is the readline-approach. scala jolly.scala 19 22 24 25 is 'using parameters' or 'arguments'. The version didn't work; maybe it was a transfer error. For "1", it is still buggy.

You are right regarding readLine; I was looking at the example in the OP, which is contradictory

That might be right for the Easy mode: Don't worry about stdin/stdout. only, yes.

Ruby, 97 102 106 (hard)
Might as well, since everyone else is:
h,*t=gets.split
d=t.map{|i|h,i=i,h;eval(i+?-+h).abs}.sort
$><<(d==[*1..d.size]??J:"Not j")+"olly"

Input taken on stdin.

You can replace (1..d.size).to_a by [*1..d.size]. Switching operands is now possible, saves another one (total -5 chars).

@Howard Oh, so that's how you do it! I've been trying to figure out a golf way to convert ranges to arrays for a while now. Thanks!

Groovy
Easy: 78
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()}

assert [[2, -1, 0, 2,], [19, 22, 24, 25], [19, 22, 24, 21]].collect { j(it) } == [true, true, false]

Hard: 151
j={m=[];it[1..-1].inject(it[0]){p,n->m<<p-n;n};m*.abs().sort()==1..<it.size()};System.in.eachLine{println "${j(it.split()*.toLong())?'J':'Not j'}olly"}

PowerShell, hard, 117 126
('Not j','J')["$(($a=-split$input)|%{if($x-ne$0){[math]::abs($x-$_)}$x=$_}|sort)"-eq"$(1..($a.Count-1)|sort)"]+'olly'

History:

2011-11-18 17:54 (123, −3) – Changed $null to a non-existent variable
2011-11-18 18:02 (117, −6) – inlined all variable declarations

Scala
A quick stab - there are probably improvements possible.
Easy: 77
def j(? :Int*)=(?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1)

Hard: 124
val? =args.map(_.toInt)toSeq;print(if((?tail,?).zipped.map(_-_).map(math.abs).sorted==(1 to?.size-1))"Jolly"else"Not jolly")

Ok - we're lost, Luigi found us! :) Welcome on CodeGolf. Immediately I start learning something. Question mark as identifier? Whooo - who allowed that? :)

Yes, and all to shave 1 character off! It's the difference between an alphanumeric characters and operator characters (see http://stackoverflow.com/q/7656937/770361) which means you can sometimes omit spaces (but sometimes need extra ones) and dots. Code golf is great for learning though - a bit like aerobatics for flying.

Q, 64 (hard), 30 (easy)
hard
{$[(1_(!)(#)x)~asc abs 1_(-':)x;(-1"Jolly";);(-1"Not jolly";)];}

easy
{(1_(!)(#)x)~asc abs 1_(-':)x}

J (easy), 19 characters
*/(=i.@#)<:/:~|2-/\

Usage:
    */(=i.@#)<:/:~|2-/\4 2 1 4
1

Vary similar to DCharness's answer, and I would have just added it as a comment but for the fact that he hasn't visited since the 23rd of February.
2-/\ takes the difference between successive pairs of numbers,
| gets the absolute value of each number,
/:~ sorts into ascending order,
<: decrements each number by 1,
(=i.@#) a J hook which generates the sequence of numbers from 0 to the length of the differences list - 1 (i.@#) and compares it with that list =.
*/ multiples the list of 1s and 0s generated by the previous verb.

Didn't realize until after I submitted my answer: we took the same approach, but I used x-:y instead of */x=y to save a character.

PHP, easy, 129
For a given array $s of integers:
for($i=1;$i<count($s);$i++)$a[abs($s[$i]-$s[$i-1])]=1;
for($i=1;$i<count($s);$i++)if(!isset($a[$i]))die('Not Jolly');echo 'Jolly';

The ungolfed version:
for( $i=1; $i<count( $s ); $i++ )
    $a[ abs( $s[$i] - $s[$i-1] ) ] = 1;

for( $i=1; $i < count($s); $i++ )
    if( !isset( $a[$i] ) )
        die( 'Not Jolly' );

echo "Jolly";

Jelly, 7 6 bytes (easy)
IAṢ⁼J$

Try it online!
IAṢ⁼J$    jolly function on N:
IAṢ       the increment list: get all the Increments, take their Absolute values, and Ṣort them
   ⁼      compare that to...
    J$    range from 1 to len(N) -- this has an extra number, but that's fine because...
          ...the increment list is one shorter, and ⁼ will only compare that many values

Takes input as comma-separated numbers in the first argument. Returns 1 if the sequence is jolly, and 0 if it isn't!
7-byte solution:
LRṖḟIA$

Try it online!
Takes input as comma-separated numbers in the first argument. Returns nothing if the list is a jolly jumper sequence, and something if it isn't.
Adding this line makes it work with the hard spec:
Jelly, 27 22 bytes (hard, feedback welcome!)
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»

Try it online!
ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»
ɠḲV                     read a line, split on spaces and eValuate the numbers
   IAṢ⁼J$               jolly function: see above!
         ị              ịndex the result into (remember Jelly is one-indexed, so 0 wraps around to the back):
          “¢⁼D“          "Jolly" compressed if true,
              ¡KṀȥƘạ»   or, "Not jolly" compressed if false!

27-byte (hard) solution:
LRṖḟIA$
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L?

Try it online!
Takes space-separated numbers on stdin, and outputs "Jolly" or "Not jolly".
Explanation:
LRṖḟIA$               jolly function:
LRP                   make a range (R) from 1 to the input length (L), popping off (P) the last number to make it 1 to N-1.
   ḟ                  reverse filter: remove all the elements from that range that are members of...
    IA$               the increment list: get all the increments, take their absolute values (expressed as one monad via '$').
ɠḲVÇ“¡KṀȥƘạ»“¢⁼D»L?    i/o main function:
ɠḲV                   read a line from stdin, split it on spaces and have Python parse each number (handling negative signs)
   Ç             ?    run the above, and use the result on the following conditional:
                L?    if the length of the result is truthy (non-empty):
    “¡KṀȥƘạ»          then, return Jelly compressed string "Not jolly",
            “¢⁼D»     else, return Jelly compressed string "Jolly".

Any feedback much appreciated!

LR is J. If you write something like IAṢ⁼J$ you get a nice 1/0 result, and you can use that to index into “Not jolly“Jolly”: ɠḲVIAṢ⁼J$ị“¢⁼D“¡KṀȥƘạ»

@Lynn Thank you, that's much better! Clever trick with the one-indexed wrapping around, and I learned more about the ⁼ atom too, handy to compare just parts of lists.

Haskell, 59 57 bytes
f n=all(`elem`map abs(zipWith(-)n$tail n))[1..length n-1]

Easy mode, returns jollyness as a boolean. Thanks to @Laikoni for two bytes.
Try it online!

Japt, 32 30 bytes Hard
-2 Bytes from @Shaggy
`not jo¥y`s4*Näa n äa e¥1
hUÎu

Try it online!

30 bytes. I only noticed the capitalisation requirement at the last second so can probably be improved further.

Python 3, 117 (hard)
l=[*map(int,input().split())]
print(["Not j","J"][{abs(a-b)for a,b in zip(l[1:],l[:-1])}=={*range(1,len(l))}]+"olly")

Try it online!

There is an error in your program. Try it online

This gives the wrong answer for the first test case. Please check your program for the test cases contained in the question.

Feel ashamed, cause when fixed wrong version forgot to reverse outputs ;(

Welcome to PPCG!!

JavaScript: 105 (easy mode)
Golfed:
function a(l){for(r=i=1;i<(m=l.length);i++){for(j=t=0;j+1<m;)t+=(d=l[j]-l[++j])*d==i*i;t||(r=0)}return r}

Un-golfed:
function isJolly(list){
    //Iterate over i to list.length-1
    for(r=i=1;i<(length=list.length);i++){
        //Check the differences between all consecutive elements squared minus i squared.  Set t to true if one was found.
        for(j=t=0;j+1<length;)t+=(diff=list[j]-list[++j])*diff==i*i;

        //if t is not true, return value is 0
        t||(r=0)
    }
    return r
}

Perl, 89 (hard)
86 characters of code + 3 for running with the -p option
@a=0;$a[abs($1-$2)]=1while s/(\S+) (\S+)/$2/;$_='Jolly';(grep{!defined}@a)&&s/J/Not j/

Javascript (hard): 138
a=prompt().split(" ")
i=0;b=[];c=[]
while(b[i]=Math.abs(a[i]-a[++i]),c[i-1]=i,i<a.length-1);b.sort()
alert(b+""==c+""?"Jolly":"Not jolly")

Python, 255 characters
r=[19,22,24,25]
i=0
k=[ i+1 for i in range(len(r)-1)]
def jolly(a):
    p=[]
    i=0
    while i<len(a)-1:
       p.append(abs(a[i+1]-a[i]))
       i+=1
    p.sort()
    if p==k:
       return 'jolly'
    else:
       return 'Not jolly'

print(jolly(r))

I've added the language name and character count to your answer (it runs as Python so that's what I assume it is). The character count I've given is the one give by the userscript. You could probably cut down the first indentation level to one space to save some characters here.

R, Easy, 110
f=function(s){p=NULL;l=length;for (i in 2:l(s))p=c(p,abs(s[i]-s[i-1]));ifelse(all(sort(p)==(1:(l(s)-1))),1,0)}

Usage:
f(c(2, -1, 0, 2))
[1] 1
f(c(19, 22, 24, 25))
[1] 1
f(c(19, 22, 24, 21))
[1] 0

Python, 72 (easy), 114 (hard)
Easy:
def f(a):return len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2

Hard:
a=map(int,raw_input().split())
print('Not j','J')[len(set(map(lambda x,y:abs(x-y),a[1:],a[:-1])))>len(a)-2]+'olly'

C, 119(hard), 97(easy)
b,c,a[];main(k){while(~scanf("%d",a+c))k=c++;for(c=k;b<c*c;)k-abs(a[b%c]-a[b++%c+1])?:k--;puts(k?"Not jolly":"Jolly");}

The easy solution reads the input from the arguments and returns a 0 as exit code if the input is a jolly jumper sequence:
i,k;main(int c,char**a){for(k=c-=2,a++;i<c*c;)k-abs(atoi(a[i%c])-atoi(a[i++%c+1]))?:k--;exit(k);}

APL (50 49 47, hard)
'Not jolly' 'Jolly'[1+K[⍋K←¯1↓|Z-1⌽Z]≡¯1↓⍳⍴Z←⎕]

Easy (24):
{K[⍋K←¯1↓|⍵-1⌽⍵]≡¯1↓⍳⍴⍵}

The function takes an array and returns 0 or 1.

Japt, 11 10 bytes
Êo1 eUäa n

Run it online
Saved 1 byte thanks to Shaggy

10 bytes

authors: Андрей Ломакин

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


text:
Exploit "free whitespace"
Suppose a codegolf challenge doesn't count whitespace in the length of your program.  Cheat this system by encoding your script into whitespace, and golf a script which decodes and executes embedded whitespace.
Example
My solution to JBernardo's Meta Golf Challenge was to encode Sage (or Python) code into whitespace, and golf the decoder.
s = ' '
for c in '<lots of whitespace>'.split(s):
    s+=chr(len(c))
exec s

The encoding is to take a script, prepend a newline, and for each character c in the script, output ord(c) tabs followed by a space.  Prepending a newline is necessary since I'm using Python and I start the script s with a space.
Scoring
A complete solution contains a description of the encoding you use (if it's complicated, provide a script), and a 'decode-and-execute' script.  Your score is the number of non-whitespace characters in the decode-and-execute script.
Whitespace (the language) is forbidden
Moreover, any language which has a complete set of operators which only use whitespace characters is not allowed: I'll accept the lowest nonzero score.

Golfscript, 12 chars
String delimited by ' goes before these 10 chars:
n/{,}%''+~

Each line is decoded into one character, whose ASCII (probably Unicode, in fact) value is the length of the line.
Unfortunately if I try pasting my Hello World example, Markdown removes the extra spaces, even in a <pre> block.

Since whitespace at the beginning of a program is always non-functional, .n/{,}%+~ would work as well.

CPAN, 16
use Acme::Bleach;

CPAN has it all.  Or at least, just the right module.

I call cheat on this, that is a complete set of operators that is nothing but whitespace

This is not a cheat.  It's cheap, but acceptable.

This program does nothing. None of the WS is there. BOOOOOO!!!! Please repost this with a program that does something useful here. Keep the Acme::Bleach use, but take advantage of it.

@trinithis: as do none of the other programs presented here. Why pick specifically on this one?

I noticed it and it stands out as a what does this do, it only looks like it imports.

Well, surprisingly enough, that's all that's needed.

This was actually the first thing I thought of when I saw this challenge.  I argue it isn't cheating because, it DOES have non-whitespace characters and, the entire spirit of the challenge is to encode everything but a decoder stub.  This decoder stub just happens to have been built several decades ago ;-)

Perl, 29
$_="";s/     */chr length $&/ge;eval

Inside that s/// are a tab then a space.  The encoding is an ultra-basic encode with spaces, precede with tabs.
Try this one on the command line:
$ tr ST ' \t' <<< '$_="TSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; s/TS*/chr length $&/ge; eval' | perl

Edit: well, lol, I can't find a proper way to copy-paste the tab/space mix.  Believe me, it works at home :)
Update: there, there, encoded with tr

you can put tabs in with \t and we'll believe it works with whitespace...

@boothby: oh, better than that, I can have the \t interpreted by the shell and actually have the damn thing work demonstrably.  Doing that in a few hours.

JavaScript
Replace \t with a tab to get the posted character count.
Standard (64 characters)
eval(eval("'<code here>'".replace(/\t */g,function(s){return"\\"+s.length})))

Arrow function (49 characters)
eval(eval("'<code here>'".replace(/\t */g,(s)=>"\\"+s.length)))

Encoder program for both
for(var i = 0, si = prompt("Enter the code."), so = ""; i < si.length; ++i) so += '\t' + Array(+si.charCodeAt(i).toString(8)).join(' '); prompt("Here is the result.", so);

Replace (s)=>... in the arrow function to s=>... to save two bytes

Keep spaces between any two char and at worst use jsfuck to make it work(and better use " t " [ 1 ] to mean "t")

44B eval("".replace(/ +/g,s=>' []+!()'[s.length]))

C (99 characters)
main(c, p)
{
    char *s = "<code here>";
    for (p = popen("cc -xc -oa -", "w"); *s;)
        *s++ - 9 ? c -= putc(c, p) : ++c;
    execl("a", pclose(p));
}

Tested only with (and perhaps only works with) GCC.
Corresponding encoder program (manually remove the first character from its output):
#include <stdio.h>

int main()
{
    int c;
    while ((c = getchar()) != EOF) {
        while (c--) putchar(9);
        putchar(32);
    }
    return 0;
}

Yabasic (88 characters)
a$ = "<code here>"
for a = 1 to len(a$)
    if mid$(a$, a) < " " then b = b + 1
    else b$ = b$ + chr$(b) : b = 0
    endif
next
compile(b$)
a()

Use the same encoder program as for my C solution, but do not remove the first character. Your original code must be in the form of a subroutine a(), for example:
sub a():?"hello, world":end sub

D (101 chars)
import std.algorithm;mixin((){char[]r;foreach(c;splitter("<lots of whitspace>"," "))r~=cast(char)c.length;return r;}());

same encoding as in the question (no need for the newline)

The point of this is that whitespace is free.  I count 98 characters.  Feel free to write readable code!

Bash (builtins only, 44 characters)
IFS=
eval `while read a
do printf '\'${#a}
done<<a
<code here>
a`

Corresponding encoder script:
od -b | cut -b9- | tr ' ' '\n' | while read a
do
    for (( b = 0; b < $((10#$a)); ++b ))
    do
        echo -n ' '
    done
    echo
done

Very nice.  I consider myself a bit of a Bash hacker, and I had to man up a bit to grok this.

K5, 12 bytes
.`c$-':&9=" "

Execute (.) the string formed from the ascii values (`c$) given by the difference between each pair (-':) of the indices where (&) the input is a tab (9=" ").
Input is a string of tab- and non-tab characters, and the character values are encoded in the number of non-tabs (spaces or newlines) between each tab. An example encoder:
" ",/{(x#" "),"\t"}'-1+

Perform a running join beginning with a space over (" ",/) x spaces (x#" ") joined with a tab (,"\t") where X is each of ({...}') one minus the character values of the input string (-1+).
In action:
  enc: " ",/{(x#" "),"\t"}'-1+
  dec: .`c$-':&9=

  enc "2+3"
"                                                  \t                                          \t                                                  \t"
  dec enc "2+3"
5

Ruby, 43
Very straightforward, encoding is putting x spaces per line, where x is the ascii value of the char, decoding is reverse.
The following script is just a unary to ASCII converter and works even when things other than spaces are free:
eval("".split("\n").map{|x|x.length.chr}.join)

Just replace the empty string with the program that pleases you.
The thing in a more reusable format:
from_space = lambda {|text| text.split("\n").map{|x| x.length.chr}.join}
to_space = lambda {|text| text.chars.map{|x| " " * x.ord}.join("\n")}

p from_space [ to_space [ "abc" ] ] #=> "abc"

source: Stack Exchange

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

sort: votes


text:
Flag Semaphore Encoder
Your goal is to write a flag semaphore encoder, which will convert a given sentence into the corresponding flag semaphore characters, according to the semaphore system described on Wikipedia.
Assume that the input is a single sentence provided through stdin (or equivalent). Your output should be a series of semaphore characters, with each row representing one word from the sentence. You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters, but you must be able to handle both uppercase and lowercase. Your output is allowed to contain extra whitespace.
Semaphore characters must be displayed as a 3x3 square, with an O in the middle and the flag positions represented by the characters | - / \. Each semaphore character must be separated from adjacent characters by a space, and each row must be separated by a blank line. Don't worry about wrapping for words that may be too long for your display - pretend that your lines have infinite length.
Sample input:
abcdefg hijklmn opqrstu vwxyz

Sample output:
        \    |    /
 O  -O   O   O   O   O-  O
/|   |   |   |   |   |   |\

    \    |   |    /
-O   O   O-  O   O   O-  O
/   /       /   /   /   / \

\    |    /         \|  \ /
-O  -O  -O  -O- -O   O   O
                  \

 |    /   / \
 O   O-  O   O-  O-
  \       \       \

Sample input:
This is Code Golf.

Sample output:
\|      \
 O  -O   O  -O
    /   /     \

\
 O  -O
/     \

\   \    |    /
 O  -O   O   O
 |       |   |

    \     /
 O  -O   O   O-
 |\     /    |

Since this is code-golf, the shortest solution wins.

[tag:kolmogorov-complexity]? It seems to me that fundamentally this is about compressing a lookup table.

@Peter Taylor Yeah, it's probably a good idea to add that tag. Thanks.

and each row must be separated by a blank line => each word is meant, isn't it?

Before I read this puzzle, I mistakenly thought it had to do with semaphores in the programming sense. ¡Jajajajajja!

@user unknown I was using row there to refer to a row of semaphore characters. Perhaps using word instead would have been a better choice.

I was confused by pretend that your lines have infinite length. So we put an empty line between every two words - the inifinte linelength is only relevant for word length.

@user unknown Yes, that's correct.

When you say ignore non [a-zA-Z] characters, do you mean the program does not need to handle them, or the program should filter them out?

It doesn't need to handle them, meaning that there shouldn't be any output. I realize it's not clear from the examples, since only the This is Code Golf. one has a non-alpha character, and it's at the end of the word. Ideally it should skip them, but since I wasn't specific, it's also okay to leave an empty placeholder like Howard's solution does.

Perl, 282 264 251 247 245 243 241 240 236 233 229 227 220 218 216 214 characters
$_=lc<>;map{y/a-z//cd;y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;@a=($/)x4;map{$s=ord;$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;$_.=" "for@a}split//;print@a}split

With some prettifying line breaks:
$_=lc<>;
map{
y/a-z//cd;
y/a-z/`HABDP\xc0(!\x12"$0\xa0\t\n\f\30\x88\3\5\x82\24\x84\21\x90/;
@a=($/)x4;
map{
$s=ord;
$a[$_/3].=substr" \\|/-O-/|\\",$_==4||$s>>$_-($_>4)&1?$_+1:0,1for 0..8;
$_.=" "for@a
}split//;
print@a}split

It's taken me a while to get this working (my first attempt at a Perl answer). It's based on a similar idea to a lot of the other answers. Each flag can be in one of 8 positions, there are two flags, and the two flags can't ever be in the same position. This means I can encode the position of both flags in one byte - which also means I can translate directly from a character to its encoding using Perl's y/// function (operator?). So:-
a = 01100000 96 = `
b = 01001000 72 = H
c = 01000001 65 = A
d = 01000010 66 = B
e = 01000100 68 = D
f = 01010000 80 = P
etc...

Therefore:
y/a-z/`HABDP..../;

I've escaped a fair few of the characters which are outside the normal used range to make the copying and pasting of the program easy - but I'm fairly sure I could write a program to replace the escape codes with the characters themselves saving me roughly 30 characters.

Python, 244 238 233 232
e='abhioptuwycdjmnsqxzfgvklebr'
for w in raw_input().split():
 for i in 0,3,6,9:print' '.join(''.join((' '+'\|/-O-/|\ '[j])[`j`in'4'+'6736031025071568328578162735'[e.find(c):][:2]]for j in range(i,9)[:3])for c in w if c.lower()in e)

This uses a favorite trick of mine: single-track encoding.  I've labeled the semaphore bits (sbits)
\|/     012
- -  -> 3 5
/|\     678

to obtain the following chart of which sbits occur for which letter:
0: ciotuy
1: djkptv
2: elquwx
3: bhopqrs
5: fjmrwyz
6: ahiklmn
7: abcdefg
8: gnsvxz

each letter occurs exactly twice in the chart, since the signalman has two arms.  Then, I view this as a graph on the letters a-z, with edges between letters sharing sbits, with the edges labeled according to the shared sbit.  Ideally, I'd find a Hamilton path through this graph, such that subsequent edges don't have the same label.  No such paths exist... so you'll note that the variable e contains the letter b twice.
With my nearly-Hamilton path e, I construct an array d of sbit labels used in the traversal of e.  Then, to figure out where to put her arms, the signalman need only find the desired letter in the following handy chart
abhioptuwycdjmnsqxzfgvklebr
6736031025071568328578162735

whence her arms go in the position directly below, and below&right of the letter.

I couldn't get this to run on ideone until I changed to_lower() to lower(). Also, it gave an error when I tried giving it non-alphabetic input.

Scala, 272 characters
println(readLine.filter(c=>c.isLetter||c==' ').toLowerCase.split(" ").map{_.map(q=>("    O    "/:("^@a,6Tr?W*+5Sq9(2Pn%/-47MU"(q-'a')-27+""))((g,x)=>g.updated(x-'0',"\\|/-O-/|\\"(x-'0'))).grouped(3).toList).transpose.map(_.mkString(" ")).mkString("\n")}.mkString("\n\n"))

Ungolfed (well, less-golfed):
println(
  readLine.filter(c => c.isLetter || c==' ').
  toLowerCase.
  split(" ").
  map{ s =>
    val lookup = "^@a,6Tr?W*+5Sq9(2Pn%/-47MU".map(c => (c-27).toString)
    s.map(q =>
      ("    O    " /: lookup(q-'a')){(g,x) =>
        g.updated(x-'0', "\\|/-O-/|\\"(x-'0'))
      }.grouped(3).toList
    ).transpose.map(_.mkString(" ")).mkString("\n")
  }.mkString("\n\n")
)

Ruby, 287 characters
gets.split.map{|w|puts (0..2).map{|l|w.chars.map{|c|(' '*576+'CAEAEADBCAF DAEBDACAAAI EAFADACAABG BAEAFEL A_ FACABADADAAG AAFBADQ AGX GAFADABAAAAF'.split.zip('\\|/-o-/|\\'.chars).map{|a,c|(a.chars.zip([' ',c]*9).map{|x,z|[z]*(x.ord-64)}.flatten)}.transpose*''*2)[c.ord*9+3*l,3]}*' '},''}

Input must be given on STDIN.

Scala 494 without newlines  520 with newlines:
def k(i:Int,d:Int=0):(Int,Int)=if(i<(7-d))(d,i+1)else k(i-(7-d),d+1)
def t(i:Char)=(if(i=='y')i-4 else
if(i=='z')i+2 else
if(i=='j')i+14 else
if(i>='v')i+3 else
if(i>'i')i-1 else i)-'a'
def q(p:(Int,Int),i:Int,c:Char)=if(p._1==i||p._1+p._2==i)""+c else" "
def g(r:Int,c:Char)={val p=k(t(c.toLower))
print((r match{case 1=>q(p,3,'\\')+q(p,4,'|')+q(p,5,'/')
case 2=>q(p,2,'-')+"o"+q(p,6,'-')
case 3=>q(p,1,'/')+q(p,0,'|')+q(p,7,'\\')})+" ")}
for(w<-readLine.split(" ")){println;for(r<-(1 to 3)){w.map(c=>g(r,c));println}}

ungolfed:
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
  if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}

def toIdx (i: Char) = {
 (if (i == 'y') i - 4  else
  if (i == 'z') i + 2  else
  if (i == 'j') i + 14 else
  if (i >= 'v') i + 3 else
  if (i > 'i') i - 1 else i ) - 'a'}

def p2c (pair: (Int, Int), i: Int, c: Char) = {
 if (pair._1 == i || pair._1 + pair._2 == i) ""+c else " "
}

def printGrid (row: Int, c: Char) = {
  val idx = toIdx (c.toLower)
  val pair = toClock (idx)
  row match {
    case 1 => { print(
      p2c (pair, 3, '\\') +
      p2c (pair, 4, '|') +
      p2c (pair, 5, '/') + " ")
    }
    case 2 => { print(
      p2c (pair, 2, '-') + "o" +
      p2c (pair, 6, '-') + " ")
    }
    case 3 => { print(
      p2c (pair, 1, '/') +
      p2c (pair, 0, '|') +
      p2c (pair, 7, '\\') + " ")
    }
  }
}

val worte = "This is Code Golf"
(1 to 3).map (row => {worte.map (c => printGrid (row, c));println})

Explanation:
I observed a clock-pattern, but not with 12 hours, but 8. And Starttime is 0 is, where 6 o'clock is, and a, b, c are the first codes, with the first (one) flag on South.
Since flag 1 and 2 are indistinguishable, we can sort all combinations with the lower number for the first flag first. Unfortunately, the fine order from the beginning is disturbed, when j doesn't follow i, but k, l, m, and later it get's a mess.
Therefore I rearrange my keys for the mapping:
val iis = is.map {i =>
  if (i == 'y') i - 4  else
  if (i == 'z') i + 2  else
  if (i == 'j') i + 14 else
  if (i >= 'v') i + 3 else
  if (i > 'i') i - 1 else i }.map (_ - 'a')

iis.zipWithIndex .sortBy (_._1) .map (p => (p._1, ('a' + p._2).toChar))

Vector((97,a), (98, b), (99, c), (100,d), (101,e), (102,f), (103,g),
      (104,h), (105,i), (106,k), (107,l), (108,m), (109,n),
      (110,o), (111,p), (112,q), (113,r), (114,s),
      (115,t), (116,u), (117,y), -------
      -------  (120,j), (121,v),
      (122,w), (123,x),
      (124,z))

If we substract 'a' from every character, we get the numbers from (0 to 7+6+5+...+1). We can map the numbers of a character-grid
3 4 5   \ | /            |
2   6   - o -    - o   - o
1 0 7   / | \    (2, ) (2,2)

A pair of two numbers can map two flags, where the first number is the index of 0 to 6 for the first flag, and the second flag isn't a number from 1 to 7 for the second flag, but for the distance from the first to the second flag. (2,2) would mean, the first flag is to WEST, and the second is two steps clockwise from there, to the NORTH.
def toClock (i: Int, depth: Int=0) : (Int, Int) = {
  if (i < (7 - depth)) (depth, i+1) else toClock (i - (7-depth), depth + 1)}

Vector( (0,1), (0,2), (0,3), (0,4), (0,5), (0,6), (0,7),
    (1,1), (1,2), (1,3), (1,4), (1,5), (1,6),
    (2,1), (2,2), (2,3), (2,4), (2,5),
    (3,1), (3,2), (3,3),
           (4,2), (4,3),
    (5,1), (5,2),
    (6,1))

I don't know much about Scala. Is there a way I can test this on ideone? I tried wrapping it in an object Main extends Application block, but that doesn't seem to be enough.

IDEONE needs a class named Main, if I remember correctly, a main method, should maybe extend App (for scala-2.9, instead of Application (-2.8)) - and does it read from stdin? In simplyscala you may test code more simply. If you replace readLine in the last line with "readLine" it should work (the code is 2.8 compatible).

Thanks! I didn't know about simplyscala, that makes things much easier.

If you need the link again: I inserted the link somewhere in the meta already, where such things are collected.

Does this handle uppercase?

I've tested it and it does handle uppercase (toLower is called). However, it prints out a rest character for non-alpha input instead of ignoring it.

The question says: You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters. Shall I ignore non-alphabet characters or my program? I ignored all non-space characters. You should rephrase the question.

The example for This is Code Golf. already shows that nothing should be displayed for a non-alphabet character. Your output doesn't match the example.

And how do I know, that the example is more autorative than the problem description? I didn't recognize the trailing dot. I can adapt my program to a better description of the problem, which you should provide first.

Haskell 331 357 339 characters
Golfed:
import Data.Char
t[x,y]=q[x,mod(y+1)8]
q z@[x,y]|x==y=[x+1,y+2]|0<1=z
x%y=[x,y]
c 65=0%1
c 74=6%4
c 75=1%4
c 79=2%3
c 84=3%4
c 86=4%7
c 87=5%6
c 89=3%6
c 90=6%7
c x=t$c$pred x
_!9='O'
c!n|n`elem`c="|/-\\"!!mod n 4|0<1=' '
s x=do n<-[3:4%5,2:9%6,1:0%7];'\n':do c<-x;' ':map(c!)n
main=putStr.s.map(c.ord.toUpper)=<<getLine

Ungolfed:
type Clock = [Int]

tick :: Clock -> Clock
tick [h, m] = tick' [h, mod (m + 1) 8]

tick' :: Clock -> Clock
tick' [h, m]
  | h == m = [h + 1, m + 2]
  | otherwise = [h, m]

clock :: Char -> Clock
clock 'a' = [0,1]
clock 'j' = [6,4]
clock 'k' = [1,4]
clock 'o' = [2,3]
clock 't' = [3,4]
clock 'v' = [4,7]
clock 'w' = [5,6]
clock 'y' = [3,6]
clock 'z' = [6,7]
clock c = tick $ clock $ pred c

arm :: Int -> Char
arm 0 = '|'
arm 1 = '/'
arm 2 = '-'
arm 3 = '\\'

drawAt :: Clock -> Int -> Char
drawAt _ 9 = 'O'
drawAt c n = if n `elem` c
  then arm $ n `mod` 4
  else ' '

-- showClock is not in golfed code. Just there for debugging.
showClock :: Clock -> String
showClock c = unlines $ map (map $ drawAt c) [
    [3,4,5]
  , [2,9,6]
  , [1,0,7]
  ]

showClocks :: [Clock] -> String
showClocks cs = unlines $ map (showClocks' cs) [[3,4,5],[2,9,6],[1,0,7]]

showClocks' :: [Clock] -> [Int] -> String
showClocks' cs ns = cs >>= \c -> ' ' : map (drawAt c)

mainx :: IO ()
mainx = putStr . showClocks . map clock =<< getLine

345    \|/                                     \
2 6 == -O-          -O          tick  -O   ==   O      tick   O   ==  -O
107    /|\          /                 /        /              |\      /
             [1,2] or [2,1]    tick [1,2] == [1,3]     tick [0,7] == [1,2]

Encoding is [hour, minute] where clocks have 8 hours and 8 minutes. Minutes move faster than hours. If a clock ticks where the hour and minute would be equal, add 1 to the hour and 2 to the minute as well (see second tick example above). That is the only way hours increase. Hours do NOT increase when the minute reaches some arbitrary minute. Only when minutes would equal hours. In the ungolfed code, clock turns letters into clocks that represent the semaphore. Most clocks are built based on ticking from previous ones. The rest are hard coded. There's nothing really more to the code.

Perl, 356, 275 chars
Great number of chars was saved by replacing 'if else' to '? :' construction.
@_=split('', $ARGV[0]);for (@_){print eval{/[ciotuy]/ ?'\\':' '}.eval{/[djkptv]/ ?'|':' '}.eval{/[elquwx]/ ?'/':' '}."\n".eval{/[bhopqrs]/ ?'-':' '}."0".eval{/[fjmrwyz]/ ?'-':' '}."\n".eval{/[ahiklmn]/ ?'/':' '}.eval{/[abcdefg ]/ ?'|':' '}.eval{/[gnsvxz]/ ?'\\':' '."\n"};}

Your code only seems to work for lower case letters. If you use <> instead of $ARGV[0] you can take input from stdin and use lc to convert all characters to lower case. This has the added benefit of saving you 4 characters. It doesn't handle non-alphabet characters either, but arguably You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters isn't very clear on what to do with them...

I'm not able to test the code right now, but it looks like the code just prints spaces for non-alpha characters, which is fine.

@migimaru I`ll try to correct it.

@zura Printing spaces for non-alphabet characters is acceptable. You don't need to fix that.

PowerShell, 198 192 191 188 bytes
-split$args|%{$s=$_
"\|/ ciotuy djkptv elquwx","-O- bho-s ^ fjmrwyz","/|\ ahik-n a-g gnsvxz"|%{$f,$p=-split$_
($s|% t*y|%{$c=$_
-join(&{$p|%{" $f"[++$i*($c-match"[$_ ]")]}})})-join' '}
''}

Try it online!
The output contains one tail empty line.
Less golfed:
-split$args|%{
    $string=$_
    "\|/ ciotuy djkptv elquwx",
    "-O- bho-s ^ fjmrwyz",
    "/|\ ahik-n a-g gnsvxz"|%{
        $flags,$patterns=-split$_
        $row=$string|% toCharArray|%{
            $char=$_
            $semaphoreRow=&{   # call the scriptblock in a new scope to reinit $i
                $patterns|%{
                    " $flags"[++$i*($char-match"[$_ ]")]  # return a flag symbol
                }
            }
            -join($semaphoreRow)
        }
        $row-join' '
    }
    ''
}

Charcoal, 70 bytes
Ｆ⪪↧Ｓ «Ｆι«Ｆ⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ＆$↥x-#↖x9｜²λＰe⁸” «Ｐ⊗№λκ↷¹»oＭ³→»⸿Ｍ³↓

Try it online! Link is to verbose version of code. Explanation:
Ｆ⪪↧Ｓ «

Split the lowercased input on spaces and loop over each word.
Ｆι«

Loop over each character.
Ｆ⪪”↶↖→∧gτ→|⮌!⧴KD✂‖5»⊞H⭆K↧ⅉ＆$↥x-#↖x9｜²λＰe⁸” «

Split the compressed string fjmrwyz gnsvxz abcdefg ahiklmn bhopqrs ciotuy djkptv elquwx on spaces and loop over each letter group.
Ｐ⊗№λκ

If the group contains the current letter then draw a line in the current direction.
↷¹»

Rotate 45° clockwise.
oＭ³→»

Output the centre o and move to the position of the next letter.
⸿Ｍ³↓

Move to the start of the next word.

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


text:
Write a code golfer
Your job, should you choose to not refuse it, is to write a program that will "golf" a piece of given code in your language of choice.
Basic functionality:

Remove extraneous whitespace
Remove comments

'Advanced' functionality:

Combine declarations (int x; int y; int z; to int x, y, z;)
Use shorter variations of basic control structures (while(1) is replaced with for(;;))
Move code around (i = 0; while(i < 10) { /* ... */ ++i; } to for(i = 0; i < 10; ++i) { /* ... */ })
Etc

I think you need some actual criteria for scoring submissions. This is way too vague as it is.

I was already thinking about a Golfscript golfer in Golfscript for my blog, so I'll certainly think about this. But I agree that you don't have a criterion for selecting a winner. You might find it useful to read the discussion on an question idea migimaru proposed.

I guess the largest % of characters in a 'normal' ungolfed simple "Hello World!" program reduced is a start.

@muntoo A typical "Hello world" program is usually already pretty condensed.

@Casey Yeah, but I wanted something that's easily available for any language. I suppose FizzBuzz is a slightly better option.

What would be more ideal would be to run an answer program against a secret collection of small programs, and score the answer based on the total of all the programs' new lengths.  Problem is, you would need a set of programs for each language golfed by an answer, and a way to compensate for differences in language.

@Joey You could request users to send example programs for each language to a mail adress.

If somebody else reduces your program with his program successfully, you're out. :) The winner is the one, who is the longest time on top. Submission time is somehow substracted or added - I have to think about it.

Perhaps I may have to limit the input/output language to one only (not sure which... GolfScript?). Then I can do: "The program with the smallest ratio of new_code to old_code will win."

If I had such a piece of software, I'd rather use it to my own benefit than share it with rivals ;)

I think a program should be rated by the % by which it has been reduced.  And by the way, I write my programs with ridiculously long variables:  m_pointerToAnUnsignedIntegerWhichMayHappenToBeYetAnotherPointer :D

@Neil What does your for loop look like? for ( size_t index_variable_in_3rd_nested_for_loop = 0; index_variable_in_3rd_nested_for_loop < MAX_VALUE_OF_index_variable_in_3rd_nested_for_loop; ++index_variable_in_3rd_nested_for_loop ) the_sum_which_is_determined_in_3rd_nested_for_loop += the_array_of_numbers_which_total_the_sum_which_is_determined_in_3rd_nested_for_loop[ index_variable_in_3rd_nested_for_loop ];

@munto:  Oh good god no.  It's at least three times as bad.  Why use size_t when you can typedef it to "AmbiguouslyLargeSizeTTypeSomewhereBetweenFourAndEightBytes"? ;)

@Neil You mean AmbiguouslyLargeSizeTTypeSomewhereBetweenAndIncludingFourAndEightBytes.

@muntoo: Yes, excellent point.  Could be interpreted to mean that it excludes the four and eight bytes.

I've rejected a proposed edit which wanted to put shortening method names in the basic functionality. Since there's no space to give a detailed reason in the rejection form, this seems to be the best place. It seems to me that it's covered already by the "Etc" for advanced functionality; and in addition, this question doesn't seem to be going anyway so it's rather a trivial change to zombie it.

Change to popcon explained in discussion on meta

I proposed a question which turned out to be a duplicate of this one. Hopefully the new activity on this question will attract some new answers, and more languages too.

Python with Python
Does a bunch of stuff including renaming of variables, getting rid of unnecessary whitespace and comments, and putting as much as it can on one line. Doesn't always completely work with fancier python syntax and I'll will be continuing to update with any fixes.
Code:
import string
import keyword
import pkgutil

builtins = __builtins__.__dict__.keys()

vars = {}
#imported = builtins+string.__dict__.keys()+['append','extend','count','index','insert','pop','remove','reverse','sort']
multiline = ''
ml_last = ''
strings = []
defined = []
undefined = []

def get_name(name):
    if name.startswith('__'):
        vars[name] = name
        return name
    if name in vars:
        return vars[name]

    for c in string.letters+'_':
        if c not in vars.values():
            vars[name] = c
            return c

    for c0 in string.letters+'_':
        for c1 in string.letters+string.digits+'_':
            if c0+c1 not in vars.values():
                if c0+c1 in keyword.kwlist:
                    continue
                vars[name] = c0+c1
                return c0+c1

def replace_names(expr,defining=False,prefix = '',assign=True):
    if ';' in expr:
        ns = ''
        for e in expr.split(';'):
            ns += replace_names(e,assign=assign)+';'
        return ns[:-1]

    global multiline
    expr = expr.strip()
    if expr in ['']+keyword.kwlist:
        return expr
    if expr == '""':
        return '"'+strings.pop(0)+'"'
    if expr == "''":
        return "'"+strings.pop(0)+"'"

    if '=' in expr and assign:
        e = expr[:]
        vals = ['']
        while '=' in e:
            i = e.index('=')
            if e != '' and e[0] == '=':
                vals[-1] += '='
                e = e[1:]
                continue
            if e[i-1] not in '!<>*/+-%' and e[i+1] != '=' and (vals[-1]+e[:i]).count('(') == (vals[-1]+e[:i]).count(')'):
                vals[-1] += e[:i]
                e = e[i+1:]
                vals.append('')
            else:
                vals[-1] += e[:i+1]
                e = e[i+1:]

        if len(vals) > 1:
            vals[-1] += e
            ns = ''
            left,val = vals[:-1],vals[-1]
            for l in left:
                rs = replace_names(l,True,assign=assign)
                ns += rs+'='
            ns += replace_names(val,assign=assign)
            return ns

    if expr[0] in ['(','[','{']:
        try:
            delimit = expr[0]
            i = 0; level = 1
            while level > 0:
                i += 1
                char = expr[i]
                if char in '([{':
                    level += 1
                if char in ')]}':
                    level -= 1
            inner = expr[1:i]
            rest = expr[i+1:]
            return expr[0]+replace_names(inner,defining,assign=False)+expr[i]+replace_names(rest,defining,assign=assign)

        except IndexError:
            multiline = expr
            return ''

    if expr.startswith('for') and not expr.endswith('in'):
        varname = ''
        curword = ''
        for i,char in enumerate(expr):
            if char in string.letters+string.digits+'_':
                curword += char
            else:
                if curword == 'in':
                    break
                curword = ''
            varname += char
        rest = expr[i:]

        dpart = replace_names(varname[3:-2],True,assign=assign)
        rpart = replace_names(rest,assign=assign)
        return 'for' + ' '*(dpart[0] in string.letters+string.digits+'_') + dpart + ' '*(dpart[-1] in string.letters+string.digits+'_') + 'in' + ' '*(rpart[0] in string.letters+string.digits+'_') + rpart

    if expr.startswith('lambda'):
        args = expr.split('lambda',1)[1].split(':')[0]
        replace_names(args,True,assign=assign)

    poses = ['' if e == -1 else e for e in (expr.find(char) for char in ['(','[','{'])]
    pos = min(poses)
    if pos != '':
        delimit = '([{'[poses.index(pos)]
        first,rest = expr.split(delimit,1)
        return replace_names(first,defining,assign=assign)+replace_names(delimit+rest,defining,assign=assign)

    multiline = ''
    if ' ' in expr:
        ns = ''
        for sub in expr.split(' '):
            rs = replace_names(sub,defining,assign=assign)
            if rs == '':
                continue
            if ns != '' and (ns[-1] in string.letters+string.digits+'_' and rs[0] in string.letters+string.digits+'_'):
                ns += ' '+rs
            else:
                ns += rs
        return ns

    for cmp in ['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.']:
        if cmp in expr:
            ns = ''
            for sub in expr.split(cmp):
                rs = replace_names(sub,defining,prefix,assign=assign)+cmp
                ns += rs
                if cmp == '.':
                    prefix += rs
            return ns[:-len(cmp)]

    if expr[0] in string.digits:
        return expr
    if not defining and expr not in defined:
        #print '---',prefix+expr
        if prefix+expr not in undefined and (prefix == '' or prefix[0] != '.') :
            undefined.append(prefix+expr)
        return expr
    if defining:
        if prefix+expr in undefined:
            undefined.remove(prefix+expr)
        if expr not in defined:
            defined.append(expr)
    return get_name(expr)

def fix_names(line):
    for cmp in ['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.','=','(',')','[',']','{','}']:
        if cmp in line:
            ns = ''
            for sub in line.split(cmp):
                ns += fix_names(sub)+cmp
            return ns[:-len(cmp)]
    if line in defined and line not in vars.values():
        return vars[line]
    return line

def first_pass(file):
    lines_firstpass = []
    for line in file:
        if line.strip() == '':
            continue
        indent = 0
        for char in line:
            if not char in string.whitespace:
                break
            indent += 1

        if multiline != '':
            line_string = ml_last
        else:
            line_string = ''
            #line_string = '\t'*indent
        line = multiline + line.strip()

        newline = ''
        while line:
            char = line[0]
            if char in ['"',"'"]:
                limit=char; i=0
                inside = ''
                escape = False
                while True:
                    i+=1; char = line[i]
                    if escape:
                        escape = False
                        inside += char
                        continue
                    if char == '\\':
                        escape = True
                    elif char == limit:
                        break
                    inside += char
                strings.append(inside)
                newline += limit*2
                line = line[i+1:]
            else:
                if char == '#':
                    break
                newline += char
                line = line[1:]
        line = newline

        if line == '':
            continue
        if ' ' not in line:
            first = ''
        else:
            first,line = line.split(' ',1)

        if first in ['class','def']:
            name = line.split('(')[0].split(':')[0].strip()
            line_string += first+' '
            defined.append(name)
            line_string += get_name(name)
            if '(' in line:
                line_string += '('
                inner = line.split('(',1)[1]
                inner = ')'.join(inner.split(')')[:-1])
                part = ''
                for char in inner:
                    if char == ',' and part.count('(') == part.count(')'):
                        line_string += replace_names(part,True)+','
                        part = ''
                    else:
                        part += char
                line_string += replace_names(part,True)+')'
            line_string += ':'

        to_import = ''
        importing = []
        if first == 'from':
            module,rest = line.split('import')
            module = module.strip()
            #imported.append(module)
            first,line = 'import',rest
            to_import += 'from '+module+' '

        if first == 'import':
            to_import += 'import '
            for module in line.split(','):
                module = module.strip()
                #imported.append(module)
                to_import += module+','
            to_import = to_import[:-1]
            line_string += to_import

        if line_string.strip() == '':
            r = replace_names(first+' '+line)
            if multiline != '':
                ml_last = line_string + r
                continue
            line_string += r
            ml_last = ''
        lines_firstpass.append((indent,line_string))
        #print '\t'*indent+line_string

    for i,(indent,line) in enumerate(lines_firstpass):
        lines_firstpass[i] = (indent,fix_names(line))
    return lines_firstpass

def second_pass(firstpass):
    lines = []
    current_line = ''
    current_line_indent = 0
    last_indent = 0
    for i,(indent,line) in enumerate(firstpass):
        for kw in keyword.kwlist:
            if line[:len(kw)] == kw:
                first = kw
                line = line[len(kw):]
                break
        else:
            first = ''
        limit=';'
        for kw in ['import','global']:
            if first == kw and current_line.startswith(kw):
                first = ''
                line = line.strip()
                limit=','

        if first not in ['if','elif','else','while','for','def','class','try','except','finally'] and indent == last_indent:
            current_line += limit*(current_line != '') + first + line
        else:
            lines.append((current_line_indent,current_line))
            current_line = first + line
            current_line_indent = indent
        last_indent = indent
    lines.append((current_line_indent,current_line))

    new_lines = []
    i = 0
    while i < len(lines):
        indent,line = lines[i]
        if i != len(lines)-1 and lines[i+1][0] == indent + 1 and (i == len(lines)-2 or lines[i+2][0] <= indent):
            new_lines.append((indent,line+lines[i+1][1]))
            i += 1
        else:
            new_lines.append((indent,line))
        i += 1
    return new_lines

def third_pass(lines):
    new_definitions = ''
    for u in sorted(undefined,key=lambda s:-s.count('.')):
        #print u
        parts = u.split('.')
        if parts[0] in vars.values():
            continue
        c = 0
        for indent,line in lines:
            if line.startswith('import'):
                continue
            c += line.count(u)
        if c > 1:
            new_definitions += ';'*(new_definitions!='')+get_name(u)+'='+u
            for ind,(indent,line) in enumerate(lines):
                if line.startswith('import'):
                    continue
                nline = ''
                cur_word = ''
                i = 0
                while i < len(line):
                    char = line[i]
                    if char not in string.letters+string.digits+'_.':
                        if cur_word == u:
                            nline += get_name(u)
                        else:
                            nline += cur_word
                        cur_word = ''
                        nline += char
                        i += 1
                        continue
                    if char in '"\'':
                        nline += char
                        limit = char
                        escape = False
                        while True:
                            i += 1
                            char = line[i]
                            nline += char
                            if escape:
                                escape = False
                                continue
                            if char == '\\':
                                escape = True
                            if char == limit:
                                break
                        i += 1
                        continue
                    cur_word += char
                    i += 1
                lines[ind] = (indent,nline+cur_word)

    return [lines[0]]+[(0,new_definitions)]+lines[1:]

def golf(filename):
    file = open(filename)
    write_file = open('golfed.py','w')
    for indent,line in third_pass(second_pass(first_pass(file))):
        write_file.write('\t'*(indent/2)+' '*(indent%2)+line+'\n')
    file.close()
    write_file.close()

#print first_pass(["for u in sorted(undefined,key=lambda s:-s.count('.')):"])
golf('golfer.py')

Tested on an old fractal drawing program I had (4672 to 1889):
Original:
import pygame
import math
import os
import colorsys
from decimal import *

#two = Decimal(2)
#half = Decimal(0.5)

def fractal_check_point(function,x,y):
    #n = (Decimal(0),Decimal(0))
    n = (0,0)
    i = 0
    last_dist = 0
    while n[0]**2 + n[1]**2 <= 16 and i < max_iter:
        nr,ni = function(n)
        n = (nr+x,ni+y)
        i+=1
    if i == max_iter:
        return False

    #extra = math.log(math.log( (n[0]**two + n[1]**two)**half )/math.log(300),2)
    extra = math.log(math.log( (n[0]**2 + n[1]**2)**0.5 )/math.log(300),2)

    #prev = math.sqrt(last_dist)
    #final = math.sqrt(n.real**2+n.imag**2)

    return i - extra

def f((r,i)):
    return (r**2 - i**2, 2*r*i)

screen_size = (500,500)
try: screen = pygame.display.set_mode(screen_size)
except pygame.error:
    print 'Too large to draw to window...'
    screen = pygame.Surface(screen_size)

#pixels = pygame.PixelArray(screen)

#xmin = Decimal(- 2.2)
#xmax = Decimal(.8)
#
#ymin = Decimal(- 1.5)
#ymax = Decimal(1.5)

max_iter = 50

xmin = -2.2
xmax = 0.8
ymin = -1.5
ymax = 1.5

def draw_fractal():
    print repr(xmin),repr(xmax)
    print repr(ymin),repr(ymax)
    print

    xlist = []
    ylist = []

    for x in range(screen_size[0]):
        #xlist.append(Decimal(x)*(xmax-xmin)/Decimal(screen_size[0])+xmin)
        xlist.append(x*(xmax-xmin)/screen_size[0]+xmin)

    for y in range(screen_size[1]):
        #ylist.append(Decimal(y)*(ymax-ymin)/Decimal(screen_size[1])+ymin)
        ylist.append(y*(ymax-ymin)/screen_size[1]+ymin)

    xi = 0
    for x in xlist:
        yi = 0
        for y in ylist:
            val = fractal_check_point(f,x,y)
            if val == False:
                screen.set_at((xi,yi),(0,0,0))
                #pixels[xi][yi] = (0,0,0)
            else:
                r,g,b = colorsys.hsv_to_rgb(val/10.0 % 1, 1, 1)
                screen.set_at((xi,yi),(r*255,g*255,b*255))
                ##screen.set_at((xi,yi),(0,(val/300.0)**.25*255,(val/300.0)**.25*255))
                #pixels[xi][yi] = (0,(val/300.0)**.25*255,(val/300.0)**.25*255)

            yi += 1
        xi += 1
        pygame.event.get()
        pygame.display.update((xi-1,0,1,screen_size[1]))
    save_surface('F:\FractalZoom\\')

def save_surface(dirname):
    i = 0
    name = '%05d.bmp' % i
    while name in os.listdir(dirname):
        i += 1
        name = '%05d.bmp' % i
    pygame.image.save(screen,dirname+name)
    print 'saved'

x_min_step = 0
x_max_step = 0
y_min_step = 0
y_max_step = 0

savefail = 0

def zoom(xmin_target,xmax_target,ymin_target,ymax_target,steps):
    global xmin
    global xmax
    global ymin
    global ymax

    xc = (xmax_target + xmin_target)/2
    yc = (ymax_target + ymin_target)/2

    d_xmin = ((xc-xmin_target)/(xc-xmin))**(1.0/steps)
    d_xmax = ((xc-xmax_target)/(xc-xmax))**(1.0/steps)
    d_ymin = ((yc-ymin_target)/(yc-ymin))**(1.0/steps)
    d_ymax = ((yc-ymax_target)/(yc-ymax))**(1.0/steps)

    for s in range(steps):
        xmin = xc-(xc-xmin)*d_xmin
        xmax = xc-(xc-xmax)*d_xmax
        ymin = yc-(yc-ymin)*d_ymin
        ymax = yc-(yc-ymax)*d_ymax

        draw_fractal()
        save_dir = 'D:\FractalZoom\\'
        global savefail
        if not savefail:
            try:
                save_surface(save_dir)
            except:
                print 'Warning: Cannot save in given directory '+save_dir+', will not save images.'
                savefail = 1

#zoom(.5,.6,.5,.6,10)
#zoom(-1.07996839017,-1.07996839014,-0.27125861927,-0.27125861923,100)

#n = 1
#while 1:
#    pygame.display.update()
#    pygame.event.get()
#
#    def f(x):
#        if x == 0:
#            return 0
#        else:
#            return x**n
#    draw_fractal()
#    n += .0001

draw_fractal()
zooming = 0
#firstx = Decimal(0)
#firsty = Decimal(0)
firstx = firsty = 0

clicking = 0
while 1:
    pygame.display.update()
    pygame.event.get()
    mx, my = pygame.mouse.get_pos()
    rx, ry = pygame.mouse.get_rel()

#   mx = Decimal(mx)
#   my = Decimal(my)
#   sx = Decimal(screen_size[0])
#   sy = Decimal(screen_size[1])
    sx = screen_size[0]
    sy = screen_size[1]

    if pygame.mouse.get_pressed()[0]:
        if clicking == 0:
            clicking = 1
        if zooming and clicking == 1:
            secondx = mx*(xmax-xmin)/sx+xmin
            secondy = my*(ymax-ymin)/sy+ymin

            firstx = firstx*(xmax-xmin)/sx+xmin
            firsty = firsty*(ymax-ymin)/sy+ymin

            if secondx < firstx:
                xmin = secondx
                xmax = firstx
            else:
                xmin = firstx
                xmax = secondx

            if secondy < firsty:
                ymin = secondy
                ymax = firsty

            else:
                ymin = firsty
                ymax = secondy

            screen.fill((0,0,0))
            screen.lock()
            draw_fractal()
            screen.unlock()
            zooming = 0

        elif clicking == 1:
            firstx = mx
            firsty = my

            zooming = 1
            screen.set_at((firstx,firsty),(255,255,255))

        if clicking:
            clicking = 2

    else:
        clicking = 0

Golfed:
import pygame,math,os,colorsys;from decimal import *
ai=pygame.event.get;aj=pygame.display.update;ak=math.log;al=pygame.mouse;am=False;an=pygame;ao=repr;ap=range;aq=os
def a(b,c,d):
 e=(0,0);f=0;g=0
 while e[0]**2+e[1]**2<=16 and f<o:h,i=b(e);e=(h+c,i+d);f+=1
 if f==o:return False
 j=ak(ak((e[0]**2+e[1]**2)**0.5)/ak(300),2);return f-j
def k((l,f)):return(l**2-f**2,2*l*f)
m=(500,500)
try:n=pygame.display.set_mode(m)
except pygame.error:print'Too large to draw to window...';n=pygame.Surface(m)
o=50;p=-2.2;q=0.8;r=-1.5;s=1.5
def t():
 print ao(p),ao(q);print ao(r),ao(s);print;u=[];v=[]
 for c in ap(m[0]):u.append(c*(q-p)/m[0]+p)
 for d in ap(m[1]):v.append(d*(s-r)/m[1]+r)
 w=0
 for c in u:
    x=0
    for d in v:
     y=a(k,c,d)
     if y==am:n.set_at((w,x),(0,0,0))
     else:l,z,A=colorsys.hsv_to_rgb(y/10.0%1,1,1);n.set_at((w,x),(l*255,z*255,A*255))
     x+=1
    w+=1;ai();aj((w-1,0,1,m[1]))
 B('F:\FractalZoom\\')
def B(C):
 f=0;D='%05d.bmp'%f
 while D in os.listdir(C):f+=1;D='%05d.bmp'%f
 pygame.image.save(n,C+D);print'saved'
E=0;F=0;G=0;H=0;I=0
def J(K,L,M,N,O):
 global p,q,r,s;P=(L+K)/2;Q=(N+M)/2;R=((P-K)/(P-p))**(1.0/O);S=((P-L)/(P-q))**(1.0/O);T=((Q-M)/(Q-r))**(1.0/O);U=((Q-N)/(Q-s))**(1.0/O)
 for V in ap(O):
    p=P-(P-p)*R;q=P-(P-q)*S;r=Q-(Q-r)*T;s=Q-(Q-s)*U;t();W='D:\FractalZoom\\';global I
    if not I:
     try:B(W)
     except:print'Warning: Cannot save in given directory '+W+', will not save images.';I=1
t();X=0;Y=Z=0;_=0
while 1:
 aj();ai();aa,ab=pygame.mouse.get_pos();ac,ad=pygame.mouse.get_rel();ae=m[0];af=m[1]
 if pygame.mouse.get_pressed()[0]:
    if _==0:_=1
    if X and _==1:
     ag=aa*(q-p)/ae+p;ah=ab*(s-r)/af+r;Y=Y*(q-p)/ae+p;Z=Z*(s-r)/af+r
     if ag<Y:p=ag;q=Y
     else:p=Y;q=ag
     if ah<Z:r=ah;s=Z
     else:r=Z;s=ah
     n.fill((0,0,0));n.lock();t();n.unlock();X=0
    elif _==1:Y=aa;Z=ab;X=1;n.set_at((Y,Z),(255,255,255))
    if _:_=2
 else:_=0

Run on itself (creating a very long quine) (9951 to 5323):
import string,keyword,pkgutil;a=__builtins__.__dict__.keys();b={};c='';d='';e=[];f=[];g=[]
aw=string.letters;ax=string.digits;ay=keyword.kwlist;az=False;aA=True;aB=len;aC=enumerate;aD=open
def h(i):
 if i.startswith('__'):b[i]=i;return i
 if i in b:return b[i]
 for j in aw+'_':
    if j not in b.values():b[i]=j;return j
 for k in aw+'_':
    for l in aw+ax+'_':
     if k+l not in b.values():
        if k+l in ay:continue
        b[i]=k+l;return k+l
def m(n,o=az,p='',q=aA):
 if';'in n:
    r=''
    for s in n.split(';'):r+=m(s,q=q)+';'
    return r[:-1]
 global c;n=n.strip()
 if n in['']+ay:return n
 if n=='""':return'"'+e.pop(0)+'"'
 if n=="''":return"'"+e.pop(0)+"'"
 if'='in n and q:
    s=n[:];t=['']
    while'='in s:
     u=s.index('=')
     if s!=''and s[0]=='=':t[-1]+='=';s=s[1:];continue
     if s[u-1]not in'!<>*/+-%'and s[u+1]!='='and(t[-1]+s[:u]).count('(')==(t[-1]+s[:u]).count(')'):t[-1]+=s[:u];s=s[u+1:];t.append('')
     else:t[-1]+=s[:u+1];s=s[u+1:]
    if aB(t)>1:
     t[-1]+=s;r='';v,w=t[:-1],t[-1]
     for x in v:y=m(x,aA,q=q);r+=y+'='
     r+=m(w,q=q);return r
 if n[0]in['(','[','{']:
    try:
     z=n[0];u=0;A=1
     while A>0:
        u+=1;B=n[u]
        if B in'([{':A+=1
        if B in')]}':A-=1
     C=n[1:u];D=n[u+1:];return n[0]+m(C,o,q=az)+n[u]+m(D,o,q=q)
    except IndexError:c=n;return''
 if n.startswith('for')and not n.endswith('in'):
    E='';F=''
    for u,B in aC(n):
     if B in aw+ax+'_':F+=B
     else:
        if F=='in':break
        F=''
     E+=B
    D=n[u:];G=m(E[3:-2],aA,q=q);H=m(D,q=q);return'for'+' '*(G[0]in aw+ax+'_')+G+' '*(G[-1]in aw+ax+'_')+'in'+' '*(H[0]in aw+ax+'_')+H
 if n.startswith('lambda'):I=n.split('lambda',1)[1].split(':')[0];m(I,aA,q=q)
 J=[''if s==-1 else s for s in(n.find(B)for B in['(','[','{'])];K=min(J)
 if K!='':z='([{'[J.index(K)];L,D=n.split(z,1);return m(L,o,q=q)+m(z+D,o,q=q)
 c=''
 if' 'in n:
    r=''
    for M in n.split(' '):
     y=m(M,o,q=q)
     if y=='':continue
     if r!=''and(r[-1]in aw+ax+'_'and y[0]in aw+ax+'_'):r+=' '+y
     else:r+=y
    return r
 for N in['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.']:
    if N in n:
     r=''
     for M in n.split(N):
        y=m(M,o,p,q=q)+N;r+=y
        if N=='.':p+=y
     return r[:-aB(N)]
 if n[0]in ax:return n
 if not o and n not in f:
    if p+n not in g and(p==''or p[0]!='.'):g.append(p+n)
    return n
 if o:
    if p+n in g:g.remove(p+n)
    if n not in f:f.append(n)
 return h(n)
def O(P):
 for N in['**=','//=','==','!=','<>','<=','>=','+=','-=','*=','/=','%=','//','**','<<','>>','<','>','+','-','*','/','%','&','|','^','~',':',',','.','=','(',')','[',']','{','}']:
    if N in P:
     r=''
     for M in P.split(N):r+=O(M)+N
     return r[:-aB(N)]
 if P in f and P not in b.values():return b[P]
 return P
def Q(R):
 S=[]
 for P in R:
    if P.strip()=='':continue
    T=0
    for B in P:
     if not B in string.whitespace:break
     T+=1
    if c!='':U=d
    else:U=''
    P=c+P.strip();V=''
    while P:
     B=P[0]
     if B in['"',"'"]:
        W=B;u=0;X='';Y=False
        while aA:
         u+=1;B=P[u]
         if Y:Y=az;X+=B;continue
         if B=='\\':Y=True
         elif B==W:break
         X+=B
        e.append(X);V+=W*2;P=P[u+1:]
     else:
        if B=='#':break
        V+=B;P=P[1:]
    P=V
    if P=='':continue
    if' 'not in P:L=''
    else:L,P=P.split(' ',1)
    if L in['class','def']:
     i=P.split('(')[0].split(':')[0].strip();U+=L+' ';f.append(i);U+=h(i)
     if'('in P:
        U+='(';C=P.split('(',1)[1];C=')'.join(C.split(')')[:-1]);Z=''
        for B in C:
         if B==','and Z.count('(')==Z.count(')'):U+=m(Z,aA)+',';Z=''
         else:Z+=B
        U+=m(Z,aA)+')'
     U+=':'
    _='';aa=[]
    if L=='from':ab,D=P.split('import');ab=ab.strip();L,P='import',D;_+='from '+ab+' '
    if L=='import':
     _+='import '
     for ab in P.split(','):ab=ab.strip();_+=ab+','
     _=_[:-1];U+=_
    if U.strip()=='':
     ac=m(L+' '+P)
     if c!='':d=U+ac;continue
     U+=ac;d=''
    S.append((T,U))
 for u,(T,P)in aC(S):S[u]=(T,O(P))
 return S
def ad(ae):
 af=[];ag='';ah=0;ai=0
 for u,(T,P)in aC(ae):
    for aj in ay:
     if P[:aB(aj)]==aj:L=aj;P=P[aB(aj):];break
    else:L=''
    W=';'
    for aj in['import','global']:
     if L==aj and ag.startswith(aj):L='';P=P.strip();W=','
    if L not in['if','elif','else','while','for','def','class','try','except','finally']and T==ai:ag+=W*(ag!='')+L+P
    else:af.append((ah,ag));ag=L+P;ah=T
    ai=T
 af.append((ah,ag));ak=[];u=0
 while u<aB(af):
    T,P=af[u]
    if u!=aB(af)-1 and af[u+1][0]==T+1 and(u==aB(af)-2 or af[u+2][0]<=T):ak.append((T,P+af[u+1][1]));u+=1
    else:ak.append((T,P))
    u+=1
 return ak
def al(af):
 am=''
 for an in sorted(g,key=lambda s:-s.count('.')):
    ao=an.split('.')
    if ao[0]in b.values():continue
    j=0
    for T,P in af:
     if P.startswith('import'):continue
     j+=P.count(an)
    if j>1:
     am+=';'*(am!='')+h(an)+'='+an
     for ap,(T,P)in aC(af):
        if P.startswith('import'):continue
        aq='';ar='';u=0
        while u<aB(P):
         B=P[u]
         if B not in aw+ax+'_.':
            if ar==an:aq+=h(an)
            else:aq+=ar
            ar='';aq+=B;u+=1;continue
         if B in'"\'':
            aq+=B;W=B;Y=False
            while aA:
             u+=1;B=P[u];aq+=B
             if Y:Y=az;continue
             if B=='\\':Y=True
             if B==W:break
            u+=1;continue
         ar+=B;u+=1
        af[ap]=(T,aq+ar)
 return[af[0]]+[(0,am)]+af[1:]
def at(au):
 R=aD(au);av=aD('golfed.py','w')
 for T,P in al(ad(Q(R))):av.write('\t'*(T/2)+' '*(T%2)+P+'\n')
 R.close();av.close()
at('golfer.py')

Impressive. This seems a substantial reduction. Is it alternating between spaces and tabs for the indentation to give a double indent with only one character...? I like it.

Only a trivial improvement, but (at least in Python 3) you can use import* instead of import *. I'm guessing that will work in Python 2 also?

@githubphagocyte Yeah, although I didn't think of it myself, I first saw it here: http://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python

That's a interesting question you linked to. Maybe some of the other answers there could apply here too... Several of them look like they'd take some careful thought to apply safely though!

BrainFuck - 489 Characters
Removes all non executable characters. Respects comments from # to end of line.
,[>--[<++>+++++++]<+[>+>+<<-]>[<+>-]+>[<->[-]]<[[,----------]]<>>--[>+
<++++++]<<--------[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<<-[>+>+<<-]>
[<+>-]+>[<->[-]]<[->>.<<]>>+<<<-[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+
<<<-[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++++++++++++++<<<------------
--[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<<--[>+>+<<-]>[<+>-]+>[<->[-
]]<[->>.<<]>++++[>+++++++<-]>+<<++++[<------->-]<-[>+>+<<-]>[<+>-]+>[<
->[-]]<[->>.<<]>>++<<<--[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>[-]<<<,]

Naturally run through itself from this source:
,[

#subtract #
>--[<++>+++++++]<+

#strip comments
[>+>+<<-]>[<+>-]+>[<->[-]]<[[,----------]]<

#put '+' in 4th cell
>>--[>+<++++++]<<
#+
--------
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<<
#,
-
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<<
#-
-
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>+<<<
#.
-
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++++++++++++++<<<
#<
--------------
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<<
#>
--
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>++++[>+++++++<-]>+<<
#[
++++[<------->-]<-
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>++<<<
#]
--
[>+>+<<-]>[<+>-]+>[<->[-]]<[->>.<<]>>[-]<<<
,]

first line of the golfed version, about 6 chars from the end, there's a <> which doesn't do anything

I should obviously write a golfer to eliminate such wasteful behavior.

Brainfuck golfer in Bash (v3)
This is a work in progress, I will keep updating it if I can.
Reads from a file (the filename should be the first command-line argument).
For now all it does is

Remove any characters that are not <>+-.,[]
Remove two-character strings that do nothing useful, e.g. <>, ><, +-, -+
When it is done, it repeats the entire procedure, so >>>><<<<< gets reduced to <

Code
#!/bin/bash

#if the file exists, take input from it
if [ -f $1 ]; then
input=`cat $1`
else
#complain to STDERR and exit
echo "File not found. Exiting with status 1.">&2
exit 1
fi

original=$input #save the original input
code=$input #save original input to another variable which we will be golfing
code=`echo $code|grep -o "[][<>.,+-]"|tr -d " \n"` #remove non-executable chars
output=$code; #this will be output
hits=-1; #Count the number of golfing operations carried out every time the code loops. When this is 0, the code will be completely golfed.

until [ $hits = 0 ]; do
hits=0
#we will be processing the optimised version from last time
code=$output
output=""

#Keep taking characters off from $code until it is empty
until [ m$code = m ]; do
#examine the first two chars
c1=${code:0:1}
code=`echo $code|cut -c2-`
c2=${code:0:1}
#if this is 1, the two characters now being read will be removed
ignore=0

if [ $c1$c2 = "<>" ] ; then
#set the second character to be taken off as well and not saved to output
ignore=1
elif [ $c1$c2 = "><" ] ; then
ignore=1
elif [ $c1$c2 = "+-" ] ; then
ignore=1
elif [ $c1$c2 = "-+" ] ; then
ignore=1
else
#save the char we took off to output, we aren't removing it
output=$output$c1;
fi

if [ $ignore = 1 ]; then
#ignore the second character and save no chars to output
code=`echo $code|cut -c2-`
#another hit
hits=`expr $hits + 1`
fi

#end inner until loop
done
#end main loop
done

#done, print output
echo $output;
exit 0;

How it works
After removing all non-executable characters, it does the following. The hits counter is set to -1 at the start - it counts how many golfing operations were carried out each time the outer loop runs.

If the code being golfed is empty, go to step 5.
Read the first two chars from the code, and remove the first char.
If they are <>, ><, +- or -+, add 1 to the hits counter and go back to step 1.
If not, save the first character to output and go to step 1.
If the hits counter is 0, print output and exit.
If not, reset the hits counter to 0, set the code being golfed to be the output variable, reset output to the empty string, and go to step 1.

HQ9+ golfer in Bash (v3)
I know HQ9+ is useless, but I might as well submit a five-liner for it. It reads from standard input a file. The path to the file should be the first command-line argument.
Features

Removes all comment characters (anything except HhQq9+)
Removes + (it increments a number but there is no way to print that number)
Converts hq to uppercase (not golfing)

Code
#!/bin/bash
if [ -f $1 ]; then
input=`cat $1`
else exit 1; fi
echo $input|tr "[[:lower:]]" "[[:upper:]]"|grep -o "[HQ9]"|tr -d ' \n'
exit 0

It still reads from standard input! Just use /dev/stdin as the first argument :)

Java with Java
Takes the file name as a command line argument, and edits the file in place.

Removes comments
Shortens identifiers (including classes, methods, variables, method parameters, and lambda expression parameters)
Trims spaces
Shortens imports
Removes unnecessary braces around one-line statements
Converts while(true) to for(;;)
Removes unneeded modifiers, such as private and final

When the program is run on itself, its size is reduced from 7792 to 4366.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Golfer {

    public static void main(String[] args) throws IOException {
        Path path = new File(args[0]).toPath();
        String program = Files.readAllLines(path).stream().collect(Collectors.joining("\n"));
        Golfer golfer = new Golfer(program);
        System.out.println(golfer.toString().length() + " characters");
        System.out.println(golfer.toString().getBytes().length + " bytes");
        golfer.golf();
        String str = golfer.toString();
        Files.write(path, Arrays.asList(str));
        System.out.println(golfer);
        System.out.println(golfer.toString().length() + " characters");
        System.out.println(golfer.toString().getBytes().length + " bytes");
    }

    private String program;

    public Golfer(String program) {
        this.program = program;
    }

    public void golf() {
        doUnicodeSubstitutions();
        protectStrings();
        removeComments();
        removeDuplicateSpaces();
        removeExcessSpaces();
        removeUnnecessaryModifiers();
        simplifyImports();
        shortenIdentifiers();
        improveControlStructures();
        unprotectStrings();
    }

    void removeDuplicateSpaces() {
        program = program.replaceAll("\\s+", " ");
    }

    void removeExcessSpaces() {
        program = program.trim();
        program = program.replaceAll("([.,;:?!@%^&*()\\[\\]{}=|/<>~]) ", "$1");
        program = program.replaceAll(" ([.,;:?!@%^&*()\\[\\]{}=|/<>~])", "$1");
        program = program.replaceAll("([^+]) \\+", "$1+").replaceAll("\\+\\+ \\+", "+++").replaceAll("\\+ ([^+])", "+$1");
        program = program.replaceAll("([^-]) -", "$1-").replaceAll("-- -", "---").replaceAll("- ([^-])", "-$1");
    }

    void removeUnnecessaryModifiers() {
        program = program.replaceAll("private |final |@Override ", "");
    }

    void simplifyImports() {
        int startImports = program.indexOf("import ");
        List<String> imports = new ArrayList();
        Matcher importMatcher = Pattern.compile("import [A-Za-z0-9$_.*]*;").matcher(program);
        while (importMatcher.find()) {
            imports.add(importMatcher.group());
        }
        for (int i = 0; i < imports.size(); i++) {
            if (!imports.get(i).endsWith("*;")) {
                imports.set(i, imports.get(i).replaceFirst("\\.[A-Za-z0-9$_]*;", "\\.*;"));
            }
            imports = imports.stream().distinct().collect(Collectors.toList());
            program = program.replaceAll("import [A-Za-z0-9$_.*]*;", "");
            program = program.substring(0, startImports) + String.join("", imports) + program.substring(startImports);
        }
    }

    private List<Character> unusedCharacters;

    void shortenIdentifiers() {
        unusedCharacters = IntStream.concat(IntStream.rangeClosed('a', 'z'), IntStream.rangeClosed('A', 'Z'))
                .mapToObj(i -> (char) i)
                .filter(c -> !Pattern.compile("[^A-Za-z0-9$_']" + c + "[^A-Za-z0-9$_]").matcher(program).find())
                .collect(Collectors.toList());
        shortenIdentifiers("(class|interface|enum) ([A-Za-z0-9$_]{2,})( extends [A-Za-z0-9$_]+)?( implements [A-Za-z0-9$_,]+)?\\{",
                           2, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_]");
        shortenIdentifiers("([A-Za-z0-9$_]+(\\[+\\]+| )|<[A-Za-z0-9$_,]+>+\\[+\\]+)(?<!implements |else |package |import |return )([A-Za-z0-9$_]{2,})(?<!null)[=,;)]",
                           3, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_(]");
        shortenIdentifiers("([A-Za-z0-9$_]+ |<[A-Za-z0-9$_,]+>+)(?<!new |else )([A-Za-z0-9$_]{2,})(?<!main|toString|compareTo|equals|hashCode|paint|repaint)\\(",
                           2, "[^A-Za-z0-9$_]", "\\(", "::", "[^A-Za-z0-9$_]");
        shortenIdentifiers("[^A-Za-z0-9$_]([A-Za-z0-9$_]{2,})(,[A-Za-z0-9$_]+)*\\)?->",
                           1, "[^A-Za-z0-9$_]", "[^A-Za-z0-9$_(]");
    }

    void shortenIdentifiers(String pattern, int groupNumber, String... afficesForReplacement) {
        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher;
        while ((matcher = compiledPattern.matcher(program)).find()) {
            String identifer = matcher.group(groupNumber);
            char newIdentifier;
            if (unusedCharacters.remove((Character) identifer.charAt(0))) {
                newIdentifier = identifer.charAt(0);
            } else if (Character.isUpperCase(identifer.charAt(0))
                       && unusedCharacters.remove((Character) Character.toLowerCase(identifer.charAt(0)))) {
                newIdentifier = Character.toLowerCase(identifer.charAt(0));
            } else if (Character.isLowerCase(identifer.charAt(0))
                       && unusedCharacters.remove((Character) Character.toUpperCase(identifer.charAt(0)))) {
                newIdentifier = Character.toUpperCase(identifer.charAt(0));
            } else if (unusedCharacters.size() > 0) {
                newIdentifier = unusedCharacters.remove(0);
            } else {
                System.err.println("out of identifiers");
                break;
            }
            for (int i = 0; i < afficesForReplacement.length; i += 2) {
                program = program.replaceAll('(' + afficesForReplacement[i] + ')' + identifer + "(?=" + afficesForReplacement[i + 1] + ')', "$1" + newIdentifier);
            }
        }
    }

    void improveControlStructures() {
        program = program.replaceAll("while\\(([^()]+)\\)\\{", "for(;$1;){");
        program = program.replaceAll("for\\(([^()]*);true;([^()]*)\\)", "for($1;;$2)");
        while (!program.equals(removeBrackets(program))) {
            program = removeBrackets(program);
        }
    }

    String removeBrackets(String string) {
        return string.replaceAll("((if|while|do)\\([^{;]*\\))\\{([^;}]*;)\\}", "$1$3")
                .replaceAll("else\\{([^;}]*;)\\}", "else $1")
                .replaceAll("(for\\([^{;]*;[^{;]*;[^{;]*\\))\\{([^;}]*;)\\}", "$1$2");
    }

    void protectStrings() {
        adjustStrings(1000);
    }

    void unprotectStrings() {
        adjustStrings(-1000);
    }

    void adjustStrings(int n) {
        char[] chars = new char[program.length()];
        for (int i = 0; i < program.length(); i++) {
            chars[i] = program.charAt(i);
            if (chars[i] == '"' && chars[i - 1] != '\'') {
                for (i++; chars.length > i + 1 && program.charAt(i) != '"'; i++) {
                    chars[i] = (char) (program.charAt(i) + n);
                }
                chars[i] = program.charAt(i);
            }
        }
        program = new String(chars);
    }

    void removeComments() {
        program = program.replaceAll("(?s)/\\*.*\\*/", "");
        program = program.replaceAll("//.*\n", "");
    }

    void doUnicodeSubstitutions() {
        List<Character> chars = new ArrayList();
        for (int i = 0; i < program.length(); i++) {
            if (program.charAt(i) != '\\' || program.charAt(i + 1) != 'u') {
                chars.add(program.charAt(i));
            } else {
                chars.add((char) Integer.parseInt(program.substring(i + 2, i + 6), 16));
                i += 5;
            }
        }
        char[] charArray = new char[chars.size()];
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = chars.get(i);
        }
        program = new String(charArray);
    }

    @Override
    public String toString() {
        return program;
    }
}

Perl, Parts 1 - 2
(removes comments and ignores # characters inside double quotes)
(removes all whitespace after brackets and = signs)
I did not try to golf this code. Maybe, when it is done, it could golf itself.
$/="\n\n";
chomp($prog = <>);
for(1..length($prog)){
 $rev.=chop $prog;
}
#print$rev;
for(1..length($rev)){
 $temp = chop$rev;
 if ($temp eq '"'){
  if($quote == 0){$quote = 1}
  else{$quote = 0}
 }
 if($temp eq '#' && $quote == 0){$comment = 1}
 if($temp eq "\n"){
  $comment = 0;
 }
 if($comment != 1){
  $prog.=$temp;
 }
}
for(1..length($prog)){
 $rev.=chop $prog;
}
for(1..length($rev)){
 $temp = chop$rev;
 if ($temp eq ";" || $temp eq "}" || $temp eq ")" || $temp eq "=" || $temp eq "{"){
  $ws = 2;
 }
 if(($temp eq "\n" || $temp eq " ") && $ws != 0){$ws = 1}elsif($ws==1){$ws=0}
 if($ws != 1){
  $prog.=$temp;
 }
}
print$prog;

Example input
for(1..10) {
 print "Hello, World!";#prints hello world
 print ($n = <>); #prints "#"
}

Output
for(1..10){print "Hello, World!";print ($n =<>);}

Next, it will eliminate spaces between symbols and alphanumeric characters.

Java golfer in Perl
WIP at the moment, although it gets pretty nice code right now.
Features:

Removes all comments
Removes unnecessary whitespace
Removes package declarations (it's single-file anyway!)

Code
#!/usr/bin/env perl
use strict;
use warnings;

my $string_re = qr/"(?:\\[btnfr"'\\]|\\(?:[0-3][0-7][0-7]|[0-7]{1,2})|\\u+[0-9a-fA-F]{4}|[^\r\n\\"])*"/;
my @lines = <>;
my @strings = ();

# First, replace strings with placeholders. Strings suck REALLY hard when replacing.
map {
  while (m/$string_re/) {
    s//"\032".@strings."\032"/e;
    push @strings, $&;
  }
} @lines;

# Remove comments
my $in_comment = 0;
my $partial_line;

sub remove_comments {
  my $line = $_[0];
  start:
  if ($in_comment) {
    if ((my $mulc_end_index = index $line, '*/') != -1) {
      $line = $partial_line . substr $line, $mulc_end_index + 2;
      $in_comment = 0;
      goto no_comment;
    }
    return 0;
  }

  no_comment:
  my $eolc_idx = index $line, '//';
  my $mulc_idx = index $line, '/*';

  if ($mulc_idx == -1 || ($eolc_idx != -1 && $eolc_idx < $mulc_idx)) {
    $line =~ s;//.*$;;;
  } elsif ($mulc_idx != -1) {
    $in_comment = 1;
    $partial_line = substr $line, 0, $mulc_idx;
    goto start;
  }
  $_ = $line;
  return 1
}

@lines = grep {&remove_comments($_)} @lines;

# Remove empty lines, remove line ends
@lines = grep(!/^\s*$/, @lines);
map {chomp;s/^\s*//;s/\s*$//} @lines;

# Remove unnecessary whitespace
map {s/\s*([][(){}><|&~,;=!+-])\s*/$1/g} @lines;

# Remove unnecessary package declaration
$lines[0] =~ s/^package [^;]+;//;

# Finally, put strings back.
map {s/\032(\d+?)\032/$strings[$1]/g} @lines;

print @lines;


text:
Set the chessboard
Objective
Given an arbitrary chessboard as standard input (in which each piece is on a square), produce as standard output a list of moves needed to regularize, or set up, the chessboard. The moves need not be legal, yet no piece may be placed above another. The program must warn about any missing or additional pieces; in the latter case, the program need not produce a list of moves.
A regular chessboard is a chessboard having sixteen pieces in their initial positions described in the Laws of Chess section of the FIDE Handbook. A partially regular board is a chessboard missing at least one of the regular board's sixteen pieces or including one or more additional pieces in ranks 3-6 (consisting of empty squares in the regular board) yet otherwise regular.
Input format
Description
Eight lines of eight characters each make up a chessboard. A hyphen (-) represents an empty square. The last line's first character represents the regular position of white's king's rook (a1 in algebraic notation) and is always a black square; both its adjacent squares are white squares (see Figure 1).
Each kind of piece has a distinct uppercase or lowercase letter for identification (see Figure 2). No two pieces having the same letter (excepting pawns) are present in a regular board, and white and black have exactly eight pawns each.
Figure 1: regular board
rnbkqbnr
pppppppp
--------
--------
--------
--------
PPPPPPPP
RNBKQBNR

Figure 2: piece names, counts, and letters
Piece    Count    White    Black
--------------------------------
King       1        K        k
Queen      1        Q        q
Bishop     2        B        b
Knight     2        N        n
Rook       2        R        r
Pawn       8        P        p

Output format
The program shall output one line per move. Each move follows the format <source><target>, where <source> is the algebraic notation for an occupied square and <target> is the algebraic notation for an unoccupied square. (Note: Algebraic notation is described in Appendix C to the FIDE Handbook.) For example,  the program shall output a4a5 to move the piece on square a4 to square a5.
The generated moves shall fully regularize the chessboard if possible. If any pieces are missing from the board, the program shall output the moves necessary to partially regularize the board and then a line containing 'M' followed by the letters of all such pieces. An 'M' line shall not be output unless there is at least one missing piece.
If any additional pieces exist on the board, the program shall either a) leave them in ranks 3-6, partially regularizing the board or b) entirely omit the list of moves from its output, even if pieces are missing. The former option (a) may not be possible in some input cases. The program shall output a line containing 'A' followed by the letters of all additional pieces after all other output (including an 'M' line if present). An 'A' line shall not be output unless there is at least one additional piece.
Score
The program's score shall be the product of its character count and the total number of moves taken for the ten test cases in regboards.txt.
Test cases
I have posted regularizable and nonregularizable test cases on Gist. On jsFiddle, I have posted the test case generator/move checker to help you check your solution. Put the board in the first box and the move list in the second box (including neither an 'M' nor an 'A' line) and click "Make Moves" to execute the moves your program has generated. To see examples of valid output, you can run my ungolfed solution on the test cases (taking 482 moves).

if a move don't need to be legal, can I make a piece jump from one side to the other of the board?

@JBernardo: Yes, that was my intent. On an unrelated note, the input description above was incorrect for the first thirty minutes it was posted - empty squares are represented by hyphens, not periods.

Any chance of an example input and corresponding output?

@Gareth: See the link to an ungolfed solution I have now posted.

Python, score 150552 = 306 moves * 492 chars
import os,re
B=os.read(0,99)
R='rnbkqbnr-'+8*'p'+37*'-'+8*'P'+'-RNBKQBNR'
def P(x,y):print'%c%d%c%d'%(97+x%9,8-x/9,97+y%9,8-y/9)
F={}
M=''
t=B.find('-',18,56)
for x in range(71):
 if R[x]>'@':
  if R[x]==B[x]:B=B[:x]+'-'+B[x+1:]
  else:
   y=B.find(R[x])
   if y<0:M+=R[x]
   else:F[x]=y;B=B[:y]+'-'+B[y+1:]
A=re.sub(r'[-\n]','',B)
if M:print'M',M
if A:print'A',A
else:
 while F:
  p=[x for x in F if x not in F.values()]
  if p:x=p[0];y=F[x];P(y,x);del F[x]
  else:x=min(F);P(F[x],t);F[x]=t

The code records a list of moves F which will regularize the board.  This list is made by choosing a piece from the input board B to go to each location of the final board R, and 'crossing it off' of the input board.  Any missing or additional pieces are computed as a side effect of this computation.  Then the moves from F are made, using the temporary location t to break any cycles.

You can lose 9 characters by using tabs for the second indentation level, and replacing if R[x]>'@' with if'@'<R[x]


text:
Organize a tournament
Here is a real question somebody asked me. Suppose you have n teams, one terrain.

Each team must play each other team exactly once.
The number of times a team plays two matches in a row should be minimized.

The problem is hard if not optimized. Your program should be able to answer this question for up to 6 teams (at least) in a reasonable time (say less than an hour). For 5 teams I have a working program which works in less than a minute.
Here is an example for 5 teams.
$ organize_for 5
[(3,5),(1,2),(4,5),(1,3),(2,4),(1,5),(2,3),(1,4),(2,5),(3,4)]

And another for 6 teams.
$ organize_for 6
[(2,4),(1,5),(2,3),(1,6),(3,5),(1,4),(2,5),(1,3),(4,6),(1,2),(3,6),(4,5),(2,6),(3,4),(5,6)]

NB for 3 and 4 teams, you'll have at least two occurrences of a team playing two matches in a row.
To win: make the shortest program to answer this problem fast enough to give you a correct answer for 6 teams.
Bonuses:

The median of the median of the waiting time between two matches for all teams should be maximized.
Example: from organize_for 5 ;
nb match between the next one (sorted, median is the one in the center)
team 1 -> 1, 1, 1 (sorted => 1, 1, 1, median => 1)
team 2 -> 2, 1, 1 (sorted => 1, 1, 2, median => 1)
team 3 -> 2, 2, 2 (sorted => 2, 2, 2, median => 2)
team 4 -> 1, 2, 1 (sorted => 1, 1, 2, median => 1)
team 5 -> 1, 2, 2 (sorted => 1, 2, 2, median => 2)

medians: (1, 1, 2, 1, 2), sorted => (1, 1, 1, 2, 2)
median of the medians = 1.

Generalize for k terrains. All match have the same duration.

The most important rules remains a team shouldn't do a match just after another.
The global time for all matches should be minimized

What's the winning criterion?

Sorry about that. The idea is to have the shortest program possible. But it must also be fast enough to give you the answer for 6 teams.

Where do the bonuses fit in?

Pretty sure you need to tweak this -- as-is, I could post a program that simply outputs [(2,4),(1,5),(2,3),(1,6),(3,5),(1,4),(2,5),(1,3),(4,6),(1,2),(3,6),(4,5),(2,6),(3,4),(5,6)] and I would meet this entirely: "To win: make the shortest program to answer this problem fast enough to give you a correct answer for 6 teams."

Haskell: 291 chars
Another solution which terminate only if there is a solution without any collision (5 and 6). It is also very fast:
import System.Environment
import Data.List
a n=[(x,y)|x<-[1..n],y<-[1..n],x<y]
s []=[[]]
s (m:[])=[[m]]
s ((x,y):(x',y'):xs )
 |(x==x')||(x==y')||(y==x')||(y==y')=s((x,y):xs++[(x',y')])
 |0<1=[(x,y):ys|ys<-s((x',y'):xs)]
main=do
 args <- getArgs
 print $ head $ s $ a (read(head args)::Int)

This ain't even close to being golfed. I did the work of applying very simple transformations. See the golfed version here https://ideone.com/4NfWV

Python 282 247 chars
import sys
n=int(sys.argv[1])+1
r=range
l=[(i,j)for i in r(1,n)for j in r(i+1,n)]
m=[(),()]
while l:
 o,p=h=l.pop(0);v=[]
 for k in r(len(m)-1):g=m[k]+m[k+1];v+=[o in g or p in g]
 m.insert(v.index(0)+1,h)if min(v)<1 else l.append(h)
print m[1:-1]

UPD: working for n>4, for testing add:
lst = m[1:-1]
conflicts = 0
for i in range(len(lst)-1):
    if lst[i][0] in lst[i+1] or lst[i][1] in lst[i+1]:
        conflicts += 1

print 'Conflicts: {}'.format(conflicts)

Haskell 585 chars
import System.Environment
import Data.Ord
import Data.List
a::Int->[(Int,Int)]
a n=[(x,y)|x<-[1..n],y<-[1..n],x<y]
b::[(Int,Int)]->Int
b ((x,y):((z,t):rest))|x==z=1+b ((z,t):rest)
 |x==t=1+b ((z,t):rest)
 |y==z=1+b ((z,t):rest)
 |y==t=1+b ((z,t):rest)
 |otherwise=b ((z,t):rest)
b _=0
c l=(b l,l)
d [] _=[[]]
d l minimal=[x:s|x<-l,s<-take 10 $ filter (\ts->b ts<minimal) (d (delete x l) minimal)]
e n minimal=take 1 $ sortBy (comparing fst) $ map c (d (a n) minimal)
f []=False
f _=True
g n=head $ filter f $ map (e n) [0..]
main = do
 args<-getArgs
 print $ g (read (head args)::Int)

Here is the non code golfed version:
import System.Environment
import Data.Ord
import Data.List

all_matches :: Int -> [(Int,Int)]
all_matches n = [ (x,y) | x <- [1..n], y <- [1..n], x < y ]

price :: [(Int,Int)] -> Int
price ((x,y):((z,t):rest))
    | x==z = 1 + price ((z,t):rest)
    | x==t = 1 + price ((z,t):rest)
    | y==z = 1 + price ((z,t):rest)
    | y==t = 1 + price ((z,t):rest)
    | otherwise = price ((z,t):rest)
price _ = 0

addPrices xs = (price xs, xs)

myPerm [] _ = [[]]
myPerm xs minimal = [x:ys | x <- xs,
                    ys <- take 10 $ filter (\ts -> price ts < minimal) (myPerm (delete x xs) minimal)]

find_best_under n minimal = take 1 $ sortBy (comparing fst) $ map addPrices ( myPerm (all_matches n) minimal)

isNonEmpty [] = False
isNonEmpty _ = True

find_best n = head $ filter isNonEmpty $ map (find_best_under n) [0..]

main = do
    args <- getArgs
    putStrLn $ show $ find_best (read (head args)::Int)

It only search for local optima. But in this case, local optima are also global one up to 6 teams.

Hui... You can golf much better: Use the legacy haskell98 imports, like import List; import System, there is no legacy module for Ord though. Shorten all variable names to a single character, replace otherwise  by 0<1, usw.