Skip to content

Instantly share code, notes, and snippets.

@joriki
Created March 9, 2016 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/95681760f0c261ef3766 to your computer and use it in GitHub Desktop.
Save joriki/95681760f0c261ef3766 to your computer and use it in GitHub Desktop.
Compute the probability that one part of a randomly cut equilateral triangle can be made to cover the other (with flipping allowed); see http://math.stackexchange.com/questions/1689806.
public class Question1689806 {
static class Point {
double x,y;
public Point (double x,double y) {
this.x = x;
this.y = y;
}
}
static class Segment {
Point a,b;
public Segment (Point a,Point b) {
this.a = a;
this.b = b;
}
public Point midPoint () {
return new Point ((a.x + b.x) / 2,(a.y + b.y) / 2);
}
}
static Point c = new Point (0,Math.sqrt (3) / 6);
static class Line {
double theta;
double d;
public Line (double theta,double d) {
this.theta = theta;
this.d = d;
}
public boolean cuts (Segment s) {
return sign (s.a) * sign (s.b) < 0;
}
public double sign (Point p) {
return Math.sin (theta) * (p.x - c.x) + Math.cos (theta) * (p.y - c.y) - d;
}
}
public static void main (String [] args) {
Point [] points = new Point [] {
new Point (0,Math.sqrt (3) / 2),
new Point (-0.5,0),
new Point (+0.5,0)
};
Segment [] sides = new Segment [3];
for (int i = 0;i < 3;i++)
sides [i] = new Segment (points [i],points [(i + 1) % 3]);
Segment [] altitudes = new Segment [3];
for (int i = 0;i < 3;i++)
altitudes [i] = new Segment (points [(i + 2) % 3],sides [i].midPoint ());
int count = 0;
int ntrials = 100000000;
for (int n = 0;n < ntrials;n++) {
Line line;
boolean cuts = false;
do {
line = new Line (Math.random () * 2 * Math.PI,Math.random () / Math.sqrt (3));
for (Segment side : sides)
cuts |= line.cuts (side);
} while (!cuts);
for (Segment altitude : altitudes)
cuts &= line.cuts (altitude);
if (!cuts)
count++;
}
System.out.println (count / (double) ntrials);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment