[ create a new paste ] login | about

Link: http://codepad.org/FDAgzxgM    [ raw code | output | fork ]

C++, pasted on Apr 23:
#include <iostream>
#include <list>
#include <cmath>

struct P {
  double x, y;
  friend std::ostream &operator<<(std::ostream &stream, P p) {
    stream << '(' << p.x << ',' << p.y << ')';
    return stream;
  }
};

class tri {
  P p;
  int sign;
  bool toggled;
public:
  tri(P p) : p(p), sign(0), toggled(false) {}
  bool result() { return toggled; }
  void operator()(P p1, P p2) {
    double s = (p1.x - p.x) * (p2.y - p.y) - (p2.x - p.x) * (p1.y - p.y);
    if (sign == 0) sign = (s > 0.0) ? 1 : -1;
    else {
      if (s * sign < 0.0)
        toggled = true;
    }
  }
};

void mytransform(std::list<P>::const_iterator s, std::list<P>::const_iterator e, tri &S) {
  std::list<P>::const_iterator p, q;
  if ((p = s) == e) return;
  if ((q = ++s) == e) return;
  while (q != e) {
    S(*p, *q);
    p++; q++;
  }
}

int main() {
  static P table[] = { {6.0, 6.0}, {5.0, 6.0}, {4.0, 4.0}, {5.0, 4.0}};
  static P O1 = {5.0, 5.0};
  static P O2 = {100.1, 100.1};
  
  std::list<P> points;
  for (unsigned int i = 0; i < sizeof(table) / sizeof(P); i++)
    points.push_back(table[i]);
  points.push_back(table[0]);

  tri s1(O1);
  mytransform(points.begin(), points.end(), s1);
  std::cout << O1 << ":" << ((s1.result() == true) ? "out" : "in") << std::endl;

  tri s2(O2);
  mytransform(points.begin(), points.end(), s2);
  std::cout << O2 << ":" << ((s2.result() == true) ? "out" : "in") << std::endl;

  return 0;
}
/* end */


Output:
1
2
(5,5):in
(100.1,100.1):out


Create a new paste based on this one


Comments: