title: Freehand red circles

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

See this post:

So, the challenge is,

## can you draw freehand red circles... with code?

Additional restrictions:

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

---

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

# Answer
> 13 votes
# C — about ~~750~~ 720 bytes if squeezed<sup>*</sup>

I think I came up with something that looks freehand-y enough.

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

Compile:

```
gcc -o freehand freehand.c -lm

```

Run:

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

```

Example:

```
./freehand 28.2 74.5 3.5 < screenshot.ppm > freehand.ppm

```

Before:

After:

Code:

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

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

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

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

    srand(MAGIC);

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

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

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

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

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

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

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

    free(p);

    return 0;
}

```

* and using `U` for `UNIFORM` and `M` for `MAGIC`

# Answer
> 27 votes
# C + GD library

Instead of just drawing circles any old where, I thought it would be fun to find something red in the picture and draw a circle around that.

Here are some examples of the results obtained with  few photos from Wikimedia Commons:

And here's the code. It's a bit messy, but not too difficult to follow, I hope:

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

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

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

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

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

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

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

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

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

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

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

```

---

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

produces the following output:

# Answer
> 10 votes
# Mathematica

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

```

`f` takes the following parameters:

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

---

**Examples**

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

```

##

A different radius, location, blue color, thicker stroke, displaying axes.

```
f[text,.22,.7,.5,Blue,.015,True]

```

---
Tags: popularity-contest, image-processing
---


# Question
Title: Determine whether a car can get around a route with a limited amount of gas
Using any programming language that supports functions, have the function

```
is_enough(strArr)

```

that take `strArr` which will be an an array consisting of the following elements:

* `N` which will be the number of gas stations in a circular route
* and each subsequent element will be the string `g:c` where
    + `g` is the amount of gas in gallons at that gas station and
    + `c` will be the amount of gallons of gas needed to get to the following gas station.

For example `strArr` may be:

```
["4","3:1","2:2","1:2","0:1"].

```

Your goal is to return the index of the starting gas station that will allow you to travel around the whole route once, otherwise return the string *"impossible"*.

For the example above there are *4* gas stations, and your program should return the string *"1"* because:

* Starting at station *1* you receive *3* gallons of gas and spend *1* getting to the next station.
* Then you have *2* gallons + *2* more at the next station and you spend *2* so you have *2* gallons when you get to the 3rd station.
* You then have *3* but you spend *2* getting to the final station,
* At the final station you receive *0* gallons and you spend your final gallon getting to your starting point.

Starting at any other gas station would make getting around the route impossible, so the answer is *"1"*.

If there are multiple gas stations that are possible to start at, return the smallest index (of the gas station). `N` will be `>= 2`.

Correct Sample Outputs:

```
Input: ["4","1:1","2:2","1:2","0:1"]
Output: "impossible"

Input: ["4","0:1","2:2","1:2","3:1"]
Output: "4"

```

The winner will be the one to use the shortest code although it will be long.

# Answer
> 1 votes
# Bash 178 170 161 157

Rather straight forward.

```
is_enough(){((t=(n=$1-1)<0))&&echo impossible||(x=(n ${@:3} $2);for z in ${@:2};do(((t+=${z%:*}-${z#*:})<0))&&is_enough ${x[*]}&&return;done;echo $[$#-++n])}

```

Spaced out:

```
is_enough() {
     ((t=(n=$1-1)<0)) && echo impossible || (
         x=(n ${@:3} $2);
         for z in ${@:2};do
             (((t+=${z%:*}-${z#*:})<0)) && is_enough ${x[*]} && return;
         done;
         echo $[$#-++n]
     )
}

```

# Answer
> 1 votes
## Ruby, 111

Here's a Ruby solution using `eval`:

```
is_enough=->a{_,*s=a
"#{(1..s.size).find{|i|g=0;s.rotate(i-1).all?{|x|g+=eval x.tr ?:,?-;g>=0}}||:impossible}"}

```

Example usage:

```
is_enough[%w(4 3:1 2:2 1:2 0:1)] #=> "1"
is_enough[%w(4 1:1 2:2 1:2 0:1)] #=> "impossible"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 1:2 2:1 4:3 0:1)] #=> "2"
is_enough[%w(4 0:1 2:2 1:2 3:1)] #=> "4"
is_enough[%w(4 0:1 0:1 4:1 0:1)] #=> "3"
is_enough[%w(8 0:1 0:1 4:1 0:1 2:1 3:1 0:0 0:1)] #=> "3"

```

**EDIT**: Corrected function name and return type.

# Answer
> 1 votes
## APL (70)

```
{×⍴G←Z/⍨0∧.≤¨+\¨¯1⌽⌽∘K¨Z←⍳⍴K←{⎕ML←3⋄-/⍎¨⍵⊂⍨⍵≠':'}¨1↓⍵:⊃G⋄'impossible'}

```

Explanation:

* `1↓⍵`: drop the first element (length), we don't need it
* `{`...: for each of the gas stations...
    + `⎕ML←3`: set `⎕ML` to 3 within the inner function (changes behaviour of )
    + `⍵⊂⍨⍵≠':'`: split the string on `:`
    + `⍎¨`: evaluate each part
    + `-/`: subtract the second number from the first (giving net effect for each gas station)
* `K←`: store them in K
* `Z←⍳⍴K`: get the indices for the gas station (`1` to length of `K`), store in `Z`
* `⌽∘K¨Z`: rotate `K` by each value of `Z`, giving an array of arrays
* `¯1⌽`: rotate this array to the left by 1 (to put the unchanged one first instead of last)
* `+\¨`: make a running sum for each inner array
* `0∧.≤¨`: for each running sum, see if there are negative values
* `Z/⍨`: select from `Z` those elements for which the running sum had no negative values
* `×⍴G←`: store in `G`. If `G` has any elements:
* `:⊃G`: return the first element of `G`.
* `⋄'impossible'`: otherwise, return `impossible`.

# Answer
> 0 votes
# Ruby 132

```
g=->a{n,*a=a.map{|e|e.split(?:).map &:to_i}
(r=(0...n[0]).find{|i|a.rotate(i).inject(0){|m,(j,k)|m&&m>=0&&m+j-k}})?r+1:"impossible"}

```

Test:

```
irb(main):003:0> g[["4","1:1","2:2","1:2","0:1"]]
=> "impossible"
irb(main):004:0> g[["4","0:1","2:2","1:2","3:1"]]
=> 4

```

# Answer
> 0 votes
## Python, 131

I find this one-liner fairly satisfying.

```
E=lambda s:([`i`for i in range(1,len(s)+1)if reduce(lambda r,t:r+eval(t[0]+'-'+t[-1])*(r>=0),s[i:]+s[1:i],0)>=0]+['impossible'])[0]

```

# Answer
> 0 votes
## GolfScript (72 chars)

```
{(~\{':'/{~}/-}%[\),1>{;.{1$-1>*+}*-1>\(+\},~"impossible"]1=}:is_enough;

```

Online demo

This performs the obvious brute force approach. The most interesting bit IMO is the determination of whether the partial sums of an array of delta-fuel ever drops below 0:

```
{1$-1>*+}*-1>

```

This saves 1 char over the more obvious

```
[{1$+}*]{0<},!

```

If the output were indexed at 0 rather than at 1, an alternative approach to rotating the array would be preferable:

```
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;

```

But this approach isn't easily adopted to indexing at 1:

```
{(;{':'/{~}/-}%:A[,),1>{A\({(+}*{1$-1>*+}*-1>},~"impossible"]0=}:is_enough;

```

or

```
{(;{':'/{~}/-}%:A[,,{A\{(+}*{1$-1>*+}*-1>},{)}%~"impossible"]0=}:is_enough;

```

---
Tags: code-golf, string
---


title: Implement a Useless interpreter

text:
# Question
Title: Implement a Useless interpreter
Your task is to build an interpreter to the Useless language:

Here are the functional requirements:

* All the described commands should be accepted by the interpreter.
* **`NO.`**, **`NOOP`** and **`INCLUDE-xxx`** must be honored.
* **`DONTUSEME(n)`** must have its base date to be easily configurable to something more reasonable for testing purposes.
* **`INCLUDE-xxx`** must be able to generate any command with a roughly equal probability. If it generates a **`DONTUSEME(n)`**, he should randomly choose a small value for n.
* **`DONTUSEME(n)`** windows should survive the **`NO.`** instruction. Tip: spawn a new process for those windows.
* **`BOOM!`** and **`KABOOM!`** must do something bad and scary, and **`KABOOM!`** must be worse than **`BOOM!`**. But this **must not** be taken too seriously, so it should not be something destructive, overly-disruptive or hard to be undone. Please, **do not, *do not*, and do not** make these instructions run a `rm -rf \` command, run a fork bomb, install malware, corrupt data in the file system, or post or download inappropriate content from the internet, or any other thing clearly abusive.
* **`TURINGVSALONZO`** should run as if it in fact was doing what it should do. Tip: Make it randomly decide if it would sleep for a random very long time, or a random short time, or forever.
* All the other predefined instructions should do something other than the aforementioned instructions and different one to the another, but never something worse than **`BOOM!`** or **`KABOOM!`**. What they do exactly is up to you, but a simple implementation would just output an error message or some other text.
* You should provide an easy way for the user to provide the program that would be run by the interpreter. i.e. Reading plaintext from a file or from `stdin` is ok. Reading it from an encrypted file somewhere in the internet is not.

Optional:

* You might invent some new commands if you want, but they should be subject to the same rules as the others are. Do not use this to circumvent the restrictions in **`BOOM!`** and **`KABOOM!`** or to defeat **`DONTUSEME(n)`**. And if you do invent new commands, explain what they do.
* You should think about what the interpreter do if it receives input with unknown commands (or even completely unparseable random bytes gibberish).
* Although no instruction should defeat the **`DONTUSEME(n)`** command, you might add a kill switch for it. Just don't expose that in the language.

We have a few non-functional requirements to avoid abuses:

* Your entry must be as complete and autocontained as possible. This means that it should not be simply some sort of installer or clearly incomplete program. This way, downloading and using libraries like jQuery or packages from maven central is ok, but downloading arbitrary code and packages from your custom server is not.
* Your entry should not get any content from this very page or from some mirror or copy of this page in order to do some sort of reflection or for any other purpose. This is essential to avoid some program that try to read other entrants answers to this question or try to disrupt the question or answers in any way.
* Your interpreter should be immutable and not self-modify or modify its input file. But, creating a mutant copy of the interpreter or of the input file without altering the original is ok.

And finally, considering that:

* The programs in the answers are expected to be pretty useless even if fully conformant;
* The language is (on purpose) very underspecified, and the answerers have a lot of liberties to take and are incentived to take them;
* The requirements and the possible implementations have a lot of subjective points;
* The objective with this is to just get some fun and creativity.

Then, this is a , and **the most upvoted answer fully conformant to the rules wins!** So, you don't need to golf or obfuscate your answer (but you might do that if you want). Just be sure to post something original and creative to deserve the upvotes, i.e. please don't post lame boring entries.

# Answer
## TI-BASIC

There is a kill button for `DONTUSEME`, can you figure out which one it is? :)

```
:Lbl 1
:Input Str1
:If Str1="NO."
:Pause
:If Str1="FAIL"
:Disp "OBSOLETE. WHAT A FAIL."
:If Str1="NOT"
:Disp "USING NOT IS HIGHLY DISCOURAGED!"
:If Str1="NEVER"
:get(Police,911)
:If Str1="IDK"
:Disp LLLundefined
:If Str1="BOOM!"
:Disp "rm -rf \"
:If Str1="KABOOM!"
:send(virus)
:If Str1="QWAOZAPWQFUOA"
:Disp "SKIPPING QWAO... UNIMPLEMENTED"
:If Str1="WUT?"
:dayOfWk(1)
:If Str1="WHERE?"
:Disp "NON-EXISTENT. SKIPPED."
:If Str1="HOW?"
:++
:If sub(Str1,1,9)="DONTUSEME"
:Then
:While 1
:sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(sin(e)
:End
:End
:If Str1="ILLEGAL"
:Archive X
:If Str1="GODEXISTS"
:Disp "GOD EXISTS, PROVEN BY LAW."
:If Str1="WINDOWS"
:Disp "UNABLE TO OPEN START MENU!"
:If Str1="NOOP"
:Lbl 0
:If sub(Str1,1,8)="INCLUDE-"
:sub(Str1,9,length(Str1-8))
:If Str1=Ans
:Then
:If not(rand)
:Goto 0
:End
:If Str1="TURINGVSALONZO"
:Then
:"+"→Str0
:randInt(5,10)
:While Ans
:Ans-1
:If fpart(Ans,4)4=3
:Str0+"+"→Str0
:If fpart(Ans,4)4=2
:Str0+"-"→Str0
:If fpart(Ans,4)4=1
:Str0+">"→Str0
:If fpart(Ans,4)4=0
:Str0+"."→Str0
:End
:Disp "0"
:"?utm_campaign=0"
:End
:Goto 1

```
> 8 votes

# Answer
# HTML + Javascript + jQuery + jQuery UI

The input should be given in the text area and should be formatted as each command in a line. The commands are not case sensitive. All of the commands were fully implemented. I hope that you enjoy.

You can try it at http://jsfiddle.net/bCBfk/

```
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>Useless interpreter</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <style type="text/css">
      textarea { height: auto; }
      .badshit { color: red; }
      .ui-dialog-titlebar-close { display: none; }
    </style>
    <script type="text/javascript">
      String.prototype.startsWith = function(x) {
        return this.substring(0, x.length) === x;
      };
      String.prototype.endsWith = function(x) {
        return this.substr(this.length - x.length, x.length) === x;
      };

      var npe = "<pre>java.lang.NullPointerException\n"
          + "       at org.esolangs.wiki.useless.memorymodel.ExistentObjectPool.findObject(ExistentObjectPool.java:684)\n"
          + "       at org.esolangs.wiki.useless.interpreter.WhereInstruction.visit(WhereInstruction.java:29)\n"
          + "       at org.esolangs.wiki.useless.interpreter.UselessProgram.run(UselessProgram.java:413)\n"
          + "       at org.esolangs.wiki.useless.interpreter.Main.main(Main.java:53)</pre>";

      var wut = navigator.userAgent + " - " + navigator.language + " - " + navigator.platform + " - Ii?".toLocaleUpperCase();

      var wut2 = "";
      for (var c = wut.length - 1; c >= 0; c--) {
          wut2 += wut.charAt(c);
      }

      var popupMasterMind;
      function killIt() {
        clearInterval(popupMasterMind);
        $(".dontuseme").remove();
        popupMasterMind = null;
      }

      function spawn() {
        var x = $("<div class='dontuseme' title=''><p></p></div>");
        $("body").append(x);
        x.dialog();
        var bw = $("body").innerWidth();
        var bh = $("body").innerHeight();
        if (bh < 500) bh = 500;
        var xw = x.width();
        var xh = x.height();
        x.parent().css({left: Math.random() * (bw - xw) + "px", top: Math.random() * (bh - xh) + "px"});
      }

      function dontuseme() {
        if (popupMasterMind) return;
        spawn();
        popupMasterMind = setInterval(spawn, 700);
      }

      var hasOutput = false;
      function clearOutput() {
        $("#output").empty();
        hasOutput = false;
        $("#cc").hide();
      }

      function out(a) {
        $("#output").append($(a));
        hasOutput = true;
      }

      function finish() {
        $("#running").hide();
        $("#bt").show();
        if (hasOutput) $("#cc").show();
      }

      var annoyingUser = false;
      function swap() {
        annoyingUser = true;
        $("#everything").toggle();
        setTimeout(swap, 800);
      }

      function randomString() {
        var r = "";
        var f = Math.floor(Math.random() * 12) + 8;
        for (var i = 0; i < f; i++) {
          r += "ABCDEFGHIJKLMNOPQRSTUVWXYZ.!?0123456789".charAt(Math.floor(Math.random() * 39));
        }
        return r;
      }

      var instructions;
      function includeInstruction(name) {
        name = name.toUpperCase();
        if (instructions[name]) return; // Do not add it twice or overwrite existing instructions.
        var array = [];
        for (var e in instructions) {
          array.push(e);
        }
        var rand = Math.floor(Math.random() * array.length);
        //alert(name + ": " + array[rand]);
        instructions[name] = instructions[array[rand]];
      }

      // DONTUSEME(n) are special cases handled elsewhere.
      instructions = {
        "FAIL": function() { out("<p class='badshit'>Warning: The <blink> tag is obsolete.</p>"); if (!annoyingUser) swap(); return "next"; },
        "NOT": function() { out("<p class='badshit'>Warning: The NOT instruction is discouraged because it breaks yor Useless program.</p>"); return "quit"; },
        "NEVER": function() { out("<pre>Wild MISSINGNO. appeared!</pre>"); return "next"; },
        "IDK": function() { out("<pre>" + {}.idk + "</pre>"); return "next"; },
        "BOOM!": function() { $("#everything").empty(); return "quit"; },
        "KABOOM!": function() { window.location = "http://answers.yahoo.com/question/index?qid=20110816062515AANqygl"; return "quit"; },
        "NO.": function() { finish(); return "quit"; },
        "QWAOZAPWQFUOA": function() { out("<p class='badshit'>Sorry, I could not understand <a href='https://www.google.com.br/#q=women+psychology+and+behaviour'>this</a>.</p>"); return "next"; },
        "WUT?": function() { out("<p>" + wut2 + "</p>"); return "next"; },
        "WHERE?": function() { out(npe); return "next"; },
        "HOW?": function() { out("<p class='badshit'>Regular expression parser failed for HTML. Cause: \"ZALGO\"</p>"); return "next"; },
        "ILLEGAL": function() { out("<pre>codegolfer is not in the sudoers file.  This incident will be reported</pre>"); return "next"; },
        "GODEXISTS": function() { out("<p>'GOD' spelled backwards is 'DOG'. A DOG is an animal that does not exists, and by backwarding this, we conclude that GOD exists and is not an animal.</p>"); return "next"; },
        "WINDOWS": function() { out("<p><img width='640' height='400' src='http://upload.wikimedia.org/wikipedia/commons/3/3b/Windows_9X_BSOD.png' alt='Sorry, this optional instruction was not implemented. Please, install the service pack.'></p>"); return "next"; },
        "NOOP": function() { return "next"; },
        "TURINGVSALONZO": function() {
          var r = Math.random() * 10;
          if (r < 2) return "next";
          if (r < 7) return "t" + (Math.random() * 14 + 1) * 1000;
          if (r < 9) return "t" + (Math.random() * 50 + 10) * 60 * 1000;
          return "quit";
        },
        "42": function() {
          out("<p>Calculating the answer of the life, the universe and everything.</p>");
          out("<p>Estimated time is 7.5 million years.</p>");
          out("<p>Don't you want to briefly take a coffe while you wait? It will not take long, I promise.</p>");
          return "quit";
        },

        // This is special, as it needs a (surprising) useless parameter, it can't be acessed directly without prior processing, this is why it is lowercase.
        "dontuseme": function() { dontuseme(); return "next"; },

        // This is special. If the INCLUDE-xxx generates a INCLUDE-yyy instruction, the yyy instruction will have an unknown random generated name.
        // Since yyy is random and unknown, it probably won't appear in the input source code, but implement it regardless.
        "include-random": function() { includeInstruction(randomString()); return "next"; }
      };

      function bad(line) {
        //alert(line);
        out("<p class='badshit'>Syntax error: </p>");
      }

      function beyondEnd() {
        out("<p class='badshit'>Unrecoverable error: Tried to execute code beyond the end or program.</p>");
      }

      function interpretInstruction(lines, idx) {
        if (idx >= lines.length) { beyondEnd(); return; }

        // The toUpperCase serves two purposes: Making the language case-insensitive and hiding private implementations as lowercase instructions.
        ins = lines[idx].trim().toUpperCase();

        var result;

        // Special handling for parsing DONTUSEME(n)
        if (ins.startsWith("DONTUSEME(") && ins.endsWith(")")) {
          try {
            parseInt(ins.substring("DONTUSEME(".length, ins.length - 1));
          } catch (e) {
            bad(ins);
            return;
          }
          ins = "dontuseme";

        // Special handling for INCLUDE-xxx
        } else if (ins.startsWith("INCLUDE-") && ins.length > 8) {
          var name = ins.substring(8);
          includeInstruction(name);
          ins = "NOOP"; // Already executed, follow-up as noop.
        }

        // Execute the instruction.
        var f = instructions[ins];
        if (!f) { bad(ins); return; }
        var result = f();

        // Move on.
        if (result === "quit") return;
        var toWait = result === "next" ? 0 : parseInt(result.substring(1));
        var ii = idx + 1;
        setTimeout(function() {
          interpretInstruction(lines, ii);
        }, toWait);
      }

      function startInterpreter() {
        $("#bt").hide();
        $("#cc").hide();
        $("#running").show();
        var src = $("#input").val();
        var lines = src.split('\n');
        interpretInstruction(lines, 0);
      }

      $(document).ready(function() {
        $("#bt").click(startInterpreter);
        $("#cc").click(clearOutput);
      });
    </script>
  </head>
  <body>
    <div id="everything">
      <p>Type here your program input:</p>
      <textarea id="input" style="width: 400px; height: 150px;"></textarea>
      <p>
        <button id="bt">Run the program</button>
        <span id="running" style="display: none;">Running the program...</span>
      </p>
      <p>Here is the program output:</p>
      <p id="output" class="useless"></p>
      <button id="cc" style="display: none;">Clear the output</button>
    </div>
  </body>
</html>

```

It has one new command:

> It is the **`42`** command which calculates the answer of the life, the universe and everything. The only quirk is that it takes 7.5 million years to finish.

Other spoilers:

> This entry has several features:
>
> * You will really hate the **`FAIL`** command.
> * **`BOOM!`** will screw up you "execution unit". At least the windows from **`DONTUSEME(n)`** are able to survive this.
> * **`KABOOM!`** is really dangerous to world in several bad ways.
> * **`DONTUSEME(n)`** always opens infinite unclosable empty windows, one each 0.8 seconds. But there is a hidden kill switch.
> * **`DONTUSEME(n)`** survives **`NO.`**, **`FAIL`** and even **`BOOM!`**. I just couldn't make it survive the **`KABOOM!`** though. The reason is that popup windows won't work as this is not the result of a click (and popups created by other ways are long banned in all major browsers), and could not use iframes too because of a violation of same-origin policy.
> * **`INCLUDE-xxx`** can create any instruction, including **`DONTUSEME(n)`** or another **`INCLUDE-yyy`** instruction.
> * If **`INCLUDE-xxx`** does generates an **`INCLUDE-yyy`** instruction, the `yyy` name is generated at random. If you grab the name of the generated command with firebug or something similar, you can use it.
> * It handles malformed syntax and incomplete or empty input.
> 9 votes

---
Tags: popularity-contest, interpreter
---


title: N-Queens problem

text:
# Question
Title: N-Queens problem
In chess, a queen can move as far as as the board extends horizontally, vertically, or diagonally.

Given a NxN sized chessboard, print out how many possible positions N queens can be placed on the board and not be able to hit each other in 1 move.

# Answer
Here's a solution (originally from this blog entry) where I construct a logical description of the solution in conjunctive normal form which is then solved by Mathematica:

```
(* Define the variables: Q[i,j] indicates whether there is a
   Queen in row i, column j *)
Qs = Array[Q, {8, 8}];

(* Define the logical constraints. *)
problem =
  And[
   (* Each row must have a queen. *)
   And @@ Map[(Or @@ #) &, Qs],
   (* for all i,j: Q[i,j] implies Not[...] *)
   And @@ Flatten[
     Qs /. Q[i_, j_] :>
       And @@ Map[Implies[Q[i, j], Not[#]] &,
         Cases[Qs,
          Q[k_, l_] /;
           Not[(i == k) && (j == l)] && (
             (i == k) ||          (* same row *)
                 (j == l) ||          (* same column *)
             (i + j == k + l) ||  (* same / diagonal *)
             (i - j == k - l)),   (* same \ diagonal *)
          2]]]];

(* Find the solution *)
solution = FindInstance[problem, Flatten[Qs], Booleans] ;

(* Display the solution *)
Qs /. First[solution] /. {True -> Q, False -> x} // MatrixForm

```

Here's the output:

```
x   x   x   x   Q   x   x   x
x   Q   x   x   x   x   x   x
x   x   x   Q   x   x   x   x
x   x   x   x   x   x   Q   x
x   x   Q   x   x   x   x   x
x   x   x   x   x   x   x   Q
x   x   x   x   x   Q   x   x
Q   x   x   x   x   x   x   x

```
> 4 votes

# Answer
### Ruby

I don't see a `golf` tag, so i'm assuming it's just a challenge.

Here's an implementation of the Algorithm mentioned on Wikipedia. It's not by me, it's at Rosetta Stone and can be found here

CommWikied this Answer.
> 0 votes

# Answer
### Python 2, 190 185 chars

```
from itertools import*
n=input()
print len(filter(lambda x:all(1^(y in(z,z+i-j,z-i+j))for i,y in enumerate(x)for j,z in enumerate(x[:i]+(1e9,)+x[i+1:])),permutations(range(1,n+1),n)))

```

I just assumed the code golf tag even though it wasn't there. N is read from stdin, the program calculates solutions up to n=10 in acceptable time.
> 0 votes

# Answer
Groovy

```
n=8
s=(1..n).permutations().findAll{
  def x=0,y=0
  Set a=it.collect{it-x++}
  Set b=it.collect{it+y++}
  a.size()==it.size()&&b.size()==it.size()
}

```

Delivers a list of all queen solutions like this:

```
[ [4, 7, 3, 0, 6, 1, 5, 2],
  [6, 2, 7, 1, 4, 0, 5, 3],
  ... ]

```

For graphical representation add:

```
s.each { def size = it.size()
         it.each { (it-1).times { print "|_" }
                   print "|Q"
                   (size-it).times { print "|_" }
                   println "|"
                 }
         println ""
         }

```

which looks like this:

```
|_|Q|_|_|_|_|_|_|
|_|_|_|Q|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|_|Q|_|_|_|

```
> 0 votes

---
Tags: code-challenge, combinatorics, chess
---


title: QR Codes... and all that Jazz!

text:
# Question
Title: QR Codes... and all that Jazz!
This is going to be relatively challenging code-golf challenge.

**Input:** Any URL, must have the protocol attached, e.g. http://codegolf.stackexchange.com (which will be our test case)

**Output:** A generated QR Code that represents this URL, which, when scanned by a smart device will take you to that URL on the smart device's browser.

Rules for this Code-Golf

1. As usual, smallest code wins.
2. No external web resources, libraries or plugins to generate the code for you. Your code must calculate the QR code image.
3. Output can be presented by an image, generated by HTML5/CSS3, or even using appropriate Unicode blocks, or if your platform's ASCII has it available, through ASCII characters that can form the QR code (this last one is directed at Commodore 64 Basic, Amiga QBasic, Amstrad Basic, etc users), but it must generate a QR code output such that I can scan the code.
4. Entries of the code must be followed with the generated output, either by a screen shot of the output after executing your code, or with a link showing the output (whichever suits the situation best)
5. You are to test your code with the URL "http://codegolf.stackexchange.com", and report the output in accordance to Rules 3 to 4.
6. You are to also test your code with a URL of your choice, and report the output in accordance to Rules 3 to 4.

References:

1) http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon\_codes\_for\_coders

2) http://www.pclviewer.com/rs2/calculator.html

3) http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon\_error\_correction

4) http://en.wikipedia.org/wiki/QR\_code

5) http://www.qrstuff.com/ for inspiration... ;)

# Answer
> 18 votes
# Python 3: 974 chars \[nb\]

Further beat with the ugly stick, see notebook on GH-Gist. Python 3 has built-in ASCII-85 encoding, which helps with the zipped saus. 3's more advanced built-in compression algorithms (LZMA) don't seem to work well with such small things.

Zipping is very fickle about changing characters around, was almost tempted to write something that would randomly try different 1-letter names for variables to minimize the zipped size.

# Python 2: 1420 1356 1085 1077 characters

I read the first argument passed when called, which can be a string up to 106-ish characters long. The output is always a version 5-L QR code and mask 4 which means it's 37x37 modules large and can only handle ~5% damage.

The program's only dependencies are `numpy` (array manipulations) and `matplotlib` (display only); **all Reed-Solomon encoding, data packing, and module layout is handled within the provided code**. For RS, I basically robbed the Wikiversity functions...it's still kind of a black-box for me. Learned a ton about QR in any event.

Here's the code before I beat it with the ugly stick:

```
import sys
import numpy as np
import matplotlib.pyplot as plt
# version 5-L ! = 108 data code words (bytes), 106 after metadata/packing

### RS code stolen from https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial
gf_exp = [1] + [0] * 511
gf_log = [0] * 256
x = 1
for i in range(1,255):
    x <<= 1
    if x & 0x100:
        x ^= 0x11d
    gf_exp[i] = x
    gf_log[x] = i
for i in range(255,512):
    gf_exp[i] = gf_exp[i-255]

def gf_mul(x,y):
    if x==0 or y==0:
        return 0
    return gf_exp[gf_log[x] + gf_log[y]]

def main():
    s = sys.argv[1]

    version = 5
    mode = 4 # byte mode
    dim = 17 + 4 * version
    datamatrix = 0.5 * np.ones((dim, dim))
    nsym = 26

    # PACK
    msg = [mode * 16, len(s) * 16] + [ord(c) << 4 for c in s]
    for i in range(1, len(msg)):
        msg[i-1] += msg[i] // 256
        msg[i] = msg[i] % 256

    pad = [236, 17]
    msg = (msg + pad * 54)[:108]

    # MAGIC (encoding)
    gen = [1]
    for i in range(0, nsym):
        q = [1, gf_exp[i]]
        r = [0] * (len(gen)+len(q)-1)
        for j in range(0, len(q)):
            for i in range(0, len(gen)):
                r[i+j] ^= gf_mul(gen[i], q[j])
        gen = r
    msg_enc = [0] * (len(msg) + nsym)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]
    for i in range(0, len(msg)):
        coef = msg_enc[i]
        if coef != 0:
            for j in range(0, len(gen)):
                msg_enc[i+j] ^= gf_mul(gen[j], coef)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]

    # PATTERN
    # position marks
    for _ in range(3):
        datamatrix = np.rot90(datamatrix)
        for i in range(4):
            datamatrix[max(0, i-1):8-i, max(0, i-1):8-i] = i%2
    datamatrix = np.rot90(datamatrix.T)

    # alignment
    for i in range(3):
        datamatrix[28+i:33-i, 28+i:33-i] = (i+1)%2

    # timing
    for i in range(7, dim-7):
        datamatrix[i, 6] = datamatrix[6, i] = (i+1)%2

    # the "dark module"
    datamatrix[dim-8, 8] = 1

    # FORMAT INFO
    L4 = '110011000101111' # Low/Mask4
    ptr_ul = np.array([8, -1])
    steps_ul = [0, 1] * 8 + [-1, 0] * 7
    steps_ul[13] = 2 # hop over vertical timing
    steps_ul[18] = -2 # then horizontal

    ptr_x = np.array([dim, 8])
    steps_x = [-1, 0] * 7 + [15-dim, dim-16] + [0, 1] * 7

    for bit, step_ul, step_x in zip(L4, np.array(steps_ul).reshape(-1,2), np.array(steps_x).reshape(-1,2)):
        ptr_ul += step_ul
        ptr_x += step_x
        datamatrix[tuple(ptr_ul)] = int(bit)
        datamatrix[tuple(ptr_x)] = int(bit)

    # FILL
    dmask = datamatrix == 0.5

    cols = (dim-1)/2
    cursor = np.array([dim-1, dim]) # starting off the matrix
    up_col = [-1, 1, 0, -1] * dim
    down_col = [1, 1, 0, -1] * dim
    steps = ([0, -1] + up_col[2:] + [0, -1] + down_col[2:]) * (cols/2)
    steps = np.array(steps).reshape(-1, 2)
    steps = iter(steps)

    # bit-ify everything
    msg_enc = ''.join('{:08b}'.format(x) for x in msg_enc) + '0' * 7 # 7 0's are for padding
    for bit in msg_enc:
        collision = 'maybe'
        while collision:
            cursor += steps.next()
            # skip vertical timing
            if cursor[1] == 6:
                cursor[1] = 5
            collision = not dmask[tuple(cursor)]
        datamatrix[tuple(cursor)] = int(bit)

    # COOK
    mask4 = lambda i, j: (i//2 + j//3)%2 == 0
    for i in range(dim):
        for j in range(dim):
            if dmask[i, j]:
                datamatrix[i, j] = int(datamatrix[i, j]) ^ (1 if mask4(i, j) else 0)

    # THE PRESTIGE
    plt.figure(facecolor='white')
    plt.imshow(datamatrix, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    main()

```

After:

```
import sys
from pylab import*
n=range
l=len
E=[1]+[0]*511
L=[0]*256
x=1
for i in n(1,255):
 x<<=1
 if x&256:x^=285
 E[i]=x;L[x]=i
for i in n(255,512):E[i]=E[i-255]
def f(x,y):
 if x*y==0:return 0
 return E[L[x]+L[y]]
m=sys.argv[1]
m=[ord(c)*16 for c in'\4'+chr(l(m))+m]
for i in n(1,l(m)):m[i-1]+=m[i]/256;m[i]=m[i]%256
m=(m+[236,17]*54)[:108]
g=[1]
for i in n(26):
 q=[1,E[i]]
 r=[0]*(l(g)+l(q)-1)
 for j in n(l(q)):
    for i in n(l(g)):r[i+j]^=f(g[i],q[j])
 g=r
e=[0]*134
for i in n(108):
 e[i]=m[i]
for i in n(108):
 c=e[i]
 if c:
    for j in n(l(g)):e[i+j]^=f(g[j],c)
for i in n(108):e[i]=m[i]
m=.1*ones((37,)*2)
for _ in n(3):
 m=rot90(m)
 for i in n(4):m[max(0,i-1):8-i,max(0,i-1):8-i]=i%2
m=rot90(m.T)
for i in n(3):m[28+i:33-i,28+i:33-i]=(i+1)%2
for i in n(7,30):m[i,6]=m[6,i]=(i+1)%2
m[29,8]=1
a=array
t=tuple
g=int
r=lambda x:iter(a(x).reshape(-1,2))
p=a([8,-1])
s=[0,1]*8+[-1,0]*7
s[13]=2
s[18]=-2
P=a([37,8])
S=[-1,0]*7+[-22,21]+[0,1]*7
for b,q,Q in zip(bin(32170)[2:],r(s),r(S)):p+=q;P+=Q;m[t(p)]=g(b);m[t(P)]=g(b)
D=m==0.1
c=a([36,37])
s=r(([0,-1]+([-1,1,0,-1]*37)[2:]+[0,-1]+([1,1,0,-1]*37)[2:])*9)
for b in ''.join('{:08b}'.format(x) for x in e):
 k=3
 while k:
    c+=s.next()
    if c[1]==6:c[1]=5
    k=not D[t(c)]
 m[t(c)]=g(b)
a=n(37)
for i in a:
 for j in a:
    if D[i,j]:m[i,j]=g(m[i,j])^(j%3==0)
imshow(m,cmap=cm.gray_r);show()

```

(relying on a tab to count as 4/8/whatever number of spaces \>= 2., not sure how well it will copy)

Because it's so long, we can zip it (saw someone do this somewhere else, forgot who though :( ) to save some more characters, bringing the total down to **1085** **1077** because `pylab` is filthy:

```
import zlib,base64
exec zlib.decompress(base64.b64decode('eJxtU0tzmzAQvvSkX6FLaglkyiM2hHRvyS2HZNobo3QwwY6IBVjQFrfT/96V3KR4Wg5I+/6+3ZXSfWdGOhwHsjWdpv1xX26oclqPtGDKdleTPezrltxCEUm/CKW3iiJyB/YWr9ZkgohsO0MVVS1tWSTi1YrnhE4fP6KFqi2d3qNfPj1CnK0IvS2UhOn6rpgkqHkkxolVFPPceeBviRpJnuot3bJJHG1Sm807AoS5qcevpqUhoX9ut4VN6d8VRymJBuQUlGb3DUGjVHTmiVXci9bUVqyw4uLdwq+eDdszzbmv5TkJp801gkDSgKf8gCSu7cVJF5a6Bqb9Ik7WIkqxLZe8yKMwk2RnW3VGbW3BH1AtLDmJoF3/sPiO+3t24MuIEwetOUVYnY3Bb5bHuvPcFMpv5CNs2Q6TiUPRSAzegSG1yxoll2dkwsxmql+h/8dWgbW69lY5favazKvWs6qNFBX/J8/fChqCyOvaemAsSQX34pPzl5NzYktqMN14FWKbyZzhpW26LicWCmw9z7OlEucibs1FTN7Cg89nQBIbH2e+ypMEQ99uEpjyI46RM+dUJKEbslhb4Gsxc8MsVyKTuMIllMaURzLC+LXf1zhd1Y7EwL7Um6eSTrkaa8NKNvHA1MNz2ddsia+Ac9JDyYpM4ApxMuBoRCS9zC/QilNKyVBEiYTYnlhoGZN7648Ny9D/E7z6YUAci9g9PpshdRQ24iAeLI0fqmcbhczjKA15EedSGDZw/H3CqfU+HK7vfXjA1R1ZzyXs2IY74f6PQG5A44sKIlK5+muRpA6wYQwr2gfALBZEYwUvSV0V/832j4l7V6ehbCzAxSJoOgS4+JmH2ebXIkCLLkfslxv8ZH1quxIvkBD6/Vnta/pyWv3KhyFo62lk3Ml2P/FpAaxzd66c9gXabqQ3SKniuMT6dDlxKwE7k85WpMxn76zMX9Pe4BI00u1CY0NPF/7ImosEm8OJ0sNz951pUemyh0oHO9yJL4ZfOzX/DQ2mdSs='))

```

If you replace the last line with the following (it adds 62 chars), you get nearly-perfect output, but the other still scans, so whatever.

```
figure(facecolor='white');imshow(m,cmap=cm.gray_r,interpolation='nearest');axis('off');show()

```

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


# Question
Title: Output the alphabet with the shortest code possible
You have to output the alphabet (upper case) with the shortest code possible.

Exact output expected : `ABCDEFGHIJKLMNOPQRSTUVWXYZ`

# Answer
# APL, 2 chars

```
⎕A

```

It's a constant string with the uppercase letters from A to Z
> 6 votes

# Answer
## Python 35 chars

```
print("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

```
> 1 votes

# Answer
**BASH 21 chars**

```
echo {A..Z}|tr -d " "

```

Output:

```
~$ echo {A..Z}|tr -d " "
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```
> 1 votes

# Answer
**Ruby 2.0.0, bytesize: 19:**

```
=> p([*'A'..'Z'].join)
=> "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

```

**update. this produce without quotes:**

```
=> ruby -e '$><<[*?A..?Z].join'
=> ABCDEFGHIJKLMNOPQRSTUVWXYZ

```
> 1 votes

# Answer
## R, 19

```
cat(LETTERS,sep="")

```

Output:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ

```
> 1 votes

# Answer
## Delphi

### 52 bytes

```
var i:int16;begin for i:=65to 90do write(chr(i))end.

```

### 45 bytes

```
begin write('ABCDEFGHIJKLMNOPQRSTUVWXYZ');end.

```
> 1 votes

---
Tags: code-golf
---


title: Concert tuning WAV

text:
# Question
Title: Concert tuning WAV
I used to play the oboe, the instrument that is, for some reason, used to tune the orchestra to A440. Anyways, continuing on with my story, I was bad at it and quit.

Write a program that generates a valid, full scale, 5 second, WAV file with a sample rate of 44.1 kHz that plays a 440 Hz (+3/-1 Hz) tone. Your code is responsible for generating the structure of the file format; no external resources.

+75 penalty if the tone does not approximate a sine wave (harmonic power must be less than 1% of the fundamental--a good polynomial approximation should be able to exceed 20 dB; I think parabolic is about -28 dB)

# Answer
> 5 votes
# GolfScript, 89 bytes

This GolfScript program contains non-printable characters, so I'm providing it as a hex dump. On Unixish systems with the xxd program installed, you can feed this hex dump to `xxd -r` to reconstruct the actual program.

```
0000000: 2752 4946 4678 5d03 0057 4156 4566 6d74  'RIFFx]..WAVEfmt
0000010: 2010 0000 0001 0001 0044 ac00 0044 ac00   ........D...D..
0000020: 0001 0008 0064 6174 6154 5d03 0027 2784  .....dataT]..''.
0000030: 8c94 9ba3 abb2 bac1 c7ce d4da e0e5 e9ee  ................
0000040: f2f5 f8fa fcfe ffff 272e 2d31 252b 2e7b  ........'.-1%+.{
0000050: 7e7d 252b 3232 3035 2a                   ~}%+2205*

```

The output of this program is a 220,545 byte 44.1 kHz 8-bit PCM WAV file that should play a 441 Hz tone for five seconds.

The code itself simply consists of two literal single-quoted strings: the first one contains a minimal WAV header, while the second 25-byte string, representing a quarter of the sine wave, is cloned, reversed, joined to the original, cloned again, inverted, joined again and finally repeated 2205 times to produce the actual audio data.

Ps. The output of the program above includes as extra trailing 0x0A byte (i.e. a line feed), which is technically not part of the WAV data. Since it lies past the end of the RIFF chunk, reasonable decoders should ignore it. (This could be fixed, at the cost of two extra bytes of code.)

# Answer
> 4 votes
# C, 204 bytes

Won't win, but here it is anyway :-)

```
x;main(i){char *h="riff\xec\xda& wave\x86\x8d\x94@0   ! ! d\xcc  \xa8x! \" 0 \x84\x81\x94\x81\xc8\xda& ";for(i=45;--i;)putchar(*h++-' ');for(;i++<220500;){x=(32767*sin(i/15.952));printf("%c%c",x,x>>8);}}

```

Needs to be compiled with the maths library, of course.

Outputs a 5-second WAV file to `stdout` (16-bit samples, 44.1 kHz sampling), but this can easily be redirected to a file (e.g., `./a.out >foo.wav`)

# Answer
> 1 votes
### R, 285 characters

```
S=44100;s=sin(0:(5*S-1)*pi*880/S);c=32767*s/max(abs(s));a=file("c.wav","wb");w=writeChar;W=function(x,z)writeBin(as.integer(x),a,z,e="little");w("RIFF",a,4,NULL);W(441036,4);w("WAVEfmt ",a,8,NULL);W(16,4);W(c(1,1),2);W(S*1:2,4);W(c(2,16),2);w("data",a,4,NULL);W(S*10,4);W(c,2);close(a)

```

Create a wav file called c.wav in the working directory.

Indented:

```
S=44100
s=sin(0:(5*S-1)*pi*880/S) #Sin Wave
c=32767*s/max(abs(s)) #Normalized
a=file("c.wav","wb") #Open connection with empty wav file
w=writeChar #Write characters
W=function(x,z)writeBin(as.integer(x),a,z,e="little") #Write binary data
w("RIFF",a,4,NULL)
W(441036,4)
w("WAVEfmt ",a,8,NULL)
W(16,4)
W(c(1,1),2)
W(S*1:2,4)
W(c(2,16),2)
w("data",a,4,NULL)
W(S*10,4)
W(c,2)
close(a)

```

---
Tags: code-golf, audio
---


title: Is an email is Spam or Ham?

text:
# Question
Title: Is an email is Spam or Ham?
# Challenge

Given an email in plain text format, including headers, decide if the email is either spam or ham, and output SPAM or HAM respectively. The emails will be given below. Your code **must** be able to correctly identify all of the samples, but should be general enough to work on any email.

# Scoring

This is a code golf, so shortest code wins.

# Restrictions

Do not:

* Rely on message length
* Rely on particular senders, recipients, dates, or subjects

# Data

### Spam

```
Subject:   favorable offer
From:   "Simon Nicolas" uopt@pictishbeast.net
Date:   Sun, August 28, 2005 0:00
To:   "UK resident"

Hello! I am Simon Nicolas, a general manager of international company IFSD Inc. (
http://www.ifsd-company.com ) and I have a favorable offer for you.

Now it is a little about our company. We are engaged the organization of plans of
reception of payments for private persons and the companies. Our services

are demanded by those who has requirement to accept remittances from clients in
other countries.

Our company conducts wide international activity; we work with the organizations and
private persons from the various countries worldwide. Our activity

constantly extends, we enter new services, we expand staff of employees we open
representations of the company in the territory of the various countries.

In connection with constant expansion of our international activity we feel
necessity of new employees in the territories of the various countries. Now we

have announced a set of employees on a post "the Regional Financial Manager".

Working on this post, our colleagues produce work with the bank transfers and the
checks. Our clients are private persons and the companies of the

different countries and for simplification of remittances we use our Regional
Financial managers.

The functions of the Regional Financial Manager:

-reception of bank payments on a bank account

The scheme of work is those: the Regional Financial Manager receives money resources
and informs us on this. We in turn at once enroll the necessary sum on

the account of our client. It allows you to save a lot of time - now the client does
not need to wait for reception of money from abroad. As such scheme

allows you to save money. From the sum of each transaction lead through you our
company pays 5 %.

The basic requirements:

-age of 21-60 years

-access to the Internet, e-mail

-opportunity to work not less than 3 hours per day

It is your really favorably chance to earn!

Start to work right now! For the beginning with us you need to fill works only
labour agreement

---

Best regards,

Simon Nicolas.

http://www.ifsd-company.com

```

### Spam

```
From: "Met Investment Fund" nclpbruehue@dancy.com
To: "UK competitor"
Subject: Job offer from http://www.metinvf.com
Date: Sat, 19 Mar 2005 00:10:07 +0000

Vacancies

We have some vacancies right now, here they are:

Financial manager:

JOB DESCRIPTION

Requirements:

Resident of the United Kingdom
Knowledge of Microsoft Word and Microsoft Excel;
Home Computer with e-mail account and ability to check your e-mail box at least
twice a day;
1-3 hours free during the week;
Be fast in decisions;
To manage MIF financial affairs through the provision of efficient and effective
financial
systems and support;
To ensure that the financial affairs are conducted in compliance with current
legislative
requirements and in line with requirements set by DCAL, DFP and DCMS;
To ensure adherence to all internal and external audit requirements;
To recieve MIF payments and our sub-companies payments and send them directly to our
investors;
To co-ordinate and control the completion of all necessary payments to our clients
(through
our site's member zone);
Have a university degree;
UK Bank account (for wire transfers from our company and our clients);

All offers here:
http://www.metinvf.com/careers.html

```

### Ham

```
From: "Tony McAdams" <tony@mcadams.com>
To: "Bobby" <bobby@mcadams.com>
Subject: Bobby, check out this job posting
Date: Sun, 30 May 2005 03:50:02 +0000

Hey Bob,

I heard you were looking for work, so I figured I'd pass along this job
offer.  A friend of mine works for Webdings Inc., and he mentioned they
are hiring.

Their site is: http://www.webdings.com

Anyways, how's the new apartment?  Get everything moved in alright? We
should be by Tuesday with some food and a house warming present. If Tuesday
doesn't work, we can drop by any time during the week.

Unfortunately Sparky won't be able to make it, she's not really feeling
all that well. The vet called and said they'd have to keep her for
observation for at least a week. Bummer.

Anyways, I hope to hear back from you soon Bob, everyone here misses you a
lot!

Talk to you soon,
Tony

```

### Ham

```
Subject:   Quote Selection
From:   "Simon Nicolas" simonsays@gmail.com
Date:   Mon, January 2, 2005 20:01
To:   "undisclosed-recipients"

Hello class,

Before next week's lecture, I need you all to read "His Last Bow" by
Doyle.  Pay particular attention to the following paragraphs:

    From that day they were seen no more in England. Some six
    months afterwards the Marquess of Montalva and Signor Rulli,
    his secretary, were both murdered in their rooms at the Hotel
    Escurial at Madrid. The crime was ascribed to Nihilism, and
    the murderers were never arrested. Inspector Baynes visited
    us at Baker Street with a printed description of the dark face of
    the secretary, and of the masterful features, the magnetic
    black eyes, and the tufted brows of his master. We could not
    doubt that justice, if belated, had come at last.
    "A chaotic case, my dear Watson," said Holmes over an evening
    pipe. "It will not be possible for you to present in that compact
    form which is dear to your heart. It covers two continents,
    concerns two groups of mysterious persons, and is further
    complicated by the highly respectable presence of our friend,
    Scott Eccles, whose inclusion shows me that the deceased Garcia
    had a scheming mind and a well-developed instinct of self preservation.
    It is remarkable only for the fact that amid a perfect
    jungle of possibilities we, with our worthy collaborator, the
    inspector, have kept our close hold on the essentials and so
    been guided along the crooked and winding path. Is there any
    point which is not quite clear to you?"

Thank you,
Simon

```

# Answer
> 3 votes
## J (40)

This program has a 100% success rate on the given samples.

```
echo>(+./(3#1)E.LF=1!:1[3){'HAM';'SPAM'

```

How does it work?

It checks if the mail contains three or more newlines in a row, and if so, classifies it as spam. For the test set, this holds. (Interestingly enough, from a cursory glance at my spam folder, this also holds for quite a lot of real spam.)

# Answer
> 1 votes
# Befunge 98 - 34

```
~a-!2*1-+:2`98+*j"SP"8j@,k3"MA"<H'

```

This is a translation of marinus's answer; it checks for 3 or more newlines in a row.

---
Tags: code-golf
---