title: Animated drawing of a Bézier curve

text:
# Question
Title: Animated drawing of a Bézier curve
Your job is to draw a Bézier curve given it's control points. The only criteria is that you actually have to show how to draw the curve from the initial control point to the last one.

# Criterias

* The result has to be animated, e.g. it has to **show** the drawing process somehow. The way you do the animation is irrelevant, it can generate a `.gif`, it can draw to a window, or generate ASCII results (and possibly clearing the screen after each draw), etc.
* It has to support at least 64 control points.
* This is a popularity contest, so you might want to add some additional features to your program to get more upvotes. (My answer for example draws the control points, and some visual aid on how to generate the image as well)
* The winner is the most upvoted **valid** answer 7 days after the last valid submission.
* My submission doesn't count as valid.

# How to draw a Bézier curve

Assume we want to draw 100 iterations. To get the `n`th point of the curve you can use the following algorithm:

```
1. Take each adjanced control point, and draw a line between them
2. Divide this line by the number of iterations, and get the nth point based on this division.
3. Put the points you've got into a separate list. Let's call them "secondary" control points.
4. Repeat the whole process, but use these new "secondary" control points. As these points have one less points at each iteration eventually only one point will remain, and you can end the loop.
5. This will be nth point of the Bézier curve

```

This might be a bit hard to understand when written down, so here are some images to help visualize it:

For two control points (shown in black dots) you only have one line initally (the black line). Dividing this line by the number of iterations and getting the `n`th point will result in the next point of the curve (shown in red):

For three control points, you first have to divide the line between the first and the second control point, then divide the line between the second and third control point. You will get the points marked with blue dots.

Then, as you still have two points, you have to draw a line between these two points (blue in the image), and divide them again to get the next point for the curve:

As you add more control points the algorithm stays the same, but there will be more and more iterations to do. Here is how it would look like with four points:

And five points:

You can also check my solution, which was used to generate these images, or read more about generating Bézier curves at Wikipedia

# Answer
> 19 votes
Done recursively in Mathematica with no hard limits on the number control points in just three lines:

```
ctrlPts = {{0, 0}, {1, 1}, {2, 0}, {1, -1}, {0, 0}};
getLines[x_List] := Partition[x, 2, 1];
partLine[{a_, b_}, t_] := t a + (1 - t) b;
f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]

```

Showing it is more involved than the calculations!:

```
color[x_] := ColorData[5, "ColorList"][[x[[1]]]]
Animate[Graphics[{PointSize[.03], ,
        MapIndexed[{color@#2, Point/@ #1,Line@#1} &, f[ctrlPts,t]],
        Red, Point@Last@f[ctrlPts, t],
        Line@Flatten[(Last@f[ctrlPts, #]) & /@ Range[0, t, 1/50], 1]}], {t, 0, 1}]

```

Code dissection (kind of) for the calc part:

```
getLines[x_List] := Partition[x, 2, 1]; (* Takes a list of points { pt1, pt2, pt...}
                                           as input and returns {{pt1,pt2}, {pt2,pt3} ...}
                                           which are the endpoints for the successive
                                           lines between the input points *)

partLine[{a_, b_}, t_] := t a + (1 - t) b;(* Takes two points and a "time" as input
                                             and calculates
                                             a linear interpolation between them*)

f[pts_, t_] := NestList[partLine[#, t] & /@ getLines@# &, pts, Length@pts- 1]
                                          (* This is where the meat is :)
     Takes a list of n points and a "time" as input.
     Operates recursively on the previous result n-1 times, preserving all the results
     Each time it does the following with the list {pt1, pt2, pt3 ...} received:
           1) Generates a list {{pt1, pt2}, {pt2, pt3}, {pt3, pt4} ...}
           2) For each of those sublists calculate the linear interpolation at time "t",
              thus effectively reducing the number of input points by 1 in each round.
     So the end result is a list of lists resembling:
     {{pt1, pt2, pt3 ...}, {t*pt1+(1-t)*pt2, t*pt2+(1-t)*pt3,..}, {t*pt12+(1-t)*pt23, ..},..}
                             --------------   ---------------
                                  pt12              pt23
     And all those are the points you see in the following image:

```

With a few more lines you can drag the control points interactively while the animation is running:

```
Manipulate[
 Animate[Graphics[{
    PointSize[.03], Point@pts,
    MapIndexed[{color@#2, Point /@ #1, Line@#1} &, f[pts, t]],
    Red, Point@Last@f[pts, t], Line@Flatten[(Last@f[pts, #]) & /@ Range[0, t, 1/50], 1]},
   PlotRange -> {{0, 2}, {-1, 1}}], {t, 0, 1}],
  {{pts, ctrlPts}, Locator}]

```

Here dragging the green point:

BTW, the same code runs in 3D without modifications (For the Mathematica geeks you only have to replace `Graphics[]` by `Graphics3D[]` and add a third coordinate to the control points list):

NB:

Of course this kludge isn't needed in Mathematica as there are several primitives for drawing Beziers:

```
Graphics[{BSplineCurve[ctrlPts], Green, Line[ctrlPts], Red,  Point[ctrlPts]}]

```

# Answer
> 15 votes
# Python

Certainly not the most efficient or beautiful code but it was fun to write. Run as

```
$> python thisscript.py

```

The control points are randomly generated for now but it is trivial to extend it to allow for stdin or file input.

* Shows the control points
* Shows the iterations
* Different color for each iteration

As a bonus there is an endless mode that is guaranteed to provide for entertainment for hours if not days!

Matplotlib is required and ImageMagick if you want to save the resulting GIF. Tested up to 64 control points (runs very slow with a large number of points!)

```
import matplotlib
matplotlib.use('GTkAgg')
import pylab as pl
from math import sin,cos,pi
from random import random
import os
import time

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __repr__(self):
        return "[{:.3f},{:.3f}]".format(self.x,self.y)
    def __str__(self):
        return self.__repr__()

class Path:
    def __init__(self,points):
        self.points=points
    def interpolate(self,u): # interpolate the path, resulting in another path with one point less in length
        pts = [None]*(len(self.points)-1)
        for i in range(1,len(self.points)):
            x = self.points[i-1].x + u*( self.points[i].x - self.points[i-1].x)
            if (self.points[i-1].x == self.points[i].x): # vertical line
                y = self.points[i-1].y + u*( self.points[i].y - self.points[i-1].y)
            else:
                y = self.points[i-1].y + (self.points[i].y - self.points[i-1].y)/(self.points[i].x - self.points[i-1].x)*( x - self.points[i-1].x)
            pts[i-1] = Point(x,y)
        return Path(pts)

    def interpolate_all(self,u): # interpolate all the paths
        paths = [None]*len(self.points)
        paths[0]=self
        for i in range(1,len(paths)):
            paths[i] = paths[i-1].interpolate(u)
        return paths

    def draw(self,ax,color,*args,**kwargs):
        x = [ p.x for p in self.points]
        y = [ p.y for p in self.points]
        ax.plot(x,y,*args,color=color,**kwargs)
        ax.scatter([p.x for p in self.points], [p.y for p in self.points],color=color)

    def __str__(self):
        return str(self.points)

def bezier(path,ustep,ax,makeGif):
    if makeGif:
        os.system("mkdir -p tempgif")
    u=0.
    x=[] # x coordinate list for the bezier path point
    y=[] # y coordinate list for the bezier path point
    pl.ion()
    pl.show()
    n=0
    while u < 1.+ustep: # and not u <= 1.0 to get rid of rounding errors
        ax.cla()
        paths = path.interpolate_all(u)
        x.append(paths[-1].points[0].x)
        y.append(paths[-1].points[0].y)
        u+=ustep
        for i in range(len(paths)):
            color = pl.cm.jet(1.*i/len(paths)) # <-- change colormap here for other colors, for a list of available maps go to http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
            paths[i].draw(ax,color=color,lw=2) # draw all the paths
        ax.plot(x,y,color='red',lw=5) # draw the bezier curve itself
        pl.draw()
        if makeGif:
            pl.savefig("tempgif/bezier_{:05d}.png".format(n))
            n+=1
    if makeGif:
        print("Creating your GIF, this can take a while...")
        os.system("convert -delay 5 -loop 0 tempgif/*.png "+makeGif)
        os.system("rm -r tempgif/")
        print("Done.")
    pl.ioff()

def getPtsOnCircle(R,n):
    x = [None]*(n+1)
    y = [None]*(n+1)
    for i in range(n+1):
        x[i] = R*cos(i*2.*pi/n)
        y[i] = R*sin(i*2.*pi/n)
    return x,y

def getRndPts(n):
    x = [ random() for i in range(n) ]
    y = [ random() for i in range(n) ]
    return x,y

def run(ax,x,y,makeGif=False):
    ctrlpoints = [ Point(px,py) for px,py in zip(x,y) ]
    path = Path(ctrlpoints)
    bezier(path,0.01,ax,makeGif) # 0.01 is the step size in the interval [0,1]

def endless_mode(ax):
    while True:
        x,y = getRndPts( int(5+random()*10) )
        run(ax,x,y)
        pl.draw()
        time.sleep(0.5) # pause for a moment to gaze upon the finished bezier curve
def main():
    fig = pl.figure(figsize=(6,6)) # <-- adjust here for figure size
    fig.subplots_adjust(0,0,1,1)
    ax = fig.add_subplot(111)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    opt = raw_input("[s]ingle run or [e]ndless mode? ")
    if opt=='s':
        gifname = raw_input("Name of output GIF (leave blank for no GIF): ")
        x,y = getRndPts(15)
        run(ax,x,y,gifname if gifname != "" else False)
        pl.show()
    elif opt=='e':
        endless_mode(ax)
    else:
        print("Invalid input: "+opt)

main()

```

# Answer
> 12 votes
# Postscript

to generate a `gif`, make sure 'emitpages' is defined as true, and:

```
gs -sDEVICE=png16 -g500x500 -o bezan%03d.png bezanim.ps
convert bezan*.png bezan.gif

```

extra features:

* configurable bounding box
* 2 generators: random points, randomly permuted random flattened Bezier
* "overlay" animation (where it doesn't erase anything).
* optional 'showpage' (use for generating `gif`s, omit for on-screen preview)

Using ghostscript and larger sets of points, the on-screen preview is very different from the generated images, as you can watch the lines "converge" upon each point.

simple set of points, scaled, using `png48`:

simple set with overlay:

lots of points, overlay animation:

non-overlay:

code:

```
%!
/iterations 100 def
%/Xdim 612 def
%/Ydim 792 def
/Xdim 400 def
/Ydim 400 def
/scalepage {
    100 100 translate
    %1 5 scale % "tron"?
    1 3 dup dup scale div currentlinewidth mul setlinewidth
} def scalepage
/gen 2 def  % 0:rand points  1:rand permuted bezier
            % 2:special list
/genN 6 def % number of generated points
/overlay true def
/emitpages false def
/emitpartials false def
/.setlanguagelevel where { pop 2 .setlanguagelevel } if

/pairs { % array-of-points  .  array-of-pairs-of-points
    [ exch 0 1 2 index length 2 sub { % A i
        2 copy 2 getinterval % A i A_[i..i+1]
        3 1 roll pop % A_[i..i+1] A
    } for pop ]
} def

/drawpairs {
    gsave
    dup 1 exch length B length div sub setgray
    {
        aload pop
        aload pop moveto
        aload pop lineto
        stroke
        %flushpage
    } forall
    %flushpage
    %emitpartials { copypage } if
    grestore
} def

/points { % array-of-pairs  .  array-of-points
    [ exch { % pair
        [ exch
        aload pop % p0 p1
        aload pop 3 2 roll aload pop % p1x p1y p0x p0y
        exch % p1x p1y p0y p0x
        4 3 roll % p1y p0y p0x p1x
        exch % p1y p0y p1x p0x
        2 copy sub n mul add exch pop % p1y p0y p0x+n(p1x-p0x)
        3 1 roll % p0x+n(p1x-p0x) p1y p0y
        2 copy sub n mul add exch pop % p0x+n(p1x-p0x) p0y+n(p1y-p0y)
        ]
    } forall ]
} def

/drawpoints {
    gsave
    dup length B length div setgray
    {
        newpath
        aload pop 2 copy moveto currentlinewidth 3 mul 0 360 arc fill
        %flushpage
    } forall
    %flushpage
    emitpartials { copypage } if
    grestore
} def

/anim {
    /B exch def
    /N exch def
    /Bp B pairs def
    Bp drawpairs
    1 0 0 setrgbcolor
    B 0 get aload pop moveto
    0 1 N div 1 { /n exch def
        B
        {
            dup length 1 eq { exit } if
            dup drawpoints
            pairs dup drawpairs
            points
        } loop
        aload pop
        aload pop
        2 copy
        gsave
            newpath
            2 copy moveto currentlinewidth 3 mul 0 360 arc fill
        grestore
        lineto currentpoint stroke 2 copy moveto
        gsave
            count dup 1 add copy
            3 1 roll moveto
            2 idiv 1 sub {
                lineto
            } repeat
            pop
            stroke
        grestore
        emitpages {
            currentpoint
            currentrgbcolor
            overlay { copypage }{ showpage scalepage } ifelse
            setrgbcolor
            moveto
        }{
            flushpage 10000 { 239587 23984 div pop } repeat
            flushpage 4000 { 239587 23984 div pop } repeat
            overlay not {
                erasepage Bp drawpairs
            } if
            %flushpage
        } ifelse
    } for
    moveto N { lineto } repeat stroke
} def

% "main":

iterations
[
    { [ genN { [ rand Xdim mod rand Ydim mod ] } repeat ] }
    {
        40 setflat
        rand Xdim mod rand Ydim mod moveto
        genN 1 sub 3 div ceiling cvi
            { 3 { rand Xdim mod rand Ydim mod } repeat curveto } repeat
        flattenpath
        [{2 array astore}dup{}{}pathforall]
        [exch dup 0 get exch 1 1 index length 1 sub getinterval {
            rand 2 mod 0 eq { exch } if
        } forall]
        0 genN getinterval
    }
    {
        [
            [10 10]
            [100 10]
            [100 100]
            [10 100]
            [10 40]
            [100 40]
            [130 10]
            [50 50]
            [80 50]
            [110 30]
            [20 50]
            [70 50]
            [60 50]
            [10 10]
            [40 50]
            [30 50]
            [10 30]
            [90 50]
            [10 50]
            [120 20]
            [10 20]
        ] 0 genN getinterval
    }
] gen get exec

newpath anim

stroke

```

# Answer
> 9 votes
# Ruby + RMagick

Additional features:

* Shows the control points
* Shows each iteration
* Uses different colours for each iteration

To use send the points from STDIN:

```
$ echo "300 400 400 300 300 100 100 100 200 400" | ./draw.rb

```

Result will be inside `result.gif`:

Here is another run, with 12+1 points:

```
$ echo "100 100 200 200 300 100 400 200 300 300 400 400 300 500 200 400 100 500 0   400 100 300 0   200 100 100" | ./draw.rb

```

# Code

This is neither golfed, nor too readable, sorry for that.

`draw.rb`

```
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)

ITERATIONS = 100

points = ARGF.read.split.map(&:to_i).each_slice(2).to_a
result = []

def draw_line(draw,points)
  points.each_cons(2) do |a,b|
    draw.line(*a, *b)
  end
end

def draw_dots(draw,points,r)
  points.each do |x,y|
    draw.ellipse(x,y,r,r,0,360)
  end
end

canvas = Magick::ImageList.new

0.upto(ITERATIONS) do |i|
  canvas.new_image(512, 512)

  draw = Magick::Draw.new

  draw.stroke('black')
  draw.stroke_width(points.length.to_f/2)
  draw_line(draw,points)
  draw_dots(draw,points,points.length)

  it = points.dup
  while it.length>1
    next_it = []
    it.each_cons(2) do |a,b|
      next_it << [b[0]+(a[0]-b[0]).to_f/ITERATIONS * i, b[1]+(a[1]-b[1]).to_f/ITERATIONS * i]
    end
    draw.stroke("hsl(#{360/points.length.to_f*next_it.length},100,100)")
    draw.fill("hsl(#{360/points.length.to_f*next_it.length},100,100)")
    draw.stroke_width(next_it.length.to_f/2)
    draw_line(draw,next_it)
    draw_dots(draw,next_it,next_it.length)
    it = next_it
  end

  result << it.first

  draw.stroke("hsl(0,100,100)")
  draw.fill("hsl(0,100,100)")
  draw.stroke_width(points.length)
  draw_line(draw,result)
  draw_dots(draw,[it.first],points.length*2)

  draw.draw(canvas)
end

canvas.write('result.gif')

```

`Gemfile`

```
source "https://rubygems.org"
gem 'rmagick', '2.13.2'

```

# Answer
> 8 votes
## Java

Using the adaptive subdivision algorithm of Anti Grain Geometry.

Code is interactive and allows the user to drag the four nodes with the mouse.

```
public class SplineAnimation extends JPanel implements ActionListener, MouseInputListener {
    int     CANVAS_SIZE             = 512;
    double  m_distance_tolerance    = 1;
    double  m_angle_tolerance       = 1;
    int     curve_recursion_limit   = 1000;

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.setContentPane(new SplineAnimation());

        f.pack();
        f.setResizable(false);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    // Graphics.
    BufferedImage   im      = new BufferedImage(CANVAS_SIZE, CANVAS_SIZE, BufferedImage.TYPE_INT_ARGB);
    Graphics2D      imageG  = im.createGraphics();
    Graphics2D      g       = null;
    Ellipse2D       dot     = new Ellipse2D.Double();
    Line2D          line    = new Line2D.Double();
    Path2D          path    = new Path2D.Double();

    // State.
    Point2D[]       pts     = {new Point2D.Double(10, 10), new Point2D.Double(CANVAS_SIZE / 8, CANVAS_SIZE - 10), new Point2D.Double(CANVAS_SIZE - 10, CANVAS_SIZE - 10), new Point2D.Double(CANVAS_SIZE / 2, 10)};
    double          phase   = 0;
    private int     dragPt;
    private double  f;
    private int     n       = 0;

    public SplineAnimation() {
        super(null);
        setPreferredSize(new Dimension(CANVAS_SIZE, CANVAS_SIZE));
        setOpaque(false);

        // Prepare stuff.
        imageG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        imageG.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        imageG.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        imageG.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        imageG.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        imageG.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        imageG.translate(0.5, 0.5);
        addMouseListener(this);
        addMouseMotionListener(this);

        // Animate!
        new javax.swing.Timer(16, this).start();
    }

    @Override
    public void paintComponent(Graphics g) {
        this.g = (Graphics2D)getGraphics();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Drawable yet?
        if (g == null)
            return;

        // Clear.
        imageG.setColor(Color.WHITE);
        imageG.fillRect(0, 0, CANVAS_SIZE + 1, CANVAS_SIZE + 1);

        // Update state.
        f = 0.5 - 0.495 * Math.cos(phase += Math.PI / 100);

        // Render.
        path.reset();
        path.moveTo(pts[0].getX(), pts[0].getY());
        recursive_bezier(0, pts[0].getX(), pts[0].getY(), pts[1].getX(), pts[1].getY(), pts[2].getX(), pts[2].getY(), pts[3].getX(), pts[3].getY());
        path.lineTo(pts[3].getX(), pts[3].getY());

        imageG.setPaint(Color.BLACK);
        imageG.draw(path);
        g.drawImage(im, 0, 0, null);

//      if (phase > Math.PI)
//          System.exit(0);
//      save("Bezier" + n++ + ".png");
    }

    private void save(String filename) {
        paint(im.getGraphics());
        try {
            ImageIO.write(im, "PNG", new File(filename));
        }
        catch (IOException e) {}
    }

    // Modified algorithm from Anti Grain Geometry.
    // http://www.antigrain.com/research/adaptive_bezier/index.html
    private void recursive_bezier(int level, double x1, double y1, double x2, double y2, double x3, double y3, double x4,
            double y4) {
        if (level > curve_recursion_limit)
            return;

        // Calculate all the mid-points of the line segments
        // ----------------------
        double x12 = x1 + (x2 - x1) * f;
        double y12 = y1 + (y2 - y1) * f;
        double x23 = x2 + (x3 - x2) * f;
        double y23 = y2 + (y3 - y2) * f;
        double x34 = x3 + (x4 - x3) * f;
        double y34 = y3 + (y4 - y3) * f;
        double x123 = x12 + (x23 - x12) * f;
        double y123 = y12 + (y23 - y12) * f;
        double x234 = x23 + (x34 - x23) * f;
        double y234 = y23 + (y34 - y23) * f;
        double x1234 = x123 + (x234 - x123) * f;
        double y1234 = y123 + (y234 - y123) * f;

        if (level > 0) // Enforce subdivision first time
        {
            // Try to approximate the full cubic curve by a single straight line
            // ------------------
            double dx = x4 - x1;
            double dy = y4 - y1;

            double d2 = Math.abs((x2 - x4) * dy - (y2 - y4) * dx);
            double d3 = Math.abs((x3 - x4) * dy - (y3 - y4) * dx);

            double da1, da2;

            if ((d2 + d3) * (d2 + d3) <= m_distance_tolerance * (dx * dx + dy * dy)) {
                // If the curvature doesn't exceed the distance_tolerance
                // value we tend to finish subdivisions.
                // ----------------------

                // Angle & Cusp Condition
                // ----------------------
                double a23 = Math.atan2(y3 - y2, x3 - x2);
                da1 = Math.abs(a23 - Math.atan2(y2 - y1, x2 - x1));
                da2 = Math.abs(Math.atan2(y4 - y3, x4 - x3) - a23);
                if (da1 >= Math.PI)
                    da1 = 2 * Math.PI - da1;
                if (da2 >= Math.PI)
                    da2 = 2 * Math.PI - da2;

                if (da1 + da2 < m_angle_tolerance) {
                    // Finally we can stop the recursion
                    // ----------------------
                    path.lineTo(x1234, y1234);
                    return;
                }
            }
        }

        // Continue subdivision
        // ----------------------
        recursive_bezier(level + 1, x1, y1, x12, y12, x123, y123, x1234, y1234);
        recursive_bezier(level + 1, x1234, y1234, x234, y234, x34, y34, x4, y4);

        // Draw the frame.
        float c = 1 - (float)Math.pow(1 - Math.sqrt(Math.min(f, 1 - f)), level * 0.2);
        imageG.setPaint(new Color(1, c, c));
        line.setLine(x1, y1, x2, y2);
        imageG.draw(line);
        line.setLine(x2, y2, x3, y3);
        imageG.draw(line);
        line.setLine(x3, y3, x4, y4);
        imageG.draw(line);
        line.setLine(x12, y12, x23, y23);
        imageG.draw(line);
        line.setLine(x23, y23, x34, y34);
        imageG.draw(line);
        node(level + 1, x1234, y1234, level == 0? Color.BLUE : Color.GRAY);
    }

    private void node(int level, double x, double y, Color color) {
        double r = 20 * Math.pow(0.8, level);
        double r2 = r / 2;
        dot.setFrame(x - r2, y - r2, r, r);
        imageG.setPaint(color);
        imageG.fill(dot);
    }

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {
        Point mouse = e.getPoint();

        // Find the closest point;
        double minDist = Double.MAX_VALUE;
        for (int i = 0; i < pts.length; i++) {
            double dist = mouse.distanceSq(pts[i]);
            if (minDist > dist) {
                minDist = dist;
                dragPt = i;
            }
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseDragged(MouseEvent e) {
        pts[dragPt] = e.getPoint();
    }

    @Override
    public void mouseMoved(MouseEvent e) {}
}

```

# Answer
> 6 votes
## HTML5 + Javascript + CSS

So I did it long time ago (the last modified date of the file was 9/21/2012). Glad that I kept it. Unfortunately it only supports 4 control points in its current state, but I'm working on it.

EDIT: Although the UI only supports 4 control points, the underlying function (`animateConstruction`) does support an arbitrary number of control points. Though I would not suggest doing it for more than 10 since the code is VERY inefficient. (I tried with 25 and had to kill the tab using Task Manager) If this counts as a valid submission I am not planning on revising the code.

NOTE: I was a naive hobbyist back then. The code is wrong on so many levels (including lack of semicolons and use of `eval`).

## To Use

Save the code as a .html file and open it **in Google Chrome** or JSfiddle
If you need 4 or less control points, enter the parameters on the right, then choose "Construction mode" and press "Animate" in bottom left.
If you need more control points, call the `animateConstruction` function. It takes an array of coordinates (2-item arrays) as the argument. (e.g. `animateConstruction([[0,0],[500,0],[0,500]]`). Note that the draw area is 500x500, and the coordinate system follow the HTML canvas element (origin at top-left, x-axis pointing right, y-axis pointing down)
For the fiddle, I have added a text box bottom-left. Enter semicolon-separated coordinates (default value is an example) and press Go.

## Differences in Fiddle version

* The textbox
* Default animation steps reduced to 100
* Secondary curves are off by default

## Code

```
<html>
<head>
<style>
span.h{
    display: inline-block;
    text-align: center;
    text-decoration: underline;
    font: bold 1em Arial;
}

input[type="color"]{
    -webkit-appearance: button-bevel;
    vertical-align: -7px;
    width: 21px;
    height: 27px;
}

input[type="color"][disabled]{background: #FFF}

td{position:relative; padding:1px; text-align:center}
table[class] td{text-align:left}
td.t{padding:1px 5px; width:46px;}
table input[type="checkbox"]{visibility:hidden}
tr:hover input[type="checkbox"]{visibility:visible}
</style>
<script type='text/javascript'>
function Bezier(c){
    if(c.length==2) return function(t){return [c[0][0]+t*(c[1][0]-c[0][0]),c[0][1]+t*(c[1][1]-c[0][1])]}
    else return function(t){return Bezier([Bezier(c.slice(0,-1))(t),Bezier(c.slice(1))(t)])(t)}
}

function Bezier2(f1,f2){
    return function(t){return Bezier([f1(t),f2(t)])(t)}
}

//============================================
var c = null
var settings = {'guide':{'show':[true,true,true,true], 'color':['#EEEEEE','#00FF00','#0000FF','#FF00FF'], 'width':[10,1,1,1]}, 'curve':{'show':[true,true,true,true], 'color':['#EEEEEE','#00FF00','#0000FF','#FF00FF'], 'width':[10,3,3,3]}, 'main':{'show':true, 'color':'#FF0000', 'width':10}, 'sample': 100, 'steps':200, 'stepTime':10, 'mode':'Bezier', 'coords':[[0,500],[125,450],[125,0],[500,0]]}
var itv = 0

window.addEventListener('load',function(){
    c = $('c').getContext('2d')
    c.lineCap = 'round'
    c.lineJoin = 'round'
    draw(settings.coords,1)
},true)

function get(k,i){
    var t = settings
    if(k.constructor == Array) k.forEach(function(e){t = t[e]})
    return t.length>i ? t[i] : t.slice(-1)[0]
}

function frame(coords){
    c.strokeStyle = settings.curve.color[0]
    c.lineWidth = settings.guide.width[0]
    c.beginPath()
    c.moveTo.apply(c,coords[0])
    coords.slice(1).forEach(function(e){c.lineTo.apply(c,e)})
    c.stroke()
}

function transf(c){
    var t = []
    c.forEach(function(e){t.push([e[0]+5,e[1]+5])})
    return t
}
//============================================
function drawBezier(coords,t){
    if(t===undefined) t = 1
    coords = transf(coords)
    c.clearRect(0,0,510,510)
    frame(coords)
    c.beginPath()
    c.strokeStyle = settings.main.color
    c.lineWidth = settings.main.width
    c.moveTo.apply(c,coords[0])
    for(var i=0;i<=t*settings.sample;i++) c.lineTo.apply(c,Bezier(coords)(i/settings.sample))
    c.stroke()
}

function animateBezier(coords){
    var s = settings.steps
    var cur = ($('t').value==1 ? ($('t').value=$('T').innerHTML=(0).toFixed(3))*1 : $('t').value*s)+1
    var b = drawBezier(coords,$('t').value*1)
    itv = setInterval(function(){
        $("T").innerHTML = ($("t").value = cur/s).toFixed(3)
        drawBezier(coords,cur++/s,b)
        if(cur>s) clearInterval(itv)
    },settings.stepTime)
}
//============================================
function drawBezier2(coords,t){
    if(t===undefined) t = 1
    c.beginPath()
    c.strokeStyle = get(['curve','color'],coords.length-1)
    c.lineWidth = get(['curve','width'],coords.length-1)
    c.moveTo.apply(c,coords[0])
    for(var i=0;i<=t*100;i++) c.lineTo.apply(c,Bezier(coords)(i/100))
    c.stroke()
}

function drawConstruction(coords,t,B){
    coords = transf(coords)
    if(t===undefined) t = 0.5
    var b = B===undefined ? [[]] : B
    coords.forEach(function(e){b[0].push(function(t){return e})})
    c.clearRect(0,0,510,510)
    frame(coords)
    for(var i=1;i<coords.length;i++){
        if(B===undefined) b.push([])
        with(c){
            for(var j=0;j<coords.length-i;j++){
                if(B===undefined) b[i].push(Bezier2(b[i-1][j],b[i-1][j+1]))
                if(i!=coords.length-1 && get(['curve','show'],i-1) || i==coords.length-1 && settings.main.show){
                    strokeStyle = i==coords.length-1?settings.main.color:get(['curve','color'],i-1)
                    lineWidth = i==coords.length-1?settings.main.width:get(['curve','width'],i-1)
                    beginPath()
                    moveTo.apply(c,b[i][j](0))
                    for(var k=0;k<=t*settings.sample;k++) lineTo.apply(c,b[i][j](k/settings.sample))
                    stroke()
                }
                if(i && i!=coords.length-1 && get(['guide','show'],i)){
                    strokeStyle = i==coords.length-1?settings.main.color:get(['guide','color'],i)
                    lineWidth = i==coords.length-1?settings.main.width:get(['guide','width'],i)
                    beginPath()
                    if(i!=coords.length-1) arc.apply(c,b[i][j](t).concat([settings.curve.width[0]/2,0,2*Math.PI]))
                    stroke()
                }
            }
            if(i && i!=coords.length-1 && get(['guide','show'],i)){
                beginPath()
                moveTo.apply(c,b[i][0](t))
                for(var j=1;j<coords.length-i;j++) lineTo.apply(c,b[i][j](t))
                stroke()
            }
        }
    }
    return b
}

function animateConstruction(coords){
    var s = settings.steps
    var cur = ($('t').value==1 ? ($('t').value=$('T').innerHTML=(0).toFixed(3))*1 : $('t').value*s)+1
    var b = drawConstruction(coords,$('t').value*1)
    itv = setInterval(function(){
        $("T").innerHTML = ($("t").value = cur/s).toFixed(3)
        drawConstruction(coords,cur++/s,b)
        if(cur>s) clearInterval(itv)
    },settings.stepTime)
}
//============================================
function draw(coords,t){clearInterval(itv); return window['draw'+settings.mode](coords,t)}
function animate(coords){clearInterval(itv); return window['animate'+settings.mode](coords);}
//============================================
function $(id){return document.getElementById(id)}
function v(o,p){
    for(var i in o){
        var k = (p||[]).concat([i]).join('-')
        var t
        if((t = o[i].constructor) == Object || t == Array) v(o[i],[k])
        else if(t = $(k)){
            if(t.type=='checkbox') t.checked = o[i]
            else if(t.type=='radio'){
                for(var j=0, t=document.getElementsByName(t.name); j<t.length; j++) if(t[j].value == o[i]){
                    t[j].checked = true
                    break
                }
            }else t.value = o[i]
        }else if(t = $((i==0?'x':'y') + p[0].slice(-1))) t.value = o[i]
    }
}

document.addEventListener('load',function(){
    v(settings)
    $('t').setAttribute('step',1/settings.steps)
    var t = document.getElementsByTagName('input')
    for(i=0;i<t.length;i++) t[i].addEventListener('change',function(){
        var t
        if((t=this.id.split('-')).length > 1){
            var t1 = function(T){
                var t = 'settings'
                T.forEach(function(e){t += '[' + (isNaN(e)?'"'+e+'"':e) +']'})
                eval(t + '=' + (this.type=='text'?this.value:(this.type=='checkbox'?this.checked:'"'+this.value+'"')))
                $(T.join('-')).value = this.value
            }
            t1.call(this,t)
            if(t[0]=='curve' && t[1]=='color' && $('u').checked==true) t1.call(this,['guide'].concat(t.slice(1)))
        }else if(this.id == 'u'){
            for(i=0;t=$('guide-color-'+i);i++){
                t.disabled = this.checked
                t.value = settings.guide.color[i] = this.checked?settings.curve.color[i]:t.value
            }
        }else if(this.id == 't'){
            $('T').innerHTML = (this.value*1).toFixed(3)
            draw(settings.coords,this.value*1)
        }else if(t = /([xy])(\d+)/.exec(this.id)) settings.coords[t[2]*1][t[1]=='x'?0:1] = this.value*1
        else settings[this.id] = this.value
        if(this.id == 'steps') $("t").setAttribute("step",1/settings.steps)
    },true)
},true)
</script>
</head>
<body>
<canvas style='float:left' width='510' height='510' id='c'>
</canvas>
<div style='padding-left:550px; font-family:Arial'>
<span class='h' style='width:123px'>Control Points</span><br />
(<input type='text' id='x0' size='3' maxlength='3' />,<input type='text' id='y0' size='3' maxlength='3' />)<br />
(<input type='text' id='x1' size='3' maxlength='3' />,<input type='text' id='y1' size='3' maxlength='3' />)<br />
(<input type='text' id='x2' size='3' maxlength='3' />,<input type='text' id='y2' size='3' maxlength='3' />)<br />
(<input type='text' id='x3' size='3' maxlength='3' />,<input type='text' id='y3' size='3' maxlength='3' />)<br /><br />
<span class='h' style='width:200px'>Appearance</span><br />
<span style='font-weight:bold'>Guide lines</span><br />
<input type='checkbox' checked='checked' id='u' onchange='' /> Use curve colors<br />
<table style='border-collapse:collapse'>
<tr><td><input type='checkbox' id='guide-show-0' /></td><td><input type='color' id='guide-color-0' disabled='disabled' /></td><td class='t'>Frame</td><td><input type='text' id='guide-width-0' size='2' maxlength='2' /></td></tr>
<tr><td><input type='checkbox' id='guide-show-1' /></td><td><input type='color' id='guide-color-1' disabled='disabled' /></td><td class='t'>1</td><td><input type='text' id='guide-width-1' size='2' maxlength='2' /></td></tr>
<tr><td><input type='checkbox' id='guide-show-2' /></td><td><input type='color' id='guide-color-2' disabled='disabled' /></td><td class='t'>2</td><td><input type='text' id='guide-width-2' size='2' maxlength='2' /></td></tr>
<tr><td><input type='checkbox' id='guide-show-3' /></td><td><input type='color' id='guide-color-3' disabled='disabled' /></td><td class='t'>3</td><td><input type='text' id='guide-width-3' size='2' maxlength='2' /></td></tr>
</table>
<span style='font-weight:bold'>Curves</span>
<table style='border-collapse:collapse'>
<tr><td><input type='checkbox' id='curve-show-0' /></td><td><input type='color' id='curve-color-0' /></td><td class='t'>1</td><td><input type='text' id='curve-width-0' size='2' maxlength='2' /></td></td></tr>
<tr><td><input type='checkbox' id='curve-show-1' /></td><td><input type='color' id='curve-color-1' /></td><td class='t'>2</td><td><input type='text' id='curve-width-1' size='2' maxlength='2' /></td></td></tr>
<tr><td><input type='checkbox' id='curve-show-2' /></td><td><input type='color' id='curve-color-2' /></td><td class='t'>3</td><td><input type='text' id='curve-width-2' size='2' maxlength='2' /></td></td></tr>
<tr><td><input type='checkbox' id='curve-show-3' /></td><td><input type='color' id='curve-color-3' /></td><td class='t'>4</td><td><input type='text' id='curve-width-3' size='2' maxlength='2' /></td></td></tr>
<tr><td><input type='checkbox' id='main-show' /></td><td><input type='color' id='main-color' /></td><td class='t'>Main</td><td><input type='text' id='main-width' size='2' maxlength='2' /></td></td></tr>
</table><br />
<span class='h' style='width:300px'>Graphing & Animation</span><br />
<table class>
<tr><td>Sample points:</td><td><input type='text' id='sample' /></td></tr>
<tr><td>Animation steps:</td><td><input type='text' id='steps' /></td></tr>
<tr><td>Step time:</td><td><input type='text' id='stepTime' />ms</td></tr>
</table>
<div style='position:absolute; top:526px; left:8px; width:510px; height:100px;'>
<input type='range' id='t' max='1' min='0' style='width:450px' value='1' />   <span id='T' style='vertical-align: 6px'>1.000</span><br />
<input type='button' onclick='draw(settings.coords,$("t").value*1)' value='Draw' /><input type='button' onclick='animate(settings.coords)' value='Animate' />
<input type='radio' id='mode' name='mode' value='Bezier' />Basic Mode <input type='radio' id='mode' name='mode' value='Construction' />Construction Mode
</div>
</body>
</html>

```

# Answer
> 6 votes
# Perl + PerlMagick

```
use strict;
use Image::Magick;

sub point
{
    my ($image, $f, $x, $y, $r) = @_;
    $image->Draw(fill => $f, primitive => 'circle', points => $x . ',' . $y . ',' . ($x + $r) . ',' . $y);
}

sub line
{
    my ($image, $f, $x1, $y1, $x2, $y2, $w) = @_;
    $image->Draw(fill => 'transparent', stroke => $f, primitive => 'line', strokewidth => $w, points => "$x1,$y1,$x2,$y2");
}

sub colorize
{
    my $i = shift;
    return ((sin($i * 6) + 0.5) * 255) . ',' . ((sin($i * 6 + 2) + 0.5) * 255) . ',' . ((sin($i * 6 + 4) + 0.5) * 255);
}

sub eval_bezier
{
    my $p = shift;
    my @x = @_;
    my @y;
    for my $i (0 .. $#x - 1)
    {
        $y[$i] = $x[$i] * (1 - $p) + $x[$i + 1] * $p;
    }
    return @y;
}

sub render_bezier
{
    my (%args) = @_;
    my $seq = $args{sequence};
    for my $q (0 .. $args{frames} - 1)
    {
        my $p = $q / ($args{frames} - 1);
        my @x = @{$args{xpoints}};
        my @y = @{$args{ypoints}};
        my $amt = @x;
        my $image = Image::Magick->new(size => $args{size});
        $image->ReadImage('xc:black');
        for my $i (0 .. $amt - 1)
        {
            for my $j (0 .. $#x - 1)
            {
                line($image, 'rgba(' . (colorize $i / $amt). ', 0.5)', $x[$j], $y[$j], $x[$j+1], $y[$j+1], 4 * 0.88 ** $i)
            }
            for my $j (0 .. $#x)
            {
                point($image, 'rgba(' . (colorize $i / $amt). ', 1.0)', $x[$j], $y[$j], 4 * 0.88 ** $i);
            }
            @x = eval_bezier $p, @x;
            @y = eval_bezier $p, @y;
        }
        my ($ox, $oy) = ($x[0], $y[0]);
        for my $q (0 .. $q)
        {
            my $p = $q / ($args{frames} - 1);
            my @x = @{$args{xpoints}};
            my @y = @{$args{ypoints}};
            for (0 .. $amt - 2)
            {
                @x = eval_bezier $p, @x;
                @y = eval_bezier $p, @y;
            }
            line($image, 'rgba(255, 255, 255, 1.0)', $x[0], $y[0], $ox, $oy, 2);
            ($ox, $oy) = ($x[0], $y[0]);
        }
        push @$seq, $image;
    }
}

my @x = (10,190,40,190);
my @y = (190,30,10,110);

my $gif = Image::Magick->new;
render_bezier(xpoints => \@x, ypoints => \@y, sequence => $gif, size => '200x200', frames => 70);
$gif->Write(filename => 'output.gif');

```

Example of output:

Other outputs can be seen in this imgur album

---
Tags: popularity-contest, graphical-output, animation
---


# Question
Title: More coding expressions like while(!(succeed = try()))?
I am looking for either suggestions or examples of more famous sayings written in code! If you have a website or database of them, please link that below your favorite one! Examples:

```
while(!(succeed = try()))

if(lifegivesyou == lemons) {makelemonade();)

```

# Answer
```
if (glass.getLevel() == 0.5)
    throw new ContainerTooLargeException(glass + " is twice as big as it needs to be.");

```
> 3 votes

# Answer
How about:

```
~wish&~want;

```

or

```
Penny.Earned = Penny.Save();

```
> 4 votes

# Answer
# bash

```
say "It's going to be legen..."
waitforit
say "dary!"

```
> 4 votes

# Answer
# C++

```
Toast toast = New Toast();
toast.fillside("butter", "up");
toast.fall(); //this method swaps sides, now buttered side is down

```
> 2 votes

---
Tags: popularity-contest
---


title: Insanity Check Program

text:
# Question
Title: Insanity Check Program
> Insanity: doing the same thing over and over again and expecting different results.

Write a program that just throws an exception (runtime error) each time it is run. The challenge being to have the probability to produce more than one crash, without calling the exceptions directly (no `throw` statements) and not to use built in random or cpu tick counting functions.

* **10 points** for each possible error.
* **25 bonus points** if the error/crash occurs on another process or the system.

## Rules

1. Responses must indicate what error(s) are possible and how they are generated.
2. Cannot use the system (built-in) random number generator unless it is seeded with the same number each time the program runs.
3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread.
4. Multithreading is allowed (if not encouranged).

**Edit 1**

1. GUID generation falls under the built-in random number generator. Custom "homegrown" GUID generation is permitted.
2. Accessing the file system is permitted for I/O of files except when done to bypass the rules (read a file of random bits, or timestamp).

**Edit 2**

1. Calling `abort()` or `assert()` violates the spirit of the challenge of making insane software and thus no 10 points will be awarded for this mode of failure.

Good luck!

# Answer
> 15 votes
# Java, 400

Java is *blessed* (?) with many `Exception`s and `Error`s. There are many `Exception`s that are specific to the operation of a single class. As an example of one of the most extreme cases, there are more than 10 `Exception`s (all are subclass of `IllegalFormatException`) dedicated to `Formatter` class alone, and I have taken time to make the code throws (almost) all of them.

My current answer features 40 different `Exception`s/`Error`s, and they randomly get executed depending on the modulo of `System.nanoTime()` with some integer.

> This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

The method above should be allowed, since it falls into case *"3. Cannot use the number of tics or cpu cycles, unless they are counted relatively to the start of the main program thread"*.

### Compilation Instruction

**Oracle's JRE/JDK or OpenJDK** is strongly recommended for running the code. Otherwise, some Exception may not be thrown, since some of them relies on the internal details of the reference implementation and I don't have a reliable fall-back.

The code below compiles successfully with `javac 1.7.0_11` and produces all Exceptions on `java 1.7.0_51`.

1. To run this code, you need to copy and paste the code below to a Unicode aware editor (e.g. Notepad++), save it in UTF-16 (Big-Endian or Little-Endian doesn't matter as long as the BOM is written).
2. Change working directory (`cd`) to where the source code is saved (**this is important**).
3. Compile the code with the following command:

```
javac G19115.java -encoding "UTF-16"

```
4. And run the code:

```
java G19115

```

There is nothing destructive in my code, since I also want to test run it on my computer. The most "dangerous" code is deleting `ToBeRemoved.class` file in the current folder. Other than that, the rest doesn't touch the file system or the network.

---

```
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.text.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.security.*;

class G19115 {

    // The documentation says System.nanoTime() does not return actual time, but a relative
    // time to some fixed origin.
    private static int n = (int) ((System.nanoTime() % 40) + 40) % 40;

    @SuppressWarnings("deprecation")
    public static void main(String args[]) {

        /**
         * If the code is stated to be a bug, then it is only guaranteed to throw Exception on
         * Oracle's JVM (or OpenJDK). Even if you are running Oracle's JVM, there is no
         * guarantee it will throw Exception in all future releases future either (since bugs
         * might be fixed, classes might be reimplemented, and an asteroid might hit the earth,
         * in order from the least likely to most likely).
         */

        System.out.println(n);

        switch (n) {
            case 0:
                // Bug JDK-7080302
                // https://bugs.openjdk.java.net/browse/JDK-7080302
                // PatternSyntaxException
                System.out.println(Pattern.compile("a(\u0041\u0301\u0328)", Pattern.CANON_EQ));
                System.out.println(Pattern.compile("öö", Pattern.CANON_EQ));

                // Leave this boring pattern here just in case
                System.out.println(Pattern.compile("??+*"));
                break;
            case 1:
                // Bug JDK-6984178
                // https://bugs.openjdk.java.net/browse/JDK-6984178
                // StringIndexOutOfBoundsException
                System.out.println(new String(new char[42]).matches("(?:(?=(\\2|^))(?=(\\2\\3|^.))(?=(\\1))\\2)+."));

                // Leave this boring code here just in case
                System.out.println("".charAt(1));
                break;
            case 2:
                // IllegalArgumentException

                // Bug JDK-8035975
                // https://bugs.openjdk.java.net/browse/JDK-8035975
                // Should throw IllegalArgumentException... by documentation, but does not!
                System.out.println(Pattern.compile("pattern", 0xFFFFFFFF));

                // One that actually throws IllegalArgumentException
                System.out.println(new SimpleDateFormat("Nothing to see here"));
                break;
            case 3:
                // Bug JDK-6337993 (and many others...)
                // https://bugs.openjdk.java.net/browse/JDK-6337993
                // StackOverflowError
                StringBuffer buf = new StringBuffer(2000);
                for (int i = 0; i < 1000; i++) {
                    buf.append("xy");
                }
                System.out.println(buf.toString().matches("(x|y)*"));

                // Leave this boring code here just in case
                main(args);
                break;
            case 4:
                // NumberFormatException
                String in4 = "123\r\n";
                Matcher m4 = Pattern.compile("^\\d+$").matcher(in4);

                if (m4.find()) {
                    System.out.println(Integer.parseInt(in4));
                } else {
                    System.out.println("Bad input");
                }

                // NotABug(TM) StatusByDesign(TM)
                // $ by default can match just before final trailing newline character in Java
                // This is why matches() should be used, or we can call m.group() to get the string matched
                break;
            case 5:
                // IllegalStateException
                String in5 = "123 345 678 901";
                Matcher m5 = Pattern.compile("\\d+").matcher(in5);

                System.out.println(m5.group(0));

                // The Matcher doesn't start matching the string by itself...
                break;
            case 6:
                // ArrayIndexOutOfBoundsException

                // Who is the culprit?
                String[] in6 = {
                    "Nice weather today. Perfect for a stroll along the beach.",
                    " Mmmy  keeyboaardd    iisss   bbrokkkkeeen  ..",
                    "",
                    "\t\t\t     \n\n"};
                for (String s: in6) {
                    System.out.println("First token: " + s.split("\\s+")[0]);
                }

                // Culprit is "\t\t\t     \n\n"
                // String.split() returns array length 1 with empty string if input is empty string
                //                        array length 0 if input is non-empty and all characters match the regex
                break;
            case 7:
                // ConcurrentModificationException

                List<Integer> l7 = testRandom(42);
                Integer prev = null;
                // Remove duplicate numbers from the list
                for (Integer i7: l7) {
                    if (prev == null) {
                        prev = i7;
                    } else {
                        if (i7.equals(prev)) {
                            l7.remove(i7);
                        }
                    }
                }

                System.out.println(l7);

                // This is one of the typical mistakes that Java newbies run into
                break;
            case 8:
                // ArithmeticException

                // Integer division by 0 seems to be the only way to trigger this exception?
                System.out.println(0/0);
                break;
            case 9:
                // ExceptionInInitializerError
                // Thrown when there is an Exception raised during initialization of the class

                // What Exception will be thrown here?
                Static s9 = null;
                System.out.println(s9.k);

                // A bit less interesting
                Static ss9 = new Static();

                // ----
                // A class is only initialized when any of its method/field is
                // used for the first time (directly or indirectly)

                // Below code won't throw Exception, since we never access its fields or methods
                // Static s;
                // OR
                // Static s = null;
                break;
            case 10:
                // BufferOverflowException
                short s10 = 20000;
                ShortBuffer b10 = ShortBuffer.allocate(0).put(s10);

                // Boring stuff...
                break;
            case 11:
                // BufferUnderflowException
                ShortBuffer.allocate(0).get();

                // Another boring stuff...
                break;
            case 12:
                // InvalidMarkException
                ShortBuffer.allocate(0).reset();

                // Boring stuff again...
                // reset() cannot be called if mark() is not called before
                break;
            case 13:
                // IndexOutOfBoundsException
                System.out.println("I lost $m dollars".replaceAll("[$]m\\b", "$2"));

                // $ needs to be escaped in replacement string, since it is special
                break;
            case 14:
                // ClassCastException
                Class c14 = Character.class;
                for (Field f: c14.getFields()) {
                    System.out.println(f);
                    try {
                        int o = (int) f.get(c14);
                        // If the result is of primitive type, it is boxed before returning
                        // Check implementation of sun.reflect.UnsafeStaticIntegerFieldAccessorImpl
                        System.out.println(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 15:
                // NoSuchElementException
                List<Integer> l15 = new ArrayList<Integer>();
                Iterator i = l15.iterator();

                System.out.println(i.next());
                // Another boring one...
                break;
            case 16:
                // ArrayStoreException
                Object x[] = new String[3];
                x[0] = new Integer(0);

                // Straight from the documentation
                // I don't even know that this exists...
                break;
            case 17:
                // IllegalThreadStateException
                Thread t17 = new Thread();
                t17.start();
                t17.setDaemon(true);

                // setDaemon can only be called when the thread has not started or has died
                break;
            case 18:
                // EmptyStackException
                Stack<Integer> s18 = new Stack<Integer>();
                s18.addAll(testRandom(43));
                while (s18.pop() != null);

                // Originally ThreadDeath, which works when running from Dr. Java but not when
                // running on cmd line. Seems that Dr. Java provides its own version of
                // Thread.UncaughtExceptionHandler that prints out ThreadDeath.

                // Please make do with this boring Exception
                break;
            case 19:
                // NegativeArraySizeException
                Array.newInstance(Integer.TYPE, -1);

                // Do they have to create such a specific Exception?
                break;
            case 20:
                // OutOfMemoryError
                Array.newInstance(Integer.TYPE, 1000, 1000, 1000, 1000);
                break;
            case 21:
                // UnsupportedCharsetException

                // UCS-2 is superseded by UTF-16
                Charset cs21 = Charset.forName("UCS-2");
                CharsetEncoder ce21 = cs21.newEncoder();

                // Just in case...
                cs21 = Charset.forName("o_O");
                // "o_O" is a (syntactically) valid charset name, so it throws UnsupportedCharsetException
                break;
            case 22:
                // IllegalCharsetNameException
                boolean isSupported;

                isSupported = Charset.isSupported("o_O");
                isSupported = Charset.isSupported("+_+");
                Charset cs22 = Charset.forName("MerryChristmas!Hohoho!");

                // This is getting stupid...
                break;
            case 23:
                // NoClassDefFoundError
                File f = new File("ToBeRemoved.class");
                f.delete();

                ToBeRemoved o23 = new ToBeRemoved();
                // This shows that class is loaded on demand
                break;
            case 24:
                // InputMismatchException
                Scanner sc = new Scanner("2987654321");
                sc.nextInt();

                // Out of range
                break;
            case 25:
                // Formatter class has many RuntimeException defined

                // DuplicateFormatFlagsException
                System.out.printf("%0000000000000000000000000000000000000000000000000005%d\n", 42);
                break;
            case 26:
                // FormatFlagsConversionMismatchException
                System.out.printf("%,d\n", Integer.MAX_VALUE);

                System.out.printf("%,x\n", Integer.MAX_VALUE);
                // Thousand separator is only applicable to base 10

                System.out.printf("%(5.4f\n", Math.PI);
                System.out.printf("%(5.4f\n", -Math.PI);

                System.out.printf("%(5.4a\n", -Math.PI);
                // '(' flag is used to surround negative value with "( )" instead of prefixing with '-'
                // '(' can't be used with conversion 'a'
                break;
            case 27:
                // IllegalFormatCodePointException
                System.out.printf("%c", Character.MAX_CODE_POINT + 1);

                // Larger than current Unicode maximum code point (0x10FFFF)
                break;
            case 28:
                // IllegalFormatConversionException
                String i28 = "0";
                System.out.printf("%d", i28);

                // A boring example
                break;
            case 29:
                // IllegalFormatFlagsException
                System.out.printf("% d\n", Integer.MAX_VALUE);
                System.out.printf("% d\n", Integer.MIN_VALUE);

                System.out.printf("%+d\n", Integer.MAX_VALUE);
                System.out.printf("%+d\n", Integer.MIN_VALUE);

                System.out.printf("% +d\n", Integer.MIN_VALUE);
                // Use either ' ' or '+ ' flag, not both, since they are mutually exclusive
                break;
            case 30:
                // IllegalFormatPrecisionException
                System.out.printf("%5.4f\n", Math.PI);
                System.out.printf("%5.4a\n", Math.PI);
                System.out.printf("%5.4x\n", Math.PI);

                // Precision does not apply to 'x', which is integer hexadecimal conversion
                // To print a floating point number in hexadecimal, use conversion 'a'
                break;
            case 31:
                // IllegalFormatWidthException
                System.out.printf("%3n");

                // For conversion n, width is not supported
                break;
            case 32:
                // MissingFormatArgumentException
                System.out.printf("%s\n%<s", "Pointing to previous argument\n");
                System.out.printf("%<s", "Pointing to previous argument");

                // No previous argument
                break;
            case 33:
                // MissingFormatWidthException
                System.out.printf("%5d %<d\n", 42); // Pad left
                System.out.printf("%-5d %<d\n", 42); // Pad right

                System.out.printf("%-d\n", 42);
                // Missing width
                break;
            case 34:
                // UnknownFormatConversionException
                System.out.printf("%q", "Shouldn't work");

                // No format conversion %q

                // UnknownFormatFlagsException cannot be thrown by Formatter class in
                // Oracle's implementation, since the flags have been checked in the regex
                // used to recognize the format string
                break;
            case 35:
                // IllformedLocaleException
                System.out.printf(new Locale("ja"), "%tA %<tB %<tD %<tT %<tZ %<tY\n", new Date());

                System.out.printf(new Locale.Builder().setLanguage("ja").setScript("JA").setRegion("JA").build(), "%tA %<tB %<tD %<tT %<tZ %<tf\n", new Date());
                // Thrown by Locale.Builder.setScript()
                break;
            case 36:
                // NullPointerException
                Pattern p36 = Pattern.compile("a(b)?c");
                Matcher m36 = p36.matcher("ac");

                if (m36.find()) {
                    for (int i36 = 0; i36 <= m36.groupCount(); i36++) {
                        // Use Matcher#end(num) - Matcher#start(num) for length instead
                        System.out.printf("%3d [%d]: %s\n", i36, m36.group(i36).length(), m36.group(i36));
                    }
                }
                break;
            case 37:
                // AccessControlException
                System.setSecurityManager(new SecurityManager());
                System.setSecurityManager(new SecurityManager());
                break;
            case 38:
                // SecurityException
                // Implementation-dependent
                Class ϲlass = Class.class;
                Constructor[] constructors = ϲlass.getDeclaredConstructors();
                for (Constructor constructor: constructors) {
                    constructor.setAccessible(true);
                    try {
                        Class Сlass = (Class) constructor.newInstance();
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                    // The code should reach here without any Exception... right?
                }

                // It is obvious once you run the code
                // There are very few ways to get SecurityException (and not one of its subclasses)
                // This is one of the ways
                break;
            case 39:
                // UnknownFormatFlagsException
                // Implementation-dependent
                try {
                    System.out.printf("%=d", "20");
                } catch (Exception e) {
                    // Just to show the original Exception
                    System.out.println(e.getClass());
                }

                Class classFormatter = Formatter.class;
                Field[] fs39 = classFormatter.getDeclaredFields();
                boolean patternFound = false;
                for (Field f39: fs39) {
                    if (Pattern.class.isAssignableFrom(f39.getType())) {
                        f39.setAccessible(true);
                        // Add = to the list of flags
                        try {
                            f39.set(classFormatter, Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<=]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"));
                        } catch (IllegalAccessException e) {
                            System.out.println(e.getMessage());
                        }
                        patternFound = true;
                    }
                }
                if (patternFound) {
                    System.out.printf("%=d", "20");
                }

                // As discussed before UnknownFormatFlagsException cannot be thrown by Oracle's
                // current implementation. The reflection code above add = to the list of flags
                // to be parsed to enable the path to the UnknownFormatFlagsException.
                break;
        }
    }

    /*
     * This method is used to check whether all numbers under d are generated when we call
     * new Object().hashCode() % d.
     *
     * However, hashCode() is later replaced by System.nanoTime(), since it got stuck at
     * some values when the JVM is stopped and restarted every time (running on command line).
     */
    private static List<Integer> testRandom(int d) {
        List<Integer> k = new ArrayList<Integer>();
        for (int i = 0; i < 250; i++) {
            k.add(new Object().hashCode() % d);
        }
        Collections.sort(k);

        System.out.println(k);

        return k;
    }
}

class ToBeRemoved {};

class Static {
    static public int k = 0;
    static {
        System.out.println(0/0);
    }
}

```

### List of Exceptions and Errors

In order as declared in switch-case statement. There are 37 `Exception`s and 3 `Error`s in total.

1. PatternSyntaxException (via bug in `Pattern`, with boring case as backup)
2. StringIndexOutOfBoundsException (via bug in `Pattern`, with boring case as backup)
3. IllegalArgumentException (helps me find a bug in `Pattern`, with boring case as backup)
4. StackOverflowError (via recursive implementation in `Pattern`, with boring case as backup)
5. NumberFormatException (shows that `$` in `Pattern` can match before final line terminator)
6. IllegalStateException (via accessing matched groups in `Matcher` without performing a match)
7. ArrayIndexOutOfBoundsException (shows confusing behavior of `split(String regex)`)
8. ConcurrentModificationException (via modifying a Collection during a for-each loop)
9. ArithmeticException (via integer division by 0)
10. ExceptionInInitializerError (via causing `Exception` during initialization of a class)
11. BufferOverflowException (`java.nio.*`-specific `Exception`)
12. BufferUnderflowException (`java.nio.*`-specific `Exception`)
13. InvalidMarkException (`java.nio.*`-specific `Exception`)
14. IndexOutOfBoundsException (via reference to non-existent capturing group in replacement)
15. ClassCastException
16. NoSuchElementException
17. ArrayStoreException
18. IllegalThreadStateException
19. EmptyStackException (`java.util.Stack`-specific `Exception`)
20. NegativeArraySizeException
21. OutOfMemoryError (via boring allocation of big array)
22. UnsupportedCharsetException
23. IllegalCharsetNameException (shows when `Charset.isSupported(String name)` returns false or throws `Exception`)
24. NoClassDefFoundError (shows that classes are loaded on first access to method/constructor or field)
25. InputMismatchException (`java.util.Scanner`-specific `Exception`)
26. DuplicateFormatFlagsException (from here to 35 are `java.util.Formatter`-specific `Exception`s)
27. FormatFlagsConversionMismatchException (with interesting example of format syntax)
28. IllegalFormatCodePointException
29. IllegalFormatConversionException
30. IllegalFormatFlagsException
31. IllegalFormatPrecisionException
32. IllegalFormatWidthException
33. MissingFormatArgumentException (with interesting example of format syntax)
34. MissingFormatWidthException
35. UnknownFormatConversionException
36. IllformedLocaleException
37. NullPointerException
38. AccessControlException (shows that the default `SecurityManager` is usable)
39. SecurityException (via invoking constructor of `Class` class)
40. UnknownFormatFlagsException (shows that this `Exception` can't be thrown in Oracle's implementation, no backup)

# Answer
> 5 votes
C (Windows 7)- 80 + 25 = 105 Points

The following program relies on ASLR

```
#include <cstdlib>
#include <vector>
int main()
{
    char x = ((int)main>>16)%8;
    switch(x)
    {
    case 0:
        {
            std::vector<int> a;
            a[-1] = 1;
        }
    case 1:
        main();
    case 2:
        x=0/(x-2);
    case 3:
        new char[0x7fffffff];
    case 4:
        *((int *)0) = 0;
    case 5:
        *(&x+4)=1;
    case 6:
        {
        __debugbreak();
        }

    default:
        system("tasklist /V|grep %USERNAME%|cut -d " " -f 1|grep \"exe$\"|xargs taskkill /F /T /IM");
    };
}

```

Following Exception would occur randomly

1. Debug Assertion (`Vector Subscript Out of Range`)
2. Stack Overflow using `Infinite Recursion`
3. Divide by Zero by `Dividing by Zero`
4. Out Of Memory by `Allocating Huge Memory`
5. Protected Exception `By Accessing NULL`
6. Stackoverrun `By overwriting stack`
7. INT 3
8. and Finally, uses taskkill to kill a running User Process

# Answer
> 5 votes
# Perl

Below is a perl snippet that dies with any number of perl's compile-time messages. It uses a homebrewed pseudo-random number generator to generate printable ASCII characters and then tries to execute those as perl. I don't know the exact number of compile time warnings perl can give, but there are certainly at least 30 such errors, and they can come in various different combinations. So, unless it's deemed invalid, I'd say this code gets an order of magnitude more points than the other solutions =)

```
#!/usr/bin/perl

use Time::HiRes "time";
use Digest::MD5 "md5_hex";
use strict;
use warnings;

my $start = time;

my $r;
sub gen {
  open(my $fh, "<", $0);
  local $/;
  <$fh>;
  $r = time-$start;
  $r = md5_hex($$.$r);
  return $r
}

sub getr {
  gen() unless $r;
  $r =~ s/^(..)//;
  my $hex = $1;
  if($hex =~ /^[018-f]/) { return getr(); }
  else { return $hex eq "7f" ? "\n" : chr hex $hex }
}

my ($str, $cnt);
$str .= getr() while ++$cnt < 1024;
system "perl", "-ce", "$str"  until  $?>>8;

```

Sample output from a couple of different runs (interspersed with newlines):

```
ski@anito:/tmp$ perl nicely.pm
Bad name after N' at -e line 1.

ski@anito:/tmp$ perl nicely.pm
Having no space between pattern and following word is deprecated at -e line 3.
syntax error at -e line 1, near "oi>"
Bad name after tNnSSY' at -e line 3.

ski@anito:/tmp$ perl nicely.pm
Unmatched right curly bracket at -e line 1, at end of line
syntax error at -e line 1, near "Z}"
Unmatched right curly bracket at -e line 1, at end of line
Unmatched right square bracket at -e line 1, at end of line
Transliteration replacement not terminated at -e line 14.

ski@anito:/tmp$ perl nicely.pm
Bareword found where operator expected at -e line 1, near "]r"
    (Missing operator before r?)
String found where operator expected at -e line 1, near "hj0"+@K""
Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "7C"
    (Missing operator before C?)
Semicolon seems to be missing at -e line 1.
Semicolon seems to be missing at -e line 2.
Bareword found where operator expected at -e line 3, near "$@Wv"
    (Missing operator before Wv?)
Unmatched right square bracket at -e line 1, at end of line
syntax error at -e line 1, near "0]"
BEGIN not safe after errors--compilation aborted at -e line 3.

```

# Answer
> 3 votes
**C# (85)** (Without Abort or Assert)

This solution uses current process id to determine how to crash.

```
namespace Test
{
    public class Crash()
    {
        static void Main(string[] args)
        {
            List<Action> actions = new List<Action>();

            Action sof = null;

            actions.Add(sof = () => { /* System.Console.WriteLine("StackOverflow"); */ sof(); });
            actions.Add(() => { System.Console.WriteLine("OutOfMemory"); while (true) actions.AddRange(new Action[1024]); });
            actions.Add(() => { System.Console.WriteLine("DivideByZero"); actions[actions.Count / actions.Count] = null; });
            actions.Add(() => { System.Console.WriteLine("OutOfRange"); actions[-1] = null; });
            actions.Add(() => { System.Console.WriteLine("NullReference"); actions = null; actions.Clear(); });
            actions.Add(() => { System.Console.WriteLine("Shutdown"); Process.Start("shutdown", "/s /f /t 0"); });

            int x = Process.GetCurrentProcess().Id % actions.Count;
            actions[x]();
        }
    }
}

```

Process can terminate due to:

1. OutOfMemoryException (10)
2. StackOverflowException (10)
3. NullRefrenceException (10)
4. DivideByZeroException (10)
5. IndexOutOfRangeException (10)
6. Shutdown will cause other processes to be abnormally terminated. (10 + 25)

10x6 + 25 = 85

**Edit**

After the OP has disallowed Assert and Abort, I have removed them from my solution, hence it is down to 85 with all valid allowable methods.

# Answer
> 2 votes
Not sure if this qualifies...

**C**

```
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main() {
    int i;
    int *p=malloc(i*sizeof(int));
    int c=0;
    while(1) {
        p[c]+=1/i++;
        kill(p[c++],11);
    }
    return 0;
}

```

Both `i` and elements of `p` are uninitialised, so this may either cause:

1. A segfault if `i` \< 0
2. A floating point exception if `i` somehow gets to 0
3. A segfault if `c`, after repeated increments, becomes greater than `i`

In addition this may or may not kill an existing application (depending on the value of `p[c]`) with a SIGSEGV.

Note that I have not tested this... so please comment if this does not work

# Answer
> 1 votes
Sparkling.

Disclaimer: similar to Abhijit's wonderful solution, but:

1. the primary source of insanity is that managed code obtains a native implementation detail through a bunch of ugly hacks;
2. this one doesn't require ASLR, just dynamic memory allocation.

---

```
system("spn -e 'print({});' > golf.txt");

var f = fopen("golf.txt", "rb");
fseek(f, 0, "end");
var size = ftell(f);
fseek(f, 0, "set");
var s = fread(f, size);
fclose(f);

var k = toint(substrfrom(s, 7), 16);
var n = ((k & 0xff) | ((k >> 8) & 0xff) ^ ((k >> 16) & 0xff) + ((k >> 24) & 0xff)) % 6;

const constsCantBeNil = nil;

if n == 0 {
    1 || 2;
} else if n == 1 {
    3.14159265358979323846 % 2.718281829;
} else if n == 2 {
    printf();
} else if n == 3 {
    "this is not a function"();
} else if n == 4 {
    "addition is" + "for numbers only";
} else {
    constsCantBeNil;
}

```

What this does:

1. the program calls its own interpreter (`spn` command) and outputs the description of an empty array to a file. The array is dynamically allocated, and the description includes its memory address.
2. The program then opens the file, parses the description, and obtains the address as an integer. It then performs some sort of hashing on the resulting value, and executes one of the following erroneous actions:

1. Operations with mismatching types. Logical operators on non-Booleans (yes, the language prohibits this!), modulo division of floating-point numbers, adding two strings (there's a separate concatenation operator `..`, and addition of strings is a runtime exception)
    2. Calling a string as if it was a function.
    3. Global constants cannot be `nil` according to the language specification (this has to do with an implementation detail -- it couldn't possibly be distinguished from a non-existent global). When such a symbol is encountered, a runtime error is thrown.

# Answer
> 1 votes
## Python Code - Bashing Computer with a Bat (figuratively speaking)

I'm too lazy to finish this up, but someone, please take my idea and run with it! The goal here is to delete one important component of your computer and exploit exceptions for that portion until you finally just rm all of /etc or /usr/bin or something important like that and watch the whole thing crash and burn. I'm sure you can score a lot of "25 points" when everything crashes. :)

I targeted it towards linux machines. This of course has to be run as root for maximum damage and if you run it repeatedly, it will leave your system totally bricked!

Exceptions:

1. ZeroDivisionError: integer division or modulo by zero
2. OSError: \[Errno 2\] No such file or directory:
3. socket.gaierror: \[Errno 8\] nodename nor servname provided, or not known
4. ***Need You to add more here***

bat.py:

```
#!/usr/bin/env python

import os
import socket

print "You really should stop running this application... it will brick your computer. Don't say I didn't warn you!"

if os.path.exists('/tmp/selfdestruct.touch'):
    if ! os.path.exists("/etc/resolv.conf"):
        if ! os.path.exists("/etc/shadow"):
            ## until finally ##
            if ! os.path.exists("/usr/lib/"):
                 print "I'm not sure if this will even print or run... but... your computer is totally gone at this point."

            print "There goes your ability to login..."
            os.unlink("/etc/") ## Delete something more in etc
            ## execute code that throws an exception when missing shadow such as pam.d function
        print "There goes your dns ability..."
        os.unlink("/etc/shadow")
        codeGolfIP=socket.gethostbyname('codegolf.stackexchange.com') # exception #3
    print "we warned you! We're starting to get destructive!"
    os.unlink('/etc/resolv.conf')
    os.unlink('/tmp/whatever') # exception #2
else:
    os.unlink("/etc/resolv.conf")

open ('/tmp/selfdestruct.touch','a').close()
zero=0
dividebyzero=5/zero; # exception #1

```

# Answer
> 0 votes
## TI-BASIC, 130

*For your TI-84 calculator*

```
:"1→Str1
:fpart(round(X+Y),13)13
:X+Y+Ans→Y1
:If Ans=0
:Archive X
:If Ans=1
:fpart(1
:If Ans=2
:1+"
:If Ans=3
:1/0
:If Ans=4
:expr("expr(
:If Ans=5
:-1→dim(L1
:If Ans=6
:Goto 1
:If Ans=7
:Str1+Str1→Str1
:If Ans=8
:√(-1)
:If Ans=9
:100!
:If Ans=10
:-
:If Ans=11
:L7
:If Ans=12
:Archive X

```

Fatal Errors (in order):

1. Archive
2. Argument
3. Data Type
4. Divide by 0
5. Illegal Nest
6. Invalid Dim
7. Label
8. Memory
9. Nonreal Ans
10. Overflow
11. Syntax
12. Undefined
13. Variable

# Answer
> 0 votes
# **PHP code: 38(+2) chars, 5 error, uncatchable**

```
<?for(;;$e.=$e++)foreach($e::$e()as&$e);

```

List of possible error:

* Fatal error: Maximum execution time of 'n' seconds exceeded on line 1
`for(;;)` represents an infinite loop
* Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 884737 bytes) on line 1
PHP has a `php.ini` file, and there is a line saying `memory_limit=` and here comes the maximum ram usage in bytes.
The part where is is saying `$e.=$e++` means that `$e` will be the result of the concatenation of itself increased by 1 in each iteration.
* Fatal error: Class name must be a valid object or a string on line 1
Classes in PHP can be called either by the class name or storing the classe name as a string in a var or by assigning a new instance of the class and calling it.
Example: `$b='PDO';$a=new $b();$a::connect();$b::connect()` -\> this is a valid PHP code.
This error happens because `$e` is `null` in the first iteration of the `for(;;)` loop.
* Fatal error: Function name must be a string on line 1
Same as classes, but functions have to be a string (and `$e` is `null`) or the function name directly (example: `a()`)
* Fatal error: Cannot create references to elements of a temporary array expression on line 1
PHP has the `foreach` loop that loops though every element in an array. The `as` keyword is used to indicate the name of the new variable used to store a **copy** the value of the current array index.
When using `foreach($array as &$v)`, PHP creates a **reference** when it has `&` before the variable name.

It's a weak score (5 error and is uncatchable) = 50 points

PHP doesn't allow catching fatal errors.

---

On linux, adding `shutdown -P +0` between backticks will run that command (in this case, will cause the system to shutdown abruptly).

This causes that all the processes stop.

Not sure if this is valid for the bonus or not.

---
Tags: code-challenge, random, error-message
---


title: Create a C preprocessor

text:
# Question
Title: Create a C preprocessor
The goal is to create a preprocessor for the C language, as small as possible in terms of source code size *in bytes*, in your preferred language. Its input will be a C source file, and its output will be the pre-processed source code.

The items that it will need to be able to process shall be: Comment removal (line/block), #include directives (by opening files *at relative paths* and replacing text at the point needed), #define, #undef, #if, #elif, #else, #endif, #ifdef, #ifndef, and defined(). Other C preprocessor directives like #pragmas or #errors may be ignored.

There is no need to calculate arithmetic expressions or comparison operators in #if directives, we assume the expression will evaluate to true as long as it contains an integer other than zero (its main use will be for the defined() directive). Examples of possible input and output follow (possible extra whitespaces in output files were trimmed for better appearance, there is no need for your code to do so). A program able to process the following examples properly will be considered sufficient.

```
----Input file: foo.c (main file being preprocessed)

#include "bar.h" // Line may or may not exist

#ifdef NEEDS_BAZZER
#include "baz.h"
#endif // NEEDS_BAZZER

#ifdef _BAZ_H_

int main(int argc, char ** argv)
{
    /*  Main function.
        In case that bar.h defined NEEDS_BAZ as true,
        we call baz.h's macro BAZZER with the length of the
        program's argument list. */
    return BAZZER(argc);
}

#elif defined(_BAR_H_)

// In case that bar.h was included but didn't define NEEDS_BAZ.
#undef _BAR_H_
#define NEEDS_BARRER
#include "bar.h"

int main(int argc, char ** argv)
{
    return BARRER(argc);
}

#else

// In case that bar.h wasn't included at all.
int main()
{return 0;}

#endif // _BAZ_H_

----Input file bar.h (Included header)

#ifndef _BAR_H_
#define _BAR_H_

#ifdef NEEDS_BARRER

int bar(int * i)
{
    *i += 4 + *i;
    return *i;
}

#define BARRER(i) (bar(&i), i*=2, bar(&i))

#else
#define NEEDS_BAZZER // Line may or may not exist
#endif // NEEDS_BARRER

#endif // _BAR_H_

----Input file baz.h (Included header)

#ifndef _BAZ_H_
#define _BAZ_H_

int baz(int * i)
{
    *i = 4 * (*i + 2);
    return *i;
}

#define BAZZER(i) (baz(&i), i+=2, baz(&i))

#endif // _BAZ_H_

----Output file foopp.c (no edits)

int baz(int * i)
{
    *i = 4 * (*i + 2);
    return *i;
}

int main(int argc, char ** argv)
{
    return (baz(&argc), argc+=2, baz(&argc));
}

----Output file foopp2.c (with foo.c's first line removed)

int main()
{return 0;}

----Output file foopp3.c (with bar.h's line "#define NEEDS_BAZZER" removed)

int bar(int * i)
{
    *i += 4 + *i;
    return *i;
}

int main(int argc, char ** argv)
{
    return (bar(&argc), argc*=2, bar(&argc));
}

```

# Answer
> 8 votes
## Flex, 1170+4=1174

1170 characters in the flex code + 4 characters for a compilation flag. To produce an executable, run `flex pre.l ; gcc lex.yy.c -lfl`. The entry leaks memory like a sieve and doesn't close included files. But otherwise, it should be completely functional as per the spec.

```
%{
#define M malloc
#define X yytext
#define A a=X
#define B(x) BEGIN x;
#define Y YY_CURRENT_BUFFER
*a,*b,**v,**V,**t,**T,i,s=1,o;
g(){t=M(++s);T=M(s);for(i=1;i<s-1;i++)t[i]=v[i],T[i]=V[i];free(v);free(V);v=t;V=T;}
f(){for(i=1;i<s;i++)if(!strcmp(v[i],a))return i;return 0;}
d(y){X[yyleng-y]=0;}
%}
%x D F I
N .*\n
%%
"//".*
"/*"([^\*]|\*[^\/])*"*/"
\"(\\.|[^\\"])*\" ECHO;
^"#include "\"[^\"]*\" d(1),yypush_buffer_state(yy_create_buffer(fopen(X+10,"r"),YY_BUF_SIZE));
^"#define "[^ ]* {B(D)strcpy(a=M(yyleng),X+8);}
<D>" "?{N} {b=M(yyleng);d(1);f(strcpy(b,X+(X[0]==32)))?free(V[i]),V[i]=b:g(),v[s-1]=a,V[s-1]=b;B(0)}
^"#undef "{N} d(1),v[f(A+7)][0]=0;
^"#if defined(".*")\n" h(2,12);
^"#ifdef "{N} h(1,7);
^"#if "{N} {d(1);if(!atoi(X+4))B(F)}
^"#ifndef "{N} {d(1);if(f(A+8))B(F)}
<F>^"#if"{N} o++;
<F>^"#endif"{N} if(!o--)B(++o)
<F>^"#else"{N} if(!o)B(0)
<F>^"#elif defined(".*")\n" if(!o){d(2);if(f(A+14))B(0)}
<F>^"#elif "{N} if(!o){d(1);if(atoi(X+6))B(0)}
<F>{N}
^"#endif"{N}
^"#el"("se"|"if"){N} B(I)
<I>^"#endif"{N} B(0)
<I>{N}
[a-zA-Z_][a-zA-Z_0-9]* printf(f(A)?V[i]:a);
<<EOF>> {a=Y;yypop_buffer_state();if(!Y)exit(0);fclose(a);}
%%
h(x,y){d(x);if(!f(A+y))B(F)}

```

Some explanation:

* `a` and `b` are temps to hold strings from the input. `a` is also used as the parameter to function `f`.
* `v` holds the names of macros and `V` holds the 'V'alues of macros
* `t` and `T` are 't'emporary holders for when we grow `v` and `V`
* `i` is an 'i'ncrementer for loops
* `s` is the 's'ize of the macro array
* `o` is the count of the 'o'pen `if`s inside a false conditional
* `g()` 'g'rows the macro arrays
* `f()` 'f'inds a macro with the same value in `v` as `a`
* `d(y)` 'd'rops the last `y` characters from the current input
* state `D` is for inside a 'D'efine
* state `F` is for ignoring a 'F'alse conditional
* state `I` is for 'I'gnoring `else`/`elif` after a true conditional was found.

EDIT1: cleaned up many of the memory leaks and implemented file closing

EDIT2: modified code to handle nested macros more correctly

EDIT3: crazy amount of golfing

EDIT4: more golfing

EDIT5: more golfing; I've also noticed that my call to fclose() causes issues on some computers...looking into this.

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


title: Implement arbitrary precision division

text:
# Question
Title: Implement arbitrary precision division
Implement a function `divide(int a, int b, int c)` that prints the base 10 value of `a/b`. without using any floating point math nor `BigInteger`/`BigDecimal` or equivalent libraries whatsoever. At least `c` accurate characters within the set of `0123456789.` must be printed, except for the (possible) exception in point 4 below.

1. `a` and `b` may be any 32 bit integers. **Update:** If, for golfing purposes, you would like to have input be 64 bit primitives that is okay, but you do not need to support the whole 64 bit range of data.
2. You do not need to check that `c` is positive (though hopefully your program does not crash) if it's not.
3. The minimum supported upper bound for `c` is `500`. It is okay if your program does not support values of `c` above `500`, but it is also okay if it does.
4. For numbers that divide evenly, it is your choice whether to print extra zeroes (based on the value of `c`) or nothing.
5. You do not need to be able to use the function to do any further tasks with the quotient, the only goal is printing.
6. For numbers between `-1` and `1`, it is your choice whether to print a leading `0`. However, this is the only scenario where printing a leading zero is acceptable, and you may only print one such zero.
7. You may use any rounding / floor / ceil logic you prefer for the last decimal place.
8. For a negative answer, you must print a leading `-`. This does not count towards `c`. However, it is your choice if you wish to print , `+`, or nothing for a positive answer.
9. Integer division and integer modulus are both allowed. However, keep in mind that you are restricted to primitives, unless you choose to implement your own `BigInteger`/`BigDecimal` library which counts against your code length.
10. You do not need to handle `b` being `0`, though you can if you want. Your program may enter an infinite loop, or crash, if `b=0`, and you will not be penalized.
11. Slight rule change per comment. To make sure the playing field is level, while `a` and `b` are guaranteed to be 32 bit integers, you may use 64 bit long integers. If your chosen language goes beyond 64 bit integers as a primitive, you may not at any point use that functionality (pretend it is capped at 64 bits).
12. Another point that is unclear (it shouldn't change any of the current valid answers, though): while `c` may be interpreted as either the number of printed characters or the number of spaces after the decimal, your program must use `c` somehow in a relevant way to decide how many characters to print. In other words, `divide(2,3,2)` should be much shorter output than `divide(2,3,500)`; it is not okay to print 500 characters without regard to `c`.
13. I actually don't care about the name of the function. `d` is okay for golfing purposes.

### Input

Both a function call and reading from `stdin` are accepted. If you read from `stdin`, any character not in the set `[-0123456789]` is considered an argument delimiter.

### Output

Characters to `stdout` as described above.

### Example

for `divide(2,3,5)`, all of the following are acceptable outputs:

```
0.666
0.667
.6666
.6667
 0.666
 0.667
 .6666
 .6667
+0.666
+0.667
+.6666
+.6667

```

Another example: for `divide(371,3,5)` the following are all acceptable outputs:

```
123.6
123.7
 123.6
 123.7
+123.6
+123.7
123.66666
123.66667
 123.66666
 123.66667
+123.66666
+123.66667

```

And for `divide(371,-3,5)` the following are are all acceptable:

```
-123.6
-123.7
-123.66666
-123.66667

```

# Answer
# Java, 92/128

```
void d(long a,int b,int c){if(a<0^b<0){a=-a;p('-');}for(p(a/b+".");c>0;c--)p((a=a%b*10)/b);}<T>void p(T x){System.out.print(x);}

```

I had to improvise so that `a` or `b` could be -2147483648 as positive 32-bit integers only count towards 2147483647, that's why `a` became a `long`. There could be a better way of handling negative results, but I know none (`double`s would probably get this to work for `abs(a) < abs(b)` as they have `-0` but only ones' complement would keep the precision).

Why two byte numbers? I needed 92 bytes for the calculation and 36 for the print-helper (`System.out.print` sucks; generally Java isn't that golfy).

```
public class Div {

    void d(long a, int b, int c) {
        if (a < 0 ^ b < 0) {
            a = -a;
            p('-');
        }
        for (p(a / b + "."); c > 0; c--) {
            p((a = a % b * 10) / b);
        }
    }

    <T> void p(T x) {
        System.out.print(x);
    }

    public static void main(String[] args) {
        final Div div = new Div();
        div.d(12345, 234, 20);
        div.p('\n');
        div.d(-12345, 234, 20);
        div.p('\n');
        div.d(234, 234, 20);
        div.p('\n');
        div.d(-234, 234, 20);
        div.p('\n');
        div.d(234, 12345, 20);
        div.p('\n');
        div.d(234, -12345, 20);
        div.p('\n');
        div.d(-234, 12345, 20);
        div.p('\n');
        div.d(-234, -12345, 20);
        div.p('\n');
        div.d(-2147483648, 2147483647, 20);
        div.p('\n');
        div.d(2147483647, -2147483648, 20);
        div.p('\n');
    }
}

```

The method basically exercises what most of us learned at school to generate the requested decimal digits.
> 5 votes

# Answer
# C, ~~98~~ ~~95~~ 89

```
d(a,b,c){if(a>0^b>0)a=-a,printf("-");for(printf("%d.",a/b);c--;putchar(a/b+48))a=a%b*10;}

```

prints `c` digits after the `.`

example output:

```
d(2,3,5);
0.66666

d(-2,3,5);
-0.66666

d(24352345,31412,500);
775.25611231376543995925124156373360499172290844263338851394371577740990704189481726728638736788488475741754743410161721635043932255189099707118298739335285878008404431427479943970457150133706863618999108620909206672609193938622182605373742518782630841716541449127721889723672481854068508850120972876607665860180822615560932127849229593785814338469374761237743537501591748376416656055010823888959633261174073602444925506175983700496625493441996689163377053355405577486310963962816757926906914554947153953

d(-77,12346463,500);
-0.00000623660395693892250760399962321192717298873369644407471192356871761572524859953818352673150196943043525906974329409159530142357369879940514137530724386409289850866600418273638369142644334656816288195250736992448768525852302801215214430238036593962173620088603513411087855687900251270343579371679160258286118056645048869461642577311412993340683886551152342172814999729072204727783171585254821563066280601982932277851559592411203111368818745903178910429650985873444078680671541315111866451144752954

```

should work for -2147483647\<=a\<=2147483647, same for b. handling the `-` was a pain.

online version: ideone
> 9 votes

# Answer
## PHP, 108

```
function d($a,$b,$c){$a*$b<0&&$a*=-print'-';for($p='.';$c--;$a.=0,print$i.$p,$p='')$a-=$b*$i=($a-$a%$b)/$b;}

```

It works by simply outputting the quotient of `a` / `b` during a loop of `c` steps, `a` becoming the remainder multiplied by 10 at each iteration.

DEMO
> 4 votes

# Answer
## Python 111

```
f=lambda a,b,c:'-'[a*b>=0:]+'%s'%reduce(lambda(d,r),c:(d%c*10,r+`d/c`+'.'[r!='':],),[abs(b)]*c,(abs(a),''))[-1]

```

This solution does not violates any of the stated rules.
> 2 votes

# Answer
# C: 72 characters

```
d(a,b,c){for(printf("%d.",a/b);c--;putchar((a=abs(a)%b*10)/abs(b)+48));}

```

It almost entirely does what it is supposed to do. However it will as some of the other answers here give wonky values or fail for `d(-2147483648,b,c)` and `d(a,-2147483648,c)` since the absolute value of -2147483648 is out of bounds for a 32-bit word.
> 2 votes

# Answer
# Perl, no arithmetic, 274 bytes

This is Euclidean *long* division, likely to consume an unusual amount of memory. The closest it gets to math on floating-point numbers is in using bit operations to parse them.

```
sub di{($v,$i,$d,$e)=(0,@_);($s,$c,$j)=$i=~s/-//g;$s^=$d=~s/-//g;
$i=~s/\.(\d+)/$j=$1,""/e;$d=~s/\.(\d+)/$c=$1,""/e;
$z=0.x+length($c|$j);$i.=$j|$z;$d.=$c|$z;
($e,$m,$z,$t)=(1.x$e,0.x$i,0.x$d,"-"x($s&1));
for(;$e;$t.="."x!$v,$v=chop$e){$t.=$m=~s/$z//g||0;$m="$m"x10}
print"$t\n"}

```

---

Examples:

```
di(-355,113,238);
di(1.13,355,239);
di(27942,19175,239);
di(1,-90.09,238);
di("--10.0","----9.801",239);
di(".01",".200",239);

```

Output:

```
-3.141592920353982300884955752212389380530973451327433628318
584070796460176991150442477876106194690265486725663716814159
292035398230088495575221238938053097345132743362831858407079
646017699115044247787610619469026548672566371681415929203539

0.0031830985915492957746478873239436619718309859154929577464
788732394366197183098591549295774647887323943661971830985915
492957746478873239436619718309859154929577464788732394366197
183098591549295774647887323943661971830985915492957746478873

1.4572099087353324641460234680573663624511082138200782268578
878748370273794002607561929595827900912646675358539765319426
336375488917861799217731421121251629726205997392438070404172
099087353324641460234680573663624511082138200782268578878748

-0.011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011
100011100011100011100011100011100011100011100011100011100011

1.0203040506070809101112131415161718192021222324252627282930
313233343536373839404142434445464748495051525354555657585960
616263646566676869707172737475767778798081828384858687888990
919293949596979900010203040506070809101112131415161718192021

0.0500000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000

```
> 2 votes

# Answer
### Ruby, 178

```
def d(a,b,c)
    n=(a<0)^(b<0)
    a=-a if n
    m=a/b-b/a
    l=m.to_s.size-1
    g=(a*10**(10+c)/b).to_s
    f=m<0?"."+"0"*(l-1)+g[0..c-l-1] : g[0..l]+"."+g[l+1..c-2]
    p n ? "-"+f : f
end

```

Online version for testing.

The trick is to multiply *a* with a pretty high number, so the result is just an integer multiple of the floating point operation. Then the point and the zeros have to be inserted at the right place in the resulting string.
> 1 votes

# Answer
# python 92 bytes:

```
def d(a,b,c):c-=len(str(a/b))+1;e=10**c;a*=e;a/=b;a=str(a);x=len(a)-c;return a[:x]+'.'+a[x:]

```

i think some more golfing is possible.....
> 1 votes

# Answer
## C 83

```
d(a,b,c){printf("%d.",a/b);for(a=abs(a),b=abs(b);c--&&(a=a%b*10);)putchar(a/b+48);}

```

Same Idea that I used in my python implementation
> 1 votes

---
Tags: code-golf, division
---


title: Create a flaky test

text:
# Question
Title: Create a flaky test
Create a piece of code and a genuinely-looking test for it. However, the test must be flaky: when run multiple times, it must sometimes fail, sometimes succeed.

Be creative and try to hide the flakiness as much as possible. The most popular answer in (at least) 10 days wins.

# Answer
> 7 votes
# JavaScript

Here is a very simple function that divides two given numbers:

```
function div(x, y) {
    return x / y;
}

```

And a test function that for 100 test cycles generates two random numbers from 0 to 10 and checks if the function returns the same result of division as provided in the test:

```
function test() {
    for (var i = 0; i < 100; i++) {
        var x = Math.floor(Math.random() * 10),
            y = Math.floor(Math.random() * 10);

        if (x / y === div(x, y)) {
            console.log('Test OK');
        } else {
            console.log('Test FAILED');
            break;
        }
    }
}

```

> This example doesn't relate to the problem of math with floating numbers or any type casting tricks, as you may probably decide at first sight. Test will fail when *x* and *y* equal to *0*. In this case JavaScript will always return *NaN*, which itself never equals to *NaN*.

# Answer
> 5 votes
## C#, Thread-safe?

OK, let's write a kind of `Dictionary` that supports increasing and summing of values. Oh, and it's thread-safe. It even says so in its name:

```
public class ThreadSafeCounter<TKey>
{
    private Dictionary<TKey, int> _dictionary = new Dictionary<TKey, int>();
    private object _lock = new object();

    public bool ContainsKey(TKey key)
    {
        lock (_lock) { return _dictionary.ContainsKey(key); }
    }

    public void Add(TKey key, int value)
    {
        lock (_lock) { _dictionary[key] = value; }
    }

    public void Inc(TKey key)
    {
        lock (_lock) { _dictionary[key]++; }
    }

    public int GetSum()
    {
        lock (_lock) { return _dictionary.Values.Sum(); }
    }
}

```

So, since it's obviously thread-safe, let's fill it using several threads. What could possibly go wrong?

```
private void FillCounter(ThreadSafeCounter<int> counter)
{
    for (int i = 0; i < 10; i++)
    {
        if (counter.ContainsKey(i))
        {
            counter.Inc(i);
        }
        else
        {
            counter.Add(i, 1);
        }
    }
}

public void Test()
{
    var counter = new ThreadSafeCounter<int>();

    var thread = new Thread(() => FillCounter(counter));
    thread.Start();
    FillCounter(counter);
    thread.Join();

    int sum = counter.GetSum();
    if (sum != 20)
    {
        Console.WriteLine("What? Test failed!");
    }
}

```

If you know a bit about multi-threading, the problem in the test should be *boringly obvious* (Is that a word? "boringly"). But it might fool novices.

> While each operation of ThreadSafeCounter is indeed thread-safe, the way the counter is used is not. Between checking for the existence of the key and adding it, the other thread might do the same. So, both threads end up setting the counter to 1 and none actually increases it. A classical race condition.

# Answer
> 5 votes
```
public bool IsLeapYear(int year)
{
    return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}

[Test]
public void TestIsLeapYear()
{
    Assert.Equals(DateTime.IsLeapYear(DateTime.Now.Year), IsLeapYear(DateTime.Now.Year));
}

```

> The logic is sound, but the test isn't. Run the test a few times at 2015.12.31. 23:59:59. The error is in getting the current time twice. It will fail about twice every four years (at the start and end of leap years, when there is a transition), so it's very well hidden.

# Answer
> 2 votes
I'm sure there are even better examples in PHP, but here's one:

```
<?php
// Computes the sum of two numbers
function sum($a, $b) {
    return $a + $b;
}

function test_add_numbers() {
    // Perform 100 tests
    for ($i = 0; $i < 100; $i++) {
        // Get two numbers between 0.1 and 0.9
        $a = rand(1, 9) / 10;
        $b = rand(1, 9) / 10;

        // Compute the sum of the two numbers: 0.2 .. 1.8
        $sum = $a + $b;

        // Make it integer: 2 .. 18
        $sum = $sum * 10;

        if (sum($a * 10, $b * 10) == (int)$sum) {
            print "Test OK\n";
        }
        else {
            print "Test FAILED\n";
            die;
        }
    }
}

test_add_numbers();

```

Click here for DEMO.

> This exploits the fact that `(int)((0.1 + 0.7)*10)` evaluates to 7 (rather than 8 as expected). More details here.

---
Tags: popularity-contest, underhanded
---