Last active
May 29, 2018 04:05
-
-
Save arnaudbrejeon/a86885e8529b5ba13953c363da23f57d to your computer and use it in GitHub Desktop.
Optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <optional> | |
#include <iostream> | |
struct Point { | |
Point(float x, float y): x{x}, y{y} { | |
} | |
float x; | |
float y; | |
}; | |
using Line = std::pair<Point, Point>; | |
Point operator+(const Point& p0, const Point& p1) { | |
return Point{p0.x + p1.x, p0.y + p1.y}; | |
} | |
Point operator-(const Point& p0, const Point& p1) { | |
return Point{p0.x - p1.x, p0.y - p1.y}; | |
} | |
Point operator*(float s, const Point& p) { | |
return Point{s * p.x, s * p.y}; | |
} | |
std::optional<Point> intersection(const Line& a, const Line& b) { | |
const auto d1 = a.first - a.second; | |
const auto d2 = b.first - b.second; | |
const auto cross = d1.x * d2.y - d1.y * d2.x; | |
if (std::abs(cross) < 1e-6f) { // No intersection | |
return {}; | |
} | |
const auto x = b.first - a.first; | |
const auto t1 = (x.x * d2.y - x.y * d2.x) / cross; | |
return a.first + t1 * d1; | |
} | |
int main() { | |
const auto i0 = intersection(Line(Point(-1, 0), Point(1, 0)), Line(Point(0, -1), Point(0, 1))); | |
std::cout << std::boolalpha << i0.has_value(); | |
if(i0) { | |
std::cout << " : " << i0->x << ", " << i0->y; | |
} | |
std::cout << '\n'; | |
const auto i1 = intersection(Line(Point(-1, 0), Point(1, 0)), Line(Point(-1, 5), Point(1, 5))); | |
std::cout << std::boolalpha << i1.has_value(); | |
if(i1) { | |
std::cout << " : " << i1->x << ", " << i1->y; | |
} | |
std::cout << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment