Skip to content

Instantly share code, notes, and snippets.

@oshea00
Last active March 22, 2020 19:29
Show Gist options
  • Save oshea00/c7d74ad2510f181fbdc58adc46246a8e to your computer and use it in GitHub Desktop.
Save oshea00/c7d74ad2510f181fbdc58adc46246a8e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace KataTriangles
{
class Program
{
static void Main(string[] args)
{
var triangles = new List<List<(double x, double y)>> {
new List<(double x, double y)> { (0,0),(0,10),(5,10) },
new List<(double x, double y)> { (0,0),(0,10),(6,10) },
new List<(double x, double y)> { (1,9),(2,6),(3,9) },
new List<(double x, double y)> { (1,0),(1,5),(8,0) },
new List<(double x, double y)> { (14,0),(16,5),(18,0) },
new List<(double x, double y)> { (-3,0),(0,0),(0,5) },
new List<(double x, double y)> { (-3,-4),(-1,1),(1,-6) },
};
IsTrue(() => TriangleCompare(triangles[0], triangles[0]) == Intersect.Enclosed).Show();
IsTrue(() => TriangleCompare(triangles[0], triangles[1]) == Intersect.Enclosed).Show();
IsTrue(() => TriangleCompare(triangles[2], triangles[0]) == Intersect.Enclosed).Show();
IsTrue(() => TriangleCompare(triangles[1], triangles[0]) == Intersect.Enclosing).Show();
IsTrue(() => TriangleCompare(triangles[0], triangles[3]) == Intersect.Overlapping).Show();
IsTrue(() => TriangleCompare(triangles[3], triangles[0]) == Intersect.Overlapping).Show();
IsTrue(() => TriangleCompare(triangles[5], triangles[6]) == Intersect.Overlapping).Show();
IsTrue(() => TriangleCompare(triangles[0], triangles[5]) == Intersect.Overlapping).Show();
IsTrue(() => TriangleCompare(triangles[0], triangles[4]) == Intersect.Separated).Show();
}
static Intersect TriangleCompare(List<(double x, double y)> t1, List<(double x, double y)> t2)
{
if (t1.All(t => PointInside(t, t2[0], t2[1], t2[2])))
return Intersect.Enclosed;
if (t2.All(t => PointInside(t, t1[0], t1[1], t1[2])))
return Intersect.Enclosing;
if (t1.Any(t => PointInside(t, t2[0], t2[1], t2[2])) ||
t2.Any(t => PointInside(t, t1[0], t1[1], t1[2])))
return Intersect.Overlapping;
return Intersect.Separated;
}
static double sign((double x, double y) p1,
(double x, double y) p2,
(double x, double y) p3)
{
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}
static bool PointInside((double x, double y) pt,
(double x, double y) v1,
(double x, double y) v2,
(double x, double y) v3)
{
double d1, d2, d3;
bool has_neg, has_pos;
d1 = sign(pt, v1, v2);
d2 = sign(pt, v2, v3);
d3 = sign(pt, v3, v1);
has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
return !(has_neg && has_pos);
}
static bool IsTrue(Func<bool> predicate) {
return predicate();
}
}
enum Intersect
{
Enclosed,
Enclosing,
Overlapping,
Separated
}
static class Ext
{
public static void Show(this object o)
{
Console.WriteLine(o.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment