title: Choosing Languages for Golfing

text:
# Question
Title: Choosing Languages for Golfing
What are some tips for choosing the right language to golf? What factors affect the language to be chosen?

Here are some example problem types:

* Problems that require *I/O* solution, either console or file
* Problems that require *parsing*
* Problems that requires you to write your solution as a *function definition*
* Math problems
* Problem dealing with prime numbers
* Solving number puzzles
* Performing numerical methods
* String processing
* Array processing
* Tricky 2D array problems
* Computational geometry
* Recursion
* 2D graphics
* 3D graphics
* Audio
* Networking / web
* Parallel processing

Don't simply say things like "Use GolfScript|J" because you like them.

# Answer
> 0 votes
Depends on what one needs, C/C++ is fast, but you have to code more of the work yourself. Python and Ruby are slower but are a lot easier to code with built in methods that shortens a lot of work and they automatically handle infinitely large values (if one has the RAM). Using a functional language like Haskell is great for purely mathematical functional use if one can frame the problem that way.

# Answer
> 15 votes
Putting my two cents in on *array programming languages*, **J** and **APL** in particular.

K/Kona, Q, and Nial fall in this category too, but they generally have the same benefits and criticisms. Use discretion. I will use J examples below, mostly because these are ASCII and thus easy to type--remember than APL characters count as single bytes, so don't let that be your problem with the language as choice for golfing.

* Math problems
* Solving number puzzles
* Performing numerical methods
* Tricky 2D array problems

These two are very good math and data-manipulation languages, because they toss arrays around a high level, and a lot of looping is done *implicitly*, by saying, e.g. add ten to each of 3, 4, and 5 (`10 + 3 4 5`) or sum each row of an array (`+/"1 arr`--the looping is in the `"1`).

* Problem dealing with prime numbers

With prime number problems in particular, J has fast and short builtin primitives, as do some dialects of APL. (Edit: I'm thinking of Nars2000, which is part dialect and part completely different implementation. APL has no builtin for primes.) N-th prime (`p:`), no. of primes up to (`_1&p:`), factoring (`q:`), GCD and LCM (`+.` and `*.`), and so on, there's a lot there. However, in practice, the question will often specify that you have to cook your own prime implementations, so these don't see too much use. There are still neat and fancy ways of getting the prime stuff you need, it just becomes a little less cut-and-paste.

* String processing
* Array processing

Array and string processing is a bit of a mixed bag: if it's something that APL/J is good at or has a primitive or common idiom for, it's nearly trivial; if it's something that's very sequential and not very parallelizable, you're going to have a bad time. Anything in between is up in the air, though usually they will respond favourably.

* Problems that require I/O solution, either console or file
* Problems that requires you to write your solution as a function definition

IO is weird. APL has a single-character input expression, but with J you have to spend at least 8 to read in a number: `".1!:1]1`. Output is a little less verbose, but you're still looking at 6 or 7 characters wasted, in practice. J in particular really likes it a lot if you can take in the input as arguments to a function, instead of having to muck around with IO itself.

In practice, with J and APL, usually the solution is written as a function that you invoke at the console. With APL, you can basically just put in variable names for your arguments and wrap the expression you were working with in curly braces and call it a day.

But with J, there's a bit of an overhead for defining functions explicitly--`3 :'...'`, and you have to escape any strings inside--so what is usually done is something called tacit programming: you program at the function level, combining primitives in a manner not unlike that of Haskell. This can be both a blessing and a curse, because you don't have to spend as many characters referring to your arguments, but it's easy to drown in parentheses and end up losing tens of characters trying to hack your otherwise short and clever solution into something that works.

* Problems that require parsing
* Computational geometry

I don't have experience with golfing these particular problems, but I will say this: in the end, array programming languages are very good at piping and transforming lots of data in the same way. If you can turn the problem into an exercise in number shuffling, you can make it an APL/J problem, no sweat.

That said, not everything is an APL/J problem. Unlike Golfscript, APL and J just happened to be good for golfing, alongside their other benefits ;)

# Answer
> 7 votes
Why hasn't Perl been praised yet? It's an excellent golfing language, for nearly every one of these, especially string related stuff (regex).

Burlesque is good for number-related programs, while Ruby is great for simpler text manipulation.

There's actually a list of languages and golfing scores over here.

# Answer
> 3 votes
I like using obscure programming languages to (try to) get the job done.

Here are my favorites for the details you listed:

**Problems that require I/O solution, either console or file**

Languages like *TI-Basic* work well, but I prefer *Ruby* because of `puts`

**Problems that require parsing**

*GolfScript* will definitely aid you here

**Problems that requires you to write your solution as a function definition**

*TI-84 Table* \- allows functions as `Y=` e.g. `Y=|X|` returns the absolute value of X

**Math problems**

*TI-Basic* \- made for a calculator, so it includes math ;)

**Problem dealing with prime numbers**

Nothing special; *Mathematica* is probably the right tool for the job

**Solving number puzzles**

*TI-Basic* as it automatically loops through arrays

**Performing numerical methods**

*TI-Basic* or *Mathematica*

**String processing**

*Python* \- has some great string functions.

No matter how good you think *TI-Basic* is, **don't use it** for strings...

**Array processing**

*TI-Basic* \- **automatically loops through arrays**; e.g. increment all values in the array - `L1+1→L1`

*Ruby* \- also has very powerful array features, and of course the `!` will help compress code also

**Tricky 2D array problems**

*Ruby* or *Python* works best here, as *TI-Basic* doesn't support 2D arrays

**Computational geometry**

*TI-Basic* has geometric features and can be used for most math up to Calculus and Linear Algebra

---

***BONUS***

**Looping**

Either *Arduino* or *Quomplex*. *Arduino* has a built-in `void loop(){}` and *Quomplex* has the infinite loops contained by brackets (`[]`)

**Drawing/GUI**

*Game Maker Language* has **very** powerful drawing features, and *TI-Basic* is also a generally useful tool because of the support for drawing on the graph.

**Quines**

Either *HQ9+* or *Quomplex* because *HQ9+* has the `Q` to output the program's source code and *Quomplex* will automatically print out its source code unless `*` (output) is specified or it produces no output, defined with `#`

# Answer
> 3 votes
If you're solving a math problem and you don't have Mathematica, try Sage. It is based on Python, so if you already know Python you don't need much time to learn its syntax.

Examples:

It is also useful for graph plotting and equation solving (e.g. you can use the `solve()` function in Sage, or if that is forbidden by the rules, it allows an easy implementation of the Newton Raphson process because it has the `diff()` function that can perform symbolic differentiation).

Besides, if you are a Python2 programmer, using Sage may allow you to cheat by skipping the long `import` statements. For example, `math` and `sys` are already imported by default. (Note that this may not work if your Python2 program depends on integer division.)

# Answer
> 2 votes
I know three languages - Java, C++, and Python 3. I know none of these at a high level, but this is my experience with them.

## Java:

I would never use Java for golfing again. It takes over 80 characters just to write `Hello World!`. However, it does have its strengths:

> Input requires creation of a `Scanner` object. It is difficult to input a single character. It requires specification of what types you are inputting.
> Parsing is simple enough because of the `for` loop. The enhanced `for` loop is excellent for this.
> Java supports methods, but the method declaration is quite long.
> Java is excellent at math, as well as all other high-level languages.
> Java is difficult to use when the problem involves modifying strings. You cannot make modifications to an existing string.
> Java's arrays are simple to use.
> Java is good at recursion.
> Java includes built-in graphics. They are very easy to use.

## C++

C++ is a very strong language, but it is somewhat lengthily when trying to golf at 56 characters for `Hello world!`.

> Input and output are easy. You need not specify what types you are inputting - that is done automatically. However, you must include the iostream library.
> Parsing is very easy.
> Function declaration is simple, but eats a lot of important characters. C++ excels at math, but it does not include PI or E, as Java does.
> C++'s strings are easy to use and change as needed.
> I use `vector`s where possible instead of `array`s, but both are easy to use.
> C++ is good at recursion.
> C++ does not include built-in graphics.

## Python 3

Python 3 is similar to C++ and Java. It is much shorter as it is not strongly-typed - in other words, it just guesses at what the variables are.

> Input is easy, but everything is input as strings. You must manually convert all input to whatever values you want.
> Parsing and looping is very simple.
> Python function declarations are quite simple and short.
> Python is good at math.
> Python's strings are simple to use.
> Arrays are simple to use.
> Python is good at recursion.
> Python does not include built-in graphics.

---
Tags: code-golf, tips
---


# Question
Title: Display the explosion of a star in ASCII-art
The goal is to animate a star exploding in ASCII art, starting from a single star character `*` to a supernovae and finally to the space void.

Rules :

* You have to display only 80 characters per line on 24 lines (this is the default terminal size on Linux)
* Only these 95 printable characters from ASCII are allowed
* Steps:
    1. The initial star must be `*` and centred horizontally and vertically
    2. The star has to grow to show that it explodes
    3. At the end the screen must be empty (the star has disappeared)
* Length of the code or languages are irrelevant
* Votes will decide of the most creative and beautiful results. Have you ever seen an exploding star? Let's see how you imagine this.

I've added an answer using Python as an example, but you're encouraged to create something different or better.

You have one week to participate, the winner will be chosen on 2014-04-01.

Samples of output (with some frames only):

```
# start

                                        *

# during explosion

                                    ****#****
                                 ***#@##*#@#****
                               *@**@@@*##**#*#**#*
                              **@@*#**#@*#@****#***
                              ****@*@***#****@**@@*
                             *******@***@@***#****#*
                              *#***#*##@****##@@@**
                              **#@###****@*********
                               *****@**@*@*****@**
                                 ************@**
                                    ****#****

# star is expanding

                                        *
                               ********* **@******
                           ****   **#**@ #**#*#   ****
                         ***  **  **##** *@@*@*  **  ***
                       **  *  @@   *@*#* ***@*   *#  *  **
                     *** #  *  *#  *@#** ***@*  **  @  * *@*
                    ** *  * ** *@  ****@ @****  ** #* *  * **
                   ** * @* * ** *@  #### *#**  ** ** * @* * **
                  *# * # ** * #* *  **** ****  @ ** * ** * * #*
                 ** * *# * @ * #  @  @*@ *#*  *  @ # # * @* * **
                 *# * * * * # * @* * **# *#* * ** * * * * * # **
                 ** # * * @ * * # * # ** @* * * * * * # @ @ * **
                *# * * * * * * * * # * * * * * * @ @ * * * * * **
                 *# * @ * @ * @ * * * ** *@ * * # * * * * * @ @*
                 *# # @ * * # * *@ * *** @#@ @ ** * @ @ * * # **
                 *# * ** * * * @  @  **@ ***  *  @ * * * @* * #*
                  ** * * ** * #@ *  #*** **##  * #* * #@ * * @*
                   *# * *@ * @@ *#  **** @***  ** ** * #* * #*
                    *# *  * *@ **  @**@* *@#**  ** ** *  * @*
                     *#* @  *  @@  **##* ****@  **  #  * @**
                       **  @  #*   @*@#* @*@*#   @#  *  **
                         *#*  @*  @#*@*# **#*@#  **  ***
                           ****   *##**# #***@*   @***
                               ****@**@* *****@***

# star is disappearing

               *  -  -  --  --   ------- -------   --  --  -  -  *
             ** -  -  -  --  --   ------ ------   --  --  -  -  - **
            * -- - -- -- --  --   ------ ------   --  -- -- -- - -- *
          ** - -  - -- -- --  --  ------ ------  --  -- -- -- -  - - **
         *  - - -- - -- -  -  --   ----- -----   --  -  - -- - -- - -  *
        ** - - - -- - -- -  -  --  ----- -----  --  -  - -- - -- - - - **
        * - - - -  - - -  - -- --  ----- -----  -- -- -  - - -  - - - - *
       * - - - -  - - - -- - -- --  ---- ----  -- -- - -- - - -  - - - - *
      * -- - - - - - - - -- - -- -  ---- ----  - -- - -- - - - - - - - -- *
      * - - - - - - - -- - - - -  -  --- ---  -  - - - - -- - - - - - - - *
      * - - - - - - - - - - - - -- - --- --- - -- - - - - - - - - - - - - *
      * - - - - - - - - - - - - - - - -- -- - - - - - - - - - - - - - - - *
     * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
      * - - - - - - - - - - - - - - - -- -- - - - - - - - - - - - - - - - *
      * - - - - - - - - - - - - -- - --- --- - -- - - - - - - - - - - - - *
      * - - - - - - - -- - - - -  -  --- ---  -  - - - - -- - - - - - - - *
      * -- - - - - - - - -- - -- -  ---- ----  - -- - -- - - - - - - - -- *
       * - - - -  - - - -- - -- --  ---- ----  -- -- - -- - - -  - - - - *
        * - - - -  - - -  - -- --  ----- -----  -- -- -  - - -  - - - - *
        ** - - - -- - -- -  -  --  ----- -----  --  -  - -- - -- - - - **
         *  - - -- - -- -  -  --   ----- -----   --  -  - -- - -- - -  *
          ** - -  - -- -- --  --  ------ ------  --  -- -- -- -  - - **
            * -- - -- -- --  --   ------ ------   --  -- -- -- - -- *
             ** -  -  -  --  --   ------ ------   --  --  -  -  - **

# the star is gone

(there is nothing)

```

Animated example of output:

If you want some inspiration, you can look at an explosion from Captain Blood, a game from 1988.

# Answer
# C + curses

I haven't made much of an effort to tidy up the source code. Basically it calculates an expanding shock wave, with a solid background added to the first few frames to give a sort of flash effect. *\[\[EDIT: The explosion looked a bit odd appearing from a single asterisk, so I added a few frames of expansion at the beginning of the animation.\]\]*

Random particles are superimposed on top of this, with positions determined according to a basic perspective calculation to give it a slightly 3D feel. (Well that was the idea, anyway.)

```
#include <curses.h>
#include <stdlib.h>
#include <math.h>

#define NUM_FRAMES 150
#define NUM_BLOBS 800
#define PERSPECTIVE 50.0

typedef struct {
  double x,y,z;
} spaceblob;

double prng() {
  static long long s=1;
  s = s * 1488248101 + 981577151;
  return ((s % 65536) - 32768) / 32768.0;
}

int main() {
  char *frames[NUM_FRAMES], *p;
  int i,j,x,y,z,v,rows,cols,ith,i0;
  int maxx,minx,maxy,miny,delay=1E6;
  double bx,by,bz,br,r,th,t;
  spaceblob *blobs;

  /* Initialize ncurses and get window dimensions */
  initscr();
  getmaxyx(stdscr,rows,cols);
  minx = -cols / 2;
  maxx = cols+minx-1;
  miny = -rows / 2;
  maxy = rows+miny-1;

  /* Generate random blob coordinates */
  blobs = malloc(NUM_BLOBS * sizeof(spaceblob));
  for (i=0; i<NUM_BLOBS; i++) {
    bx = prng();
    by = prng();
    bz = prng();
    br = sqrt(bx*bx + by*by + bz*bz);
    blobs[i].x = (bx / br) * (1.3 + 0.2 * prng());
    blobs[i].y = (0.5 * by / br) * (1.3 + 0.2 * prng());;
    blobs[i].z = (bz / br) * (1.3 + 0.2 * prng());;
  }

  /* Generate animation frames */
  for (i=0; i<NUM_FRAMES; i++) {
    t = (1. * i) / NUM_FRAMES;
    p = frames[i] = malloc(cols * rows + 1);
    for (y=miny; y<=maxy; y++) {
      for (x=minx; x<=maxx; x++) {

        /* Show a single '*' in first frame */
        if (i==0) {
          *p++ = (x==0 && y==0) ? '*' : ' ';
          continue;
        }

        /* Show expanding star in next 7 frames */
        if (i<8) {
          r = sqrt(x*x + 4*y*y);
          *p++ = (r < i*2) ? '@' : ' ';
          continue;
        }

        /* Otherwise show blast wave */
        r = sqrt(x*x + 4*y*y) * (0.5 + (prng()/3.0)*cos(16.*atan2(y*2.+0.01,x+0.01))*.3);
        ith = 32 + th * 32. * M_1_PI;
        v = i - r - 7;
        if (v<0) *p++ = (i<19)?"%@W#H=+~-:."[i-8]:' '; /* initial flash */
        else if (v<20) *p++ = " .:!HIOMW#%$&@08O=+-"[v];
        else *p++=' ';
      }
    }

    /* Add blobs with perspective effect */
    if (i>6) {
      i0 = i-6;
      for (j=0; j<NUM_BLOBS; j++) {
        bx = blobs[j].x * i0;
        by = blobs[j].y * i0;
        bz = blobs[j].z * i0;
        if (bz<5-PERSPECTIVE || bz>PERSPECTIVE) continue;
        x = cols / 2 + bx * PERSPECTIVE / (bz+PERSPECTIVE);
        y = rows / 2 + by * PERSPECTIVE / (bz+PERSPECTIVE);
        if (x>=0 && x<cols && y>=0 && y<rows)
          frames[i][x+y*cols] = (bz>40) ? '.' : (bz>-20) ? 'o' : '@';
      }
    }

    /* Terminate the text string for this frame */
    *p = '\0';
  }

  /* Now play back the frames in sequence */
  curs_set(0); /* hide text cursor (supposedly) */
  for (i=0; i<NUM_FRAMES; i++) {
    erase();
    mvaddstr(0,0,frames[i]);
    refresh();
    usleep(delay);
    delay=33333; /* Change to 30fps after first frame */
  }
  curs_set(1); /* unhide cursor */
  endwin(); /* Exit ncurses */
  return 0;
}

```
> 29 votes

# Answer
## Javascript

Thought it was worth a shot in JS. Suggest saving and running; very very slow if you paste in console.

```
var boomboom = (function() {
    //Clear any existing page
    document.getElementsByTagName("body")[0].innerHTML="";

    var space=document.createElement("div");
    var iterator=0;
    var stars = 50;
    var timer=100;

    //Set container
    space.setAttribute("id","space");
    space.setAttribute("style","width:1000px;height:600px;margin:auto;border:solid 1px #000;position:relative;overflow:hidden;background:#000;color:#fff");
    document.getElementsByTagName("body")[0].appendChild(space);

    //Set interval and draw...
    var interval = setInterval(function(){ drawStars(iterator,stars); }, timer);
    drawStars(iterator, stars);

    function drawStars(r,c) {
        clearInterval(interval);

        //a container for this set of stars
        var starContainer=document.createElement("div");

        //don't draw more if there are too many, it's got to go
        if(iterator < 1000) {
            for(var i = 0; i < c; i++) {
                var x,y;

                if(iterator < 100) {
                    x=500 + r * Math.cos(2 * Math.PI * i / c) * 0.7;
                    y=300 + r * Math.sin(2 * Math.PI * i / c) * 0.7;
                }

                //add some randomness for the boom boom
                if(iterator > 100) {
                    x=500 + r * Math.cos(2 * Math.PI * i / c) * 0.7*Math.random();
                    y=300 + r * Math.sin(2 * Math.PI * i / c) * 0.7*Math.random();
                }

                //Make a star
                var star=document.createElement("div");
                star.setAttribute("class","star");

                //Exploding stars are red, I hope
                var color = iterator < 100 ? "color:#fff" : "color:rgb("+parseInt(255*Math.random())+",0,0)";
                star.setAttribute("style","position:absolute; left:"+ x +"px;top:"+ y +"px;"+color);

                //Change the star character as boom boom gets bigger
                if(iterator <= 200) {
                    star.innerText="*";
                }
                else if(iterator >=200 & iterator <= 400) {
                    star.innerText="O";
                }
                else  {
                    star.innerText="-";
                }
                //Add the star to its container
                starContainer.appendChild(star);
            }
        }
        //draw the container
        space.appendChild(starContainer);

        //increment the iterator.  It's an iterator because we're using intervals and it's late.
        iterator+=5;

        //remove stars when we get too many
        if(iterator > 200) {
            space.removeChild(space.firstChild);
        }
        if(iterator < 1500) { //do it all again
            timer = timer > 10 ? timer-10 : timer;
            interval=setInterval(function(){ drawStars(iterator,stars); }, timer);
        }

        //make sure it's actually empty
        else {
            space.innerHTML="";
        }
    }
}());

```

**Edits** In JSBin: http://jsbin.com/worofeqi/5/watch?js,output

Oddly runs much more smoothly when done from local file system than in JSBin. Honestly not sure why; may look at that this evening.
> 7 votes

# Answer
# Python

```
#!/usr/bin/python

import sys, math, time, random

def distance(x, y):
    # ((y - y_center) * 2) -> correct ratio for a true circle
    return math.ceil(math.sqrt(((x - 40) ** 2) + (((y - 12) * 2) ** 2)))

def star(radiuses):
    for r in radiuses:
        #~ clear screen: http://stackoverflow.com/a/2084521/2257664
        print chr(27) + "[2J"

        # width
        for y in range(24):
            # height
            for x in range(80):
                d = distance(x, y)

                #~ border
                if (d == r):
                    sys.stdout.write('*')
                #~ inside the star
                elif (d < r):
                    if (r > 35):
                        sys.stdout.write(' ')
                    elif (r > 25) and ((d % 2) != 0):
                        sys.stdout.write('-')
                    elif (r > 15) and ((d % 2) == 0):
                        sys.stdout.write(' ')
                    else :
                        sys.stdout.write(random.choice('****#@'))
                #~ space outside the star
                else:
                    sys.stdout.write(' ')
            print
        time.sleep(0.1)

star(range(0, 12) + range(10, 0, -1) + range(0, 50))

```

Example output (using less steps and without clearing the screen).

Excerpts of the output are also displayed in the question.
> 1 votes

---
Tags: popularity-contest, ascii-art
---


# Question
Title: Underhanded contest (?): Anti-Virus wars
Prove anti-virus software is paranoid by making a program that simply opens and alphabetically sorts a CSV file, that will get flagged as a virus (or malware/spyware/any threat really) when run.

You will be assessed by the following criteria:

* Does the cross-platform anti-virus package ClamAV detect it as a threat?
* Your code is not actually a virus (if the code looks fishy it will be deducted points)
* Conciseness of code

The specific target for this challenge is the following version of ClamAV with the following virus definitions (current as of the posting of this challenge). Your program must trigger this set of software/definitions to be eligible.

You may wish to use a virtual machine for testing your code.

```
Latest ClamAV® stable release is: 0.98.1
ClamAV Virus Databases:
main.cvd ver. 55 released on 17 Sep 2013 10:57 :0400 (sig count: 2424225)
daily.cvd ver. 18639 released on 19 Mar 2014 06:45 :0400 (sig count: 839186)
bytecode.cvd ver. 236 released on 05 Feb 2014 12:36 :0500 (sig count: 43)
safebrowsing.cvd ver. 41695 released on 19 Mar 2014 03:00 :0400 (sig count: 1147457)

```

# Answer
> 13 votes
# bash (113)

```
sort -t, "$1"
#PK^C^D^@^@^@^@^@^@^@^@^@^@^@^@^@^@D^@^@^@D^@^@^@^@^@^@^@X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

```

The above uses caret notation. Notably, `^@` indicates a null byte.

### How it works

* `sort -t, "$1"` sorts the file specified as the first command-line argument (`$1`), using the comma character as field delimiter (`-t,`).
* `#` at the beginning of the second line comments it out; it will get ignored by bash.
* `PK^C^D^@^@^@^@^@^@^@^@^@^@^@^@^@^@D^@^@^@D^@^@^@^@^@^@^@` is the shortest possible *ZIP file local file header*:

+ `PK^C^D` (0x04034B50) is the *local file header signature*.
    + `^@^@^@^@^@^@^@^@^@^@^@^@^@^@` specifies the ZIP version, a bit flag, the compression method and the compressed file's mtime and checksum. All are set to zero.
    + The twice occurring `D^@^@^@` (0x00000044 or 68) specifies the file's compressed and uncompressed length (68 bytes).
    + `^@^@^@^@` specifies the filename and extra header length. Both are set to zero.
* `X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*` is the 68 byte long EICAR test string, which serves as the data associated to the above header.

This takes advantage of the fact that ClamAV will act on all *ZIP file local file headers*, even if they're encountered outside of actual ZIP files.

### Malware scan

VirusTotal gives 15 false positives out of its current 51 scanners. This includes ClamAV.

---
Tags: code-golf, underhanded
---


title: Taking the dog for a walk

text:
# Question
Title: Taking the dog for a walk
My dog is barking at me, but I'm too lazy to take him for a walk. I have an idea! I'll get the people at Code Golf to do it for me!

Your challenge is to simulate a dog's walk. Here are the rules for walking the dog:

* The human (`H`) will start at `0,0` on a (Cartesian) coordinate plane, and will randomly go one space either up, left, right, or down every second.
* The dog (`D`) will start at the same location, and will go either zero, one, two, or three spaces either up, left, right, or down every second (randomly, of course). The dog is less predictable and will sometimes run faster or stop completely.
* The dog will never get more than a certain amount of units away from the human (in Euclidean distance), which is the length of the leash (`L`). For example, if `L` is `6`, a valid position would be `H(0,0) D(4,4)` (since the distance is about 5.65 units), but not `H(0,0) D(5,4)` (about 6.4 units).
    + If, when the dog moves, it would violate the leash distance requirement, it must go the farthest it can in its determined direction that does not violate the distance requirement. For example, if the position is `H(0,0) D(3,4)` and the dog is randomly decided to move 3 spaces to the right, it will go to `D(4,4)`, since that's the farthest it can go without getting more than 6 units away. (Note that this might result in a movement of 0 spaces, i.e. no movement at all!)
* Miscellaneous rules: the human moves first. The human must not exceed the leash length on its move. If it does, it must choose another direction. "Random" means "with an even distribution and with no patterns."

The input will be given in this format (can be STDIN, function parameter, file, etc.):

```
"<amount of seconds the walk will last> <leash length>"

```

For example:

```
300 6 // a 5 minute walk with a 6 yard leash

```

You must give output in this format (can be STDOUT, function return value, file, etc.):

```
H(0,0) D(0,0)
H(0,1) D(2,0)
H(1,1) D(2,1)
H(1,0) D(2,-1)
...

```

(The amount of lines output will be `seconds + 1`, since the `H(0,0) D(0,0)` line doesn't count.)

This is , so the shortest code in bytes will win!

# Answer
> 2 votes
### GolfScript, 140 characters

```
~.*:L;)[0.].@{['H('1$','*') D('4$','*')'n]@@{[@~]}+[{)}{(}{\(\}{\)\}]:^%{{~2$~@-.*@@-.*+L>!},}:F~.,{rand}:R~=\[.;{.[~}^4R=+{]}+4R*]F-1=\}*;;

```

Example run (try online):

```
> 10 3
H(0,0) D(0,0)
H(0,1) D(0,0)
H(0,0) D(0,2)
H(0,1) D(-1,2)
H(1,1) D(-1,2)
H(1,2) D(-1,4)
H(1,3) D(-1,5)
H(0,3) D(-1,5)
H(-1,3) D(1,5)
H(-1,4) D(1,5)
H(0,4) D(-1,5)

```

# Answer
> 6 votes
# CoffeeScript - 324 + function call

Demo (Using Leash 10):

```
H(0,0) D(0,0)
H(0,-1) D(0,3)
H(-1,-1) D(0,3)
H(-1,-2) D(-1,3)
H(-1,-3) D(-4,3)
H(-1,-2) D(-4,4)
H(-1,-3) D(-5,4)
H(-1,-2) D(-2,4)
H(-1,-3) D(-2,5)
H(-1,-4) D(-2,5)
H(-1,-3) D(-3,5)
H(0,-3) D(-4,5)
H(-1,-3) D(-4,6)
H(-1,-4) D(-2,6)
H(-2,-4) D(-2,6)
H(-3,-4) D(-5,6)
H(-4,-4) D(-5,6)
H(-4,-3) D(-5,8)
H(-5,-3) D(-2,8)
H(-5,-2) D(-2,8)
H(-5,-3) D(-2,5)

```

Code:

```
w=(i)->
    [s,l]=i.split ' ';m=Math;h=[0,0];d=[0,0];r=->(4*m.random())|0
    a=->m.abs(h[0]-d[0])**2+m.abs(h[1]-d[1])**2<=l**2
    b=(x)->if x%2 then 1else-1
    for i in[0..s]
        console.log "H(#{h}) D(#{d})"
        loop
            H=h.slice();x=r();h[(x/2)|0]+=b x;break if a();h=H
        D=r();x=r();(d[(x/2)|0]+=b x;d[(x/2)|0]-=b x if!a())while D-->0

```

Long Code:

```
human = [ 0, 0 ]
doge = [ 0, 0 ]
randomDirection = -> [ 'u', 'd', 'l', 'r' ][(4*Math.random())|0]
allowed = -> Math.abs(human[0] - doge[0]) ** 2 + Math.abs(human[1] - doge[1]) ** 2 <= leash**2
leash = 0
walk = (input) ->
    [ seconds, leash ] = input.split ' '
    for i in [0..seconds]
        console.log "H(#{human}) D(#{doge}) #{Math.sqrt Math.abs(human[0] - doge[0]) ** 2 + Math.abs(human[1] - doge[1]) ** 2}"
        valid = no
        loop
            oldHuman = human.slice()
            switch randomDirection()
                when 'u'
                    human[0]--
                when 'd'
                    human[0]++
                when 'l'
                    human[1]--
                when 'r'
                    human[1]++

            if allowed()
                break
            else
                human = oldHuman

        dogeDistance = (Math.random() * 4)|0
        switch randomDirection()
            when 'u'
                while dogeDistance-- > 0
                    doge[0]--
                    doge[0]++ if !allowed()
            when 'd'
                while dogeDistance-- > 0
                    doge[0]++
                    doge[0]-- if !allowed()
            when 'l'
                while dogeDistance-- > 0
                    doge[1]--
                    doge[1]++ if !allowed()
            when 'r'
                while dogeDistance-- > 0
                    doge[1]++
                    doge[1]-- if !allowed()
walk "10 2"

```

# Answer
> 4 votes
## Ruby, 189 177

I can possibly drop this a bit. I don't love `j`.

```
h=d=0;e,l=$*
def j;[1,-1,?i,'-i'].sample.to_c end
0.upto(e.to_i){puts'H(%d,%d) D(%d,%d)'%(h.rect+d.rect)
1 while((g=h+j)-d).abs>l.to_i
h,s=g,j
3.times{d+=s if(d+s-h).abs<=l.to_i}}

```

Ungolfed:

```
h=d=0 # use complex numbers since it has distance built in
time,leash=$*

def randomDirection
  [1,-1,'i','-i'].sample.to_c
end

0.upto(time.to_i) { # (1 + time) times
  puts"H(%d,%d) D(%d,%d)"%(h.rect+d.rect) # that's [h.real, h.imag, d.real, d.imag]

  # find a newH that doesn't violate the leash
  newH = h + randomDirection
  while((g-d).abs > leash.to_i)
    newH = h + randomDirection
  end

  h = newH

  newD = randomDirection
  3.times{
    # keep adding newD until you hit the leash
    d += newD if(d + newD - h).abs <= leash.to_i
  }
}

```

# Answer
> 2 votes
# Mathematica 285

## Golfed

```
r=RandomChoice;k=False;
s:=r[{{0,1},{-1,0},{1,0},{0,-1}}]
w:=r[{0,1,2,3,4}]
f[{-1,___}]:="";
f[{n_,l_,{h_,d_}}]:=
(Print["H(",h,")\t","D(",d,")"];
m[i_,u_,v_]:=EuclideanDistance[u+i,v]<l;
z=k;While[z==k,t=s;z=m[t,h,d]];
y=h+t;t=w*s;z=k;While[z==k,t=t-Sign@t;z=m[t,d,y]];
dp=d+t;f[{n-1,l,{y, dp}}])

```

**Example**

```
f[{17,7,{{0,0},{0,0}}}]

```

> H({0,0}) D({0,0})
> H({1,0}) D({0,0})
> H({2,0}) D({0,2})
> H({2,-1}) D({0,-1})
> H({1,-1}) D({-3,-1})
> H({1,0}) D({-3,1})
> H({1,1}) D({0,1})
> H({1,2}) D({0,2})
> H({1,1}) D({0,2})
> H({1,0}) D({-2,2})
> H({2,0}) D({1,2})
> H({2,-1}) D({-2,2})
> H({2,0}) D({-2,3})
> H({2,1}) D({-2,0})
> H({1,1}) D({-2,3})
> H({2,1}) D({-2,6})
> H({1,1}) D({-3,6})
> H({0,1}) D({-4,6})

---

## UnGolfed

There are some comments in the text below. I've also included a printout which makes it possible to follow some of the calculations.

```
step:=RandomChoice[{{0,1},{-1,0},{1,0},{0,-1}}]
dogWander:=RandomChoice[{0,1,2,3,4}]

f[{-1,___}]:="";

f[{n_,l_,{humanPos_,dogPos_}}]:=
Module[{tempStep,moveOK,hp,hp1,dp,p,test},

(* human imagines step, checks with leash, chooses another step if would choke the dog *)
moveOK[intendedStep_,pos1_,pos2_]:=EuclideanDistance[pos1+intendedStep,pos2]<l;
test=False;While[test==False,tempStep=step;test=moveOK[tempStep,humanPos,dogPos]];
hp=humanPos+tempStep;
Print["humanPos before: ", humanPos,"\t","human step: ",tempStep,"\thumanPos after: ",hp,"\tdistance from dog: ",N@EuclideanDistance[hp,dogPos]];

(*move closer to human if needed *)
tempStep=dogWander*step;
test=False;While[test==False,tempStep=tempStep-Sign[tempStep];test=moveOK[tempStep,dogPos,hp]];
dp=dogPos+tempStep;
Print["dog's intended step: ",tempStep,"\tdogPos before: ",dogPos,"\t","dog actual step: ",tempStep, "\t","dogPos after: ",dp,"\tdistance: ",N@EuclideanDistance[hp,dp],"\n"];
f[{n-1,l,{hp, dp}}]]

```

Example

```
f[{17,5,{{0,0},{0,0}}}]

```

\[Part of the printout is shown to give a sense of how the code works. \]

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


title: Make a word cloud from a text

text:
# Question
Title: Make a word cloud from a text
The code should take text from standard input:

```
The definition of insanity is quoting the same phrase again and again and not expect despair.

```

The output should be a PNG file containing the word cloud corresponding to that text:

The above word cloud was created using a specialized online application and it filtered the word `The` and other common words (`of`, `is`, `and`, `not`, and `the`). Since this is code golf, the common words will not be filtered and I leave secondary aesthetics of the word cloud to the choice of each coder. Unlike the image exampled here, no words should be excluded, common or otherwise. The definition of a word is defined below.

In this case a word is anything alpha-numeric; numbers are not acting as separators. So, for example, `0xAF` qualifies as a word. Separators will be anything that is not alpha-numeric, including `.`(dot) and `-`(hyphen). Thus `i.e.` or `pick-me-up` would result in 2 or 3 words, respectively. Should be case sensitive - `This` and `this` would be two different words, `'` would also be separator so `wouldn` and `t` will be 2 different words from `wouldn't`.

The tags should appear clustered but not overlapping and the font size should be directly proportional to the number of occurrences of that word in the text. The word should appear only once. Specific font color is not required in this case. Semantic association is not a requirement.

**Hint** \- This other code golf could help: Count the words in a text and display them

# Answer
# Python 3, 363 308 293 274 characters

```
import os,sys,re,collections as C
c=C.Counter()
n=sys.argv[1]
o="graph d{"
for w in re.findall("\w*",open(n).read()):c[w]+=1
for w,x in c.most_common(75)[1:]:o+="%s[fontsize=%s,shape=none];"%(w,x/5)
open(n+'.dot','w').write(o+"}")
os.system("fdp -Tpng %s.dot>%s.png"%(n,n))

```

Call it like this: `python cloud.py file.txt`. The script uses Graphviz's `fdp` force-directed graph generator to generate the image (it will spit out a GraphViz file to file.txt.dot and a PNG image file to file.txt.png). *This means you'll need to have Graphviz installed.*

The image above is the cloud it makes of Shakespeare's Hamlet - you can tell, since it contains "To be or not to be". There's also some delightful nonsense to be found:

> It is, to You and I, the Ham of Not thatO lord have us, what now...
> 7 votes

# Answer
## JAVASCRIPT 473

```
var wordCloud=function(e){var t=e.split(/[\s-.,;]+/);var n={},r;for(r in t){var i=t[r];n[i]=n[i]+1||1}var s=document;var o=s.createElement("canvas");o.width=600;o.height=400;o.style.display="none";s.body.appendChild(o);var u=o.getContext("2d");var a=0,f=50;for(var i in n){u.font=n[i]*50+"px monospace";u.fillText(i,a,f+n[i]*5);a+=i.length*n[i]*50;if(a>o.width*.6){a=0;f+=n[i]*5+100}}var l=o.toDataURL("image/png");var c=s.createElement("img");c.src=l;s.body.appendChild(c)}

```

### Ungolfed demo

```
wordCloud("string;abc,test-omg shouldn't test omg lalala. s2 s2 s2")

```
> 5 votes

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


title: Swap genders on this page (code-golf)

text:
# Question
Title: Swap genders on this page (code-golf)
Yesterday at work, the Google Doodle convinced me to share my rather long gender swap script here, but the code-golf criteria of the question i asked were not clear. As my question still got downvoted after giving examples, i changed the tag to popularity-contest, as suggested before i clarified it.

Here's a more golfy version:

The UN theme for International Women's Day 2014 is "Equality for Women is Progress for All".

In the interest of gender equality, write a program that correctly changes that Wikipedia page from a female to a male perspective. Names and anatomical details may be left unchanged. It should not change who is being referred to.

Example:

Before:

> He said she took her girlish books on Feminism with her.

After:

> She said he took his boyish books on Masculism with him.

All gendered pronouns and nouns, as well as all adjectival forms of such words, must be changed in the visible English text.

The shortest code that fully transforms the linked version of the IWD Wikipedia page according to the stated rules, wins.

# Answer
**JavaScript, 707 bytes (680 in web console)**

```
javascript:(function(){l=function(s){return s.toLowerCase()};b=document.body;t=b.innerHTML;s="Actress;Actor;Daughters;Sons;Feminine;Masculine;Feminism;Masculism;Feminist;Masculist;Femininity;Masculinity;Mother;Father;Mothers;Fathers;Motherland;Fatherland;Motherhood;Fatherhood;Woman;Man;Female;Male;Females;Males;Girl;Boy;Girls;Boys;Girlfriends;Boyfriends;Grandmothers;Grandfathers;Her;His;She;He;Sister;Brother;Wives;Husbands;WomenWatch;MenWatch;Women;Men;Womensday;Mensday;Internationalwomensday;Internationalmensday;IWD;IMD";a=s.split(';');c=t.split(/\b/);d={};for(i=0;i<a.length;i+=2){x=a[i];y=a[i+1];d[x]=y;d[y]=x;d[l(x)]=l(y);d[l(y)]=l(x)}t='';for(i=0;i<c.length;++i)t+=d[c[i]]||c[i];b.innerHTML=t})()

```

This is a bookmarklet/favelet; set as URL of a bookmark/favorite and click to transform the loaded webpage.
> 2 votes

# Answer
Not a completely worked out answer, but Cees' substitution solution reminded me of the str\_replace syntax in PHP:

```
$body = file_get_contents($url);
$body = str_replace(
  array("Actress", "Daughters", "Feminine", "Feminism", "Feminist", "Femininity", "Mother", "Mothers", "Motherland", "Motherhood", "Woman", "Female", "Females", "Girl", "Girls", "Girlfriends", "Grandmothers", "Her", "She", "Sister", "Wives", "WomenWatch", "Women", "Womensday", "Internationalwomensday", "IWD"),
  array("Actor", "Sons", "Masculine", "Masculism", "Masculist", "Masculinity", "Father", "Fathers", "Fatherland", "Fatherhood", "Man", "Male", "Males", "Boy", "Boys", "Boyfriends", "Grandfathers", "His", "He", "Brother", "Husbands", "MenWatch", "Men", "Mensday", "Internationalmensday", "IMD"),
  $body);

```

You can shorten this by putting everything into one string, e.g.

```
str_replace(
  split(';', "Actor;Sons;Masculine;Masculism;Masculist;Masculinity;Father;Fathers;Fatherland;Fatherhood;Man;Male;Males;Boy;Boys;Boyfriends;Grandfathers;His;He;Brother;Husbands;MenWatch;Men;Mensday;Internationalmensday;IMD"),
   ....

```

but that only makes it marginally better. I'll leave it up to someone to come up with the creative solution.
> 1 votes

---
Tags: code-golf
---


title: A golfed golfing game

text:
# Question
Title: A golfed golfing game
You have to make a golf game with the following specification :-

1. The field is 10 X 10 characters without spaces.
2. Free ground is represented by `.`
3. A hole generated at random(not at `0,0`) is shown by `O` (its alphabet and not zero).
4. The ball starts at `0,0` represented by `X`.
5. You can hit the ball with input `d 4` (meaning direction to the bottom with magnitude of 4 characters after the ball more like vectors in physics).

**Example:**

```
X.........
..........
..........
..........
..........
..........
..........
..........
..........
.........O
score : 0
b 4

```

But, since you are not so good at golfing therefore the force you think is applied is often only close to the actual force that is applied !(if `x` the offset in force then **-2 \< X \< +2**)
6. you should have to tell the real force applied and display the ball moved to that real force like this :-

```
lets say the ball actually moved by 3.

..........
..........
..........
X.........
..........
..........
..........
..........
..........
.........O
score : 1
applied force : 4
real force    : 3

```

The four directions are `U (up), D (down), l (left), r (right)` and magnitude of force should be between 0 and 10 (excluding both 0 and 10).
7. The ball should not bounce off the edges, if the force reaches that much then the the ball stops at the last point at the boundary.

```
r 9

..........
..........
..........
.........X
..........
..........
..........
..........
..........
.........O
score : 2
applied force : 9
real force    : 11

```
8. In the end when the game is finished you have to display `Par in <n> shots!` (where n is score)

## Coding:

1. You have to design a working program showing the exact output.
2. post the code in `golfed` and `ungolfed` versions.
3. also post a successful test run (images if possible).
4. No use of functions or languages excessively specialized to this task (I don't know if they really exist!)

## Winner:

Winner will be chosen 1 week from now. Winner is the submission with least characters.

# And, most important thing

Best of luck **:)**

# Answer
# K, 319 305 308

```
{b:(10*!-_-(100)%10)_@[100#".";0,1?100;:;"XO"];c:0 0;e:s:-1;while["O"in,/b;e@b;e"Score : ",$s+:1;h:"SI"$" "\:0:0;h[1]:1|*(w:h 1)+1?-2+!5;b:.[;;:;]/[b;(c;d:9&((`r`d`l`u!({(0,x)+};{(x,0)+};{(0,-x)+};{(-x,0)+}))[h 0]h 1)c);".X"];c:d;e"Applied force : ",$w;e"Real force    : ",$h 1];e"Par in ",($1+s)," shots!";}

```

Could definitely golf this more. Incrementing/decrementing the indices is what kills me and could probably be done much simpler.

(Slightly) more readable than the one liner:

```
golf:{[]
    b:(10*!-_-(100)%10)_@[100#".";0,1?100;:;"XO"];
    c:0 0;e:s:-1;
    while["O"in,/b;
        e@b;
        e"Score : ",$s+:1;
        h:"SI"$" "\:0:0;
        h[1]:1|*(w:h 1)+1?-2+!5;
        b:.[;;:;]/[b;(c;d:9&((`r`d`l`u!({(0,x)+};{(x,0)+};{(0,-x)+};{(-x,0)+}))[h 0]h 1)c);".X"];
        c:d;
        e"Applied force : ",$w;
        e"Real force    : ",$h 1];
    e"Par in ",($1+s)," shots!";
    }

```

.

```
k)golf[]
X.........
..........
..........
..........
.......O..
..........
..........
..........
..........
..........
Score : 0
d 4
Applied force : 4
Real force    : 4
..........
..........
..........
..........
X......O..
..........
..........
..........
..........
..........
Score : 1
r 7
Applied force : 7
Real force    : 5
..........
..........
..........
..........
.....X.O..
..........
..........
..........
..........
..........
Score : 2
r 2
Applied force : 2
Real force    : 1
..........
..........
..........
..........
......XO..
..........
..........
..........
..........
..........
Score : 3
r 1
Applied force : 1
Real force    : 1
Par in 4 shots!

```
> 2 votes

# Answer
# Scala, 605

Golfed:

```
import scala.util.Random;object G extends App{var b,h=(0,0);while(b==h)h =(Random.nextInt(10),Random.nextInt(10));var s=0;def f{for(y<- 0 to 9){for(x<- 0 to 9)print(if(b==(x,y))"X"else if(h==(x,y))"O"else ".");println};println("score : "+s)};f;while(b!=h){val i=readLine.split(" ");val x=i(1).toInt.ensuring(a=>a>0&&a<10)-1+Random.nextInt(3);b=i(0).toLowerCase match{case "d"=>(b._1,b._2+x) case "u"=>(b._1,b._2-x) case "r"=>(b._1+x,b._2) case "l"=>(b._1-x,b._2)};b=(b._1.min(9).max(0),b._2.min(9).max(0));s+=1;f;println("applied force : "+i(1));println("real force : "+x)};println("Par in "+s+" shots!")}

```

Just a straight-forwardly implemented ice-breaker. Input is read line-by-line from stdin and power lower then 1 or higher then 9 will result in an `AssertionError` to comply with the specs.

I am pretty sure there are shorter programs, but let's see how far we get ;-)

Ungolfed:

```
import scala.util.Random

object Golf extends App {
  var b, h = (0, 0)
  while (b == h) h = (Random.nextInt(10), Random.nextInt(10))
  var s = 0

  def field {
    for (y <- 0 to 9) {
      for (x <- 0 to 9)
        print(if (b ==(x, y)) "X" else if (h ==(x, y)) "O" else ".")
      println
    }
    println("score : " + s)
  }
  field
  while (b != h) {
    val i = readLine.split(" ")
    val x = i(1).toInt.ensuring(a => a > 0 && a < 10) - 1 + Random.nextInt(3)
    b = i(0).toLowerCase match {
      case "d" => (b._1, b._2 + x)
      case "u" => (b._1, b._2 - x)
      case "r" => (b._1 + x, b._2)
      case "l" => (b._1 - x, b._2)
    }
    b = (b._1.min(9).max(0), b._2.min(9).max(0))
    s += 1
    field
    println("applied force : " + i(1))
    println("real force : " + x)
  }
  println("Par in " + s + " shots!")
}

```

Random example run:

> ```
> X......O..
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 0
>
> ```
>
> r 8
>
> ```
> .......OX.
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 1
> applied force : 8
> real force : 8
>
> ```
>
> l 1
>
> ```
> .......OX.
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 2
> applied force : 1
> real force : 0
>
> ```
>
> l 1
>
> ```
> .......X..
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> ..........
> score : 3
> applied force : 1
> real force : 1
> Par in 3 shots!
>
> ```
> 2 votes

# Answer
## Julia, 427

This is pretty straightforward on the whole. Julia isn't really designed to deal with I/O very heavily, as she's intended for large-scale scientific computation. But for our limited purposes here, she obliges by accepting some STDIO and playing a little game of golf with us.

*Edit: charged myself two additional characters because I had omitted the spaces after the colon for applied force and real force.*

```
a=fill(".",10,10)
x,y,s,b,c=1,1,0,iceil(10rand()),iceil(10rand())
a[x,y],a[b,c]="X","O"
while(x,y)!=(b,c)
print(a)
m=readline(STDIN)
d,f=m[1],m[2]
o=(d in"Ul"?-1:d in "Dr"?1:0)
g=clamp(round((f-48)+4rand()-2),1,9)*o
a[x,y]="."
x,y=(d in "UD"?clamp(x+g,1,10):x),(d in "lr"?clamp(y+g,1,10):y)
a[x,y]="X"
s+=1
print("score : ",s,"\napplied force : ",f,"\nreal force    : ",abs(g),"\n")
end
print(a,"\nPar in ",s," shots!")

```

Here's a sample game, in which the final putt becomes an increasingly trying situation for our golfer.

(Note that occasionally our Ints get converted to Floats on the fly...ah, the vagaries of dynamic typing.)

```
X . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> r5
score : 1
applied force : 5
real force    : 7.0
. . . . . . . X . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D3
score : 2
applied force : 3
real force    : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . X . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> l3
score : 3
applied force : 3
real force    : 3.0
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D1
score : 4
applied force : 1
real force    : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . O . . . . .
. . . . X . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> U1
score : 5
applied force : 1
real force    : 2.0
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . O . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
STDIN> D1
score : 6
applied force : 1
real force    : 1
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . X . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

Par in 6 shots!

```
> 2 votes

# Answer
# PHP - 563

```
<?php
$b=[0,0];do{$h=[rand(0,9),rand(0, 9)];}while(!($h[0]|$h[1]));
$s=0;function o(){global$b,$h,$s;for($y=0;$y<10;$y++){for($x=0;$x<10;$x++){$p=[$y,$x];if($p==$b)echo'X';elseif($p==$h)echo'O';else echo '.';}echo "\n";}echo "score : $s
";}o();while($h!=$b){list($d,$p)=explode(' ',fread(STDIN,9));$P=max(1,min(9,$p+rand(-2,2)));switch($d){case'u':$b[0]-=$P;break;case'd':$b[0]+=$P;break;case'l':$b[1]-=$P;break;case'r':$b[1]+=$P;break;}$b=[max(0,min(9,$b[0])),max(0,min(9,$b[1]))];$s++;o();echo "applied force : ${p}real force    : $P
";}echo "Par in $s shots!";

```

```
X.........
......O...
..........
..........
..........
..........
..........
..........
..........
..........
score : 0
d 1
..........
X.....O...
..........
..........
..........
..........
..........
..........
..........
..........
score : 1
applied force : 1
real force    : 1
r 5
..........
......X...
..........
..........
..........
..........
..........
..........
..........
..........
score : 2
applied force : 5
real force    : 6
Par in 2 shots!

```

Ungolfed:

```
<?php
$ball = [0,0];
do {
    $hole = [ rand(0,9), rand(0, 9) ];
}while(!($hole[0]|$hole[1]));
$score = 0;
function out() {
    global $ball, $hole, $score;
    for($y=0;$y<10;$y++) {
        for($x=0;$x<10;$x++) {
            $p=[$y,$x];
            if($p==$ball)echo'X';
            elseif($p==$hole)echo'O';
            else echo '.';
        }
        echo "\n";
    }
    echo "score : $score
";
}
out();
while($hole!=$ball) {
    list($direction, $power) = explode(' ',fread(STDIN,10));
    $rPower=$power+rand(-2,2);
    switch($direction) {
        case 'u':$ball[0]-=$rPower;break;
        case 'd':$ball[0]+=$rPower;break;
        case 'l':$ball[1]-=$rPower;break;
        case 'r':$ball[1]+=$rPower;break;
    }
    $ball[0]=max(0,min(9,$ball[0]));
    $ball[1]=max(0,min(9,$ball[1]));
    $score++;
    out();
    echo "applied force : ${power}real force    : $rPower
";
}
echo "Par in $score shots!";

```
> 1 votes

---
Tags: code-golf, ascii-art, game
---


title: The poet's quine

text:
# Question
Title: The poet's quine
Write a quine with 1 or more rhyme scheme from http://en.wikipedia.org/wiki/Rhyme\_scheme when read. The following characters are spoken aloud:

* any alphanumeric words or characters not in a comment;
* comparison and arithmetic characters (+ plus; - minus; * times, / divided by, | or, || or, & and, && and, ! not, = equals, == equals, === equals).

The following is not accounted for (is not spoken aloud):

* any characters which signify the beginning or end of string literals ("');
* any characters which signify the beginning or end of logical blocks ((){}\[\]);
* any characters which signify the delineation of a variable, function or line of code (.,;).
* any characters in comments;

The "spoken aloud" rules always apply. the "not spoken aloud" rules apply to all languages, except Brainfuck, K, J, APL, Befunge and Sclipting. In the case of APL, Brainfuck, Befunge, K and J, any character not mentioned in "spoken aloud rules" are subject to the "choose consistently" rule outlined above. Sclipting characters are pronounced like they would be if they were that Chinese character, with free choice of which pronounciation you use.

Any characters which are not explicitly allowed or denied pronounciation are free to be pronounced or kept silent. However, a specific character is either always pronounced or always kept silent. You may not pronounce # as hashtag in one line and keep # silent in the next.

Words may be pronounced in any dialect or language, but it needs to be consistent within the same stanza (no having the first word be pronounced in a Scottish way and the second in a Welsh way).

Contest type is popularity contest. The deadline is April 23rd in honor of one of the most well known bards, William Shakespeare, who was born and allegedly died on that day. Winner is he who gets the most votes.

Edit: because I don't think there will be any more submissions, I've decided to end the contest early. I'll mark the winner momentarily.

# Answer
# Batch AABBA (Limerick)

This is my best try, but I have never been any good at poems.

Code:

```
@Echo off || cd \.
If "this"=="a largeish" pot
Type %0 || chef
Color 7f
Goto :eof || shallot

```

In english:

> Echo off else CD slash dot
> If this equals a largeish pot
> Type zero else chef
> Color seven f
> Go to EOF else shallot
> 9 votes

# Answer
# Fortran 95 (McCarron Couplet)

> McCarron Couplet: "AABBABCCDDCDEEFFEF" a contemporary take on a classic rhyming pattern, introduced by the academic James McCarron.

My code (which should be saved as `all.f95` in order for it to work):

```
character (LEN=100) :: &
bend; logical :: wondered
inquire(file="superstar &
&car",exist=wondered,number=i_r)

open(unit=100, &
file="superstar car")
if (.NOT.(.NOT.(wondered))) then
i_sum = 1; read(100,*) n

i_sum = n + i_sum
rewind(100); else; i_sum = 1
endif; write(100,*) i_sum, 10
codingThis = fun

write(bend,"(I5)") n; call &
SYSTEM ("copy all.f95 all"//&
TRIM(TRIM(ADJUSTL(bend)))//&

".f95"); open(access="append", &
unit=10,file="waterfall")
write(10,*) "foo bar"; end

```

It will copy itself to numbered files, starting with `all0.f95`, then `all1.f95`, `all2.f95`, and so on...

It reads:

```
character len equals hundred
bend logical wondered
inquire file superstar
car exist wondered, number equals IR

open unit equals hundred
file equals superstar car
if not not wondered then
I sum equals one, read hundred N

I sum equals N plus I sum
rewind hundred else I sum equals one
endif write hundred I sum ten
conding this equals fun

write bend I five N call
system copy all F point ninety five all
trim trim adjust L bend

point ninety five access append
open unit ten file waterfall
write ten foo bar end

```
> 1 votes

---
Tags: popularity-contest, quine
---


title: Implement the game of life in 3D

text:
# Question
Title: Implement the game of life in 3D
The challenge is to find the shortest implementation of the game of life in 3D (example). These are the rules:

Cells (in this case, cubes) with only 1 or less neighbours die, as if by lonliness.
If exactly 5 cells surround an empty cell, they breed and fill it.
If a cell has 8 or more neighbours, it dies from overcrowding.

Make it at least a 10x10x10, where the layers are outputted individually like this:

```
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 X 0 0 X 0 0 0 0 0
0 0 X X X 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

```

Of course, a graphic 3D simulation is also accepted
The starting position may be hardcoded but it must work if it is changed to any starting position. It must be able to calculate any amount of generations, and the user must be able to manually ask for the next generation.

Shortest code in characters wins!

I made my own implementation of this for any (cube) size: http://jensrenders.site88.net/life3D.htm You can use this to test, and you can base your code on mine, although I didn't comment it.

# Answer
> 14 votes
## Mathematica - 120 bytes

```
g=CellularAutomaton[{(l=Flatten@#;c=l[[14]];n=Total@Drop[l,{14}];Which[n<2||n>7,0,n==5||c==1,1,0<1,0])&,{},{1,1,1}},##]&

```

Certainly not a contender for the win, but that was not my intention. Also, this could probably be golfed down significantly by just figuring out the rule number. I just really wanted to write a visualisation (although I'm actually sure there are already tons out there). So here we go):

```
animateGol3d[size_, i_, n_] :=
  ListAnimate[
    Graphics3D[
      Cuboid /@ Position[#, 1],
      PlotRange -> {{0, size}, {0, size}, {0, size}} + 1
    ] & /@ g[i, n]
  ];

```

And after experimenting with a bunch of initial conditions, I got things like the following:

And here is one with a grid size of `20x20x20`. This took a few seconds to simulate and render:

By the way, this assumes periodic boundary conditions.

# Answer
> 12 votes
# APL, 46

It took me some time, but I got it down to 46 chars:

```
{(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵}

```

This is a function that takes a boolean 3D matrix of any size and computes the next generation, according to the given rules. Boundary conditions were not specified, so I chose to wrap around the other side, as in toroidal space.

**Explanation**

```
{                           ⊂⍵}   Take the argument matrix and enclose it in a scalar
               (i←2-⍳3)           Prepare an array with values -1 0 1 and call it i
                       ⌽[2]¨      Shift the matrix along the 2nd dim. by each of -1 0 1
           i∘.⊖                   Then for each result do the same along the 1st dimension
       i∘.⌽                       And for each result again along the 3rd dimension
 m←⊃+/,                           Sum element-wise all 27 shifted matrices and call it m

```

The intermediate result `m` is a matrix with the same shape as the original matrix, which counts for each element how many cells are alive in its 3×3×3 neighbourhood, including itself. Then:

```
           |5.5-m   For each element (x) in m, take its distance from 5.5
       ⍵∧3>         If that distance is <3 (which means 3≤x≤8) and the original cell was 1,
 (5=m)∨             or if the element of m is 5, then the next generation cell will be 1.

```

**Example**

Define a random 4×4×4 matrix with about 1/3 cells = 1 and compute its 1st and 2nd generation. The `⊂[2 3]` at the front is just a trick to print the planes horizontally instead of vertically:

```
      ⊂[2 3] m←1=?4 4 4⍴3
 1 0 0 0  1 0 1 0  1 0 1 0  0 0 0 1
 1 1 0 0  0 0 0 0  0 0 0 1  1 0 1 0
 0 0 0 0  0 1 0 0  0 0 0 0  0 0 1 0
 1 1 0 0  0 0 0 1  1 0 0 1  0 0 1 0
      ⊂[2 3] {(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵} m
 0 0 0 0  0 0 1 0  1 0 1 0  0 0 0 0
 1 0 0 0  0 0 1 0  0 0 0 0  1 0 1 0
 0 0 0 0  0 1 0 0  0 0 0 0  0 0 1 0
 1 1 0 0  0 0 0 0  1 0 0 0  0 0 1 0
      ⊂[2 3] {(5=m)∨⍵∧3>|5.5-m←⊃+/,i∘.⌽i∘.⊖(i←2-⍳3)⌽[2]¨⊂⍵}⍣2⊢ m
 0 0 1 0  1 0 1 0  1 0 1 0  0 0 0 0
 1 0 1 0  0 0 1 1  0 0 0 0  1 0 1 0
 1 0 0 0  1 1 0 0  0 0 1 0  1 0 1 0
 1 1 1 0  1 0 0 1  1 0 1 0  0 0 1 0

```

# Answer
> 9 votes
# J - 42 char

We are assuming a toroidal board (wraps around) in all three dimensions. J's automatic display of results appears to follow the output spec, using `1` for live cells and `0` for dead. This code works on boards of any width, length, and height (can be 10x10x10, 4x5x6, and so on).

```
(((1&<*<&8)@-*]+.5=-)~[:+/(,{3#<i:1)|.&><)

```

An explanation follows:

* `,{3#<i:1` \- Subexpression of the list of offsets for the cell and all its neighbours.
    + `<i:1` \- The list of integers between 1 and -1 inclusive.
    + `,{3#` \- Make three copies of the list (`3#`), and take the Cartesian product (`,{`).
* `(,{3#<i:1)|.&><` \- For each set of 3D offsets, shift the array. At a cost of 3 characters, you can change `|.&>` to `|.!.0&>` to not have wrap-around.
* `[:+/` \- Sum the all the shifted boards together.
* `((1&<*<&8)@-*]+.5=-)~` \- The long outer verb was a hook so it receives the board on the left and the right, and the side on the right we've been shifting and summing. The `~` swaps this around for this inner verb.
    + `5=-` \- 1 in each cell that the sum-of-shifted-boards minus the original board (i.e. the neighbour count) equals 5, and 0 in all others.
    + `]+.` \- Logical OR the above with the original board.
    + `(1&<*<&8)` \- 1 if the number being compared between 1 and 8 exclusive, 0 otherwise.
    + `(1&<*<&8)@-*` \- Compare (as above) the neighbour count, and multiply (i.e. logical AND when the domain is only 1 or 0) the logical OR result by this.

Usage is as with the APL, just apply the function to the initial board for each step. J has a functional-power operator `^:` to make this easy.

```
   life =: (((1&<*<&8)@-*]+.5=-)~[:+/(,{3#<i:1)|.&><)  NB. for convenience
   board =: 1 = ?. 4 4 4 $ 4  NB. "random" 4x4x4 board with approx 1/4 ones
   <"2 board  NB. we box each 2D plane for easier viewing
+-------+-------+-------+-------+
|0 0 0 0|1 1 0 0|0 1 0 0|0 0 1 0|
|0 1 0 0|0 0 0 0|0 0 0 1|1 0 0 0|
|0 0 0 0|0 0 1 0|0 1 0 0|0 0 0 1|
|1 1 0 0|1 0 0 0|0 0 0 1|0 1 1 0|
+-------+-------+-------+-------+
   <"2 life board
+-------+-------+-------+-------+
|0 0 0 0|0 1 0 1|0 1 0 0|0 0 1 0|
|1 1 1 1|0 0 0 0|0 0 0 1|1 1 0 0|
|0 0 0 0|0 0 1 1|0 1 0 0|0 0 0 1|
|1 0 0 0|1 0 0 1|0 0 0 1|0 1 1 1|
+-------+-------+-------+-------+
   <"2 life^:2 board  NB. two steps
+-------+-------+-------+-------+
|0 0 0 0|0 1 0 0|0 1 0 0|0 0 0 0|
|0 1 0 0|0 0 0 0|0 0 0 1|0 1 0 0|
|0 0 0 0|0 0 0 0|0 1 0 0|0 0 0 0|
|0 0 0 0|0 0 0 1|0 0 0 0|0 1 1 1|
+-------+-------+-------+-------+
   <"2 life^:3 board  NB. etc
+-------+-------+-------+-------+
|0 1 0 0|1 1 1 0|0 1 0 0|0 1 0 0|
|0 1 0 0|1 0 1 0|1 0 1 0|1 1 1 0|
|1 0 0 0|0 0 0 0|0 1 0 0|0 1 0 0|
|0 0 1 0|0 0 0 0|0 1 0 0|0 1 1 0|
+-------+-------+-------+-------+

```

I say "random" because the `?.` primitive gives reproducible random results by using a fixed seed every time. `?` is the true RNG.

---
Tags: code-golf, game-of-life
---


# Question
Title: Output an image of your source code (not-quite-a-Quine)
Code golf: Print an image of the source code.

**Requirements**

1. Must output the image of the source code itself, not a version stored elsewhere and retrieved at run time.
2. Code must be legible enough to copy out by hand and reproduce the results.

Any image format is applicable.

**Bonuses**

* -10% of your score if you allow more than one output format.
* -15% if your code is *also* a 'true' quine. i.e. it does not read its source code but the source code is embedded (see here for an example)
* -30% if your code is a strict quine - i.e the image of the code is embedded in the program (Piet solutions, I'm looking at you.).

# Answer
> 8 votes
# Sh, X & ImageMagick 18.9:

```
 import -window root a.jpg

```

This should work in any shell that has ImageMagick.

To print only the code prepend `clear &&` this comes out at 26.1

```
clear && import -window root a.jpg

```

Sample output:

# Answer
> 26 votes
# shell

By "Print an image of the source code", I assume that actually printing an image on paper would be acceptable.

```
#!/bin/sh
lpr $0

```

# Answer
> 21 votes
## Piet, 24399.76

This was not made by me.

# Answer
> 14 votes
# PHP - 487 × 0.9 × 0.85 = 372.555 (2000×99px)

```
<?php $y="imagecolorallocate";$l=[
'<?php $y="imagecolorallocate";$l=[',
'];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,"o");',
];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,"o");

```

# If warnings are fine: PHP - 479 × 0.9 × 0.85 = 366.435

```
<?php $y=imagecolorallocate;$l=[
'<?php $y=imagecolorallocate;$l=[',
'];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,o);',
];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,o);

```

You provide the output function to use as the first command line argument:

```
php timwolla.php imagepng

```

Solution with warnings:

# Answer
> 13 votes
**Whitespace, 125**

```

```

Outputs an image file in the pbm format.

If you're testing this code, please copy it by clicking on "Edit", and copying everything between the `<pre>` tags.

**Output:**

```
P1 1 1 0

```

# Answer
> 13 votes
# Mathematica, ~~37~~ 31 chars

~~```
(#2[#1[#0[#1,#2]]]&)[Defer,Rasterize]

```~~
```
(Rasterize[#1[#0[#1]]]&)[Defer]

```

Inspired by an answer in mathematica.stackexchange.com.

# Answer
> 10 votes
## AppleScript, 68 37

Alright, if you can call ImageMagick in zsh then this too is valid. I'm still hacking at something more elegant and of-the-quine-spirit for my own satisfaction, but for pure golfiness, here we are:

**New version**

```
do shell script "screencapture q.jpg"

```

**Old version**

```
tell application "System Events" to keystroke "#" using command down

```

I imagine this will still be beaten, but verbose old AppleScript does an admirable imitation of succinctness for this one.

```
do shell script "screencapture -c"

```

# Answer
> 8 votes
## Mathematica, 83

```
SelectionMove[InputNotebook[],Previous,Cell];Rasterize@NotebookRead@SelectedCells[]

```

# Answer
> 5 votes
**HTML5/Javascript : 615**

```
<canvas id='i' width=500 height=5000></canvas><script>function d(){var e=document.getElementById("i");var t=e.getContext("2d");t.font="20px Arial";var n=400;var r=25;var i=(e.width-n)/2;var s=60;str="<canvas id='i' width=5000 height=500></canvas>\n<script>"+d+"d();"+wrapText+"<\/script>";wrapText(t,str,i,s,n,r)}function wrapText(e,t,n,r,i,s){var o=t.split(" ");var u="";for(var a=0;a<o.length;a++){var f=u+o[a]+" ";var l=e.measureText(f);var c=l.width;if(c>i&&a>0){e.lineWidth=1;e.strokeStyle="blue";e.strokeText(u,n,r);u=o[a]+" ";r+=s}else{u=f}}e.lineWidth=1;e.strokeStyle="blue";e.strokeText(u,n,r)}d()</script>

```

Demo : http://jsfiddle.net/E2738/2/

One can right click on the image and save its as a PNG

# Answer
> 4 votes
## Javascript + JQuery 153 148

Regular

```
(function f(){
  c=$('<canvas/>')[0];
  a=c.getContext('2d');
  l=('('+f+')()').split('\n');
  for(i=0;i<l.length;i++)
    a.fillText(l[i],5,12*(i+1));
  $('body').append('<img src="'
      +c.toDataURL("image/png")+'"/>')
})()
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```

Golfed

```
function f(){c=$('<canvas>')[0];c.width=750;a=c.getContext('2d');a.fillText(f+'f()',5,9);$('body').append('<img src="'+c.toDataURL("png")+'"/>')}f()
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```

# Answer
> 4 votes
# Java, 570 - 10% - 15% = 427.5

("filepath" included), 554 - 10% - 15% = 415.5 ("filepath" not included)
Thanks to Andreas for removing `BufferedImage` in `java.awt.image.BufferedImage`

```
import java.awt.image.*;class Q{public static void main(String[]a)throws Exception{BufferedImage i=new BufferedImage(3500,12,1);String s="import java.awt.image.*;class Q{public static void main(String[]a)throws Exception{BufferedImage i=new BufferedImage(3500,12,1);String s=%s%s%s;char q=34;i.getGraphics().drawString(String.format(s,q,s,q,q,q,q,q),0,9);javax.imageio.ImageIO.write(i,%spng%s,new java.io.File(%sfilepath%s));}}";char q=34;i.getGraphics().drawString(String.format(s,q,s,q,q,q,q,q),0,9);javax.imageio.ImageIO.write(i,"png",new java.io.File("filepath"));}}

```

Output:

To view properly, see this link: https://i.stack.imgur.com/RRSDw.png

This works just like a regular quine, except it outputs to an image. The current format is `png`, but the format can easily be changed by replacing all instances of `png` in the program with whatever format you want.

Unlike a few answers here, this is a true quine; no reading of the program file.

# Answer
> 3 votes
## zsh, 57 × 0.9 = 51.3

Pass it the output filename as an argument.

```
convert -annotate +0+10 "$(<$0)" -size 320x14 xc:white $1

```

Produces:

>

# Answer
> 3 votes
## C99 (using SDL & SDL\_ttf), ~~414~~ ~~354~~ 346 - 15% = 294.1

```
#include<SDL_ttf.h>
#define Q(P)char*q=#P;P
Q(
i=5;main(){for(SDL_Surface*s=SDL_SetVideoMode(2048,80,SDL_Init(SDL_INIT_VIDEO),TTF_Init());i--;SDL_SaveBMP(s,"q.bmp"))SDL_BlitSurface(TTF_RenderText_Blended(TTF_OpenFont("q.ttf",9),(char*[]){"#include<SDL_ttf.h>","#define Q(P)char*q=#P;P","Q(",q,")"}[i],(SDL_Color){~0}),0,s,&(SDL_Rect){0,16*i});}
)

```

This is pretty ugly without more line breaks, but unfortunately they need to be absent. The text-rendering function doesn't grok control characters at all, so any line breaks in the code have to be rendered manually in the output.

Here's the same code but with some extra line breaks thrown in for legibility:

```
#include<SDL_ttf.h>
#define Q(P)char*q=#P;P
Q(
i=5;main(){for(SDL_Surface*s=SDL_SetVideoMode(2048,80,
SDL_Init(SDL_INIT_VIDEO),TTF_Init());i--;SDL_SaveBMP(s,"q.bmp"))
SDL_BlitSurface(TTF_RenderText_Blended(TTF_OpenFont("q.ttf",9),
(char*[]){"#include<SDL_ttf.h>","#define Q(P)char*q=#P;P","Q(",q,")"}[i],
(SDL_Color){~0}),0,s,&(SDL_Rect){0,16*i});}
)

```

Sadly, this doesn't also add line breaks to the graphical output:

The output is still legible, though with 9-point output and the red font color, it's a bit squinty. You can improve it at the cost of a character by replacing the `9` with `12`. (Note that the dimension of the resulting image is hardcoded to 2048x80. To accommodate the differences in various fonts, a fair bit of excess has been added to the right margin and the leading, enough so that a size-12 font should still fit comfortably. If you wish to increase it further, however, the dimensions will probably need to be altered as well.)

The command to build the program is:

```
gcc -Wall -o imgquine imgquine.c -lSDL_ttf `sdl-config --cflags --libs`

```

The program assumes that there is a font file called `q.ttf` in the current directory when run. I took care of this beforehand by running the following command (which should work on most modern Linuxes):

```
ln -s `fc-match --format='%{file}' sans` ./q.ttf

```

(Feel free to import your own favorite TrueType font instead.)

After running the program, the image output will be created in the current directory, in a file named `q.bmp`. Unfortunately Windows bitmap files are the only output format that this program provides. Adding more output formats would require linking in more libraries.

Note that this program takes advantage of C99's syntax for introducing non-simple literal values, thus significantly reducing the number of variables that need to be defined. This is something that more C golfers should take advantage of.

# Answer
> 2 votes
## Ruby, 104 characters

```
require "RMagick"
include Magick
Draw.new.annotate(i=Image.new(999,99),0,0,0,9,File.read($0))
i.display

```

Example output, per request: i.imgur.com/jMC594C.png

# Answer
> 2 votes
# C# - 498 - 15% = 423.3

This can probably be golfed more. I've never done quines or this kind of graphics in C# before:

```
using System;using System.Drawing;class Q{static void Main(){var b = new Bitmap(3050, 20);var g=Graphics.FromImage(b);string f="using System;using System.Drawing;class Q{{static void Main(){{var b = new Bitmap(3050, 20);var g=Graphics.FromImage(b);string f={0}{1}{0},e={3}{0}{2}{0};g.DrawString(String.Format(f,(char)34,f,e,'@'),SystemFonts.MenuFont,Brushes.Black,0,0);b.Save(e);}}}}",e=@"D:\p.png";g.DrawString(String.Format(f,(char)34,f,e,'@'),SystemFonts.MenuFont,Brushes.Black,0,0);b.Save(e);}}

```

Output:

Adding a different format support would be easy. Not sure if it's worth it, though.

# Answer
> 1 votes
# Python: ~~255~~ 238 -10% -15% = ~~195.075~~ 182.07

```
import sys,PIL.ImageDraw as D;i=D.Image.new('L',(2000,20));r="import sys,PIL.ImageDraw as D;i=D.Image.new('L',(2000,20));r=%r;D.Draw(i).text((0,0),r%%r,fill=255);i.save(sys.argv[1])";D.Draw(i).text((0,0),r%r,fill=255);i.save(sys.argv[1])

```

Usage:

```
python imgquine.py quine.jpg

```

This is a true quine that draws the output to the file specified on the commandline. The file format is set simply by changing the filename extension (e.g. `quine.jpg` for a JPEG and `quine.png` for a PNG).

Example output (2000x20 image):

---
Tags: code-golf, quine, graphical-output, image-processing
---


title: Undefined Behavior Killed My Cat

text:
# Question
Title: Undefined Behavior Killed My Cat
# Undefined Behavior Killed My Cat

It's well known that undefined behavior can kill your cat \[citation needed\].
But can it?

## Your Task

1. Write a program that invokes undefined behavior.
2. Describe a scenario that starts with the above program being run, resulting in a *Felis catus* ending its life while in your ownership, as a result of the aforementioned UB.
3. Estimate the probability for each stage in the scenario.
4. Calculate the total probability that a single run of the program would kill your cat.

## Rules

1. This is a , so be creative if you can.
2. This is a programming related challenge, so the chain of events should be mostly within the computer, not in the real world (of course, if has to reach the real world if that's where your cat is).
3. If you choose a language that doesn't have undefined behavior, use something similar.
4. No animals may be harmed in the production of your answer.

## Scoring

Vote count plus the scenario's total probability (which can't exceed 1).

## Example in C:

```
main(){printf();}

```

Scenario:

1. `printf` called with garbage from the stack - undefined behavior. Probablity: 100%.
2. The first parameter happens to be the string `Your cat is ugly!`. Probablity: (1/256)17 = (1.148 * 10-37)%.
3. Seeing the message, you pick up your gun and shoot your cat. Probability: 3%.
4. The cat dies. Probability: 93%.

Total probability: (3.202 * 10-39)%.

# Answer
# C

Most answers to this question misinterpreted the question in that it was killing the `cat` process on a UNIX system. Here is a program which can cause the demise of a biological lifeform of the species Felis Cattus as specificed by the question.

This example runs on Windows, but it could be easily ported to most UNIX operating systems by replacing `iexplore -k` with the command to launch an installed web browser.

```
#include <stdlib.h>
#include <stdio.h>

int main() {
    char i; // uninitialised
    printf("Redirecting you to a website which will inform you how to properly feed your cat.");
    if (i != 42) {
         system("iexplore -k https://pets.stackexchange.com/questions/tagged/cats+diet");
    } else {
         system("iexplore -k https://cooking.stackexchange.com/questions/tagged/chocolate");
    }
    return 0;
}

```

This program pretends to provide advise about cat diet to the user.

It will start Internet Explorer and direct the user to pets stackexchange listing lots of helpful questions about how to feed cats. There is, however, a low (1/256) chance that it will send the user to cooking stackexchange instead listing tips how to prepare dishes containing chocolate, which is **highly toxic** to cats. To make matters worse, it will launch internet explorer in kiosk mode (fullscreen), which hides the address bar and is hard to escape from for a non-tech-savy user.

This clever ruse will coax the user into feeding their cat chocolate believing that it is an appropriate diet for it, thus causing them to inadvertedly kill it.
> 117 votes

# Answer
# Bash

According to this, `INT_MIN % -1` may or may not be undefined *(what ???)*, and so might cause trouble for any language implemented in c/c++.

```
#!/bin/bash

cat <<< $((2**63%-1))

```

The `cat` will be killed early if the parent `bash` process crashes, which may or may not happen.

On my VM I get this output:

```
$ ./schroedinger.sh
./schroedinger.sh: line 3:  7805 Floating point exception(core dumped) cat <<< $((2**63/-1))
$

```

---

*(I don't really understand the scoring for this question, but here goes anyway)*

Calculate `$((2**63%-1))`. Crash always happens on bash 4.2.25, but seems to just hang on some 3.x versions. More uncertainty. I could tell you the exact probability, but due to the Heisenburg uncertainty principle I would then fall down a black hole. Or something. So I think we can safely say they probability is approximately 42%.
> 89 votes

# Answer
# C (sequence point)

**deadcat.c:**

```
#include <stdio.h>
int main()
{
    int i=3;
    int k=0;
    k=i+(++i);
    if (k==7)
        printf("The cat is fine. k=i+(++i) =%d\n",k);
    else
        printf("Urgent Notice: Your cat has rabies. k=i+(++i) =%d\n",k);
}

```

**Execution (or not):**

```
$ clang -w deadcat.c -o deadcat; ./deadcat
The cat is fine. k=i+(++i) =7
$ gcc deadcat.c -o deadcat; ./deadcat
Urgent Notice: Your cat has rabies. k=i+(++i) =8

```

**Scenario and probability**

Assuming that five percent of people running this program use clang for compiling C code (versus 90 percent using gcc and 5 percent using other C compilers):

```
 Probability of getting "The cat is fine."                           =  .050
 Probability of getting "Urgent Notice: Your cat has rabies."        =  .950

 Probability of reacting to "Your cat has rabies" by putting it down =  .040
 Probability of ignoring the notice                                  =  .900
 Probability of taking the cat to the vet for treatment              =  .060

 Total probability of cat living:.05 + .95 * (.90 + .06)             =  .962
 Total probability of cat dying: .95 * .04                           =  .038
 Check: Total probability of cat living or dying:                    = 1.000

```

**Explanation:**

k=i+(++i) accesses and changes "i" between sequence points. The probability is not determinable by the program; it depends upon the choice of compiler, which is made by the user. "Undefined" does not necessarily mean "random".

See https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points
> 41 votes

# Answer
# C

### Backstory

My wife inherited a cat from family. Unfortunately, I am very allergic to animals. The cat was well past its prime and should have been euthanized even before we got it, but she could not bring herself to get rid of it due to its sentimental value. I hatched a plan to end my its suffering.

We were going on an extended vacation, but she did not want to board the cat at the veterinarian's office. She was concerned about it contracting illness or being mistreated. I created an automatic cat feeder so that we could leave it at home. I wrote the microcontroller's firmware in C. The file containing `main` looked similar to the code below.

However, my wife is also a programmer and knew my feelings towards the cat, so she insisted on a code-review before agreeing to leave it at home unattended. She had several concerns, including:

* `main` does not have a standards compliant signature (for a hosted implementation)
* `main` does not return a value
* `tempTm` is used uninitialized since `malloc` was called instead of `calloc`
* the return value of `malloc` should not be cast
* the microcontroller time may be inaccurate or roll over (similar to the Y2K or Unix time 2038 problems)
* the `elapsedTime` variable may not have sufficient range

It took a lot of convincing, but she finally agreed that theses weren't problems for various reasons (it didn't hurt that we were already late for our flight). Since there was no time for live testing, she approved the code and we went on vacation. When we returned a few weeks later, my the cat's misery was over (though as a result I've now got plenty more).

† Entirely fictitious scenario, no worries.

---

### Code

```
#include <time.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

//#include "feedcat.h"
// contains extern void FeedCat(struct tm *);
// implemented in feedcat.c
// stub included here for demonstration only
#include <stdio.h>
// passed by pointer to avoid putting large structure on stack (which is very limited)
void FeedCat(struct tm *amPm)
{
    if(amPm->tm_hour >= 12)
        printf("Feeding cat dinner portion\n");
    else
        printf("Feeding cat breakfast portion\n");
}

// fallback value calculated based on MCU clock rate and average CPI
const uintmax_t FALLBACK_COUNTER_LIMIT = UINTMAX_MAX;

int main (void (*irqVector)(void))
{
    // small stack variables
    // seconds since last feed
    int elapsedTime = 0;
    // fallback fail-safe counter
    uintmax_t loopIterationsSinceFeed = 0;
    // last time cat was fed
    time_t lastFeedingTime;
    // current time
    time_t nowTime;

    // large struct on the heap
    // stores converted calendar time to help determine how much food to
    // dispense (morning vs. evening)
    struct tm * tempTm = (struct tm *)malloc(sizeof(struct tm));

    // assume the cat hasn't been fed for a long time (in case, for instance,
    // the feeder lost power), so make sure it's fed the first time through
    lastFeedingTime = (size_t)(-1);

    while(1)
    {
        // increment fallback counter to protect in case of time loss
        // or other anomaly
        loopIterationsSinceFeed++;

        // get current time, write into to nowTime
        time(&nowTime);

        // calculate time since last feeding
        elapsedTime = (int)difftime(nowTime, lastFeedingTime);

        // get calendar time, write into tempTm since localtime uses an
        // internal static variable
        memcpy(&tempTm, localtime(&nowTime), sizeof(struct tm));

        // feed the cat if 12 hours have elapsed or if our fallback
        // counter reaches the limit
        if(  elapsedTime >= 12*60*60 ||
             loopIterationsSinceFeed >= FALLBACK_COUNTER_LIMIT)
        {
            // dispense food
            FeedCat(tempTm);

            // update last feeding time
            time(&lastFeedingTime);

            // reset fallback counter
            loopIterationsSinceFeed = 0;
        }
    }
}

```

---

### Undefined behavior:

For those who don't want to bother finding the UB themselves:

> There's definitely local-specific, unspecified, and implementation-defined behavior in this code, but that all should work correctly. The problem is in the following lines of code:
> `struct tm * tempTm //...
>  //...
>  memcpy(&tempTm, localtime(&nowTime), sizeof(struct tm));`
> `memcpy` overwrites the `tempTM` pointer instead of the object it points to, smashing the stack. This overwrites, in addition to other things, `elapsedTime` and `loopIterationsSinceFeed`. Here's an example run where I printed out the values:
> `pre-smash : elapsedTime=1394210441 loopIterationsSinceFeed=1
>  post-smash : elapsedTime=65 loopIterationsSinceFeed=0`

---

### Probability of killing the cat:

* Given the constrained execution environment and build chain, the undefined behavior always occurs.
* Similarly, the undefined behavior always prevents the cat feeder from working as intended (or rather, allows it to "work" as intended).
* If the feeder does not work, it is extremely likely the cat will die. This is not a cat that can fend for itself, and I failed to ask the neighbor to look in on it.

I estimate that the cat dies with probability **0.995**.
> 39 votes

# Answer
# bash

### Classic version

```
cat & # This is your cat.
pkill -$RANDOM cat

```

Has the advantage of killing *all* cats in its range.

Note that the process is *stopped* immediately, so the only way to end it with a single invocation of *pkill* is to send SIGKILL (9).

Therefore:

`p(SUCCESS) = p(RANDOM == 9) = 0.0275 %`

---

### Quantum version

```
schroedinger=/dev/null             # We'll need this guy.
heisenberg=/dev/urandom            # Also needed, for uncertainty principle.
cat $heisenberg > $schroedinger &  # Steal cat from Heisenberg and give it to Schrödinger.
felix=$!                           # Name cat for future references.
exec 2> $schroedinger              # Send all results to Schrödinger.
kill -SIGSTOP $felix               # Catch Felix and put him into a box.
if (($RANDOM & 1))                 # Flip a coin.
then kill $felix                   # Heads: Kill! Kill! Kill!
fi                                 # By now, Felix can be thought of as both alive and dead.
read -sn 1                         # Wait for somebody to open the box.
kill -SIGCONT $felix               # Let him open it.
if ps p $felix > $schroedinger     # Let Schrödinger check on Felix.
then echo The cat is alive.        # Hooray for tails!
else echo The cat is dead.         # At least, now we know.
fi                                 # This concludes the experiment.
kill -SIGKILL $felix               # Felix is no longer required.

```

Probability of killing the cat during the experiment: 50 %
> 33 votes

# Answer
# C

Note that this only works on linux.

```
main() {
  FILE *f = fopen("skynet", "w");
  srand(time(0));
  while(rand() != rand())
    fputc(rand()%256, f);
  fclose(f);
  system("chmod +x skynet");
  system("./skynet");
}

```
1. Write random data to a file and invoke it (100%)
2. Random data happens to be the source code to skynet (1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.)
3. Cat dies in resulting doomsday (99.999%)

Total probability: 1x10^-999999999999999999999999999999999999999999999999999999999999999, aprox.
> 17 votes

# Answer
# C++

Your Cat is Both Dead and Alive until you are Curious. Then you realize that there is a 0.5 probability that your Cat is Dead.

```
#ifdef WIN32
#pragma warning(disable: 4700)
#endif
#include <random>
#include <iostream>
#include <vector>
#include <climits>
#include <memory>
class Cat
{
public:
    enum class State {DEAD, ALIVE};
    Cat()
    {
        int x; // Uninitialized Variable on Stack
        if (x % 2 == 0) // Is the Uninitialized Variable even? 50-50
        {
            m_dead = State::DEAD;

        }
        else
        {
            m_dead = State::ALIVE;
        }
    };
    operator State() //Check if your Cat is Dead / Alive
    {
        if (m_dead == State::DEAD)
        {
            delete this; //Boom Cat is dead
            std::cout<<"Your Curiosity killed your Cat"<<std::endl;
            return false;
        }
        return m_dead;
    }
private:
    State m_dead;
};

class Schrödinger
{
public:
    Schrödinger(size_t size):m_size(size)
    {
        for(size_t i = 0; i < size; i++)
        {
            cats.push_back(new Cat());
        }
    }
    ~Schrödinger()
    {
    }
    void Curiosity()
    {
        std::default_random_engine generator;
        std::uniform_int_distribution<int> distribution(0,m_size);
        if(*cats[distribution(generator)] == Cat::State::ALIVE)
        {
            std::cout<<"You Cat is alive and still kicking" <<std::endl;
        }
    }
private:
    std::vector<Cat *> cats;
    size_t m_size;
};
int main()
{
    int size;
    std::cout<<"How Big is Your Example Space ?";
    std::cin>>size;
    Schrödinger your(size);
    your.Curiosity();
    return 0;

}

```
> 16 votes

# Answer
# C

Runs on Linux.

```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void f(char x) {
    if(sleep(1)==x) system("killall cat");
}
int main() {
    char x; // uninitialised
    system("cat /dev/urandom &");
    f(x);
    return 0;
}

```

Probability of killing the cat: 1/256 (The `sleep(1)` returns 0, so it will be killed if `x` is zero.)

As a bonus, it kills all cats currently running on your system.

---

If you hate cats so much, I present to you:

### The Cat Centipede (Bash)

```
echo "Hello World"|cat|cat|cat

```

Based on the fact that, in *The Human Centipede (First Sequence)*, all three dogs of the dog centipede died, and two out of three people of the human centipede died, I estimate that the probability of killing one cat is 5/6.
> 13 votes

# Answer
```
int foo() {}

void main() {
    int x = foo();
}

```

Reading a value of function supposed to return a value results in undefined behaviour. Now, it is obvious,\[citation needed\] that "Every time you reach undefined behaviour, God kills a kitty." Using this we conclude:

* Probability you reach undefined behaviour - 100%
* Probability it is your kitty which god killed - 1/200 000 000 see why
* So probability is 0.0000005%

Can be easily extended by loop to exterminate all cats in the world.
> 10 votes

# Answer
# JavaScript

```
~"cat".localeCompare("dead")
  ? "Cat is dead"
  : "Cat is fine"

```

**Execution:**

* **Chrome:** Results in `"Cat is fine"`
* **Firefox:** Results in `"Cat is dead"`

**Explanation:**

> 15.5.4.9 String.prototype.localeCompare (that)
>
> The two Strings are compared in an **implementation-defined** fashion

Quoting Glenn Randers-Pehrson, the probability is not determinable by the program; it depends upon the choice of browser, which is made by the user.
> 10 votes

# Answer
# Java (Garbage Collection)

Although code can invoke System.gc() is does not make sure that the Garbage Collector will collect all of the unused objects. Thus, for the following code, it's unpredictable if the cat will be killed or not.

```
public class KillTheCat {
    public static void main(String[] args) throws InterruptedException {
        KillTheCat cat = new KillTheCat();
        cat = null;
        System.gc();
        System.out.println("Cat is still alive.");
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Cat has been killed.");
        System.exit(0);
    }
}

```

The probability cannot be calculated.

Note that there's still a chance that the cat will be "revived" if there's a context switch in the GC thread after sysout and before System.exit(0) but I preferred not to cover it to keep the concept simpler.
> 6 votes

# Answer
# C

If your cat's name is too long, it dies. `gets` causes cat deaths, along with other problems.

```
#include <stdio.h>
#include <stdbool.h>

/* Stores instances of cats. */
struct cat {
    /* 6 bytes are more than enough. */
    char name[6];

    /* Stores whether your cat is dead. */
    bool dead;
};

int main(void) {
    /* This is your cat. */
    struct cat your_cat;
    /* It lives. */
    your_cat.dead = false;
    /* Determine its name. */
    printf("Your cat name: ");
    gets(your_cat.name);

    /* Output the cat state. */
    const char *state = your_cat.dead ? "dead" : "alive";
    printf("Your cat, %s, is %s.\n", your_cat.name, state);

    return your_cat.dead;
}

```
> 6 votes

# Answer
Anybody having thought of really killing (a) `cat`?

```
[ $[ $RANDOM % 6 ] == 0 ] && rm /bin/cat || echo Meow

```

### Probabilitiy of `cat` dying

For the probability... I guess we need to distinguish some cases:

1. **Windows user**: Probably will not be able to execute it. Chance of dying `cat`s is very low, can safely be assumed to be zero. If he's got Cygwin installed, he'll count as unix user.
2. **Unix user, running without root privileges**: Killing the `cat` will fail.
3. **Unix user, running with root privileges**: While each call will only kill `cat`s with a chance of 1/6, he will very probably repeat it until something unexpected occurs. Without loss of generality, I assume `cat` will definitely die.

Overall probability depends on how the users are mixed and is hard to determine. But we can surely say: Windows is a safe place for kittens.

### Testing for obedience of the rules

> No animals may be harmed in the production of your answer.

This did not kill animals, the answer is approved by the *American Humane Association*.

```
$ file `which cat`
/bin/cat: Mach-O 64-bit executable x86_64

```

clearly proves that `cat` is no animal (as long `file` does not know any kind of hidden file type inheritance).
> 5 votes

# Answer
## Haskell

```
import Acme.Missiles
import System.IO.Unsafe
main = print (unsafePerformIO launchMissiles, undefined)

```

Here, we apply `unsafePerformIO` to an action that has observable side-effects. That is always undefined behaviour, at least so is the order of effects. So either will the program first crash on trying to evaluate `undefined` (that one, ironically, is *not* undefined behaviour: it must never yield a value that would allow the program to carry on with something else), or it will in fact incur the serious international side-effects. In that case, survival chance is only 0.001%.

Probability of killing the cat thus: 49.9995%.
> 5 votes

# Answer
# Thue

Since the question allows for a language that doesn't have undefined behavior as long as the effect is similar, I choose Thue for its **non-determinism** in choosing which rule to execute when there are more than 1 rule which can be applied on the current state.

The program will be fed into the controller for a microwave oven, inside of which is my cat. The door to the microwave oven is closed and reinforced by a zip tie. The output of the program will decide whether the microwave oven starts to microwave the cat or not.

* If the output is 0, we will start the experiment on the effect of long exposure of microwave on live mammal (which is currently insufficiently researched).
* If the output is 1, we will just be satisfied with the fact that the cat has just lost one of its 9 lives and let it out.

---

```
i::=~0
i::=~1
::=
i

```

The probability of killing the cat is dependent on the implementation of the interpreter, but let's say it's 50%. Then the probability that the cat will die is **0.5**.
> 4 votes

# Answer
## Java

According to spec `java.util.Date` will have undefined behaviour. So try your luck:

```
import java.util.Date;

public class App3
{
    public static void main (String args[])
    {
        String aliveOrDead;
        Date d = new Date(-1000,-1000,-1000);
        aliveOrDead = (d.getTime()<0)? "dead" : "alive";
        System.out.println("The cat is:" +aliveOrDead );
    }
}

```
> 1 votes

---
Tags: popularity-contest
---