text:
xkcd challenge: "Percentage of the screen that is [x] color"
So I think we've all probably seen this xkcd comic:
:
This might either be too general or too difficult, I'm not sure. But the challenge is to create a program in any language that creates a window that has at least 2 colors and displays in English words what percentage of the screen is each color.
ex. The simplest solution would be a white background with black letters that read "Percentage of this image that is black: [x]%. Percentage of this image that is white: [y]%"
You can go as crazy or as simple as you want; plain text is a valid solution but if you make interesting images like in the xkcd comic that's even better! The winner will be the most fun and creative solution that gets the most votes. So go forth and make something fun and worthy of xkcd! :)
So, what do you think? Sound like a fun challenge? :)
Please include a screenshot of your program running in your answer :)

A "this program has 64 A's, 4 B's, ... and 34 double quotes in the source code" program would be more interesting :-)

OK... what are the objective winning criteria? How do you determine if any specific output is valid? Is it sufficient that it is true and it describes a property of itself numerically?

@JanDvorak Oh, that's a good one! The alphabet program is actually what made me think of this originally, but I didn't consider adding the source code element to it! You should post that as a question :) Yes, it is sufficient that it is true and describes itself. Hmm, you're right though, I didn't think about how I would prove that the final results were correct. I'll need a way to count all the pixels of each color in a result image, I suppose. I'll go investigate that now. (Sorry my first question had problems... I tried but I'm new at this! Thank you :))

if truthiness and self-reference are the sufficient criteria, here's my golfscript contestant: "/.*/" (read: [the source code] doesn't contain a newline)

@JanDvorak Hmm, I tried your code here and the output was the same as the code except without the quotes. Maybe I'm not explaining this right, sorry. There must be at least 2 colors generated, and in some form of an English sentence the output must generate true words that describe what percentage of the screen each of the colors occupies. Maybe this was a silly idea. I thought it would be fun but it might not work in practice :)

Maybe if you convert this to a popularity contest, you'll attract some more interesting answers. Code golf doesn't really promote creativity as far as output is concerned.

@JanDvorak Okay, will do! That's what I was hoping for anyway but I thought the idea of the site was to encourage the shortest code. Changing now!

popularity contest = votes decide for the winner. You can still specify some secondary criteria for the voters. code golf = the shortest code that satisfies the specified (objective) criteria ("working code") wins no matter how uncreative or unpopular it may be.

there's a [tag:popularity-contest] tag that I was suggesting

What kind of assumptions do we get to make about the screen? Does the code take up the entire screen? Do we get to pick the font?

@minitech The screen can have anything you want on it (pictures, words, as many colors as you want (though more colors makes it harder)). There doesn't have to be any code on the screen at all, you can write code that creates a web page for all I care ;) It's all up to you, be as creative as you want! The screen, whatever form it takes, just has to be accurately self-descriptive of the colors, in English words that make sense :) For example, if you made a program that pixel-perfectly reproduced that xkcd strip, you'd have met the criteria.

Elm
Haven't seen anyone use this loophole yet: demo
import Color exposing (hsl)
import Graphics.Element exposing (..)
import Mouse
import Text
import Window

msg a = centered <| Text.color a (Text.fromString "half the screen is this color")

type Pos = Upper | Lower

screen (w,h) (x,y) =
  let (dx,dy) = (toFloat x - toFloat w / 2, toFloat h / 2 - toFloat y)
      ang = hsl (atan2 dy dx) 0.7 0.5
      ang' = hsl (atan2 dx dy) 0.7 0.5
      box c = case c of
        Upper -> container w (h // 2) middle (msg ang) |> color ang'
        Lower -> container w (h // 2) middle (msg ang') |> color ang
  in  flow down [box Upper, box Lower]

main = Signal.map2 screen Window.dimensions Mouse.position

Great loophole!

I love this!!! At least for now, you get the checkmark for sheer clever points. Love it!

The best part is, I'm still not sure which sentence is talking about which color.

It would be correct, if view source wasn't there.

The view source is put there by share-elm.com and is not part of the compiled JS/HTML.

What about when the page height is an odd number of pixels?

Ah, that's a quick fix - "about half the screen is this color"

The letters are antialiased, so the image is not using only 2 colors ;)

@ML That depends on the scope of the word "this".  JavaScript programmers understand...

demo link is dead

JavaScript with HTML
I tried to reproduce the original comic more precisely. A screenshot is taken using the html2canvas library. The numbers are calculated repeatedly, so you can resize the window or even add something to page in real time.
Try it online: http://copy.sh/xkcd-688.html
Here's a screenshot:

Fraction of
this website
which is white _/
<canvas width=150 id=g></canvas>
  Fraction of
- this website
  which is black

0
<canvas style="border-width: 0 0 1px 1px; border-style: solid" id=z></canvas>

Location of coloured pixels in this website

Nice!! Love the similarities to the xkcd comic, and the fact that I can change the text. Neat! : D

impressive work o.O

Nifty... but I think it has to stabilize to be a "solution".  Haven't thought through it entirely--but as there isn't necessarily a solution for arbitrary precision when drawing from a limited set of digit glyphs, you'll have to back off precision if it can't be solved at the higher precision you're trying.  I imagine that using a monospace font that you pre-compute the black/white pixels will be necessary as well.

You are using 3 colors, so where are the percentages for grey? ;)

Processing, 222 characters

I've always wanted to make my own version of that comic strip! The simplest (only?) way I could think of doing this was trial and error - draw something, count, draw again...
This program settles for an accurate percentage after a few seconds. It's not very pretty, but it's interactive; you can resize the window and it will start to recalculate.
Added some newlines for readability:
float s,S,n;
int i;
void draw(){
frame.setResizable(true);
background(255);
fill(s=i=0);
text(String.format("%.2f%% of this is white",S/++n*100),10,10);
loadPixels();
while(i<width*height)if(pixels[i++]==-1)s++;
S+=s/height/width;
}

It only shows percentage of white pixels; Because of antialiasing of the text, non-white pixels are not necessarily black. The longer it is running the more time it will need to update itself on a resize.
Edit:
So, it's a code-challenge; I sort of golfed it anyways. Maybe I could add some sort of graphs later, but the general principle would remain the same. The interactiveness is the neat part I think.

Very nice!! I think you get extra credit for the interactivity; I had fun resizing the window! Very cool :) And you're my first ever response! I didn't know if anyone would want to play, so thanks. You've made my day. : D +1! (I'm curious though, why does it slow down as time goes on and it gets closer to reaching the correct percentage? I'm just curious as to what's happening, I've never seen this language before. I'm seeing a lot of new stuff poking around this site!)

headdesk Except I accidentally forgot to click the +1. Now +1...haha. Sorry!

You could add another function that allows users to draw on it with the mouse, for added interactivity.

Holy box shadow, Batman

If you want to golf, you can use background(-1) instead of background(255)

Great challenge. Here's my solution. I tried to get as close as possible to the original comic, I even used the xkcd font.

It's a WPF application, but I used System.Drawing to do the drawing parts because I'm lazy.
Basic concept: In WPF, windows are Visuals, which means they can be rendered. I render the entire Window instance onto a bitmap, count up the black and total black or white (ignoring the grays in the font smoothing and stuff) and also count these up for each 3rd of the image (for each panel). Then I do it again on a timer. It reaches equilibrium within a second or two.
Download:
MEGA
Always check files you download for viruses, etc, etc.
You'll need to install the font above to your system if you want to see it, otherwise it's the WPF default one.
XAML:
<Window
 x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="xkcd: 688" Height="300" Width="1000" WindowStyle="ToolWindow">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.3*"/>
            <ColumnDefinition Width="0.3*"/>
            <ColumnDefinition Width="0.3*"/>
        </Grid.ColumnDefinitions>

        <Border BorderBrush="Black" x:Name="bFirstPanel" BorderThickness="3" Padding="10px" Margin="0 0 10px 0">
            <Grid>
                Fraction of this window that is white
                Fraction of this window that is black
                <Image x:Name="imgFirstPanel"></Image>
            </Grid>
        </Border>
        <Border Grid.Column="1" x:Name="bSecondPanel" BorderBrush="Black" BorderThickness="3" Padding="10px" Margin="10px 0">
            <Grid>
                <TextBlock FontSize="18" FontFamily="xkcd" VerticalAlignment="Top" HorizontalAlignment="Left">Amount of <LineBreak></LineBreak>black ink <LineBreak></LineBreak>by panel:</TextBlock>
                <Image x:Name="imgSecondPanel"></Image>
            </Grid>
        </Border>
        <Border Grid.Column="2" x:Name="bThirdPanel" BorderBrush="Black" BorderThickness="3" Padding="10px" Margin="10px 0 0 0">
            <Grid>
                <TextBlock FontSize="18" FontFamily="xkcd" VerticalAlignment="Top" HorizontalAlignment="Left">Location of <LineBreak></LineBreak>black ink <LineBreak></LineBreak>in this window:</TextBlock>
                <Image x:Name="imgThirdPanel"></Image>
            </Grid>
        </Border>

    </Grid>
</Window>

Code:
using System;
using System.Drawing;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Brushes = System.Drawing.Brushes;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        private Timer mainTimer = new Timer();
        public MainWindow()
        {
            InitializeComponent();

            Loaded += (o1,e1) =>
                          {
                              mainTimer = new Timer(1000/10);
                              mainTimer.Elapsed += (o, e) => {
                                  try
                                  {
                                      Dispatcher.Invoke(Refresh);
                                  } catch(Exception ex)
                                  {
                                      // Nope
                                  }
                              };
                              mainTimer.Start();
                          };
        }

        private void Refresh()
        {
            var actualh = this.RenderSize.Height;
            var actualw = this.RenderSize.Width;

            var renderTarget = new RenderTargetBitmap((int) actualw, (int) actualh, 96, 96, PixelFormats.Pbgra32);
            var sourceBrush = new VisualBrush(this);

            var visual = new DrawingVisual();
            var context = visual.RenderOpen();

            // Render the window onto the target bitmap
            using (context)
            {
                context.DrawRectangle(sourceBrush, null, new Rect(0,0, actualw, actualh));
            }
            renderTarget.Render(visual);

            // Create an array with all of the pixel data
            var stride = (int) actualw*4;
            var data = new byte[stride * (int)actualh];
            renderTarget.CopyPixels(data, stride, 0);

            var blackness = 0f;
            var total = 0f;

            var blacknessFirstPanel = 0f;
            var blacknessSecondPanel = 0f;
            var blacknessThirdPanel = 0f;
            var totalFirstPanel = 0f;
            var totalSecondPanel = 0f;
            var totalThirdPanel = 0f;

            // Count all of the things
            for (var i = 0; i < data.Length; i += 4)
            {
                var b = data[i];
                var g = data[i + 1];
                var r = data[i + 2];

                if (r == 0 && r == g && g == b)
                {
                    blackness += 1;
                    total += 1;

                    var x = i%(actualw*4) / 4;

                    if(x < actualw / 3f)
                    {
                        blacknessFirstPanel += 1;
                        totalFirstPanel += 1;
                    } else if (x < actualw * (2f / 3f))
                    {
                        blacknessSecondPanel += 1;
                        totalSecondPanel += 1;
                    }
                    else if (x < actualw)
                    {
                        blacknessThirdPanel += 1;
                        totalThirdPanel += 1;
                    }
                } else if (r == 255 && r == g && g == b)
                {
                    total += 1;

                    var x = i % (actualw * 4) / 4;

                    if (x < actualw / 3f)
                    {
                        totalFirstPanel += 1;
                    }
                    else if (x < actualw * (2f / 3f))
                    {
                        totalSecondPanel += 1;
                    }
                    else if (x < actualw)
                    {
                        totalThirdPanel += 1;
                    }
                }
            }

            var black = blackness/total;

            Redraw(black, blacknessFirstPanel, blacknessSecondPanel, blacknessThirdPanel, blackness, renderTarget);
        }

        private void Redraw(double black, double firstpanel, double secondpanel, double thirdpanel, double totalpanels, ImageSource window)
        {
            DrawPieChart(black);
            DrawBarChart(firstpanel, secondpanel, thirdpanel, totalpanels);
            DrawImage(window);
        }

        void DrawPieChart(double black)
        {
            var w = (float)bFirstPanel.ActualWidth;
            var h = (float)bFirstPanel.ActualHeight;
            var padding = 0.1f;

            var b = new Bitmap((int)w, (int)h);
            var g = Graphics.FromImage(b);

            var px = padding*w;
            var py = padding*h;

            var pw = w - (2*px);
            var ph = h - (2*py);

            g.DrawEllipse(Pens.Black, px,py,pw,ph);

            g.FillPie(Brushes.Black, px, py, pw, ph, 120, (float)black * 360);

            g.DrawLine(Pens.Black, 30f, h * 0.1f, w / 2 + w * 0.1f, h / 2 - h * 0.1f);
            g.DrawLine(Pens.Black, 30f, h - h * 0.1f, w / 2 - w * 0.2f, h / 2 + h * 0.2f);

            imgFirstPanel.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(b.Width, b.Height));
        }

        void DrawBarChart(double b1, double b2, double b3, double btotal)
        {
            var w = (float)bFirstPanel.ActualWidth;
            var h = (float)bFirstPanel.ActualHeight;
            var padding = 0.1f;

            var b = new Bitmap((int)w, (int)h);
            var g = Graphics.FromImage(b);

            var px = padding * w;
            var py = padding * h;

            var pw = w - (2 * px);
            var ph = h - (2 * py);

            g.DrawLine(Pens.Black, px, py, px, ph+py);
            g.DrawLine(Pens.Black, px, py + ph, px+pw, py+ph);

            var fdrawbar = new Action<int, double>((number, value) =>
                {
                    var height = ph*(float) value/(float) btotal;
                    var width = pw/3f - 4f;

                    var x = px + (pw/3f)*(number-1);
                    var y = py + (ph - height);

                    g.FillRectangle(Brushes.Black, x, y, width, height);
                });

            fdrawbar(1, b1);
            fdrawbar(2, b2);
            fdrawbar(3, b3);

            imgSecondPanel.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(b.Width, b.Height));
        }

        void DrawImage(ImageSource window)
        {
            imgThirdPanel.Source = window;
        }
    }
}

The code isn't cleaned up, but it should be somewhat readable, sorry.

A late entry, but one of the best.

C (with SDL and SDL_ttf): Grayscale solution
Here's a solution that takes advantage of the pie chart form to capture the complete spectrum of grayscale pixel colors, clocking in at just under 100 lines.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "SDL.h"
#include "SDL_ttf.h"

int main(void)
{
    SDL_Surface *screen, *buffer, *caption;
    SDL_Color pal[256];
    SDL_Rect rect;
    SDL_Event event;
    TTF_Font *font;
    int levels[256], plev[256];
    Uint8 *p;
    float g;
    int cr, redraw, hoffset, h, n, v, w, x, y;

    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();
    screen = SDL_SetVideoMode(640, 480, 0, SDL_ANYFORMAT | SDL_RESIZABLE);
    font = TTF_OpenFont(FONTPATH, 24);
    buffer = 0;
    for (;;) {
        if (!buffer) {
            buffer = SDL_CreateRGBSurface(SDL_SWSURFACE, screen->w, screen->h,
                                          8, 0, 0, 0, 0);
            for (n = 0 ; n < 256 ; ++n)
                pal[n].r = pal[n].g = pal[n].b = n;
            SDL_SetColors(buffer, pal, 0, 256);
        }
        memcpy(plev, levels, sizeof levels);
        memset(levels, 0, sizeof levels);
        SDL_LockSurface(buffer);
        p = buffer->pixels;
        for (h = 0 ; h < buffer->h ; ++h) {
            for (w = 0 ; w < buffer->w ; ++w)
                ++levels[p[w]];
            p += buffer->pitch;
        }
        for (n = 1 ; n < 256 ; ++n)
            levels[n] += levels[n - 1];
        redraw = memcmp(levels, plev, sizeof levels);
        if (redraw) {
            SDL_UnlockSurface(buffer);
            SDL_FillRect(buffer, NULL, 255);
            caption = TTF_RenderText_Shaded(font,
                        "Distribution of pixel color in this image",
                        pal[0], pal[255]);
            rect.x = (buffer->w - caption->w) / 2;
            rect.y = 4;
            hoffset = caption->h + 4;
            SDL_BlitSurface(caption, NULL, buffer, &rect);
            SDL_FreeSurface(caption);
            SDL_LockSurface(buffer);
            cr = buffer->h - hoffset;
            cr = (cr < buffer->w ? cr : buffer->w) / 2 - 4;
            p = buffer->pixels;
            for (h = 0 ; h < buffer->h ; ++h) {
                y = h - (screen->h + hoffset) / 2;
                for (w = 0 ; w < buffer->w ; ++w) {
                    x = w - buffer->w / 2;
                    g = sqrtf(x * x + y * y);
                    if (g < cr - 1) {
                        g = atanf((float)y / (x + g));
                        v = levels[255] * (g / M_PI + 0.5);
                        for (n = 0 ; n < 255 && levels[n] < v ; ++n) ;
                        p[w] = n;
                    } else if (g < cr + 1) {
                        p[w] = (int)(128.0 * fabs(g - cr));
                    }
                }
                p += buffer->pitch;
            }
        }
        SDL_UnlockSurface(buffer);
        SDL_BlitSurface(buffer, NULL, screen, NULL);
        SDL_UpdateRect(screen, 0, 0, 0, 0);
        if (redraw ? SDL_PollEvent(&event) : SDL_WaitEvent(&event)) {
            if (event.type == SDL_QUIT)
                break;
            if (event.type == SDL_VIDEORESIZE) {
                SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
                                 SDL_ANYFORMAT | SDL_RESIZABLE);
                SDL_FreeSurface(buffer);
                buffer = 0;
            }
        }
    }
    SDL_Quit();
    TTF_Quit();
    return 0;
}

As with my previous solution, the path to the font file needs to be either hardcoded in the source or added to the build command, e.g.:
gcc -Wall -o xkcdgolf `sdl-config --cflags`
    -DFONTPATH=`fc-match --format='"%{file}"' :bold`
    xkcdgolf.c -lSDL_ttf `sdl-config --libs` -lm

The output of the program looks like this:

This one is fun to watch, because all the math slows down the redraws to where you can see the program zero in on the stable solution. The first estimate is wildly off (since the surface starts out all-black), and then shrinks down to the final size after about a dozen or so iterations.
The code works by taking a population count of each pixel color in the current image. If this population count doesn't match the last one, then it redraws the image. The code iterates over every pixel, but it transforms the x,y coordinates into polar coordinates, computing first the radius (using the center of the image as the origin). If the radius is within the pie chart area, it then computes the theta. The theta is easily scaled to the population counts, which determines the pixel color. On the other hand, if the radius is right on the border of the pie chart, then an anti-aliased value is computed to draw the circle around the outside of the chart. Polar coordinates make everything easy!

You're mostly using the float versions of math-library functions, but then shouldn't fabs be fabsf?

Technically, perhaps, but fabs() is more portable.

True, I've had trouble with that one not being defined in headers even when present in the library. Also there's less performance to be gained than with the transcendentals. :)

C (with SDL and SDL_ttf)
Here's a very simple implementation, in about 60 lines of C code:
#include <stdio.h>
#include "SDL.h"
#include "SDL_ttf.h"

int main(void)
{
    char buf[64];
    SDL_Surface *screen, *text;
    SDL_Rect rect;
    SDL_Color black;
    SDL_Event event;
    TTF_Font *font;
    Uint32 blackval, *p;
    int size, b, prevb, h, i;

    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();
    screen = SDL_SetVideoMode(640, 480, 32, SDL_ANYFORMAT | SDL_RESIZABLE);
    font = TTF_OpenFont(FONTPATH, 32);
    black.r = black.g = black.b = 0;
    blackval = SDL_MapRGB(screen->format, 0, 0, 0);

    b = -1;
    for (;;) {
        prevb = b;
        b = 0;
        SDL_LockSurface(screen);
        p = screen->pixels;
        for (h = screen->h ; h ; --h) {
            for (i = 0 ; i < screen->w ; ++i)
                b += p[i] == blackval;
            p = (Uint32*)((Uint8*)p + screen->pitch);
        }
        SDL_UnlockSurface(screen);
        size = screen->w * screen->h;
        SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 255, 255));
        sprintf(buf, "This image is %.2f%% black pixels", (100.0 * b) / size);
        text = TTF_RenderText_Solid(font, buf, black);
        rect.x = (screen->w - text->w) / 2;
        rect.y = screen->h / 2 - text->h;
        SDL_BlitSurface(text, NULL, screen, &rect);
        SDL_FreeSurface(text);
        sprintf(buf, "and %.2f%% white pixels.", (100.0 * (size - b)) / size);
        text = TTF_RenderText_Solid(font, buf, black);
        rect.x = (screen->w - text->w) / 2;
        rect.y = screen->h / 2;
        SDL_BlitSurface(text, NULL, screen, &rect);
        SDL_FreeSurface(text);
        SDL_UpdateRect(screen, 0, 0, 0, 0);
        if (b == prevb ? SDL_WaitEvent(&event) : SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT)
                break;
            if (event.type == SDL_VIDEORESIZE)
                SDL_SetVideoMode(event.resize.w, event.resize.h, 32,
                                 SDL_ANYFORMAT | SDL_RESIZABLE);
        }
    }

    TTF_Quit();
    SDL_Quit();
    return 0;
}

To compile this, you need to define FONTPATH to point to a .ttf file of the font to use:
gcc -Wall -o xkcdgolf `sdl-config --cflags`
    -DFONTPATH='"/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"'
    xkcdgolf.c -lSDL_ttf `sdl-config --libs`

On most modern Linux machines you can use the fc-match utility to look up font locations, so the compile command becomes:
gcc -Wall -o xkcdgolf `sdl-config --cflags`
    -DFONTPATH=`fc-match --format='"%{file}"' :bold`
    xkcdgolf.c -lSDL_ttf `sdl-config --libs`

(Of course you can replace the requested font with your personal favorite.)
The code specifically requests no anti-aliasing, so that the window contains only black and white pixels.
Finally, I was inspired by @daniero's elegant solution to permit window resizing. You'll see that sometimes the program oscillates between counts, stuck in an orbit around an attractor it can never reach. When that happens, just resize the window a bit until it stops.
And, per request, here's what it looks like when I run it on my system:

Finally, I feel that I should point out, in case anyone here hasn't already seen it, that the MAA published an interview with Randall Munroe in which he discusses the making of cartoon #688 in some detail.

Very nice solution.  Could you possibly put in some screenshots of the program running, following off of @daniero's post? :)

+1, very nice! Thanks for adding the screenshot :) And the interview link is interesting, thanks!

The image is 100x100 and the numbers are exact, and I do mean exact - I chose a 10000 pixel image so that the percentages could be expressed with two decimal places. The method was a bit of math, a bit of guessing, and some number crunching in Python.
Seeing as I knew in advance that the percentages could be expressed in 4 digits, I counted how many black pixels were in each of the digits 0 through 9, in 8 pixel high Arial, which is what the text is written in. I wrote a quick function weight which tells you how many pixels are needed to write a given number, left padded with zeros to have 4 digits:
def weight(x):
    total = 4 * px[0]
    while x > 0:
       total = total - px[0] + px[x % 10]
       x = x / 10
    return total

px is an array mapping digits to number of required pixels. If B is the number of black pixels, and W is the number of white pixels, we have B + W = 10000, and we need:
B = 423 + weight(B) + weight(W)
W = 9577 - weight(B) - weight(W)

Where did the constants come from? 423 is the "initial" number of black pixels, the number of black pixels in the text without the numbers. 9577 is the number of initial white pixels. I had to adjust the amount of initial black pixels several times before I managed to get constants such that the above system even has a solution. This was done by guessing and crossing my fingers.
The above system is horribly non-linear, so obviously you can forget about solving it symbolically, but what you can do is just loop through every value of B, set W = 10000 - B, and check the equations explicitly.
>>> for b in range(10000 + 1):
...     if b == weight(b) + weight(10000 - b)+423: print b;
...
562
564

Maybe do a 250 x 400 image so you can get it to 3 decimal places and display more text in the meantime.

Very nice solution, some brute force math can always solve this kind of problems!

QBasic
Because nostalgia.
And because I don't really know any image libraries in modern languages.
SCREEN 9

CONST screenWidth = 640
CONST screenHeight = 350
CONST totalPixels# = screenWidth * screenHeight

accuracy = 6

newWhite# = 0
newGreen# = 0
newBlack# = totalPixels#

DO
    CLS
    white# = newWhite#
    green# = newGreen#
    black# = newBlack#

    ' Change the precision of the percentages every once in a while
    ' This helps in finding values that converge
    IF RND < .1 THEN accuracy = INT(RND * 4) + 2
    format$ = "###." + LEFT$("######", accuracy) + "%"

    ' Display text
    LOCATE 1
    PRINT "Percentage of the screen which is white:";
    PRINT USING format$; pct(white#)
    LOCATE 4
    PRINT white#; "/"; totalPixels#; "pixels"
    LOCATE 7
    PRINT "Percentage of the screen which is black:";
    PRINT USING format$; pct(black#)
    LOCATE 10
    PRINT black#; "/"; totalPixels#; "pixels"
    LOCATE 13
    PRINT "Percentage of the screen which is green:";
    PRINT USING format$; pct(green#)
    LOCATE 16
    PRINT green#; "/"; totalPixels#; "pixels"

    ' Display bar graphs
    LINE (0, 16)-(pct(white#) / 100 * screenWidth, 36), 2, BF
    LINE (0, 100)-(pct(black#) / 100 * screenWidth, 120), 2, BF
    LINE (0, 184)-(pct(green#) / 100 * screenWidth, 204), 2, BF

    newBlack# = pixels#(0)
    newGreen# = pixels#(2)
    newWhite# = pixels#(15)
LOOP UNTIL black# = newBlack# AND white# = newWhite# AND green# = newGreen#

' Wait for user keypress before ending program: otherwise the "Press any
' key to continue" message would instantly make the results incorrect!
x$ = INPUT$(1)

FUNCTION pixels# (colr)
' Counts how many pixels of the given color are on the screen

pixels# = 0

FOR i = 0 TO screenWidth - 1
    FOR j = 0 TO screenHeight - 1
        IF POINT(i, j) = colr THEN pixels# = pixels# + 1
    NEXT j
NEXT i

END FUNCTION

FUNCTION pct (numPixels#)
' Returns percentage, given a number of pixels

pct = numPixels# / totalPixels# * 100

END FUNCTION

Pretty straightforward output-count-repeat method. The main "interesting" thing is that the program randomly tries different precisions for the percentages--I found that it didn't always converge otherwise.
And the output (tested on QB64):

AWK
... with netpbm and other helpers
The 'x' file:
BEGIN {
        FS=""
        n++
        while(n!=m) {
                c="printf '%s\n' '"m"% black pixels'"
                c=c" '"100-m"% white pixels'"
                c=c" | pbmtext -space 1 -lspace 1 | pnmtoplainpnm | tee x.pbm"
                n=m
                delete P
                nr=0
                while(c|getline==1) if(++nr>2) for(i=1;i<=NF;i++) P[$i]++
                close(c)
                m=100*P[1]/(P[0]+P[1])
                print m"%"
        }
}

The run:
$ awk -f x
4.44242%
5.2424%
5.04953%
5.42649%
5.27746%
5.1635%
5.15473%
5.20733%
5.20733%

The picture is written as 'x.pbm', I converted it to png for uploading:

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


text:
Manufactoria: generate the slowest possible accepting program
Write a Manufactoria program that will accept the empty input tape.  But don't do it quickly!  I mean, write the program quickly, but don't let it run quickly.  The slower the program, the better, as long as it terminates eventually.  The example program below takes 3:51 (the "total time" reported by the simulator).

http://pleasingfungus.com/Manufactoria/?lvl=36&code=g12:5f3;r9:8f1;p12:9f3;c13:9f0;r11:9f0;r10:9f0;r9:9f1;b11:8f0;b10:8f1;r9:7f2;c10:7f2;c11:7f2;c12:7f3;q12:8f3;y13:8f2;y14:8f2;y15:8f1;y15:7f0;y14:7f0;y13:7f0;g12:6f3;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;
Your program starts with the empty tape.  It must doodle around a bit, but eventually reach the output square.  You may leave data on the tape if you wish.  The slowest program on the 7x7 Manufactoria board wins!
Your right arrow key is your friend, it speeds up the simulator.
Bonus points for crashing the simulator!

So there's no requirements for accepting/rejecting input other than the empty tape?

@Volatility: correct.

Annoyingly, the simulator won't report the running time unless the tape is empty at the end, since it doesn't match the challenge's expected output. (Luckily it was easy for me to erase the tape at the end without needing too much extra space.)

~1023 iterations ~1015 iterations ~108 iterations

http://pleasingfungus.com/Manufactoria/?lvl=32&code=g9:7f2;b12:8f2;p13:8f5;p11:8f3;r14:8f0;q11:10f3;q13:7f1;y13:9f1;r10:10f1;c12:9f2;c9:9f2;i11:9f7;i10:9f4;c9:8f3;i10:8f2;c14:9f0;c15:9f0;c15:8f3;c15:7f3;c14:7f2;g12:7f0;c11:7f3;c10:7f2;q9:6f7;r10:6f1;r9:5f3;c11:6f0;r10:5f2;r11:5f1;r9:4f3;r10:4f0;r11:4f0;y12:5f2;y13:5f2;y14:5f3;y14:6f0;y13:6f0;y12:6f0;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;
The machine is basically an odometer running in base three, using the red, blue and yellow symbols to stand for the digits 0, 1, and 2 respectively. The green symbol is used to mark the end of the number. At the start, the tape is initialized with 49 red symbols. This is done by the parts in the top three rows of the machine. The bottom four rows handle the task of incrementing the number in a loop. On each iteration, the two branch cells on left-hand side work out how to apply the increment to current number, and then the branch cells on the right-hand side copy the remaining, unaffected digits.
Previously I've tried to estimate the machine's running time, were it allowed to run to completion, but at this level it makes more sense to just go by the number of iterations. Roughly speaking, it takes about a minute to complete one iteration -- but even if it took a second that would only decrease the running time by a single order of magnitude.

Ok, I give up..

Don't give up! I've no doubt that this is still just scratching the surface. For example, compacting the odometer logic by merely one or two cells would allow an order-of-magnitude increase in running time.

Wow. I knew there must be some way to get a huge time, but my brain has no hope of inventing this.

Very much like I had.  I was able to pack the binary circuit a bit differently, might save a spot or two:

http://pleasingfungus.com/Manufactoria/?lvl=37&code=p10:10f5;r11:10f0;b9:10f2;g9:9f2;i10:9f3;p11:9f2;b11:8f3;q10:8f1;c9:8f3;y12:5f2;y13:5f1;y13:4f2;y14:4f2;y15:4f3;y15:5f3;y15:6f3;c15:7f0;q14:7f4;b14:8f0;b13:8f3;b13:9f3;b13:10f2;b14:10f2;b15:10f1;b15:9f1;c15:8f1;c13:7f0;c12:7f0;c11:7f0;c10:7f0;c9:7f3;c12:9f3;&ctm=Slow_Accepter!;Generate_the_slowest_possible_accepting_machine;:;7;3;0;

I'm trying really hard to fight the urge to delete my answer.

If it helps, I've often submitted golf answers that were way behind the leader, just because it was a different approach. One of the things I love about this site is that it preserves the diversity of responses.

@breadbox, can you explain how this ends? It looks like when you count up to YYY...YG you will copy the whole Y string, leaving GYY..., then copy G back to the end for YYY...YG again, and just repeat that forever. Don't you need GG to end this?

Not that it matters, but you can extend the main loop by a fraction by making the bottom right conveyor take the longer path available

I figured out how it ends myself. After GYY.. the  green gets bumped to the end, and all Ys get converted to Rs by the bottom left. Now G is at the front again, and it fails the B/R test, and finally gets bumped to the end.

Dang, your result is almost the best one could possibly do, being equivalent to 3^50 iterations.

@SimplyBeautifulArt One could conceivably improve by having pairs of symbols be the digits (in which case you could use 15 out of 16 rather than 3 out of 4). Of course, you would run into a lot of difficulty with the small board size in trying to implement that.

603:25

Online test
I was re-reading through the Manufactoria questions today, and suddenly had an idea which would dramatically slow down the process: instead of just having 50 values and changing colours 3 times, the new program does that, but then after that, it decrements the number of values by 1, and goes through the colour-changing again, until there is an empty tape at which time the program stops.
The queue won't store any more than 50 values at one time, so there's no use trying to push too many values onto the tape - they just get pushed off straight away. As before, the conveyor belts aim to maximise the time taken for the thing to run. In fact, there was minimal tweaking down to achieve a tremendous increase in run-time.
Still nowhere near breadbox's answer though.

Interesting how similar our solutions are. We both started with a 9x6 multiplier, and we put the branch and x6 group in the same place! Yours is more elegant though - you used every cell and finished with a clean tape.

33:33
Worked on this for quite a while (Volatility set the bar pretty high), but once I hit 33:33, I thought it was a neat time to stop at.
The strategy is pretty blunt: basically fill up the tape with one colour, then another, then another, and always try to traverse as many cells as possible between each write (or group of writes).
I'm sure there are ways to be found that we can go a lot further with this.

Level link

+1 I'll see what I can do to beat it ;) (although I'll probably not gonna get too far)

3^49*c in 5x5
?lvl=33&code=c10:7f2;c10:8f1;r10:9f2;i11:7f7;p11:8f3;q11:9f5;r12:6f0;y12:7f2;b12:8f2;r13:6f0;q13:7f3;p13:8f5;r13:9f1;r14:7f1;r14:8f3;r14:9f0;r14:6f1;r14:5f0;r13:5f3;i11:6f6;c10:6f1;c10:5f2;g11:5f3;&ctm=Long_Runtime;Level_description!;:*;5;3;0;

Red = 0
Blue = 1
Yellow = 2
After a few cycles, tape is full and, erasing one red add at most one red, the red path(right-up) do nop
Left-top circle only add some cycles

source: Stack Exchange

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

sort: votes


text:
Rubik's Revenge
Everyone likes a good puzzle.  After all, that's the basis for Code Golf and Code Challenge!  What better puzzle exists than the famous Rubik's Cube?  Well what else but her slightly larger sister, the Rubik's Revenge!

Rubik's Revenge Background
Released in 1982 following the success of the classic Rubik's Cube invented by Hungarian sculptor and professor of architecture Ernő Rubik, a Rubik's Revenge is a cubic combination puzzle.
Each face contains sixteen stickers (as opposed to the traditional nine), each of which is one of six colours.  An internal pivot mechanism enables each face to turn independently, effectively mixing up the colours.
The puzzle is solved when each face contains only one colour.
The biggest difference between the Rubik's Revenge and the Rubik's Cube is that the Revenge contains no fixed facets; the two inner facets are freely movable, allowing for every face to move freely.
Move Notation
A move is defined as a change of state for the Rubik's Revenge.  This challenge will stick with the basic 12 moves:

F (Outer Front): the outer side currently facing the solver
f (Inner Front): the inner side currently facing the solver
B (Outer Back): the outer side opposite the front
b (Inner Back): the inner side opposite the front
U (Outer Up): the outer side above (on top of) the front side
u (Inner Up): the inner side above (on top of) the front side
D (Outer Down): the outer side opposite the top (underneath the Revenge)
d (Inner Down): the inner side opposite the top (underneath the Revenge)
L (Outer Left): the outer side directly to the left of the front
l (Inner Left): the inner side directly to the left of the front
R (Outer Right): the outer side directly to the right of the front
r (Inner Right): the inner side directly to the right of the front

All moves are clockwise turns associated with the respective face of the cube.  To denote a counter-clockwise turn, a prime symbol (') is used.  Example moves and their equivalences follow.

Move: b (clockwise inner back)

Rotate the cube clockwise 180° horizontally (such that the back side of the cube now faces the front)
Rotate the inner front face clockwise
Rotate the cube counter-clockwise 180° horizontally (such that the original front side of the cube now faces the front)

Move: l' (counter-clockwise inner left)

Rotate the cube counter-clockwise 90° horizontally (such that the left side of the cube now faces the front)
Rotate the inner front face counter-clockwise
Rotate the cube clockwise 90° horizontally (such that the original front side of the cube now faces the front)

Move: D (clockwise outer down)

Rotate the cube clockwise 90° vertically (such that the down side of the cube now faces the front)
Rotate the outer front face clockwise
Rotate the cube counter-clockwise 90° vertically (such that the original front side of the cube now faces the front)

More examples will be provided upon request.
Color Scheme
The Rubik's Revenge uses six basic colours for each of the stickers on a face.  In this challenge, the colours will be represented as numbers.

White (W): 0
Red (R): 1
Blue (B): 2
Green (G): 3
Yellow (Y): 4
Orange (O): 5

A 2-Dimensional representation of the solved cube is as follows:
        O O O O                        5 5 5 5
        O O O O                        5 5 5 5
        O O O O                        5 5 5 5
        O O O O                        5 5 5 5
G G G G W W W W B B B B        3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B  ===>  3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B  ===>  3 3 3 3 0 0 0 0 2 2 2 2
G G G G W W W W B B B B        3 3 3 3 0 0 0 0 2 2 2 2
        R R R R                        1 1 1 1
        R R R R                        1 1 1 1
        R R R R                        1 1 1 1
        R R R R                        1 1 1 1
        Y Y Y Y                        4 4 4 4
        Y Y Y Y                        4 4 4 4
        Y Y Y Y                        4 4 4 4
        Y Y Y Y                        4 4 4 4

Where the corresponding faces are arranged as follows:
        U U U U
        U U U U
        U U U U
        U U U U
L L L L F F F F R R R R
L L L L F F F F R R R R
L L L L F F F F R R R R
L L L L F F F F R R R R
        D D D D
        D D D D
        D D D D
        D D D D
        B B B B
        B B B B
        B B B B
        B B B B

The Task
In this challenge, the goal will be to write the shortest and most efficient Rubik's Revenge solver.  Efficiency in this challenge is defined with respect to the total number of moves to solve a given input.  Further, to promote the design of good heuristics, each input should run in less than 5 minutes and take less than 1,000 moves to solve.
Input
The input will be a single value consisting of a sequence of the numbers 0-5.  Each input will have exactly 96 digits.  The faces of the Revenge will be represented as the following ranges of numbers within the input:

[0-15] : Front
[16-31] : Right
[32-47] : Back
[48-63] : Left
[64-79] : Up
[80-95] : Down

For a single face, the 16 corresponding digits will be represented as follows:
[ 0][ 1][ 2][ 3]
[ 4][ 5][ 6][ 7]
[ 8][ 9][10][11]
[12][13][14][15]

where the upper left digit (i.e. 0) corresponds to the upper left digit in the 2-dimensional representation above.  The indices of the input sequence corresponding to the spaces on the Rubik's Revenge are as follows:
                [64][65][66][67]
                [68][69][70][71]
                [72][73][74][75]
                [76][77][78][79]
[48][49][50][51][ 0][ 1][ 2][ 3][16][17][18][19]
[52][53][54][55][ 4][ 5][ 6][ 7][20][21][22][23]
[56][57][58][59][ 8][ 9][10][11][24][25][26][27]
[60][61][62][63][12][13][14][15][28][29][30][31]
                [80][81][82][83]
                [84][85][86][87]
                [88][89][90][91]
                [92][93][94][95]
                [32][33][34][35]
                [36][37][38][39]
                [40][41][42][43]
                [44][45][46][47]

An example solved Revenge can be represented as follows:
000000000000000022222222222222224444444444444444333333333333333355555555555555551111111111111111

Where the front face is white (0), the right face is blue (2), the back face is yellow (4), the left face is green (3), the up face is orange (5), and the down face is red (1).
Note that there are many different possible representations of a solved Revenge, depending on the colour of the front face and the overall orientation of the Revenge.
Assume that a valid solution is reachable from any input.
Output
The output should be the sequence of moves taken to find a solution.  The output may or may not have a delimiter between moves; it is up to the coder.
Scoring
Scoring for each test case will be based on the criteria defined in the The Task section.

Points for length are calculated as follows (integer division): 100,000 / (characters in code)
Points for efficiency are calculated as follows (integer division): 500 / (number of moves)

The total points for a single test is the sum of the above two calculations.  The total points for your code will be the sum of the points for all tests.  The winner of the challenge will be the highest number of points.
Note that since your score increases with the fewer amount of moves for a solution, it is recommended to find optimal moves for certain patterns.
To preserve readability, white-space and newlines will not count toward code length.
Tests
Tests will be provided (ideally) within a week of posting.  Each code must run each of the provided inputs and report total score as well as scores for each test.

Since solving the Rubik's Revenge is considerably more difficult than solving the Rubik's Cube and can require many more algorithms to produce optimized solutions, this challenge will be open for an undetermined amount of time.
I project the challenge will remain open for at least three (3) weeks, possibly more.  Suggestions on the length of the challenge are encouraged.
Remember to have fun, and happy coding!

As currently specified, this is asking for a Dijkstra's implementation, which is a) not very interesting, because previous questions have covered that ground; b) unlikely to run to completion in a reasonable time.

@PeterTaylor This is in no way requiring an implementation using Djikstra's Algorithm.  If you feel it is, please let me know how I can reword the post to better promote any type of solution.

It favours optimal solutions and has no time constraints. Ok, there is an even simpler brute-force approach than Dijkstra, but that hardly improves the situation. The most similar existing question has a tough time limit which forces optimal solutions to be very well designed, and pushes people instead to good heuristics.

@PeterTaylor Thank you for the suggestion.  I updated the The Task section to include some limitations on the speed and efficiency of the code.

OMG, @AlexBrooks, I was happy enough resolving the standard cube, 8 panel puzzle and the clock...

Inb4 a solution in Whitespace appears...

Are moves with 2 after the face allowed, or would F2 have to be replaced with F F or F' F'? Also, what orientation is each face in? I assume the F face is right side up, but what about the others?

As per the WCA regulations (https://www.worldcubeassociation.org/regulations/#12a3a), something like F2 will count as 1 move, but F F will be 2. I'm not quite sure I understand your second question

I guess I didn't word it very clearly. In the input, the 80th character represents the color of one of the squares on the D face. Which one? The grid shows that it represents the top left one, but what orientation is the face in?

I see. I've updated the question to address the problem you mention. To ensure clarity, I used the 2-D representation as a means of describing what the top-left digit represents.  For the Back face, the 0 digit corresponds to the DLB (Down-Left-Back) corner.

You have yellow opposite white? On mine, yellow is advacent to white and blue is opposite white.

Could we have some test cases?

So this question can't be scored without test cases. So can we get some of those or put it on hold until we do?

@Liam Yes I am very sorry.  I have honestly forgotten about this post... I will get some test cases out tomorrow.

just a btw whitespace should either count or only text-based programs should be accepted because of this

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


text:
Four fours puzzle
The Four fours puzzle is a popular recreational mathematical puzzle that involves using exactly four 4s (and no other number) and a defined set of operations to reach every number from 0 to a given maximum.
In this version, the only following operators are allowed:

Any grouping symbols may be used
Addition (+), Subtraction (-), Multiplication (*), Division (/)
Factorial (!), Gamma function (Γ)
Exponentiation (^), Square root (√)
Concatenation (eg. 44 is two 4s)
Decimal point (eg. 4.4 is two 4s), Overbar (eg. .4~ = 4/9)

Standard order of operations applies.
Your program should generate, given an input between 0 and 100 inclusive, a correct solution for that input. If the program outputs an invalid solution to any input, that program is invalid.
For example, with an input of 0, your program might generate 44-44.
The use of external modules is not allowed. Only _.4~ is allowed for the overbar operator - that is, only one 4 can be behind the decimal point.
This is code golf, so shortest solution wins.

Edit: To be extra clear, the program must output a set of the above operations applied to exactly four 4s - no more, no less. Also, .4 = 4/10 is a valid term, and counts as using only one 4.

no rounding operations? :-(

@JanDvorak err, no, that wouldn't be allowed.

gamma and factorial are both allowed?

@JanDvorak everthing that is listed (but only the things that are listed) can be used.

are we allowed to output factorial as a prefix function (!(4) rather than (4)!)?

@JanDvorak no, factorial should be postfix, like it normally is.

I've made some ruby code, but I want to wait until it finishes before I upload.

GolfScript (129 chars*)
[4.`2'√4'24'4!'6'Γ4'1'Γ√4'120'ΓΓ4']2/:F{.F=[[44.`]]*\{`{+{'+*-'1/{:^;.[~@[\]{'()'1/*}%^*@@^~\]\}/}:|~2/~\+|;}+F/}%+}3*\{\0==}+?1=

Running time is on the order of 4 minutes on my PC. A moderate speed-up can be obtained at the cost of two characters by adding a uniqueness operation .& immediately after the %+.
I use pre-coded expressions for 1, 2, 4, 6, 24, 120, and 44, and build the rest up from those using only +, *, and -. This way I don't need to do any non-integer arithmetic in the program itself. I've tried to get simpler expressions by placing the simpler pre-coded values at the start.
All of those values are required†, and it's necessary to support both directions of subtraction (complex_expression - simple_expression and vice versa). It's also necessary to include some operations which require parentheses (specifically, a*(b-c)), so I bracket all subexpressions indiscriminately.
* I'm counting Unicode code points assuming the program to be UTF-8 encoded, and brushing under the carpet the fact that unless you're using a recent version of Ruby to run the interpreter it's really treating it as ASCII characters. If you're very worried about this, use G for Gamma and v for sqrt.
† Well, strictly I could remove 44 in exchange for 11 as 44/4 and 71 as √(Γ√4+(ΓΓ4+Γ√4)!), but that's not a good trade-off.

Python 155 bytes
ï»¿h={4:'4',24:'4!',6:'â4',.4:'.4',1:'âû4',4/9.:'.4~'}
f={}
def g(r,s='24',y='4!'):f[eval(s)]=y;[g(r-1,s+o+`k`,y+o+h[k])for k in h for o in'/*-+'if r]
g(3)

The first three bytes (\xEF\xBB\xBF) are the UTF-8 byte order mark, although the file should be saved in an ANSI format. The û and â will be interpretted as √ and Γ respectively in cp437 and cp850, which should work on just about any Windows box.
Runtime is about 0.4s on my computer.
Sample usage (name the file four_fours.py):
$ python
>>> from four_fours import f
>>> f[39]
'4!+4!/.4/4'
>>> f[87]
'4!*4-4/.4~'
>>> for i in range(101): print i, f[i]
0 4!+4!-4!-4!
1 4!+4!/4!-4!
2 4!-4!+Γ4-4
3 4!-4!+4-Γ√4
4 4!+4!/Γ4-4!
.
.
.
96 4!+4!+4!+4!
97 4!*4!/Γ4+Γ√4
98 4!*4+Γ4-4
99 4!*4+4-Γ√4
100 4!*4!/Γ4+4

Results for 0..100. Due to the way the hash is iterated, it prefers to use 4! as often as possible.
Edit: saved a number of bytes by adding Γ√4 = 1, which eliminates the need for any groupings, and by removing √4 = 2, which was no longer necessary.

J, 175 161 chars
   f=.')',~'(',;@((<;._2'+ - * % .4 .4~ g(r(4)) r(4) 4 g(4) 4! ( ) '){~(143402 A.i.9)
      /:~(12,11,0,6$0 4 4)+(9$4 7 7)#:((,@(+/,-/,*/,%/)~)^:2,0.4 4r9 1 2 4 6 24)&i.)

   f 1
(.4+.4)+(.4%r(4))

   f 42
(r(4)+4)+(g(4)*g(4))

   f 100
(r(4)+r(4))+(4*4!)

Checked format is (v op v) op (v op v) where v={0.4 4/9 1 2 4 6 24} and op={+ - * /}
full 0..100 results

I don't think .4 is a valid number for this game.

@JanDvorak it is - maybe I should have made it clearer

05AB1E, 70 69 bytes
•1OF•₂в"(4/9)"ª0.4ª©4ã"+-*/"3ãâε`.ιJ}.Δ.EQ}®¦¨ŽYyç"Γÿ4 Γ4 4! .4~"#:0K

Try it online or verify all test cases.
Explanation:
Uses a similar approach as some of the other answers. Creates all possible combinations of four of the values \$[1,4,6,24,\frac{4}{9},0.4]\$ and three of the operators +-*/ (both of course with duplicates).
•1OF•                       # Push compressed integer 71160
     ₂в                     # Convert it to base-26 as list: [4,1,6,24]
       "(4/9)"ª             # Append "(4/9)": [4,1,6,24,"(4/9)"]
       0.4ª                 # As well as 0.4: [4,1,6,24,"(4/9)",0.4]
           ©                # Store this list in variable `®` (without popping)
4ã                          # Create all possible quartets by using the cartesian product times 4
"+-*/"                      # Push the string "+-*/"
      3ã                    # Create all possible triplets by using the cartesian product times 3
â                           # Create all possible pairs of both lists by using the cartesian product
 ε    }                     # Map each pair of lists by:
  `                         #  Push the list and string separated to the stack
   .ι                       #  Interleave them
     J                      #  And join them together
.Δ                          # Find the first which is truthy for:
  .E                        #  Evaluate the expression-string as Python code
                            #  (NOTE: Unfortunately doesn't work with .4 instead of 0.4)
    Q                       #  And check if it equals the (implicit) input-integer
}®                          # After we've found our result: push the list from variable `®`
  ¦¨                        # Remove the first and last items: [1,6,24,"(4/9)"]
    ŽYy                     # Push compressed integer 8730
       ç                    # Convert it to a character with this unicode: "√"
                            # (`√` isn't part of 05AB1E's codepage, hence why this is necessary)
        "Γÿ4 Γ4 4! .4~"     # Push this string, where the `ÿ` is automatically filled with the "√"
                       #    # Split it on spaces: ["Γ√4","Γ4","4!",".4~"]
                        :   # Replace the [1,6,24,"(4/9)"] with ["Γ√4","Γ4","4!",".4~"]
                         0K # And remove all 0s to convert the "0.4"s to ".4"s
                            # (after which the result is output implicitly)

See this 05AB1E tip (section How to compress large integers? and How to compress integer lists?) to understand why •1OF• is 71160; •1OF•₂в is [4,1,6,24]; and ŽYy is 8730.


text:
Golfing Relay Race
You need to write a program in any language that will produce (source code for) a program in a different language. That program will produce a 3rd program in another language and so on.
You should aim to create many programs; you aren't limited to 3. You can re-use a language, but it won't be counted in the scoring.
Your entry is the source code of the first program, together with a list of the languages of subsequent programs produced in the order they are produced. For easy reading maybe include each program's output/source.
Scoring will be the length of the source code of the first program divided by the number of different languages used.

To prevent solutions such as 1 (that has been pointed out in the comments) I suggest the following extra rule:
The output of one program must not be valid code in the language of that program.

You do know that 1 is at the very least a Golfscript program that outputs a PHP program that outputs an APL program that outputs a J program that outputs a Perl program that outputs nothing, right?

Or what about this non-trivial quine version, going through 50 languages: https://github.com/mame/quine-relay

Similar to http://codegolf.stackexchange.com/questions/2582/golf-a-mutual-quine

@marinus: maybe I should add a rule that states the source code produced for the next language must be invalid in the one producing it.

@marinus: I'm curious what your point is. Are you suggesting that nobody should pose a challenge which can be trivially accomplished with GolfScript? That would make most challenges moot, and render this stackexchange site pointless. Is it perhaps better to consider non-GolfScript solutions worthwhile in spite of the existence of GolfScript?

Many languages accept bare numbers as valid programs that output that number. It has nothing to do with Golfscript per se.

@IgbyLargeman, surely by definition anything which can be "trivially accomplished" isn't a challenge?

@IgbyLargeman: I was just pointing out a loophole in the question that would allow trivial answers like 1 to win, because that would make the question uninteresting. George has indeed fixed it now.

Wow. Did anyone look at the source of the quine-relay? It is even ascii art.

Clojure → C → Python 2.7 → BASIC → Bash
Score: 13.40
(println"int main(){puts(\"print'PRINT\\\"echo\\\"'\");return 0;}")

Here is the breakdown:

Clojure
(println"int main(){puts(\"print'PRINT\\\"echo\\\"'\");return 0;}")

C
int main(){puts("print'PRINT\"echo\"'");return 0;}

Python 2.7
print'PRINT"echo"'

BASIC
PRINT"echo"

Bash
echo

I guess a simpler alternative would be
print'echo'

in Python 2.7, which outputs Bash code. This has a score of 5.5, but isn't as fancy as what's above.

My first time for that kind of challenge:
R > Julia > BrainF**k - 91 characters - Score: 30.33
The initial R code:
cat("'+'^8","\"[>\"","'+'^9","'>'","'+'^13","'>'","'+'^4","'<'^3","\"-]>.>+.>+.\"",sep="*")

It produces the following Julia code:
'+'^8*"[>"*'+'^9*'>'*'+'^13*'>'*'+'^4*'<'^3*"-]>.>+.>+."

Which produces:
++++++++[>+++++++++>++++++++++++++>++++<<<-]>.>+.>+.

which equates to:
Hi!

in BrainF**k.
NB: None of the three programs is valid in any of the two other languages.


text:
Generate cyclic numbers in decimal
The formula on the wiki article for cyclic numbers can be used to generate cyclic numbers in any base. Using this formula, or any other appropriate formula, compute the first ten cyclic numbers in base 10. (The numbers cannot simply be stored and read out, even if the encoding is obscure or novel.)
Repeated cyclic numbers, for example 142857142857, should be avoided if possible.
Output can include 0. if desired, but it is not required. Each number to be delimited by line, space, comma, etc.
The program which is the shortest and which follows the rules as closely as possible will be declared the winner.

GolfScript (30 29 chars)
As xxd output:
0000000: 2207 1113 171d 2f3b 3d61 6d22 7b2e 2831  "...../;=am"{.(1
0000010: 305c 3f2e 402f 2b60 283b 6e7d 25         0\?.@/+`(;n}%

This illustrates the importance of making codegolf problems take input so that the results can't be effectively hard-coded.

It is noted in the question that the answer should be computed, though congratulations on finding a loop hole I forgot to mention -- I suppose this is one of the points of code golf...

@ThomasO, it is computed using the formula you specify - it's just that I've hard-coded the values of the primes rather than looping over all candidates and filtering to the ones which work.

GolfScript (45 44 43 chars but less hard-coded)
110,{:^(.[-1{.10*^%}^*]?={10^(?.^/+`(;n}*}/

This implementation just uses a bound on the possible primes and performs a naïve (but golfed) primitive root check to filter.
Online demo

Nice idea for padding zeros with (;. I'd take this also for my solution ;-)

GolfScript, 60 53 50 characters
107,{))9)1$?.(@)/+`(;.,,{)1$~*`1$.+\?0<}%0-!\n+*}%

A plain loop, checking strings for cyclical identity.
Output:
142857
0588235294117647
052631578947368421
0434782608695652173913
0344827586206896551724137931
0212765957446808510638297872340425531914893617
0169491525423728813559322033898305084745762711864406779661
016393442622950819672131147540983606557377049180327868852459
010309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567
009174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211

Python 77 bytes
p=0;exec"p+=2\nif len(set(10**i%~p for i in range(p)))/p:print-10**p/~p\n"*54

Output:
142857
588235294117647
52631578947368421
434782608695652173913
344827586206896551724137931
212765957446808510638297872340425531914893617
169491525423728813559322033898305084745762711864406779661
16393442622950819672131147540983606557377049180327868852459
10309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567
9174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211

Mathematica 51 67
Cases[Range@110,p_/;10~MultiplicativeOrder~p==p-1:>Round[10^(p-1)/p]]

{142857, 588235294117647, 52631578947368421, 434782608695652173913, 344827586206896551724137931, 212765957446808510638297872340425531914893617,
169491525423728813559322033898305084745762711864406779661,
16393442622950819672131147540983606557377049180327868852459,
10309278350515463917525773195876288659793814432989690721649484536082474226804123711340206185567,
9174311926605504587155963302752293577981651376146788990825688073394495412844036697247706422018348623853211}

Correct. It searches through all numbers in the range, but only primes satisfy the desired constraint.  It would be more efficient to search only among primes, but that would cost some extra characters.

Hmmm.  Ok. I'll correct the code in a bit.


text:
Parse a Python string literal
The challenge is to parse a string like Python does and print the contents of the string.

Input (command-line argument or stdin): a string literal (e.g. "hello") (or multiple literals, see string literal concatenation below)
Output (stdout): the contents of the string (e.g. hello)

Rules for parsing the string:

A string literal is enclosed in matching pairs of single quotes ('a'), double quotes ("a"),  triple single quotes ('''a''') or triple double quotes ("""a""").  The first reoccurrence of the type of quotes that opened the string ends the string.
Backslash escapes: \' within a string becomes ', \" becomes " and \\ becomes \.  You do not need to implement any other backslash escapes.  A backslash that is not part of an escape sequence stays a backslash.
String literal concatenation: The contents of adjacent string literals are concatenated. For example, "hello" 'world' becomes helloworld.
The input may contain spaces that are not part of any literal.
You do not need to support any other kind of whitespace, neither within nor outside literals.

Additional rules:

eval, exec and similar stuff is not allowed for parsing the literal or parts of it.
You may assume that the input is valid.
You may assume a maximum input length of 1023 characters.

Examples:

"hello"  ' world' -> hello world
"""\"""'\\\A""" -> """'\\A
( '''"""'''"""'''""" ) (without parentheses, but with spaces) -> """'''

Shortest code wins.

Is the output to be of a form that can be stored, or is it sufficient to print it and be done with it?

@David Printing it is all you need to do.

So in (e.g.) "\z", the code is specifically required to output the backslash and the z? But ' becomes just an apostrophe, even if it appears inside double-quotes or triple-quotes? Is that correct?

@breadbox Exactly.

Should the code support raw strings? And what about concatenation of non-raw and raw strings?

@Bakuriu You don't need to support raw strings.

Damn, just saw rule 6 - was about to do .E in 05AB1E (legacy) and eval in Python.

Perl, 54 characters
#!/usr/bin/perl -p
s/ |("""|'''|"|')((\\?.)*?)\1/$2/g;s/\\(["'\\])/$1/g

Just as I was posting this, I noticed that it's almost identical to Jan Dvorak's Ruby solution. I'm a little put out by how similar it is, in fact, but I'm going to say "Great minds think alike" and let it go at that.
This program highlights a weird corner case in counting characters in Perl scripts: By my reading, the presence of single-quotes in the script means that I need to count the -p option as two characters towards my total. Typically, when computing Perl script sizes, the initial dash character on the options is considered to be free, on the justification that it can be bundled with the -e that introduces the program proper ... but then you also have to account for any extra escapes you need to enter the script on the command-line. The single-quotes require lots of escaping, so to avoid that penalty I have to count it as a script run from a file, and therefore I get the #!/usr/bin/perl for free, but not any option characters. It's a little confusing.

If you want to be different, (('|")\2{2}?) is the same length as ("""|'''|"|')

C, 178 characters
char*p,*q,b[1024];d;main(t){for(p=q=gets(b);*p=*q++;)
d?*p==92&!(*q-*p&&*q-34&&*q-39)?*p++=*q++:*p-d||t&&*q-d|q[1]-d?++p:
(d=0,q+=2*t):*p-32?d=*p,t=*q==d&q[1]==d,q+=2*t:0;puts(b);}

This is one of those C solutions where everything is done inside a ternary-operator chain gang.
The program works by copying characters back into the same buffer, overwriting the metacharacters. d holds the delimiter when inside of a string, and t is true if the delimiter is a triple-quote.

I think you need to include a conditional extra incrementation of the loop control variable. For 'foo\'bar' it gives foo\ar', which looks like it replaces \ with , but then continues the parsing with the freshly entered , seeing the next token as '.

Actually, that example is invalid input. 'foo\\' refers to the string foo, which is then followed by a character that is neither whitespace nor a string delimiter.

Oops. I misread that rule. Then of course your code is correct.

Ruby, 74 73 characters
puts gets.gsub(/('''|"""|'|")((\\?.)*?)\1|./,'\2').gsub /\\([\\'"])/,'\1'

The core here are two regexes: The first one determines the string boundaries and selects the contents only. The alteration is there to remove everything not inside strings, and it also drops unclosed strings.  Backslashes are treated as possesive-optional followed by anything. Thus,  Since the regex engine will not backtrack into (\\?.) for valid inputs (thanks @breadbox), a sole backslash cannot match there. Quotes are handled via lazy repetition. The second regex then strips a backslash before each escapeable character. The regex depends on the engine to always pick the leftmost alternative first.
I have also considered a state-machine approach, but it turned out quite big (19 states x 4 character classes) compared to the regex solution. I can still post the state machine if anyone is interested.

One minor glitch with this method: 'foo\'bar' becomes foo\ instead of 'foo'bar'.

@manatwork this is correct, unless something has been lost in formatting. The first backslash escapes the second one. 'foo\\' is the first string and bar' is outside a string context when the input is 'foo\\'bar'

Oops. No idea how I calculated it earlier. Of course it is correct. Sorry.

When I try to run this I get an error message: "nested *?+ in regexp". Is there some minimum version or runtime flag that I need?

@breadbox I haven't checked other versions, but I'm running ruby 1.9.3 (JRuby 1.7.2). should I assume 1.9.3 at least and edit that in?

Actually, I'm starting to think it's due to a typo in your posting: The root cause seems to be the (\\?+.) part, and in fact ?+ doesn't make sense in a regex. I think you meant to just type ?.

@breadbox I did mean ?+. ? stands for "optional" (at most once) and + stands for "possesive" (as much as possible and do not backtrack). Does your version of Ruby not support possesive regexes? Which version is  it? I'll do some testing when I'm off mobile.

I used version 1.8.7. Unfortunately I don't have a 1.9 version handy to test on. I have heard of the possessive forms, but forgot about them when I wrote that comment. But wouldn't that mis-parse "\\" ?

@breadbox nope. The first alternation grabs the quote. Then the backreference cannot match, so \\?+ grabs the first backslash, and the period grabs the second one. Then the backreference matches the closing quote. Not having the quantifier possesive would be a bug, because it would allow the period to match \ in "\", which it shouldn't.

Okay, in my head I got the 0-or-1 behavior mixed up with the 1-or-more behavior ... thus my stupid question. (I think you can still use a plain ? though, since you're allowed to "assume that the input is valid". I can't think of a valid input that would cause an incorrect parse.)

Yeah, your're right. A simple greedy optional will suffice here because the engine will never backtrack into $3 if the input is valid. Thanks


text:
Rock, Paper, Scissors, Lizard, Spock
Create a function that will take two strings as input and return a single output for the result.  Most popular answer wins.
The rules of Rock-paper-scissors-lizard-Spock are:

Scissors cut paper
Paper covers rock
Rock crushes lizard
Lizard poisons Spock
Spock smashes scissors
Scissors decapitate lizard
Lizard eats paper
Paper disproves Spock
Spock vaporizes rock
Rock breaks scissors

The output for every possible input case is:
winner('Scissors', 'Paper') -> 'Scissors cut Paper'
winner('Scissors', 'Rock') -> 'Rock breaks Scissors'
winner('Scissors', 'Spock') -> 'Spock smashes Scissors'
winner('Scissors', 'Lizard') -> 'Scissors decapitate Lizard'
winner('Scissors', 'Scissors') -> 'Scissors tie Scissors'
winner('Paper', 'Rock') -> 'Paper covers Rock'
winner('Paper', 'Spock') -> 'Paper disproves Spock'
winner('Paper', 'Lizard') -> 'Lizard eats Paper'
winner('Paper', 'Scissors') -> 'Scissors cut Paper'
winner('Paper', 'Paper') -> 'Paper ties Paper'
winner('Rock', 'Spock') -> 'Spock vaporizes Rock'
winner('Rock', 'Lizard') -> 'Rock crushes Lizard'
winner('Rock', 'Scissors') -> 'Rock breaks Scissors'
winner('Rock', 'Paper') -> 'Paper covers Rock'
winner('Rock', 'Rock') -> 'Rock ties Rock'
winner('Lizard', 'Rock') -> 'Rock crushes Lizard'
winner('Lizard', 'Spock') -> 'Lizard poisons Spock'
winner('Lizard', 'Scissors') -> 'Scissors decapitate Lizard'
winner('Lizard', 'Paper') -> 'Lizard eats Paper'
winner('Lizard', 'Lizard') -> 'Lizard ties Lizard'
winner('Spock', 'Rock') -> 'Spock vaporizes Rock'
winner('Spock', 'Lizard') -> 'Lizard poisons Spock'
winner('Spock', 'Scissors') -> 'Spock smashes Scissors'
winner('Spock', 'Paper') -> 'Paper disproves Spock'
winner('Spock', 'Spock') -> 'Spock ties Spock'

Extra challenge suggested by @Sean Cheshire: Allow custom lists, such as those from this site. With the n-item list, the item loses to the (n-1)/2 previous, and wins over the (n-1)/2 following

Creating a 25-element lookup table isn't a challenge, and being popular isn't a [tag:code-challenge].

Your example is inconsistent with verb forms - "Scissors cut" vs. "Scissors ties". Important?

@ugoren, I guess it should be "Scissors tie".  I could add an 'ScSc': 'tie' entry.

@Peter Taylor, All code can be represented by a lookup table.  Programming is about creating code that is shorter than the most obvious table.

Most interesting problems have an unbounded number of possible inputs, and can't be represented by a finite lookup table. Creating a minimal perfect hash for this particular lookup table might be interesting, but if that's what you're looking for them it should be a code golf rather than a popularity contest.

And when I say that being popular isn't a [tag:code-challenge]: the explanation of that tag begins A code challenge is a competition for creative ways to solve a programming puzzle for an objective criterion other than code size. "Most popular answer wins" is not an objective criterion: you couldn't give the text of two answers to someone and ask them which is the most popular.

There are many code challenges on the site that are decided by upvotes without any criteria as to why someone should upvote.  You should be familiar with this one .

@PeterTaylor, dansalmo is right, so long as that lookup table is in a loop: this is a famous theorem of Conway: http://en.wikipedia.org/wiki/FRACTRAN

@dansalmo The challenge you link to was created before the existence of the [tag:popularity-contest] tag.

A suggestion to add to the challenge - Allow custom lists, such as those from this site that go up to 101 items. With the n-item list, the item loses to the (n-1)/2 previous, and wins over the (n-1)/2 follwing

@primo, it would be helpful to new users if the more knowledgeable users could update the wiki to explain the popularity-contest tag and that it is mutually exclusive with code-challenge.

This would be a great challenge as a [tag:code-golf] [tag:kolmogorov-complexity] challenge, but I'm going to vote to close it since there is no winning criteria or any good reason it should be a popularity contest.

APL
vs←{
    n←'Scissors' 'Paper' 'Rock' 'Lizard' 'Spock'
    x←n⍳⊂⍺ ⋄ y←n⍳⊂⍵ ⋄ X←⍺ ⋄ Y←⍵ ⋄ r←{X,⍵,⊂Y}
    x=y:     r (-x=0)↓'ties'
    y=5|1+x: r x⌷'cut' 'covers' 'crushes' 'poisons' 'smashes'
    y=5|3+x: r x⌷'decapitate' 'disproves' 'breaks' 'eats' 'vaporizes'
    ⍵∇⍺
}

Output exactly as required in all cases, including tie/ties. No lookup table, except for the actual words.
You can try it on http://ngn.github.io/apl/web/
'Spock' vs 'Paper'
Paper  disproves  Spock

APL just knows!

+1, Never noticed APL until now.  Mesmerizing. Your structure is also cool.  I like the last line the best.

@dansalmo Thanks :) I like it a lot. And now thanks to https://github.com/ngn/apl we have an open source and web-ready interpreter (for decades there were only commercial interpreters)

@dansalmo btw, APL is a perfect fit for the kind of functional coding you seem to be doing in Python (which I like to do as well)

SED
#!/bin/sed
#expects input as 2 words, eg: scissors paper

s/^.*$/\L&/
s/$/;scissors cut paper covers rock crushes lizard poisons spock smashes scissors decapitates lizard eats paper disproves spock vaporizes rock breaks scissors/
t a
:a
s/^\(\w\+\)\s\+\(\w\+\);.*\1 \(\w\+\) \2.*$/\u\1 \3 \u\2/
s/^\(\w\+\)\s\+\(\w\+\);.*\2 \(\w\+\) \1.*$/\u\2 \3 \u\1/
t b
s/^\(\w\+\)\s\+\1;\(\1\?\(s\?\)\).*$/\u\1 tie\3 \u\1/
:b

This is... diabolical.

Here is a general solution based on a rule string of any size.  It performs correct capitalization for the proper name "Spock" and also allows rules for specifying 'tie' instead of 'ties' for plural objects.
def winner(p1, p2):
    rules = ('scissors cut paper covers rock crushes lizard poisons Spock'
    ' smashes scissors decapitate lizard eats paper disproves Spock vaporizes'
    ' rock breaks scissors tie scissors'.split())

    idxs = sorted(set(i for i, x in enumerate(rules)
                      if x.lower() in (p1.lower(), p2.lower())))
    idx = [i for i, j in zip(idxs, idxs[1:]) if j-i == 2]
    s=' '.join(rules[idx[0]:idx[0]+3] if idx
          else (rules[idxs[0]], 'ties', rules[idxs[0]]))
    return s[0].upper()+s[1:]

Results:
>>> winner('spock', 'paper')
'Paper disproves Spock'
>>> winner('spock', 'lizard')
'Lizard poisons Spock'
>>> winner('Paper', 'lizard')
'Lizard eats paper'
>>> winner('Paper', 'Paper')
'Paper ties paper'
>>> winner('scissors',  'scissors')
'Scissors tie scissors'

When defining rules you can use a multiline string instead of literal concatenation. This allow you to remove the redundant parentheses.

Python
class Participant (object):
    def __str__(self): return str(type(self)).split(".")[-1].split("'")[0]
    def is_a(self, cls): return (type(self) is cls)
    def do(self, method, victim): return "%s %ss %s" % (self, method, victim)

class Rock (Participant):
        def fight(self, opponent):
                return (self.do("break", opponent)  if opponent.is_a(Scissors) else
                        self.do("crushe", opponent) if opponent.is_a(Lizard)   else
                        None)

class Paper (Participant):
        def fight(self, opponent):
                return (self.do("cover", opponent)    if opponent.is_a(Rock)  else
                        self.do("disprove", opponent) if opponent.is_a(Spock) else
                        None)

class Scissors (Participant):
        def fight(self, opponent):
                return (self.do("cut", opponent)       if opponent.is_a(Paper)  else
                        self.do("decaitate", opponent) if opponent.is_a(Lizard) else
                        None)

class Lizard (Participant):
        def fight(self, opponent):
                return (self.do("poison", opponent) if opponent.is_a(Spock) else
                        self.do("eat", opponent)    if opponent.is_a(Paper) else
                        None)

class Spock (Participant):
        def fight(self, opponent):
                return (self.do("vaporize", opponent) if opponent.is_a(Rock)     else
                        self.do("smashe", opponent)    if opponent.is_a(Scissors) else
                        None)

def winner(a, b):
    a,b = ( eval(x+"()") for x in (a,b))
    return a.fight(b) or b.fight(a) or a.do("tie", b)

Scissors are plural, so "cuts" paper and "decaitates" lizard" is wrong (the last one misses a P too) . And "Spock smashs" should be "smashes" ;)

@daniero, thanks. I noticed the scissors problem, but fixing it complicates things. Fixing "smashes" now.

@Daniel "Scissors" is plural.  "Scissors" is also singular. See http://en.wiktionary.org/wiki/scissors

So subtle. Love it.

Ruby, arithmetic approach
The actors can can be arranged in an array in such a way that each actor a[i] wins against the actors a[i+1] and a[i+2], modulo 5, for instance:
%w(Scissors Lizard Paper Spock Rock)

Then, for an actor A with index i we can see how he matches agains actor B with index j by doing result = (j-i)%5: Result 1 and 2 means that actor A won against an actor 1 or 2 places in front of him respectively; 3 and 4 similarly means he lost against an actor behind him in the array. 0 means a tie. (Note that this may be language dependent; in Ruby (j-i)%5 == (5+j-i)%5 also when j>i.)
The most interesting part of my code is the use of this property to find a sorting function of the indices of two actors. The return value will be -1, 0 or 1 as it should:
winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

Here's the whole thing:
def battle p1,p2
    who = %w(Scissors Lizard Paper Spock Rock)
    how = %w(cut decapitate poisons eats covers disproves smashes vaporizes crushes breaks)
    i,j = [p1,p2].map { |s| who.find_index s }

    winner,loser = [i,j].sort { |x,y| ((y-x)%5+1)/2-1 }

    method = (winner-loser)%5/2
    what = method == 0 && "ties" || how[winner*2 + method-1]

    return "#{who[winner]} #{what} #{who[loser]}"
end

Python
def winner(p1, p2):
    actors = ['Paper', 'Scissors', 'Spock', 'Lizard', 'Rock']
    verbs = {'RoLi':'crushes', 'RoSc':'breaks', 'LiSp':'poisons',
             'LiPa':'eats', 'SpSc':'smashes', 'SpRo':'vaporizes',
             'ScPa':'cut', 'ScLi':'decapitate', 'PaRo':'covers',
             'PaSp':'disproves', 'ScSc':'tie'}
    p1, p2 = actors.index(p1), actors.index(p2)
    winner, loser = ((p1, p2), (p2, p1))[(1,0,1,0,1)[p1 - p2]]
    return ' '.join([actors[winner],
                     verbs.get(actors[winner][0:2] + actors[loser][0:2],
                               'ties'),
                     actors[loser]])

By the way, "looser" is the opposite of "tighter".  "Loser" is the opposite of "winner".  And it'll save you a few characters in your code.

Python

  def winner(p,q):
        if p==q:
           return(' '.join([p,'tie',q]))
        d = {'ca':'cut','ao':'covers','oi':'crushes','ip':'poisons','pc': 'smashes','ci':'decapitate','ia':'eats', 'ap':'disproves', 'po':'vaporizes','oc': 'breaks'}
        [a,b] = [p[1],q[1]]
        try:
           return(' '.join([p,d[a+b],q]))
        except KeyError:
           return(' '.join([q,d[b+a],p]))

Using a tricky dictionary.

Nice one.  return(' '.join([p,'tie' + 's'*(p[1]!='c'),q])) will get the verb tense correct.

C#
Assumptions
The opponents are arranged in an n-item array where players beat the (n-1)/2 players ahead of them and lose to the (n-1)/2 players behind them. (With even length lists, the player loses to the ((n-1)/2 + 1) players behind them)
Player actions are arranged in an array where actions within the range of [(indexOfPlayer * (n-1)/2)] to [(indexOfPlayer * (n-1)/2)) + (n-2)/2 - 1].
Additional Info
CircularBuffer<T> is a wrapper around an array to create an "infinitely" addressable array. The IndexOf function returns the index of an item within the actual bounds of the array.
The Class
public class RockPaperScissors<T> where T : IComparable
{
    private CircularBuffer<T> players;
    private CircularBuffer<T> actions;

    private RockPaperScissors() { }

    public RockPaperScissors(T[] opponents, T[] actions)
    {
        this.players = new CircularBuffer<T>(opponents);
        this.actions = new CircularBuffer<T>(actions);
    }

    public string Battle(T a, T b)
    {
        int indexA = players.IndexOf(a);
        int indexB = players.IndexOf(b);

        if (indexA == -1 || indexB == -1)
        {
            return "A dark rift opens in the side of the arena.\n" +
                   "Out of it begins to crawl a creature of such unimaginable\n" +
                   "horror, that the spectators very minds are rendered\n" +
                   "but a mass of gibbering, grey jelly. The horrific creature\n" +
                   "wins the match by virtue of rendering all possible opponents\n" +
                   "completely incapable of conscious thought.";
        }

        int range = (players.Length - 1) / 2;

        if (indexA == indexB)
        {
            return "'Tis a tie!";
        }
        else
        {
            indexB = indexB < indexA ? indexB + players.Length : indexB;
            if (indexA + range < indexB)
            {
                // A Lost
                indexB = indexB >= players.Length ? indexB - players.Length : indexB;
                int actionIndex = indexB * range + (indexA > indexB ? indexA - indexB : (indexA + players.Length) - indexB) - 1;

                return players[indexB] + " " + actions[actionIndex] + " " + players[indexA];
            }
            else
            {
                // A Won
                int actionIndex = indexA * range + (indexB - indexA) - 1;

                return players[indexA] + " " + actions[actionIndex] + " " + players[indexB];
            }
        }
    }
}

Example
string[] players = new string[] { "Scissors", "Lizard", "Paper", "Spock", "Rock" };
string[] actions = new string[] { "decapitates", "cuts", "eats", "poisons", "disproves", "covers", "vaporizes", "smashes", "breaks", "crushes" };

RockPaperScissors<string> rps = new RockPaperScissors<string>(players, actions);

foreach (string player1 in players)
{
    foreach (string player2 in players)
    {
        Console.WriteLine(rps.Battle(player1, player2));
    }
}
Console.ReadKey(true);

Python, one-liner
winner=lambda a,b:(
    [a+" ties "+b]+
    [x for x in
        "Scissors cut Paper,Paper covers Rock,Rock crushes Lizard,Lizard poisons Spock,Spock smashes Scissors,Scissors decapitate Lizard,Lizard eats Paper,Paper disproves Spock,Spock vaporizes Rock,Rock break Scissors"
        .split(',')
     if a in x and b in x])[a!=b]

Very cool!  You can .split(', ') and not have to jam,the,rules,together.

@dansalmo, Thanks, But I see no harm in JammingTheRulesTogether. Though it isn't a golfing contest, I think the shorter the better.

Just a small thing I came up with:
echo "winners('Paper', 'Rock')"|sed -r ":a;s/[^ ]*'([[:alpha:]]+)'./\1/;ta;h;s/([[:alpha:]]+) ([[:alpha:]]+)/\2 \1/;G"|awk '{while(getline line<"rules"){split(line,a," ");if(match(a[1],$1)&&match(a[3],$2))print line};close("rules")}' IGNORECASE=1

Here, rules is the file containing all the rules that were given.

Python
Inspired by @Tobia's APL code.
def winner(p1, p2):
  x,y = map(lambda s:'  scparolisp'.find(s.lower())/2, (p1[:2], p2[:2]))
  v = (' cut covers crushes poisons smashes'.split(' ')[x*(y in (x+1, x-4))] or
       ' decapitate disproves breaks eats vaporizes'.split(' ')[x*(y in (x+3, x-2))])
  return ' '.join((p1.capitalize(), v or 'tie'+'s'*(x!=1), p2)) if v or p1==p2 \
    else winner(p2, p1)

Results:
>>> winner('Spock', 'paper')
'Paper disproves Spock'
>>> winner('Spock', 'lizard')
'Lizard poisons Spock'
>>> winner('paper', 'lizard')
'Lizard eats paper'
>>> winner('paper', 'paper')
'Paper ties paper'
>>> winner('scissors',  'scissors')
'Scissors tie scissors'

C++
#include <stdio.h>
#include <string>
#include <map>
using namespace std ;
map<string,int> type = { {"Scissors",0},{"Paper",1},{"Rock",2},{"Lizard",3},{"Spock",4} };
map<pair<int,int>, string> joiner = {
  {{0,1}, " cuts "},{{0,3}, " decapitates "}, {{1,2}, " covers "},{{1,4}, " disproves "},
  {{2,3}, " crushes "},{{2,0}, " crushes "},  {{3,4}, " poisons "},{{3,1}, " eats "},
  {{4,0}, " smashes "},{{4,2}, " vaporizes "},
} ;
// return 0 if first loses, return 1 if 2nd wins
int winner( pair<int,int> p ) {
  return (p.first+1)%5!=p.second && (p.first+3)%5!=p.second ;
}
string winner( string sa, string sb ) {
  pair<int,int> pa = {type[sa],type[sb]};
  int w = winner( pa ) ;
  if( w )  swap(pa.first,pa.second), swap(sa,sb) ;
  return sa+(pa.first==pa.second?" Ties ":joiner[pa])+sb ;
}

A bit of a test
int main(int argc, const char * argv[])
{
  for( pair<const string&, int> a : type )
    for( pair<const string&, int> b : type )
      puts( winner( a.first, b.first ).c_str() ) ;
}

Javascript
function winner(c1,c2){
    var c = ["Scissors", "Paper", "Rock", "Lizard", "Spock"];
    var method={
        1:["cut", "covers", "crushes", "poisons", "smashes"],
        2:["decapitate", "disproves", "breaks", "eats", "vaporizes"]};
    //Initial hypothesis: first argument wins
    var win = [c.indexOf(c1),c.indexOf(c2)];
    //Check for equality
    var diff = win[0] - win[1];
    if(diff === 0){
        return c1 + ((win[0]===0)?" tie ":" ties ") + c2;
    }
    //If s is -1 we'll swap the order of win[] array
    var s = (diff>0)?1:-1;
    diff = Math.abs(diff);
    if(diff >2){
        diff = 5-diff;
        s= s * -1;
    }
    s=(diff==1)?s*-1:s;
    if(s === -1){
        win = [win[1],win[0]];
    }
    return c[win[0]] + " " + method[diff][win[0]] + " " + c[win[1]];
}

Javascript
I see this isn't a golfing contest, but I had been fiddling with this puzzle for a while before finding this thread, so here goes.
Here's a (standard) js version in 278 characters:
function winner(a,b){var c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5;return i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b}

Or one using E6 features (likely only works in Firefox) in 259 characters:
winner=(a,b,c={rock:0,paper:1,scissors:2,spock:3,lizard:4},d="crushe,crushe,cover,disprove,cut,decapitate,smashe,vaporize,poison,eat".split(","),i=c[a],j=c[b],I=i==(j+3)%5)=>i^j?i==(j+1)%5||I?a+" "+d[i*2+I]+"s "+b:b+" "+d[j*2+(j==(i+3)%5)]+"s "+a:a+" ties "+b