Skip to content

Instantly share code, notes, and snippets.

@reuk
Created August 19, 2013 19:38
Show Gist options
  • Save reuk/6273120 to your computer and use it in GitHub Desktop.
Save reuk/6273120 to your computer and use it in GitHub Desktop.
euler 102 solution (well, nearly) using Processing
void line(PVector p, PVector q) {line(p.x, p.y, q.x, q.y);}
class Line {
private PVector i, j;
float a, b, c;
Line(PVector i_, PVector j_) {
i = i_; j = j_;
recalc();
}
void recalc() {
a = i.y - j.y;
b = j.x - i.x;
c = (a * i.x) + (b * i.y);
}
void setI(PVector i_) {
i = i_;
recalc();
}
void setJ(PVector j_) {
j = j_;
recalc();
}
void draw() {line(i, j);}
}
boolean withinBounds(float p, float b1, float b2) {
return min(b1, b2) < p && p < max(b1, b2);
}
boolean pointWithinLine(PVector p, Line l) {
return withinBounds(p.x, l.i.x, l.j.x) && withinBounds(p.y, l.i.y, l.j.y);
}
boolean linesIntersect(Line i, Line j) {
final float DET = (i.a * j.b) - (j.a * i.b);
if (DET != 0) {
PVector p = new PVector((j.b * i.c - i.b * j.c) / DET, (i.a * j.c - j.a * i.c) / DET);
if (pointWithinLine(p, i) && pointWithinLine(p, j)) {
noStroke();
fill(255);
ellipse(p.x, p.y, 2, 2);
return true;
}
}
return false;
}
PVector randomVector(float l) {
final float ANGLE = random(TWO_PI);
return new PVector(sin(ANGLE) * l, cos(ANGLE) * l);
}
boolean pointInPolygon(PVector p, ArrayList listOfLines) {
int tests = 200;
float meanIntersections = 0;
for (int a = 0; a != tests; ++a) {
int intersections = 0;
while (intersections == 0) {
Line testLine = new Line(p, PVector.add(p, randomVector(2000)));
stroke(255, 127);
testLine.draw();
for (int i = 0; i != listOfLines.size(); ++i) {
if (linesIntersect(testLine, (Line)listOfLines.get(i))) {
++intersections;
}
}
}
meanIntersections += intersections;
}
meanIntersections /= tests;
println(meanIntersections);
if (meanIntersections % 2 == 1) return true;
return false;
}
ArrayList[] polygon;
void setup() {
size(1000, 1000);
String[] lines = loadStrings("/Users/reuben/Desktop/triangles.txt");
polygon = new ArrayList[lines.length];
for (int i = 0; i != lines.length; ++i) {
String[] pieces = split(lines[i], ',');
polygon[i] = new ArrayList();
for (int j = 0; j < pieces.length; j += 2) {
PVector a = new PVector(int(pieces[j]),
int(pieces[j + 1]));
PVector b = new PVector(int(pieces[(j + 2) % pieces.length]),
int(pieces[(j + 3) % pieces.length]));
Line l = new Line(a, b);
polygon[i].add(l);
}
}
noFill();
// noLoop();
}
int count = 0;
void draw() {
int frame = frameCount - 1;
background(0);
stroke(255, 127);
translate(width / 2, height / 2);
scale(0.5);
if (pointInPolygon(new PVector(0, 0), polygon[frame])) {
++count;
}
if (frame == 999) {
noLoop();
println(count);
}
saveFrame("###-102.png");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment