text:
Program a 2048 AI using an existing Framework

EDIT : Recently, my question has been proposed as a duplicate of 2048 Bot Challenge. I would like to stress that this question is different from that question, and will require answers to be thought of differently than that question. 2048 Bot Challenge asked the user to create a bot, and it would be run for an hour, with the highest score being the user's score. Additionally, it had a limit of 555 bytes. My challenge runs the code much less frequently, only 3 times. Your score is calculated by using the average score of those three times and dividing by the character length of your golfed code. My question encourages entries to be "smarter," and not try and get the highest score by brute force.

-

EDIT: The get method was changed to getTile, to avoid confliction with the JS keyword get. Additionally, a high score section was added.

Recently, I created a site that allows the popular game 2048 to be controlled using JavaScript. My site is linked here:
http://thatcoolidea.com/2048
How:
An Ace Editor is located above the board. You place code in it, which is run once every 250 ms, or 4 times per second. This is called a cycle.
Use the following methods to control the board. You can't use the arrow keys.
up();            //move up
down();          //move down
left();          //move left
right();         //move right

move(integer);   //integer is a direction. 0:up,1:right,2:down,3:left

getTile(y,x);        //gets the value of the tile in position y,x on the board. See diagram

The following variables are defined for your convenience:
eother        //boolean, alternates every cycle
frozen        //integer, counts how many cycles the board has remained stationary
lastDir       //integer, indicates the last direction that was tried to move in
              //uses same format as the move method above.
startup       //boolean, will always be true when the game first starts
              //you can change it as you wish
a
b             //a b and c are all persistant variables, they do not change each cycle
c             //any other variables defined in the cycle will be reset every time

Rules:

No Randomness, you must use logic. (Yes, I know the example code uses random.)
No hooking into the game functions or cheating in other ways
Generally, try to only call one move method per cycle. It is OK if you use more, but it screws with the animation
The board must start in a random state, no modification of pre-game state
You must provide both the uncompressed and golfed version of the code in your post.
You must provide a link to the site that already loads the uncompressed version of your code, served via PasteBin (For example, ...thatcoolidea.com/2048?i=pH18GWtu loads the example code.)

Scoring:

Your code will be scored by me.
Part A of your score is an average of 3 runs of the code, rounded down.
Part B of your score is the character length of your golfed code.
Your final score is Part A divided by Part B

The winner will have their code immortalized as the example code on the site, if they choose, and acknowledged in a comment in the code.
Good luck! Hope you enjoy the challenge.
Current High Score
225.22 - Freezer - user3217109

The fact that you've written a framework for 2048 is pretty awesome and very convenient for this type of challenge, but I don't see how it actually affects any of the strategies already found in our existing 2048 AI challenge.

Well I would say that mine Is different, simply because you are required to use one code base which will be the same each execution. This is much more user friendly and I don't think it would constitute a duplicate.

The other question looks pretty dead. There were only four answers and a time limit of an hour, so I'm going to answer because this looks really cool.

@samweaver add a note to the top of your question to explain why answers from the other question wouldnt be valid/competitive for your question, and then create a meta post for scrutiny.

If you cant do that, you will likely need to change your challenge in order to get it re-opened e.g. rules/scoring/restrictions

Clarified. Please enlighten me to create a meta post, I am not aware of the proper procedure. I am new to the SO scene.

@SamWeaver each SO site has an accompanying meta site in which users can ask about and discuss site policy. You can ask a question here and you may want to look at a few other meta questions to get a feel for what they're like. From what I've seen, you can directly reference your question in your meta question.

I always remember this SO post each time there is a 2048 bot challenge, because his solution is so cool, achieving tile 8192 everytime on 100 runs.

That's very very nice.

I will get to grading all the new submissions tomorrow. Sorry for the delay. :P

Sinker/Shaker, 65 bytes
Here's mine. It's as blind and simple as they come.
if(startup){startup=false;a=0}b=(a++)%4;move(frozen>2?0:b==0?2:b)

Uncompressed(ish)...
if(startup){startup=false;a=0;}
b=(a++)%4;
move(frozen>2?0:b==0?2:b)

All it does is repeats down, right, down, left, etc. and hits up once if it gets stuck. It doesn't always do very well, but it'll occasionally get 512s. My high score during testing was 7520.

I am beginning the scoring process now! Thanks for the first entry!

Final Score: 67.6!
Run 1: 3980
Run 2: 4080
Run 3: 5128
I really liked this, I didn't envision you could get such a high score with such a small bot.

Thanks for setting it up! I think it's pretty cool. It's sad that people have reacted this way so far. SO users tend to be very negative towards duplicate questions, usually for good reasons.

Why thank you! I appreciate the support! This project originated from when a friend and I stayed late at work one night and wanted to see who could make the better bot. I searched through the code, but I couldn't find a way to do it well. I built this with the helper methods to make it so much easier!

Traffic light - 23 21 bytes
move(frozen&2|eother)

This is the link.
This will move alternatingly up and right, except when the board has remained stationary for the last two moves, in which case it will move down and left respectively.
My original, functionally equivalent submission was 23 bytes long and scored 182.72:
move((frozen&2)+eother)

This is pretty much the same thing I do when I play quickly without really looking at the board.

Excellent work.
Run 1: 2208
Run 2: 1216
Run 3: 2336
23 bytes
Final Score: 182.72

Whirlpool - 37 21 17 bytes - Score: 211.22
I decided to go with a "less is more" approach. My code is a simple design that tries to go up, right, down, left... I will be working on a learning AI to see a more optimal way to approach the puzzle.
a=a|0;move(a++%4)

Optimizer helped to shorten a's initialization.
Sam helped to shorten a's initialization, removed var.
Ungolfed?
var a=a|0;
a++;
move(a%4);

My top score with this AI is 5120.
Freezer - 12 bytes - Score: 225.22
This bot has move priority. It attempts to go up. If it can' go up, it goes right. If it can't go right, it does down. If it can't go down it goes left.
move(frozen)

James Bond Explanation
The encrypted code decrypts to say:
HTMLActuator.prototype.updateScore=function (score) {score*=9989800000;
  this.clearContainer(this.scoreContainer);

  var difference = score - this.score;
  this.score = score;

  this.scoreContainer.textContent = this.score;

  if (difference > 0) {
    var addition = document.createElement("div");
    addition.classList.add("score-addition");
    addition.textContent = "+" + difference;

    this.scoreContainer.appendChild(addition);
  }
}

Optimizer should have golfed his decrypted code. This could have been #Optimized.

You have to actually define a too. So that should be added in the code length.

Unfortunately, the backend preserves variables through resets, so you can define/initialize a once and forget about it, but if you close the tab/window and come back to it, I don't think it will work anymore. This is why I had to add the if(startup) bit on mine.

you can use var a=a|0;move(a++%4) - 21 bytes

Thank you! I have never used javascript before, so I will make mistakes like that...

Actually, A does not need to be defined. A is defined in the backend, so you can reference it using just a without doing var a

In fact, in my browser, the code won't run unless I remove the var declaration. Consider your code 4 bytes less. :)

Whirlpool:
Run 1: 3144
Run 2: 3132
Run 3: 4496
17 bytes
Final Score: 211.22

Freezer:
Run 1: 1644
Run 2: 3628
Run 3: 2836
12 bytes
Final Score: 225.22

Well done! I would never have thought of the idea for Freezer. I apologize about the issue with get, I forgot to update this page after it was changed to getTile. I realize it is more bytes, but it is necessary to avoid conflicting with the JS keyword get. Original Post updated.

I should be less surprised that small code gets such higher scores. @Optimizer I'm tempted to steal that a=a|0; init, it's pretty slick.

I can't get whirlpool to work - it appears to be moving upwards every time.

Hanger - 20 bytes
Official score: 224.87 - 2nd place by 0.35 points
This bot uses the down, left, down, right approach, but with the unusual feature that it will never move up. I'm not sure how to score cases where it hangs and does not complete, or whether the fact that that occurs renders it illegal. Here it is, though:
b=b|0;move(b++%4||2)
OR
move(startup++%4||2)

Initialization pattern thanks to @Optimizer.
In my 3 test runs, it scored 4284, 6352 and 4232, for an average of 4956. I will update when the official test is run.

Alternate version which gets out of hangs (27 bytes):
b=b|0;move(b++%4||b%997&&2)

No need to leave a hang, the score will just be measured there as if the game was over.

How does the last one get out of hangs?

@krs013 The last one will move up once every 4*997 cycles, so if up is the only way to move, it will move up.

Gotcha. I wondered if it was something like that; I just didn't wait long enough, I guess.

Final Score: 224.87, great job!

@SamWeaver Thanks! What were the individual scores, if you have them?

3384, 6868, and 3240.


text:
Un-hash the Java Hash
Hash Un-hashing
The basic goal of this challenge is to exploit the high probability of collision in the Java Hash function to create a list of plausible inputs that created an outputted hash. The program that can print the most results in one hour wins.
For example, hashing golf produces the number 3178594. Other 'words' you could hash to get the same number would be: hQNG, hQMf, hPlf
Details
The basic Java hash function is defined as:
function hash(text){
    h = 0;
    for(i : text) {
        h = 31*h + toCharCode(i);
    }
    return h;
}

You can use an altered or more efficient variant of the hash function (such as using bitwise to replace multiplication) if it produces the same results.
If your language of choice does not use signed ints or have integer overflow, you must implement a wrap function in the hash to emulate integer overflow so that 2147483648 would overflow to -2147483648.
You can choose not to worry about inputs that wrap around multiple times, such as those with 6-7 characters or more. If you choose to include those, you have a better chance of winning.
Additional Requirements

Your code should have at least one input: the hash itself. An optional second input is the maximum number of letters to guess. For example, guessHash(53134) might produce a list of all input combinations up to the absolute maximum amount (see the next requirement), and guessHash(53134, 4) will display all input combinations that contain 1-4 letters.
As there are an infinite amount of results, the most letters that can be in a single result will be set at 256. If your program can manage to output all 256 letter results in a reasonable amount of time (see next requirement), you automatically win.
Your program should not run for more than an hour on any non-specialized computer you use. Non-specialized means it can't run on a server system using 256 different cores or on a super-computer, it must be something that any regular consumer would/could buy. The shorter time period is for practicality, so that you don't have to use all your processing power for too long.
All the results in your final list of inputs must produce the same hash as the inputted hash.
You are to implement your own search, brute-force, or any algorithm to produce the final list.
Using a native search method or search method from another library is not allowed (example: binary search library). Using String.search(char) or Array.find(value) is okay if it is not a primary feature of your search algorithm (such as to spot duplicate results or find if a letter exists in given string).
The final list of input values should use all readable ASCII characters (32 to 126).

Example
I went ahead and created a very inefficient version of this challenge to produce an example list! Each result I gave is separated by spaces, although you can print each result on a new line or any other readable method of organization.
i30( i3/G i2NG hQNG hQMf hPlf golf

You do not have to print results to a file, just record how many results you get.
Judging
The number to un-hash is: 69066349
I will pick the best answer based on which-ever code produces the most results.  If you remember above where I said wrapping was optional, it'd be a good idea to include multiple wrappings if you want the most results in your final list.

If you have any questions or additional comments, feel free to ask.
Good Luck!

Great trolling: state that the question is about "Java" and then provide a JavaScript code snippet.

You say "this code golf" but the judging is not by character count?

Also the question states that characters should be ASCII, but provides a list including many non-ASCII characters. It appears Latin-1 instead of ASCII was desired.

@xnor Sorry about that! I'm a tad bit new and haven't picked up on all the terminology in the community!

@feersum The code snippet was meant to be as non-language specific as possible, but yeah, it's almost JavaScript. And again, sorry about that, I first had it as the 33-127 ASCII characters, but later switch to include Latin-1 character set without going back and changing the definition. Fixing that.

I don't think you have to worry about a program finding all preimages. With 256 characters out of a pool of 155, each with a probability of 2**-64 of matching the given hash (to give a rough estimate), there are 155**256/2**64 preimages.

That's 28773653479426574679752045985983708651314241076486969565840047647896492733218091801018247637865462591153254380909630939358483142387095514874963147201793135934206287462851566531896641573510502833532739091940091000563990339507011267238877057288024527221865244498474278775782301655262770952804980910234712459807545306017935605110278792039014148511645685233861391147234783503715268543704093987748985203419178705457137415361429762778270019610641592268726043290782629279945031794639464412329913307721831669515436033160513633497782473587351945837412 preimages.

@Dennis Shouldn't that be 2^-32 ? And why wouldn't we worry, given that there is no runtime limit, or anything else that would prevent a brute force generation of every possible string...

@feersum in the second additional requirement, I did specify that the program can not run for more than a day. I should have probably made it a new requirement or made it stand out instead of hiding it in parenthesis though.

@feersum: Yes, don't know where I got 64 bits from... So the number is a few digits bigger. The question specifies a time limit of a day. To find all preimages, you'd have to find (not try) 10**444 of them every second to finish before the universe's estimated death.

What's the rationale behind the limitations on characters and libraries? This seems like a potentially fun challenge, but I don't see the restrictions making it any more fun.

@James_pic For the character sets, I did that because using the readable ASCII characters 32-126 doesn't create many results. I guess it doesn't make much sense either to then switch to Latin-1, but remove a lot of the characters. I'll switch it back to the readable ASCII 32-126.
For libraries, I want people to write a search algorithm on their own. The project is basically implementing a search or brute-force algorithm to find each results, it wouldn't be much fun if people used a preexisting libraries to get results. I will lift some of those restrictions though.

What about libraries that have nothing to do with hashing, brute-forcing, or cryptography? For example, if I want to use an obscure data structure that isn't included in my language's standard library.

@James_pic I removed the restriction on most libraries. Use anything as long as you don't use it for searching/brute-force.

If your program can manage to output all 256 letter results in a reasonable amount of time (see next requirement), you automatically win. Looks like its already a tie!

C, 3.2 × 1010 preimages
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char output[29] = { 0 }, preimages[64][8], zeros[512][8] = { "/*$+06(" };
    unsigned i, j, k, l, t;

    t = atoi(argv[1]);

    for(i = 7; i --> 0; t /= 31)
        preimages[0][i] = zeros[0][i] + (t % 31);

    for(i = 0, j = 2, k = 1; i < 6; i += 1, j *= 2)
        for(l = 0; k < j; k++, l++)
            strcpy(preimages[k], preimages[l]),
            preimages[k][i] -= 1,
            preimages[k][i + 1] += 31;

    for(i = 0, j = 3, k = 1; i < 6; i += 1, j *= 3)
        for(l = 0; k < j && k < 512; k++, l++)
            strcpy(zeros[k],zeros[l%(j/3)]),
            t = 1 + (l/(j/3)),
            zeros[k][i] -= t,
            zeros[k][i + 1] += 31 * t;

    for(i = 0, k = 0; i < (1L << 36); i++)
    {
        strcpy(&output[0],  zeros[(i >> 27) & 511]);
        strcpy(&output[7],  zeros[(i >> 18) & 511]);
        strcpy(&output[14], zeros[(i >>  9) & 511]);
        strcpy(&output[21], zeros[(i >>  0) & 511]);

        for(j = 0; j < 64; j += 4)
        {
           // k += 4;
           // if(k++ % 1000000 == 0) printf("%d\n", k);

           printf("%s%s\n%s%s\n%s%s\n%s%s\n",
               output, preimages[j + 0],
               output, preimages[j + 1],
               output, preimages[j + 2],
               output, preimages[j + 3]
           );
        }
    }
    return 0;
}

Calculates a preimage and adds and prefixes strings with hash 0. The time spent to generate the preimages should be negligible; all the code has to do is piece together five strings. That means that most of the time will be spent printing the results.
In one hour, only 3.2 × 1010 preimages can be printed. If I comment the printf statement out, the program reports that it has found 5.5 × 1012 preimages. However, I don't know if the compiler just ignores parts of the code (and I don't have the assembly knowledge to verify).

C#, 1.052 × 1010
The idea is to do the hash function in reverse to get all possible un-hashed strings from the given number. Integer overflow of the 32-bit hash value is also emulated in reverse by incrementing the given hash value by 2^32 on each iteration.
UPDATE: I've made several micro-optimisations that significantly improved the performance of my program. The new version produced 10.52 billion results in 15 minutes (compared to 9.05 billion in 1 hour for the previous version).
Futher improvement may be difficult since the output file was 117GB in size and that's about how much free space I have on my SSD. Writing results to the screen doesn't seem to be a viable option since it's almost a thousand times slower than writing to a file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

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

        const int maxChar = 126;

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

        static long[] minHashValues;

        static long[] maxHashValues;

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

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

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

            if (maxLength > maxStrLength)
                maxLength = maxStrLength;

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

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

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

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

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

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

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

                c += (char)31;
            }
        }

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

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

You don't have to write to a file, just record each result. I should have posted that though, sorry, and great work!

@jocopa3 Thanks! My idea was that the results have to be stored somewhere, and writing them to a file seems to be the fastest option. So, is that okay to just increment a counter for each result, and then discard the produced string?

Scala
One "useful" characteristic of Java's String.hashCode method is that if you have a string z with z.hashCode() == 0, then you also have that (z + x).hashCode() == x.hashCode() for any other string x. So even if we can find a relatively small number of strings with a given hashCode, we can just prefix it with a bunch of zero-hash strings, and generate as many strings as we like with that hashCode - the performance limit becomes string concatenation and IO at that point.
So how do we find a string with a particular hashCode? In truth, brute force would probably be enough, due to the zero-hash trick, but we can easily get more speed with a meet-in-the-middle trick.
Let's suppose we want a string of length 10. To do this, we calculate the hashes of all strings of length 5. In this case, the hash of x + y will be x.hashCode() * 31 ** 5 + y.hashCode, so we can either start with x, and look for strings y whose hash is target - x.hashCode() * 31 ** 5, or start with y and look for strings whose hash is (target - y.hashCode) / (31 ** 5) (where division is modulo 2^32). In fact, we do both.
Right now, even length strings are better optimised than odd length strings, for reasons that are probably apparent.
Using the zero-hash trick, I can get 1.6 million strings per second on my laptop - printing the output is the main bottleneck.
Without the zero-hash trick (for example, if you want short strings - too short to pad with zero-hash strings), the performance is more modest. The birthday paradox means it gets faster as it runs, but it seems to level-off at around 70000 strings per second, for strings of length 10.
There's one worthwhile optimisation to note. If we're storing the hashes for a large number of strings, it would seem to make sense to either keep them in a hashtable, or an equivalent on-disk structure. However, an on-disk structure is too slow, and there isn't room for everything in memory (on my laptop, at least). So instead, we keep the data in a fixed-size 1-way cache. This means that data can be lost from the cache, but it improves performance. By increasing hashtableSize, you can increase the size of this cache, using more memory, and leading to more matches.
import scala.collection.mutable
import scala.collection.JavaConversions._
import java.io.File
import java.io.RandomAccessFile
import java.io.FileWriter

object Unhash {
  val maxChar = 126.toChar
  val minChar = 32.toChar
  val hashtableSize = 0x4000000

  def allStrings(l: Int): Iterator[String] = {
    new Iterator[String] {
      val currentArray = Array.fill(l)(minChar)
      var _hasNext = l > 0
      def hasNext = _hasNext

      def next(): String = {
        if (!_hasNext) throw new NoSuchElementException
        val result = new String(currentArray)
        var i = 0
        while (i < l) {
          if (currentArray(i) != maxChar) {
            val result = new String(currentArray)
            currentArray(i) = (currentArray(i) + 1).toChar
            return result
          } else {
            currentArray(i) = minChar
            i += 1
          }
        }
        _hasNext = false
        return result
      }
    }
  }

  def pow(x: Int, n: Int) = {
    var r = 1
    var p = n
    var m = x
    while (p > 0) {
      if ((p & 1) == 1) r *= m
      m *= m
      p >>= 1
    }
    r
  }

  def guessHash(target: Int, length: Int) = {
    length match {
      case l if l % 2 == 0 => findEven(target, length / 2)
      case _ => findOdd(target, (length - 1) / 2)
    }
  }

  def findEven(target: Int, halfLength: Int) = {
    val hashes = new HashCache(halfLength, hashtableSize)
    val multFactor = pow(31, halfLength)
    val divideFactor = BigInt(multFactor).modInverse(BigInt(2) pow 32).intValue

    new Traversable[String] {
      def foreach[U](f: String => U) = {
        for (string <- allStrings(halfLength)) {
          val hash = string.hashCode
          hashes.put(string)

          // Find possible suffixes
          {
            val effectiveTarget = target - hash * multFactor
            for (x <- hashes.get(effectiveTarget)) f(string + x)
          }

          // Find possible prefixes
          {
            val effectiveTarget = (target - hash) * divideFactor
            for (x <- hashes.get(effectiveTarget)) f(x + string)
          }
        }
      }
    }
  }

  def findOdd(target: Int, halfLength: Int) = {
    val hashes = new HashCache(halfLength, hashtableSize)
    val multFactor = pow(31, halfLength)
    val divideFactor = BigInt(multFactor).modInverse(BigInt(2) pow 32).intValue

    new Traversable[String] {
      def foreach[U](f: String => U) = {
        for (string <- allStrings(halfLength);
             hash = string.hashCode;
             _ = hashes.put(string);
             firstChar <- minChar to maxChar) {
          // Adjust the target, by subtracting the contribution from the first char
          val currentTarget = target - firstChar * pow(31, 2 * halfLength)

          // Find possible suffixes
          {
            val effectiveTarget = currentTarget - hash * multFactor
            for (x <- hashes.get(effectiveTarget)) f(firstChar + string + x)
          }

          //Find possible prefixes
          {
            val effectiveTarget = (currentTarget - hash) * divideFactor
            for (x <- hashes.get(effectiveTarget)) f(firstChar + x + string)
          }
        }
      }
    }
  }

  def guessAnyLength(target: Int) = {
    new Traversable[String] {
      def foreach[U](f: String => U) = {
        val zeroHashes = findEven(0, 4).toArray
        for (len5 <- findEven(target, 4);
             zero1 <- zeroHashes.iterator;
             zero2 <- zeroHashes.iterator;
             zero3 <- zeroHashes.iterator) f(zero1 + zero2 + zero3 + len5)
      }
    }
  }

  def main(args: Array[String]) = {
    val startTime = System.nanoTime
    val Array(output, length, target) = args
    val t = target.toInt

    val resultIterator = length match {
      case "any" =>
        guessAnyLength(t)
      case _ =>
        val l = length.toInt
        guessHash(t, l)
    }

    var i = 0L
    var lastPrinted = System.nanoTime
    var lastI = 0L

    val outputWriter = new FileWriter(output)
    try {
      for (res <- resultIterator) {
        outputWriter.write(res + "\n")

        i += 1

        val now = System.nanoTime
        if (now > lastPrinted + 1000000000L) {
          println(s"Found $i total, at ${i - lastI} per second")
          lastPrinted = System.nanoTime
          lastI = i
        }
      }
    } finally {
      outputWriter.close()
    }

  }
}

class HashCache(stringLength: Int, size: Int) {
  require ((size & (size - 1)) == 0, "Size must be power of 2")
  val data = new Array[Char](stringLength * size)

  def get(hash: Int) = {
    val loc = hash & (size - 1)
    val string = new String(data, stringLength * loc, stringLength)
    if (string.hashCode == hash) Some(string)
    else None
  }

  def put(string: String) = {
    val loc = string.hashCode & (size - 1)
    string.getChars(0, stringLength, data, stringLength * loc)
  }
}

PHP
I found 81 possible solutions for 69066349 within 0.016 seconds with this code!
Btw I didn't try to implement the overflow functionality.
$results = 0;

/**
 * Get the string for a hash
 * @param integer $hash hash value
 * @param integer $length length of the returned string
 * @return string $string
 */
function reverseHash($hash,$length=false,$val='',$counter=0) {
    global $results;
    if (!$length) {
        $length = 0;
        $copyHash = $hash;
        while (($copyHash-32)/31 > 0) {
            $copyHash = ($copyHash-126)/31;
            $length++;
        }
        echo 'MaxLength: '.$length.'<br>';
    }

    // if at least one more recursion is needed
    if ($counter < $length) {
        for ($i = 32; $i <= 126; $i++) {
            $string = false;
            $newhash = ($hash-$i)/31;
            $newval = chr($i).$val;
            if ($newhash > 0) {
                // if the new hash isn't an integer => $newval is wrong
                if (floor($newhash) == $newhash) {
                    $string = reverseHash($newhash,$length,$newval,$counter+1);
                }
                if ($string) {
                    return $string;
                }
            } else if ($counter <= $length-1 and $newhash == 0) {
                echo $newval.'<br>';
                $results++;
            }
        }
    } else {
        return false;
    }
}

$start = microtime(true);
reverseHash($_GET['hash']);
$end = microtime(true);
$dif = $end-$start;
echo "Time ".$dif." sec (".$results.")";

source: Stack Exchange

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

sort: votes


text:
Create a grid as close to a square as possible
Create a function or program that makes a grid as close to an square as possible

You will be given an integer N as input, whole numbers (1,2,3,25, etc)
The output must be a perfect rectangular grid of N letters as close to a square as possible
The (wannabe)square must consist of one of the the letters O or X as specified by user

Points:

Hardcoded to only O or X: +1
A param(0/1, true/false, something similar) to rotate output (like with 5 or 8): -10
Design the square (use both O and X in some sort of pattern): -5

A pattern is considered valid if it contains both types of characters (where x/y-axis >= 3) and the pattern stays the same when flipped horizontally or vertically (exchanging Xs with Os is allowed)
Examples
INPUT: 4         INPUT: 5       INPUT: 8              INPUT: 9
OO               OOOOO          XXXX                  XOX
OO                              XXXX                  OXO
                                or rotated 90deg      XOX

Examples which aren't allowed (not same length row or columns)
BAD RESULT: 5a        BAD RESULT: 5b      BAD RESULT: 8
OOO                   OO                  OOO
OO                    OO                  OOO
                      O                   OO

If possible please provide an online example.

Is a function enough, or do you want a full program?

" Design the square ... in case of 9 change the center" -- under which exact circumstances is the pattern not a checkerboard? Can you provide an example?

re the edit: do I read correctly that I get three points for doing "xo"[i] instead of i? That doesn't seem worth it. In general, all of your rewards seem kinda low.

"some sort of pattern" is kinda vague. Does it count if I replace the first 'x' with 'o'?

Nice question. The only interesting bonus/penalty is the rotation one. Personally I would stick with one, hardcoded character (i.e. make the penalty the default) and eliminate all the bonuses / penalites except perhaps the rotation one. It's not a good idea to have too many bonuses or penalties. The important thing is to specify the main problem clearly.

@steveverrill I don't consider them too many - just generally not worth it

Wasn't sure about one of bonusses, changed it to the two now. I like the design one, a bit of creativity.

I don't see any X in the examples. Really don't understand the X/O point.

@edc65 I think the Pattern is meant like this: At least one of the characters in your output must be X and at least one must be O and your program must support the rotation-flag so that the pattern changes like you would rotate the grid

@Falco then put just a single X at top left, no change rotating (seriously, I'm going to try that)

1 X amongst all O's isnt really a pattern is it? We're all smart people.

@Martijn if it happens to be in the exact center, it's a valid pattern under the definition you have included.

See, we're all smart ;) You're right. But one top left isn't

CJam, 16 (31 - 10 - 5)
This takes two integers are input, first one being 0 or 1 for direction and second one being the number of O or X in the grid.
It prints an alternate O and X.
:X"OX"*X<\Xmqi){(_X\%}g_X\/?/N*

This is just the function body, to try it out add l~ in front of the code like:
l~:X"OX"*X<\Xmqi){(_X\%}g_X\/?/N*

and give input like
0 10

to get output like
OXOXO
XOXOX

or input like
1 10

for
OX
OX
OX
OX
OX

Try it online here

How it works:
l~                                 "Put the two input integers to stack";
  :X                               "Assign the number of cells to X";
    "OX"*                          "Take string "OX" and repeat it X times";
         X<                        "Slice it to take only first X characters";
           \                       "Swap top two stack elements, now string is at bottom";
            Xmqi)                  "Take square root of X, ceil it and put on stack";
                 {(_X\%}g          "Keep decrementing until it is perfectly divisible by X";
                         _X\/      "Copy it, divide X by that and put it on stack";
                             ?     "Based on first input integer, take either of numbers";
                              /    "Divide the XOXO string that many times";
                               N*  "Join the string parts with a new line";

Example run:
l~ed:X"OX"*edX<ed\edXmqi)ed{(_X\%}ged_edXed\ed/ed?ed/edN*ed

#INPUT:
1 10

#OUTPUT:
Stack: [1 10]

Stack: [1 "OXOXOXOXOXOXOXOXOXOX"]

Stack: [1 "OXOXOXOXOX"]

Stack: ["OXOXOXOXOX" 1]

Stack: ["OXOXOXOXOX" 1 4]

Stack: ["OXOXOXOXOX" 1 2]

Stack: ["OXOXOXOXOX" 1 2 2]

Stack: ["OXOXOXOXOX" 1 2 2 10]

Stack: ["OXOXOXOXOX" 1 2 10 2]

Stack: ["OXOXOXOXOX" 1 2 5]

Stack: ["OXOXOXOXOX" 2]

Stack: [["OX" "OX" "OX" "OX" "OX"]]

Stack: ["OX
OX
OX
OX
OX"]

OX
OX
OX
OX
OX

APL (36 - 5 - 10 = 21)
{'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]}

The left argument is rotation, the right argument is the size. It also uses a simple pattern (it just alternates 'X' and 'O').
      0{'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]}¨4 5 8 9
 OX  OXOXO  OXOX  OXO
 OX         OXOX  XOX
                  OXO
      1{'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]}¨4 5 8 9
 OX  O  OX  OXO
 OX  X  OX  XOX
     O  OX  OXO
     X  OX
     O

Explanation:

∆←,⍳2/⍵: generate all possible pairs of numbers from 1 to ⍵ and store in ∆.
∆←∆[⍋|-/¨∆...]: sort ∆ ascending in the absolute difference of the two numbers in each pair, and store the result back in ∆.
⊃∆/⍨⍵=×/¨∆: for each pair, multiply the numbers together. Select only those pairs that multiply to ⍵, and take the first one that matches (which is the  'most square' because of the sort).
⍺⌽: rotate the list of lengths (which has 2 elements) by ⍺.
'OX'⍴⍨: create a matrix of that size, and fill it with alternating O and X.

Python, 79 75 (no bonuses)
The bonuses seem tricky, so here is a pretty simple Python function:
def f(N):c=max(x*((x*x<=N)>N%x)for x in range(1,N+1));print(N/c*'O'+'\n')*c

Online example for the interested: http://repl.it/Zq9

Did you change this after testing? I tried this and it does not work, for example f(8) gave me one column of 8 Os, which is incorrect.

@marinus: I did test it but seem to have copied a wrong version. There was a > where there should have been a <. It's fixed now. Thanks for the note!

Haskell, 59 characters
r=replicate
f n=[r x$r y '0'|x<-[1..n],y<-[1..x],x*y==n]!!0

JavaScript (E6) 84 (83+1) or 101 (116-10-5)
Pattern + rotation (parameter f, 0 or 1) - bonus 15
F=(n,f)=>{
  for(r=x=0;y=n/++x|0,x<=y;)x*y-n?0:z=f?x:y;
  for(o='';n;)o+=(n--%z?'':(r^=1,c='\n'))+'OX'[r^(c^=1)];
  alert(o)
}

No pattern, no rotation - penalty 1
F=n=>{
  for(x=0;y=n/++x|0,x<=y;)x*y-n?0:z=y;
  alert(('O'.repeat(z)+'\n').repeat(n/z));
}

Test In FireFox/FireBug console
F(30,0)

OXOXOX
XOXOXO
OXOXOX
XOXOXO
OXOXOX

F(30,1)

OXOXO
XOXOX
OXOXO
XOXOX
OXOXO
XOXOX

CJam, 25 22 21 (31 - 10)
This is a function body. If you want a complete program, add riri to the front. If you want to use it as a code block, surround it in {}. Test it on cjam.aditsu.net.
It takes input as two integer arguments: the switch for whether the rectangle is vertical (any non-zero value) or horizontal (zero), and the number of Os to use.
:Xmqi){(_X\%}g_X\/@{\}{}?'O*N+*

Explanation
:X "Assign the top item on the stack (the second input) to variable X";
mq "Take its square root";
i  "Convert to integer (round)";
)  "Increment it";

{  "Start code block";
  (  "Decrement";
  _X "Duplicate top item on stack; push X to the stack";
  \% "Swap top 2 items and take division remainder";
}g "Loop until top item on stack is 0; pop condition after checking it";

_X "Duplicate top item on stack; push X to the stack";
\/ "Swap top 2 items and divide";

"OMIT THIS BIT TO GET A 25-CHAR FUNCTION WITHOUT THE 10PT BONUS";
 @  "Rotate top 3 items on stack";
 {\}"Code block 1: swap top two items";
 {} "Code block 2: do nothing";
 ?  "If top item of stack is 0, run code block 1, otherwise run code block 2";

'O "Push the character O to the stack";
*  "Repeat it N times, where N is the second item from the top of the stack (O is first)";
N+ "Push a new line and concatenate it with the string on the top of the stack";
*  "Repeat the string N times";

Decrement should be quite faster for big numbers, without loss in byte count

Who downvoted? Why?

I can only guess it's because someone doesn't consider CJam a real language

Your explanation is kinda broken. Are you currently editing?

@JanDvorak Yes, I was halfway through editing it and accidentally pressed Tab and Enter. It's fixed now.

Ruby, 74
f=->n{w=(1..n).min_by{|z|n%z>0?n:(n/z-n/(n/z))**2};$><<("X"*w+"\n")*(n/w)}

Explanation

Input is taken as arguments to a lambda. It expects an Integer.
Check if n (the input) is divisible by every integer from 1 to n.

If it is, calculate the difference between the length and width.
If it is not, return a large number (n).

Take the smallest of length-width differences to best resemble a square.
Use (the overly concise) String#* method to "draw" the square.

Why was I downvoted? Does my answer contain a bug?

You have a typo. The last word should be "square" and you have "sqaure". (I am not the downvoter, I'm pointing this mistake).

APL (Dyalog Unicode), 30 - 15 = 15 bytesSBCS
Anonymous infix lambda. Takes N as right argument and param as left argument. Rectangles will either have stripes of X and O or be chequered.
{⍉⍣⍺⍴∘'XO'⊃∘c⌈.5×≢c←⍸⍵=∘.×⍨⍳⍵}

Try it online!
{…} "dfn"; ⍺ is left argument (param), ⍵ is right argument (N):
 ⍳⍵ ɩndices 1…N
 ∘.×⍨ multiplication table of that
 ⍵= mask where N is equal to that
 ⍸ ɩndices of true values in the mask
 c← store that in c (for candidates)
 ≢ tally the candidates
 .5× one half multiplied by that
 ⌈ ceiling (round up)
 ⊃∘c pick that element from c
 ⍴∘'XO' use that to cyclically reshape "XO"
 ⍉⍣⍺ transpose if param

05AB1E (legacy), score: 7 (22 bytes - 15 bonus)
„OXI∍¹tï[D¹sÖ#<}äIiø}»

Try it online or verify some more test cases.
Takes the inputs N first, then the boolean (0/1) whether it should rotate or not.
Uses the Python legacy version of 05AB1E since zip with a string-list implicitly flattens and joins the characters, unlike the newer Elixir rewrite version of 05AB1E.
Explanation:
„OX         # Push string "OX"
   I∍       # Extend it to a size equal to the first input
            #  i.e. 9 → "OXOXOXOXO"
            #  i.e. 10 → "OXOXOXOXOX"
¹t          # Take the first input again, and square-root it
            #  i.e. 9 → 3.0
            #  i.e. 10 → 3.1622776601683795
  ï         # Then cast it to an integer, removing any decimal digits
            #  i.e. 3.0 → 3
            #  i.e. 3.1622776601683795 → 3
   [        # Start an infinite loop:
    D       #  Duplicate the integer
     ¹sÖ    #  Check if the first input is evenly divisible by that integer
            #   i.e. 9 and 3 → 1 (truthy)
            #   i.e. 10 and 3 → 0 (falsey)
        #   #  And if it is: stop the infinite loop
    <       #  If not: decrease the integer by 1
            #   i.e. 3 → 2
   }        # After the infinite loop:
ä           # Divide the string into that amount of equal sized parts
            #  i.e. "OXOXOXOXO" and 3 → ["OXO","XOX","OXO"]
            #  i.e. "OXOXOXOXOX" and 2 → ["OXOXO","XOXOX"]
 Ii }       # If the second input is truthy:
   ø        #  Zip/transpose; swapping rows/columns of the strings
            #   i.e. ["OXOXO","XOXOX"] → ["OX","XO","OX","XO","OX"]
»           # And finally join the strings in the array by newlines
            #  i.e. ["OXO","XOX","OXO"] → "OXO\nXOX\nOXO"
            #  i.e. ["OX","XO","OX","XO","OX"] → "OX\nXO\nOX\nXO\nOX"
            # (and output the result implicitly)

GolfScript 26 (41 - 10 - 5)
:x),1>{x\%!},.,2/=.x\/@{\}*'X'*n+*1>'O'\+

Expects two parameters to be on the stack:

0 for normal or 1 for transposed
the n value

The pattern is that the board is full of Xs and the top left corner is an O. Needless to say, this pattern is maintained when transposing the board.
Demo: regular, transposed

Mathematica, 71 chars
f@n_:=#<>"\n"&/@Array["O"&,{#,n/#}&[#[[⌊Length@#/2⌋]]&@Divisors@n]]<>""

Petit Computer BASIC, 72 bytes
INPUT N,S$FOR I=1TO SQR(N)IF N%I<1THEN M=I
NEXT
?(S$*M+" "*(32-M))*(N/M)

J, 32 bytes - 15 = 17 bytes
'XO'$~[|.](%,])i.@]{~0 i:~i.@]|]

Try it online!
The rotation is controlled by a 0/1 flag taken as the left argument

Retina 0.8.2, 66 bytes + 1 byte penalty = 67
.+
$*X
((^|\3)(X(?(3)\3)))+(\3)*$
$3 $3$#4$*X
X(?=X* (X+))| X+
$1¶

Try it online! Explanation:
.+
$*X

Convert the input to a string of Xs.
((^|\3)(X(?(3)\3)))+(\3)*$

The first pass of the outer capture matches the start of the string while on subsequent passes the previous value of the inner capture is matched. The inner capture is then incremented and matched. The upshot of this is that the amount of string consumed by the outer capture is the square of the inner capture, which therefore cannot exceed the square root of the input. Meanwhile the subsequent repetition ensures that the inner capture is a factor of the length of the string.
$3 $3$#4$*X

Save the discovered factor and calculate the other divisor by adding on the number of subsequent repetitions.
X(?=X* (X+))| X+
$1¶

Rearrange the factors into a rectangle.

Charcoal, 33 bytes - 10 - 5 = 18
Ｎθ≔⌊Φ⊕θ¬∨‹×ιιθ﹪θιηＥ÷θη⭆η§XO⁺ιλ¿Ｎ⟲

Try it online! Link is to verbose version of code. Explanation:
Ｎθ

Input N.
≔⌊Φ⊕θ¬∨‹×ιιθ﹪θιη

Take the range 0..N, keep only the numbers whose squares are not less than N and divide N, and take the minimum of those numbers.
Ｅ÷θη⭆η§XO⁺ιλ

Use the discovered factor to output a rectangle of the appropriate width and height using a chequerboard pattern. (This should be ＵＯη÷θηXO¶OX for a 1-byte saving but that's buggy right now.)
¿Ｎ⟲

If the second input is nonzero then rotate the output. (If requiring the second input to be 0 or 2 is acceptable, then this could be ⟲Ｎ for a 1-byte saving.)

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

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


text:
Play the Chaos Game
The Chaos Game is a simple method to generate fractals. Given a starting point, a length ratio r and a set of 2D points, repeatedly do the following:

From your set of points, pick one at random (uniformly).
Average that point and the last drawn point (or the starting point) using r and 1 - r as the weights (i.e. r = 0 means you get the starting point, r = 1 means you get the random point and r = 0.5 means you get the point halfway in between.)
Draw the resultant point.

For instance, if you picked the vertices of an equilateral triangle and r = 0.5, the plotted points would map out a Sierpinski triangle:

Image found on Wikipedia
You're to write a program or function which "plays" the chaos game to create a fractal.
Input
You may write either a program or a function, and take following inputs via ARGV, STDIN or function argument:

The number of points to plot.
The starting coordinate (which has to be plotted, too!).
The averaging weight r in the interval [0,1].
A list of points to choose from.

Output
You may render on screen or write an image file. If the result is rasterised, it needs to be at least 600 pixels on each side, all points must be on the canvas, and at least 75% of the horizontal and vertical extent of the image must be used for points (this is to avoid answers with a single black pixels saying "it's really far zoomed out"). The x and y axis must be on the same scale (that is the line from (0,0) to (1,1) must be at a 45 degree angle) and each point plotted in the chaos game must be represented as a single pixel (if your plotting method anti-aliases the point, it may be spread over 2x2 pixels).
Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the dots plotted during the chaos game. You may but don't have to plot the input points.
Please include three interesting example outputs in your answer.
Scoring
This is code golf, so the shortest answer (in bytes) wins.
Edit: You no longer need to plot the input points, as they aren't really visible as single pixels anyway.

What does "each point plotted ... must be represented as a single pixel" mean? Is it a) that no anti-aliasing should be used; or b) that the number of points in the second colour must be equal to the first item from the input? Note that b) is impossible to guarantee unless the iteration procedure has a test for "Does this pixel coincide with a previously plotted one?", because if the random number selector selects the same point enough times in a row then the position will converge to that point.

@PeterTaylor It was intended to avoid people plotting large dots as the points (like Mathematica does by default), but I've already noticed that anti-aliasing causes some trouble with ensuring single pixels in Soham's answer. I think I'll relax this to "must not be larger than 2x2 pixels", which should cover all the anti-aliasing trouble.

I think I misunderstood something: You do always take the 'mean' of the last point you plotted and a random point of the current list. Then you add that new point to the list. Is that correct? It seems that if you have many points in one 'corner' you will get many more there but it is unlikely to get out of that cloud - at least my code always 'converges' pretty fast to points that are too close to each other to really enhance the picture.

@flawr no, you don't add the new point to the list. The list is fixed - the algorithm only cares about the last point that was plotted, not the ones before it.

Thanks, that explains a lot, should perhaps be clarified in the question.

Mathematica, 89
f[n_,s_,r_,p_]:=Graphics@{AbsolutePointSize@1,Point@NestList[#-r#+r RandomChoice@p&,s,n]}

f[10000, {0, 0}, .5, {{-(1/2), Sqrt[3]/2}, {-(1/2), -(Sqrt[3]/2)}, {1, 0}}]

How it works
In Mathematica the Graphics[] function produces scalable graphics, you render it to whatever size you want by simply dragging the picture corners. In fact, the initial size of all displayed graphics is a ".ini" setting that you may set at 600 or at any other value you wish. So there is no need to do anything special for the 600x600 requirement.
The AbsolutePointSize[] thing specifies that the point size will not be modified by enlarging the image size.
The core construct is
 NestList[#-r#+r RandomChoice@p&,s,n]

or in non-golfed pseudo-code:
 NestList[(previous point)*(1-r) + (random vertex point)*(r), (start point), (iterations)]

It is recursively building a list starting from (start point) and applying the (vectorial) function in the first argument to each successive point, finally returning the list of all calculated points to be plotted by Point[]
Some self-replication examples:
Grid@Partition[Table[
   pts = N@{Re@#, Im@#} & /@ Table[E^(2 I Pi r/n), {r, 0, n - 1}];
   Framed@f[10000, {0, 0}, 1/n^(1/n), pts], {n, 3, 11}], 3]

@MartinBüttner Instructions for testing this answer without Mathematica installed: 1) Download this from pastebin and save it as *.CDF 2) Download and install the free CDF environment from Wolfram Research at  (not a small file). Enjoy. Tell me if it works!

Your golfed version doesn't quite work (at least on V10): you need to switch around #r to r# to get away without a space or * in between.

@MartinBüttner Curious! It works like a charm on v9 (I don't have v10 yet). Anyway, I (blindly) swapped the # and r.

Ah, it's a new feature. You can now apply functions to associations, in which case you get named parameters that can be accessed by #key. I'm sure that will come in handy. :)

Java : 246 253 447
As a function m():
void m(float[]a){new java.awt.Frame(){public void paint(java.awt.Graphics g){int i=0,x=i,y=i,v;for(setSize(832,864),x+=a[1],y+=a[2];i++<=a[0];v=a.length/2-2,v*=Math.random(),x+=(a[v+=v+4]-x)*a[3],y+=(a[v+1]-y)*a[3])g.drawLine(x,y,x,y);}}.show();}

Line breaks (within a program to show usage):
class P{
    public static void main(String[]a){
        new P().m(new float[]{1000000,            // iterations
                              416,432,            // start
                              0.6f,               // r
                              416,32,16,432,      // point list...
                              416,832,816,432,
                              366,382,366,482,
                              466,382,466,482});
    }

    void m(float[]a){
        new java.awt.Frame(){
            public void paint(java.awt.Graphics g){
                int i=0,x=i,y=i,v;
                for(setSize(832,864),x+=a[1],y+=a[2];
                    i++<=a[0];
                    v=a.length/2-2,v*=Math.random(),
                    x+=(a[v+=v+4]-x)*a[3],
                    y+=(a[v+1]-y)*a[3])
                    g.drawLine(x,y,x,y);
            }
        }.show();
    }
}

Drawing input points was removed from the requirements (yay 80 bytes!). They're still shown in the old screenshots below, but won't show up if you run it. See revision history if interested.
The inputs are given as an array of floats. The first is iterations, the next two are starting x y. Fourth is r, and last comes the list of coordinates, in x1 y1 x2 y2 ... fashion.
Ninja Star
1000000 400 400 0.6 400 0 0 400 400 800 800 400 350 350 350 450 450 350 450 450

Cross
1000000 400 400 0.8 300 0 500 0 500 300 800 300 800 500 500 500 500 800 300 800 300 500 0 500 0 300 300 300

Octochains
1000000 400 400 0.75 200 0 600 0 800 200 800 600 600 800 200 800 0 600 0 200

this does't work in my computer, and java complains show is deprecated

@proudhaskeller show() is deprecated, but it still works. When you say "doesn't work", what does that mean? If you don't have Java 8, you'll need to add a final to String[]a in main at least.

Ported your answer to Processing and cut 100 chars.

@ace Nice. You can do that with pretty much any Java golf for graphical output, but I like that it's exactly 100 chars :D

JavaScript (E6) + Html 173  176 193
Edit: big cut, thanks to William Barbosa
Edit: 3 bytes less, thanks to DocMax
173 bytes counting the function and the canvas element needed to show the output.
Test save as html file and open in FireFox.
JSFiddle

<canvas id=C>
<script>
F=(n,x,y,r,p)=>{
  for(t=C.getContext("2d"),C.width=C.height=600;n--;x-=(x-p[i])*r,y-=(y-p[i+1])*r)
    i=Math.random(t.fillRect(x,y,1,1))*p.length&~1
}
F(100000, 300, 300, 0.66, [100,500, 500,100, 500,500, 100,100, 300,150, 150,300, 300,450, 450,300]) // Function call, not counted
</script>

<canvas id=C><script>F=(n,x,y,r,p)=>{t=C.getContext("2d"),C.width=C.height=600;for(;n--;)t.fillRect(x,y,1,1),i=Math.random()*p.length&~1,x-=(x-p[i])*r,y-=(y-p[i+1])*r}</script> is 176 bytes long, I didn't understand your count

@WilliamBarbosa my count is right based on my answer. With your hints it gets better - thank you!

You can shave off two more if you move the size initialization and y update into the for call: for(C.width=C.height=600;n--;y-=(y-p[i+1])*r)

Python - 200 189
import os,random as v
def a(n,s,r,z):
    p=[255]*360000
    for i in[1]*(n+1):
        p[600*s[0]+s[1]]=0;k=v.choice(z);s=[int(k[i]*r+s[i]*(1-r))for i in(0,1)]
    os.write(1,b'P5 600 600 255 '+bytes(p))

Takes input as function arguments to a, writes result to stdout as pgm file.
n is iterations, s is starting point, r is r, and z is list of input points.
Edit: No longer draws input points in gray.
Interesting outputs:

Iterations: 100000
Starting Point: (200, 200)
r: 0.8
Points: [(0, 0), (0, 599), (599, 0), (599, 599), (300, 300)]

Iterations: 100000
Starting Point: (100, 300)
r: 0.6
Points: [(0, 0), (0, 599), (599, 0), (300, 0), (300, 300), (0, 300)]

Iterations: 100000
Starting Point: (450, 599)
r: 0.75
Points: [(0, 0), (0, 300), (0, 599), (300, 0), (599, 300), (150, 450)]

Some common Python character saves: Initial values like p=[255]*360000 can go as optional parameters to the function; the body of a for loop can all go on the same line if it has no control flow; you can shave parens from [1]*(n+1) as [1]*-~n; since you don't use i in the outer for loop, it's shorter to run code the n times as exec"code;"*n); I think the parens in for i in(0,1) can be removed.

Python, 189 183 175
Edit: fixed the inversed r ratio, and switched to B&W image in order to save a few bytes.
Takes the number of points as n, first point as p, ratio as r and list of points as l.
Needs the module Pillow.
import random,PIL.Image as I
s=850
def c(n,p,r,l):
    i=I.new('L',(s,s));x,y=p;
    for j in range(n):w,z=random.choice(l);w*=r;z*=r;x,y=x-x*r+w,y-y*r+z;i.load()[x,s-y]=s
    i.show()

Examples:
I am generating points in circle around the image's center
points = [(425+s*cos(a)/2, 425+s*sin(a)/2) for a in frange(.0, 2*pi, pi/2)]
c(1000000, (425, 425), 0.4, points)

XOXO repetitions, just changing ratio from 0.4 to 0.6

Some sort of snow flake
stars = [(425+s*cos(a)/2,425+s*sin(a)/2) for a in frange(.0,2*pi, pi/4)]
c(1000000, (425, 425), 0.6, stars)

Dunno about fixing the backwards r thing, but you can save quite a few characters by making this a program using n,p,r,l=input(). You can also remove the brackets from the *= operations and use import random as R.

@FryAmTheEggman Unfortunately, correcting my answer invalidates the optimisation on *= :(. The input thing would be good be very unpleasant to work with, and the import currently is the most concise form possible (or have I missed something ?).

I am pretty sure the line can be import random as R,PIL.Image as I and then random.choice can be R.choice. Yeah, using input is lame, but you can use the function version for testing and post the input() one for a better score!!1! :P

Oh, I've just noticed defining random actually saves 0 characters. Oops :S Anyway, I also realized that math is your friend: y=x*(1-r)+w == y=x-x*r-w.

@FryAmTheEggman that was my point :p. But thanks for the maths.

SuperCollider - 106
SuperCollider is a language for generating music, but it can do graphics at a pinch.
f={|n,p,r,l|Window().front.drawHook_({{Pen.addRect(Rect(x(p=l.choose*(1-r)+(p*r)),p.y,1,1))}!n;Pen.fill})}

I've used some obscure syntax shortcuts to save a few bytes - a more readable and more memory-efficient version is
f={|n,p,r,l|Window().front.drawHook_({n.do{Pen.addRect(Rect(p.x,p.y,1,1));p=l.choose*(1-r)+(p*r)};Pen.fill})}

at 109 chars.
As with the Mathematica example, you have to manually resize the window to get 600x600 pixels. You have to wait for it to re-draw when you do this.
This generates a basic Sierpinsky triangle (not shown because you've seen it before)
f.(20000,100@100,0.5,[0@600,600@600,300@0])

This makes a kind of Sierpinsky pentagon type thing:
f.(100000,100@100,1-(2/(1+sqrt(5))),{|i| (sin(i*2pi/5)+1*300)@(1-cos(i*2pi/5)*300)}!5)

The same thing with 6 points leaves an inverted Koch snowflake in the middle:
f.(100000,100@100,1/3,{|i| (sin(i*2pi/6)+1*300)@(1-cos(i*2pi/6)*300)}!6)

Finally, here's a riff on the 3D pyramids from ace's answer. (Note that I've used one of the points twice, to get the shading effect.)
f.(150000,100@100,0.49,[300@180, 0@500,0@500,350@400,600@500,250@600])

JavaScript (407) (190)
I'm happy to get any feedback on my script and on golfing since I am not comfortable with JS=) (Feel free to use this/change it for your own submission!)
Reading Input  (To be comparable to edc65's entry I do not count the the input.):
p=prompt;n=p();[x,y]=p().split(',');r=p();l=p().split(';').map(e=>e.split(','));

Canvas Setup & Calculation
d=document;d.body.appendChild(c=d.createElement('canvas'));c.width=c.height=1000;c=c.getContext('2d');
for(;n--;c.fillRect(x,y,2,2),[e,f]= l[Math.random()*l.length|0],x-=x*r-e*r,y-=y*r-f*r);

Somewhat more ungolfed (including an example input where the real input promts are just commented out, so ready to use):
p=prompt;
n=p('n','4000');
[x,y]=p('start','1,1').split(',');
r=p('r','0.5');
l=p('list','1,300;300,1;300,600;600,300').split(';').map(e=>e.split(','));d=document;
d.body.appendChild(c=d.createElement('canvas'));
c.width=c.height=1000;c=c.getContext('2d');
for(;n--;c.fillRect(x,y,2,2),[e,f]= l[Math.random()*l.length|0],x-=x*r-e*r,y-=y*r-f*r);

Examples
for(k = 0; k<50; k++){
rad = 10;
l.push([350+rad*k*Math.cos(6.28*k/10),350+rad*k*Math.sin(6.28*k/10)]);
}
r = 1.13;

r = 0.5;list = [[1,1],[300,522],[600,1],[300,177]];

r = 0.5
list = [[350+350*Math.sin(6.28*1/5),350+350*Math.cos(6.28*1/5)],
[350+350*Math.sin(6.28*2/5),350+350*Math.cos(6.28*2/5)],
[350+350*Math.sin(6.28*3/5),350+350*Math.cos(6.28*3/5)],
[350+350*Math.sin(6.28*4/5),350+350*Math.cos(6.28*4/5)],
[350+350*Math.sin(6.28*5/5),350+350*Math.cos(6.28*5/5)],

[350+90*Math.sin(6.28*1.5/5),350+90*Math.cos(6.28*1.5/5)],
[350+90*Math.sin(6.28*2.5/5),350+90*Math.cos(6.28*2.5/5)],
[350+90*Math.sin(6.28*3.5/5),350+90*Math.cos(6.28*3.5/5)],
[350+90*Math.sin(6.28*4.5/5),350+90*Math.cos(6.28*4.5/5)],
[350+90*Math.sin(6.28*5.5/5),350+90*Math.cos(6.28*5.5/5)]];

Which ones do you mean?

Oh thanks for telling me, I am gonna update the submission soon!

You linked my answer, but I do count the setup of the canvas. I just don't count the single line calling the function. Nice images anyway, espacially the first one.

Ah I didn't notice that, I just wanted to make it 'comparable', but it's difficult when I try to rely on JS only=) @MartinBüttner Updated, now that I understood it the right way I was able to remove much of the garbage=)

Processing, 153
Ported @Geobits' Java answer to Processing and did some more golfing, resulting in a reduction of 100 chars. I originally intended to animate the process, but the input constraints are too harsh on this (Processing does not have stdin or argv, which means that I must write my own function instead of using Processing's native draw() loop).
void d(float[]a){int v;size(600,600);for(float i=0,x=a[1],y=a[2];i++<a[0];v=(int)random(a.length/2-2),point(x+=(a[v*2+4]-x)*a[3],y+=(a[v*2+5]-y)*a[3]));}

Complete program with line breaks:
void setup() {
  d(new float[]{100000,300,300,.7,0,600,600,0,600,600,0,0,400,400,200,200,400,200,200,400});
}
void d(float[]a){
  int v;
  size(600,600);
  for(float i=0,x=a[1],y=a[2];
      i++<a[0];
      v=(int)random(a.length/2-2),point(x+=(a[v*2+4]-x)*a[3],y+=(a[v*2+5]-y)*a[3]));
}

Above program gives Crosses:

d(new float[]{100000,300,300,.65,142,257,112,358,256,512,216,36,547,234,180,360});

This gives Pyramids:

d(new float[]{100000,100,500,.5,100,300,500,100,500,500});

This gives Sierpinski triangle:

I love the 3D effect of the pyramids. :)

Ungolfed "reference implementation", Python
Update: much, much faster (by orders of magnitude)
Check out the interactive shell!
Edit the file and set interactive to True, then do one of these:
polygon numberOfPoints numeratorOfWeight denominatorOfWeight startX startY numberOfSides generates, saves and displays a polygon.
points numberOfPoints numeratorOfWeight denominatorOfWeight startX startY point1X point1Y point2X point2Y ... does what the spec asks for.

import matplotlib.pyplot as plt
import numpy as np
from fractions import Fraction as F
import random
from matplotlib.colors import ColorConverter
from time import sleep
import math
import sys
import cmd
import time

def plot_saved(n, r, start, points, filetype='png', barsize=30, dpi=100, poly=True, show=False):
    printed_len = 0

    plt.figure(figsize=(6,6))
    plt.axis('off')

    start_time = time.clock()
    f = F.from_float(r).limit_denominator()

    spts = []
    for i in range(len(points)):
        spts.append(tuple([round(points[i].real,1), round(points[i].imag,1)]))

    if poly:
        s = "{}-gon ({}, r = {}|{})".format(len(points), n, f.numerator, f.denominator)
    else:
        s = "{} ({}, r = {}|{})".format(spts, n, f.numerator, f.denominator)

    step = math.floor(n / 50)

    for i in range(len(points)):
        plt.scatter(points[i].real, points[i].imag, color='#ff2222', s=50, alpha=0.7)

    point = start
    t = time.clock()

    xs = []
    ys = []

    for i in range(n+1):
        elapsed = time.clock() - t
        #Extrapolation
        eta = (n+1-i)*(elapsed/(i+1))
        printed_len = rewrite("{:>29}: {} of {} ({:.3f}%) ETA: {:.3f}s".format(
                s, i, n, i*100/n, eta), printed_len)
        xs.append(point.real)
        ys.append(point.imag)
        point = point * r + random.choice(points) * (1 - r)

    printed_len = rewrite("{:>29}: plotting...".format(s), printed_len)
    plt.scatter(xs, ys, s=0.5, marker=',', alpha=0.3)

    presave = time.clock()
    printed_len = rewrite("{:>29}: saving...".format(s), printed_len)
    plt.savefig(s + "." + filetype, bbox_inches='tight', dpi=dpi)

    postsave = time.clock()
    printed_len = rewrite("{:>29}: done in {:.3f}s (save took {:.3f}s)".format(
                            s, postsave - start_time, postsave - presave),
                            printed_len)

    if show:
        plt.show()
    print()
    plt.clf()

def rewrite(s, prev):
    spaces = prev - len(s)
    sys.stdout.write('\r')
    sys.stdout.write(s + ' '*(0 if spaces < 0 else spaces))
    sys.stdout.flush()
    return len(s)

class InteractiveChaosGame(cmd.Cmd):
    def do_polygon(self, args):
        (n, num, den, sx, sy, deg) = map(int, args.split())
        plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), list(np.roots([1] + [0]*(deg - 1) + [-1])), show=True)

    def do_points(self, args):
        l = list(map(int, args.split()))
        (n, num, den, sx, sy) = tuple(l[:5])
        l = l[5:]
        points = []
        for i in range(len(l)//2):
            points.append(complex(*tuple([l[2*i], l[2*i + 1]])))
        plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), points, poly=False, show=True)

    def do_pointsdpi(self, args):
        l = list(map(int, args.split()))
        (dpi, n, num, den, sx, sy) = tuple(l[:6])
        l = l[6:]
        points = []
        for i in range(len(l)//2):
            points.append(complex(*tuple([l[2*i], l[2*i + 1]])))
        plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), points, poly=False, show=True, dpi=dpi)

    def do_default(self, args):
        do_generate(self, args)

    def do_EOF(self):
        return True

if __name__ == '__main__':
    interactive = False
    if interactive:
        i = InteractiveChaosGame()
        i.prompt = ": "
        i.completekey='tab'
        i.cmdloop()
    else:
        rs = [1/2, 1/3, 2/3, 3/8, 5/8, 5/6, 9/10]
        for i in range(3, 15):
            for r in rs:
                plot_saved(20000, r, np.complex(0,0),
                            list(np.roots([1] + [0] * (i - 1) + [-1])),
                            filetype='png', dpi=300)

Without running this, I have no idea what awesome means. Perhaps you could explain, or show some pictures of what makes it different from the shorter ones?

@Geobits edited to include disclaimer and picture :)

I'd prefer if you included this under a separate heading (e.g. Ungolfed Reference Implementation) in your other answer as posting only ungolfed code is technically "not an answer".

Python (202 chars)
Takes the number of points as n, the averaging weight as r, the starting point as a tuple s and the list of points as a list of XY tuples called l.
import random as v,matplotlib.pyplot as p
def t(n,r,s,l):
 q=complex;s=q(*s);l=[q(*i)for i in l];p.figure(figsize=(6,6))
 for i in range(n):p.scatter(s.real,s.imag,s=1,marker=',');s=s*r+v.choice(l)*(1-r)
 p.show()

@MartinBüttner Does the fact that I'm taking a specific type of input meet the spec?

Also, on my machine, the result is not 600x600 pixels, x and y have different length scales and the points cover more than 1 pixel.

authors: Александр Полянский


text:
Rotate a Block of Text
Rules

Write a program in a language of your choice.
That program is designed to rotate a block of text. Example:
BOB   90 deg  DCB
CAT    -->    OAO
DOG    CW     GTB

You may assume the blocks of text are loaded into a variable block.
You may assume a square block, but of any size.
You may assume the line-endings are \n.
You're not allowed to use a library that already rotates blocks of text.
Code Golf rules, shortest program wins.

Rotate in which direction? 90 degrees clockwise, or is that just an example?

GolfScript, 11 characters
n/-1%zip n*

Explanation:
n/  # split on newline
-1% # reverse array
zip # "rotate" (will turn ['abc' 'def' 'ghi'] into ['adg' 'beh' 'cfi'])
n*  # join with newline again

Didn't he say that you cannot use an predefined method which rotates the text ? Seems like zip is doing that only

This can be improved by one char. See my answer to the question it duplicates

Python, 0 bytes

My program rotates the block of text by 720 degrees.

Problem, it does not echo.


text:
Uncertainty in the Timeline of a Day
Suppose your alarm wakes you up one morning, but you hit snooze so you can sleep for 8 more minutes. When it rings again you grudgingly get up and take a shower, which you estimate takes 15 to 17 minutes. You then brush your teeth for exactly 2 minutes, and get dressed, which takes about 3 to 5 minutes. Finally, you eat a hurried breakfast in 6 to 8 minutes and run out the door.
We can denote this timing sequence as 8 15-17 2 3-5 6-8.
Given the uncertainty of your morning's routine, what is the probability you were doing each task at some particular number of minutes since you first woke up?
Assuming every task takes a whole number of minutes, we can chart every possible combination of uncertain time spans (e.g. 3, 4, and 5 minutes for brushing teeth). This chart shows all 27 possibilities, with time increasing to the right, and each task of N minutes represented by (N - 1) dashes and one vertical bar, just to mark its ending. The minute boundaries occur between characters, so the space between the 8 and 9 column is 8 min 59 sec turning into 9 min.
         1111111111222222222233333333334
1234567890123456789012345678901234567890  <-- Minute
-------|--------------|-|--|-----|
-------|--------------|-|--|------|
-------|--------------|-|--|-------|
-------|--------------|-|---|-----|
-------|--------------|-|---|------|
-------|--------------|-|---|-------|
-------|--------------|-|----|-----|
-------|--------------|-|----|------|
-------|--------------|-|----|-------|
-------|---------------|-|--|-----|
-------|---------------|-|--|------|
-------|---------------|-|--|-------|
-------|---------------|-|---|-----|
-------|---------------|-|---|------|
-------|---------------|-|---|-------|
-------|---------------|-|----|-----|
-------|---------------|-|----|------|
-------|---------------|-|----|-------|
-------|----------------|-|--|-----|
-------|----------------|-|--|------|
-------|----------------|-|--|-------|
-------|----------------|-|---|-----|
-------|----------------|-|---|------|
-------|----------------|-|---|-------|
-------|----------------|-|----|-----|
-------|----------------|-|----|------|
-------|----------------|-|----|-------|
1234567891111111111222222222233333333334  <-- Minute
         0123456789012345678901234567890

It is clear that the routine could have taken 40 minutes at most and 34 minutes at least.
The question is, at a particular minute, say minute 29, what is the chance you were doing each of the 5 tasks? Assume each uncertain time frame is uniformly distributed over the exact whole minutes. So a 4-7 task has 25% chance of taking 4, 5, 6, or 7 minutes.
From the chart it can be seen that at minute 29 there was a...
0/27 chance you were snoozing (task 1)
0/27 chance you were showering (task 2)
0/27 chance you were brushing (task 3)
24/27 chance you were dressing (task 4)
3/27 chance you were eating (task 5)

Similarly at minute 1 there was a 27/27 chance you were snoozing with 0/27 everywhere else.
At minute 38 for example, 17 of the potential routines have already ended. So in 10 out of 10 cases you will be eating. This means the probabilities look like
0/10 task 1, 0/10 task 2, 0/10 task 3, 0/10 task 4, 10/10 task 5

Challenge
Write a function that takes an integer for the minute value, and a string consisting of a sequence of single integers, or pairs of integers a-b with b > a, all separated by spaces (just like 8 15-17 2 3-5 6-8). All the integers are positive. The input minute will be less than or equal to the maximum time possible (40 in example).
The function should return another string denoting the unreduced fractional chance of being in each task at the given minute.
Examples

myfunc(29, "8 15-17 2 3-5 6-8") returns the string 0/27 0/27 0/27 24/27 3/27
myfunc(1, "8 15-17 2 3-5 6-8") returns the string 27/27 0/27 0/27 0/27 0/27
myfunc(38, "8 15-17 2 3-5 6-8") returns the string 0/10 0/10 0/10 0/10 10/10
myfunc(40, "8 15-17 2 3-5 6-8") returns the string 0/1 0/1 0/1 0/1 1/1

If your language does not have strings or functions you may use named variables, stdin/stdout, the command line, or whatever seems most appropriate.
Scoring
This is code golf. The shortest solution in bytes wins.

The question does not specify a particular probability distribution for the time spent on each task. Should it be normally distributed? Can I assume any distribution I want?

@Calvin that's not a normal distribution. Maybe you wanted to have a uniform distribution?

Does each task include the left |, the right |, or half of each?

All mentioned issues fixed in question. Any other problems?

what happens if there is a chance that no task was happening?

@proud the last two examples cover that case

Do I have to use a function just because my language has them? A program using STDIN or command-linearguments would suit me much better...

@Dennis Ah, I see. I'd prefer you to use functions.

CJam, 124 115 100 92 89 bytes
This can be golfed a lot, but I have to sleep, so posting now itself :)
l~\:N;S/{'-/2*2<~i),\i>}%_{m*{(\+}%}*{[0\{1$+}*]}%:B;,,{0B{I>2<~N<!\N<*+}/}fI]_:+m*'/f*S*

Try it online here
Input is like:
29 "8 15-17 2 3-5 6-8"

Where first integer is the input minute and the second string is the time range sequence (as shown in examples in the question, just without the ,)
Output for the above mentioned input:
0/27 0/27 0/27 24/27 3/27

I'll accept this if you can get it to follow the updated rules.

All the other examples give 0/27's.

Now it's a bunch of `0/0's.

@Calvin'sHobbies Let's take it to chat : http://chat.stackexchange.com/rooms/18161/room-for-optimizer-and-calvins-hobbies

Never mind, sorry, I was just giving the input wrong.

Mathematica, 237 216 bytes
I'm sure I can shorten this a bit, but not now. At least I finally got to use the new associations from Mathematica 10! :)
f=(j=#;s=StringSplit;r=ToString;t=Lookup[Counts@Flatten[FirstPosition[#,n_/;n>=j]&/@Accumulate/@Tuples@i],#,0]&/@Range@Length[i=ToExpression[#~s~"-"&/@s@#2]/.{a_,b_}:>a~Range~b];Riffle[r@#<>"/"<>r@Tr@t&/@t," "]<>"")&

Ungolfed:
    f = (
   j = #;
   s = StringSplit;
   r = ToString;
   t = Lookup[
       Counts@Flatten[
         FirstPosition[#, n_ /; n >= j] & /@
          Accumulate /@ Tuples@i], #, 0] & /@
     Range@Length[
       i = ToExpression[#~s~"-" & /@ s@#2] /. {a_, b_} :> a~Range~b];
   Riffle[r@# <> "/" <> r@Tr@t & /@ t, " "] <> "") &

Usage as specified in the challenge:
f[29, "8 15-17 2 3-5 6-8"]

It returns 0/1 for all elements if the first input is larger than the maximum time span.

I think Cases[] is not necessary given how Tuples works. If so, then t = Lookup[Counts[Join @@(FirstPosition[#, n_ /; n >= j] & /@ Accumulate /@ Tuples@i)], #, 0].

Lookup and Counts are welcome additions to the language.

@DavidCarraher Thanks, but I had to switch to Flatten (instead of Join@@) because FirstPosition can now return Missing[NotFound] which can't be joined.

Haskell, 232
f=(\(a,b)->[a..fst$head$reads(tail$b++" ")++[(a,b)]]).head.reads
n%l=(tail>>=zipWith(-))(0:map(\i->drop i&l*e[x|x<-map sum$mapM f$take i$w l,x>=n])[1..e$w l])>>=(++'/':show(id&l)++" ").show
(&)i=product.map(e.f).i.w
w=words
e=length

run like this:
*Main> putStrLn $ 1 % "8 15-17 2 3-5 6-8"
27/27 0/27 0/27 0/27 0/27

APL, 162
{{⍵,'/',y}¨⌊|-2-/0,(y←+/,⍺≤⊃⌽x)×1,⍨¯1↓⍺{+/÷∘⍴⍨⍺≤,⍵}¨x←∘.+\{⊃{⍺,⍺↓⍳⍵}/⍎('-'⎕R' ')⍵}¨('\S+'⎕S'\0')⍵}

Example runs
      f←{{⍵,'/',y}¨⌊|-2-/0,(y←+/,⍺≤⊃⌽x)×1,⍨¯1↓⍺{+/÷∘⍴⍨⍺≤,⍵}¨x←∘.+\{⊃{⍺,⍺↓⍳⍵}/⍎('-'⎕R' ')⍵}¨('\S+'⎕S'\0')⍵}
      29 f '8 15-17 2 3-5 6-8'
 0 / 27  0 / 27  0 / 27  24 / 27  3 / 27

      1 f '8 15-17 2 3-5 6-8'
 27 / 27  0 / 27  0 / 27  0 / 27  0 / 27

      38 f '8 15-17 2 3-5 6-8'
 0 / 10  0 / 10  0 / 10  0 / 10  10 / 10

      40 f '8 15-17 2 3-5 6-8'
 0 / 1  0 / 1  0 / 1  0 / 1  1 / 1

I hope you don't mind the weird spacing

This is 98 bytes only. APL has their own codepage such that all of their symbols fit in the ASCII range.

authors: ทวีชัย เรืองกระโทก


text:
Coating Every Pancake
You have a stack of pancakes on a plate with a glob of syrup on top so thick it can't run down the sides. You won't be happy to eat until both faces of each pancake have at least touched the syrup, but right now only one face of the top pancake has.
You know that the syrup will never soak through even one pancake, but it can be transferred indefinitely via face-to-face contact between two pancakes. Once a face of a pancake has touched syrup it is considered coated in syrup forever, and will make any non-syrup coated face that touches it syrup coated as well. It is possible to transfer syrup to and from the top side of the plate as well.
You proceed to coat every pancake face with syrup by inserting a spatula below one or more pancakes and flipping them all over, exactly as is done in pancake sorting. (Unfortunately this spatula is syrup-resistant, and does not help to distribute the syrup by touching pancake faces.) Sadly you lose track of which pancake faces have touched syrup but you do remember the flips you have made.
Given your past flips can you determine if your pancakes are all coated with syrup yet?
Challenge
Write a program that takes in a positive integer N for the number of pancakes, and a list of positive integers (all <= N) for the flips you have made so far. Each number in the list represents the number of pancakes that were flipped. Output a truthy value if the pancakes are done being coated and a falsy value if not. (truthy/falsy definition)
The input should come from stdin or the command line and the output should go to stdout (or closest alternatives). It's fine if your input needs a little extra formatting: e.g. [1, 1, 2, 2] instead of 1 1 2 2 for the list.
Examples
Assume N = 2, so we have a stack of two pancakes on a plate, starting with the syrup on top.
If the list is 1 1 2 2, this means we...

flip the top pancake - coating the upper face of the bottom pancake
flip the top again - coating the original bottom face of the top pancake
flip both - coating the plate
flip both again - coating the original bottom face of the bottom pancake

Since all four faces are coated the output would be something like True or 1.
If the list is 1 2 2 1, this means we...

flip the top pancake - coating the upper face of the bottom pancake
flip both - coating nothing
flip both again - coating nothing
flip the top again - coating the original bottom face of the top pancake

Since the face touching the plate is still syrup-free the output would be something like False or 0.
Notes

The flip list may be arbitrarily large and can be empty, in which case the output is falsy.
The plate acts as a syrup-carrier but it doesn't matter if it gets coated or not. (In fact any flip solution will coat the plate because the pancake face it touches must be coated, but regardless.)
The plate cannot be flipped.
You can assume these pancakes are unit disks with no sides to speak of, only two opposite faces.

Scoring
This is code-golf. The shortest solution in bytes wins.

This is a very, very nice challenge. ;)

is a function that gets a list and returns a boolean is okay?

@proudhaskeller Not if your language has support for stdin/command line.

"The top side of the plate can also be syrup coated" is ambiguous. I think it would be clearer as "It is possible to transfer syrup to and from the top side of the plate".

There should be a bonus if anyone can implement it in this language.

@grc There is now a bounty for just that!

@Calvin'sHobbies Awesome! It looks hard though...

Is there an upper limit for the number of pancakes?

@TwiNight No, except for some reasonable int max value like 2^16.

I did try to do this in Pancake Stack. It is way too hard. However, I feel honored to have my ugly, quickly thrown together interpreter being used (hopefully).

Heres my solution in Pancake Stack: Put syrup on the pancakes! ;)

If I have understood that correctly, a working Pancake Stack solution should be about 300 lines long. It has neither arrays nor 3-variable rotations.

CJam, 32 30 29 bytes
q~2@#2b\{)/(W%)1$0=|@]s:~}/:&

Try it online.
Test cases
$ cjam pancakes.cjam <<< '2 [1 1 2 2]'; echo
1
$ cjam pancakes.cjam <<< '2 [1 2 2 1]'; echo
0

How it works
q~                            " N, L := eval(input())                                     ";
  2@#2b                       " P := base(2 ** N, 2)                                      ";
       \{                }/   " for F in L:                                               ";
         )/                   "   P := split(P, F + 1)                                    ";
           (W%)               "   T, U, V := P[1:], reverse(P[0])[:-1], reverse(P[-1])[0] ";
               1$0=|          "   V |= U[0]                                               ";
                    @]s:~     "   P := map(eval, str([U, V, T]))                          ";
                           :& " print and(P)                                              ";

CJam? More like CRup.

Haskell, 92 90 86 84 114 110 99 98
the requirement of a full program is so annoying. I wonder why would anyone require this.
m(n:s)=all(<1)$foldl(\r@(p:s)n->reverse(take n s)++(p*r!!n):drop n s)[0..n]s
main=readLn>>=print.m

this solution works by representing the pile of pancakes by a list of the sides, when adjacent pancakes share the same side. every side is a number, and a side is coated if it has a zero value.
run as:
*Main> main
[2,1,1,2,2]
True

+1 for not using Python 2 ;)

@Calvin'sHobbies lol

I'm afraid a full program is required...

@JanDvorak I didn't see that... I just asked if a function is okay in the comments of the question. if it isn't, i'll change it

@proudhaskeller now you have been told explicitly by OP... I expect a change soon.

@JanDvorak of course

It's possible to tweak the input format, meaning you can read it as a whole without splitting into words. Another hint of mine is that using interact isn't always beneficial ;-)

@JanDvorak thanks for the hints! I never thought of giving hints instead of giving straightforward tips. I used your first tip, but I still use interact. is there any better than this?

Here's another hint before I get home: there's a function that combines half of interact with read, and there's a function that combines half of interact with show. Can you guess their signatures? The rest is Hoogle.

@JanDvorak thanks for the hints! is this what you thought of?

Python, 92 bytes
I think this works:
s=[1]+[0,0]*input()
for f in input():x=f*2;s[0]=s[x]=s[0]|s[x];s[:x]=s[x-1::-1]
print all(s)

It uses a list of pancake faces (plate included) to remember which are coated with syrup. Pancakes are flipped by reversing part of the list, but any syrup is first transferred between the top face and the newly revealed face.
Usage:
$ python pancakes.py
2
1, 1, 2, 2
True

That is a really, really clever way to reverse. +1

It looks like you're excluding the plate from the "is everything syrupy" check. Do you need to? When all pancake faces are coated, the plate will be touching a syrupy pancake face, so the plate will be syrupy too.

@user2357112 Yes, you're right. Thanks!

Python 2: 75
A simplification of grc's and feersum's solution.
n,b=input()
s=[1]+[0]*n
for x in b:s[:x+1]=s[x::-1];s[x]|=s[0]
print all(s)

Storing the syrup state of 2*n+1 pancake edges is redundant because touching edges are always the same. This instead remembers the state of each of n+1 pancake junctions. That way, syrup transfer is automatically accounted for.
The only update needed is to preserve the syrup at the x junction when a flip cuts it. This is done by or-ing the post-flip syrup at 0 into x.
Taking input twice doesn't affect the character count.
s=[1]+[0]*input()
for x in input():s[:x+1]=s[x::-1];s[x]|=s[0]
print all(s)

Python 2, 93 bytes
At first I was going to post my answer, but then grc had already posted a very similar one a minute before. So I tried to come up with some improvements. The only one I could find is to use a lexicographic list comparison instead of all().
Edit: Fixed a mistake introduced by unsuccessfully trying different input methods which doesn't change character count.
n,F=input()
L=[1]+2*n*[0]
for f in F:f*=2;L[0]=L[f]=L[0]|L[f];L[:f]=L[~-f::-1]
print[1]*2*n<L

Sample input/output:
2, [1, 1, 2]

False

APL, 77
∧/⊃{x[1]+←⍺⌷x←⍵⋄(⌽⍺↑x),⍺↓x}/(⌽1+⎕),⊂1,⎕⍴0

Haskell, 129 125
t(m:l)=all(any(<1).(\i->foldr(\n->foldr($)[].map(n%))[i]l))[0..m]
n%i|i>n=(i:)|i<n=(n-i:)|1>0=(n:).(0:)
main=readLn>>=print.t

Probably not completely golfed yet, but it works without manipulating a list of coated sides.  Instead, it works its way backwards to figure out whether a given side of a given pancake has ever come in contact with anything that was the top side at the beginning.  foldr effectively traverses the list of flips backwards, therefore there is no reverse.
So here is the algorithm:  We map over all relevant sides ([0..m]) and make a list of sides that our side inherits syrup from at each step, starting from the back: initially the list is just [i], but with a flip of n pancakes, each entry becomes [n-i] if i<n, [n,0] if i==n, and [i] if i>n.  The side in question has been coated if and only if the resulting list after all flips contains a 0 (any (<1)).  all does the rest, and main converts all this into a runnable program.
The program takes its input from stdin in the form of [n_pancakes, flip1, flip2, flip3, ...], terminated by a newline.

interesting approach.

how about instead of using functions to code the inherits list to use lists, i.e. n%i|i>n=[i]|i<n=[n-i]|0<1=[n,0] and instead of foldr($)[].map(n%) have (=<<).(%), that will map all inherits and join them.

you made me realize I can start with a stack of [0..] and represent a coated pancake as 0 instead of making nonzero pancakes coated. thanks!

Python 2, 107
d=[1]+[0,0]*input()
for i in input():n=2*i;d[:n]=reversed(d[:n]);d[n]=d[n-1]=d[n]|d[n-1]
print(all(d[:-1]))


text:
Create a Flowchart Quine
A flowchart algorithm is a type of pseudocode designed for human readability and makes it easy to see the program flow.
For this program, you need to output your own program as a flowchart. You may not read your own source code and the output must be a PNG of any size.
The flowchat must be a step by step representation, therefore the number of blocks in your chart should roughly the same number of operations in your program.
Please include your code's output in your answer.
The shortest code wins.
Specs
These are guidelines, if your language is not good enough to make the necessary calculations easily, you may approximate the shape as good as you can.
Conditional
The largest angles in this diamond shape should be 126.86° and the smallest angles should be 53.18°. The colour of it should be HTML colour #E5E4E2. All of the sides should be the same length.
Data Input/Output
The largest angles in this parallelogram should be 116.57° and the smallest angles should be 63.43°. The colour of it should be HTML colour #667C26. The long side to short side ratio should be 3:2.
Process
This should be a rectangle with the colour being HTML colour #FBF6D9. The dimensions should be in the height-length ratio 2:3.
Terminator
This should be an ovaloid with the colour being HTML colour #B38481. The dimensions should be in the height-length ratio 2:3.
Arrowhead
This should be an isoceles triangle with the smallest angle being 40° and the two bigger angles being 70°. The entire arrow must be of HTML colour #000000.
http://www.utexas.edu/courses/streeter/s15-5037.04/Overheads/Symbols.jpg

I'm really unclear on how flowchart units are expected to correspond to code units. You say 'the number of blocks in your chart should roughly the same number of lines in your program", but a line can contain many operations. Could the whole program sans output go into a basic processing symbol?

There are no specs on how the ovaloid corners should be shaped. May we use just a rectangle?

There are no specs concerning the arrow size. May we omit the arrow entirely, saying it is of size 0? Also, what are the requirements concerning edge routing?

I think the constraints on the graphics are too strict. In most languages at least one thing will add enormous complexity to draw the correct angles which will make it almost impossible to solve the actual challenge. But maybe I'm wrong.

Someone use tupper's formula somehow

Why are you guys nitpicking about the graphical specification so much? There is no reason to use anything except one rectangle, which is a quite straightforward shape.


text:
Let's play countdown!
For those of you who have seen the popular daytime TV show Countdown, you will know that the contestants are given 9 randomly selected letters and must then find the longest word they can in 30 seconds.
Your challenge is, given a string of 9 letters, to find the longest word that is an anagram of the largest subset of input letters, this means that you don't have to use all of the letters in the input string.
Input/output can be stdin/stdout, or whatever the equivalent in your language is.
Rules

Input will always a 9 letter string, all lower-case
You can use as few or as many of the letters from the input string
A word is allowed if it is found in the specified dictionary file, the dictionary file containing all the allowed words can be found here (note: I didn't compile this, credit goes to the github uploader). The file is is a .txt file which contains ~101,000 words with each word on a new line - approx 985kB.
You must use the dictionary file specified above, this is to ensure that all fairness across all the entries, e.g. so everyone has the same chance of finding the longest word.
You are allowed to manipulate the dictionary file in such a way that none of the words are edited in any way and no new ones are added, for example copying all the words to an array, making all words comma separated or copying the whole contents of the file to another file would be allowed.
Inputs may contain any number of vowels and consonants, e.g. 9 vowels or 8 consonants and 1 vowel
If there are multiple words with the same length, then you must output all of them (up to a limit of 5 - to prevent long lists of 5/6 letter words). Multiple words must be delimited, but this can be done in any way - comma, space etc.

Test Cases
Input: mhdexaspo
Output: hexapods, mopheads
Input: iesretmng
Output: regiments
Input: cmilensua
Output: masculine calumnies
Input: floiufhyp
Output: huffily puffily
Input: frtuasmjg
Output: frusta,jurats,jumars,tragus,grafts
This is code-golf, so shortest code wins!

Input can be stdin/stdout or whatever the equivalent for your language is.

Borderline dupe of Anagram Code Golf!

@PeterTaylor I don't think so as that one you are just working out whether 2 strings have the same amount of characters. Where mine you have to work out the longest anagram of a single string.

So yours adds a loop, changes an == to a <=, and adds some post-processing to sort by length. I haven't voted to close as a dupe, but I did consider it.

I'm a little bit in love with Rachel Riley :x

Countdown fans may also like the question, Express a number - a modern “Des Chiffres et des Lettres”.  (“Des Chiffres et des Lettres” was the original from which Countdown was licensed).

CJam, 51 bytes
Laeas$W%{1$f++}/:A;qN/{$aA&},{,~}$5<_0=,:L;{,L=},S*

CJam has no file I/O, so I opted to read the dictionary (converted to Unix format) from STDIN and read the string of letters as a command-line argument.
Test cases
$ for w in mhdexaspo iesretmng cmilensua floiufhyp frtuasmjg
> do cjam countdown.cjam $w < dictionary.txt
> echo
> done
hexapods mopheads
regiments
calumnies masculine
huffily puffily
frusta gamuts grafts jumars jurats

How it works
La        " Push T := [ '' ].                                                         ";
eas       " Push the command-line argument (R) as a string.                           ";
$W%       " Sort its letters, then reverse.                                           ";
{1$f++}/  " Iterate over the letters; prepend them to copies of the strings in T.     ";
:A;       " Save in A and discard. A contains all sorted substrings of R.             ";
qN/       " Read from STDIN and split at linefeeds.                                   ";
{$aA&},   " Filter; keep dictionary words D such that {sort(D)} ∩ A ≠ ∅.              ";
{,~}$     " Sort by negated word length.                                              ";
5<        " Keep only the first five words.                                           ";
_0=,:L;   " Save the length of the first in L.                                        ";
{,L=},    " Filter; keep dictionary words D such that len(D) = L.                     ";
 S*       " Separate by spaces.                                                       ";

Python 3, 171 bytes
This requires the dictionary to be stored in a file named w with each word separated by spaces.
Thanks to @wjandrea
s=input()
z=lambda s,f:all(f>{c}and not f.remove(c)for c in s)
l=[i for i in open('w').read().split()if z(i,set(s))]
print([x for x in l if len(x)==max(len(x)for x in l)])

Examples
gbahrcswn # Input
['branch', 'whangs'] # Output

andapandamandarandaonsdf
['fandoms', 'pardons']

Split on whitespace (newlines) instead of commas and you can save three bytes.

Python, 175
Instead of checking if each word in the dictionary is an anagram of the input, this program calculates all the anagrams of the input and looks for them in ths dictionary.
If the dictionary is pre-sorted, this scales logarithmically, instead of linearly, with the size of the dictionary; it's probably also shorter :)
from itertools import*
s=raw_input()
n=9
J="".join
while n:
 W=[J(p)for c in combinations(s,n)for p in set(permutations(c))if J(p)+"\n"in open("d")];n-=1
 if W:print W[:5];n=0

Assumes the dictionary is in a newline-terminated file named d in the current directory.
Note that the golfed program is ridiculously slow since it re-reads d on every search.
If you want to test it, add D=set(open("d")) at the beginning, and replace open("d") with D.

JavaScript (ES6), 165 bytes
I fear I may have gone down the wrong path with this one - it's pretty ugly! It works, but it's very resource intensive - I thought my machine might explode if I tried a combination of letters that only contained 6 (or fewer) letter words!
I was so focused on getting this to work that I didn't leave myself much time to golf it; any help would be appreciated. In particular, I'm trying to figure out why, when I pass the initial string of letters as a single element array, thus allowing me to remove the 2 splits and the join, it throws an error on y.replace()
Assumes the dictionary is already available in an array variable named d.
f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`)

Try It
As I said, this solution is resource intensive so the following Snippet uses a limited dictionary, with only the words necessary for the 2 test cases I've included. If you're brave enough to try the full dictionary and your own input, you can do so here.

d=["dapping","genipap","huffily","kepping","knapped","peaking","puffily"]
f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`)
console.log(f("floiufhyp"))
console.log(f("ingpepkad"))