Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in VB as shown in this Mathematica implementation.
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}}; p2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, 0}, {3, 2}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, -2}, {3, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 0}, {0, 1}}; p2 = Polygon@{{1, 0}, {2, 0}, {1, 1}}; ! RegionDisjoint[p1, p2]
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Write the same code in VB as shown below in Mathematica.
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}}; p2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, 0}, {3, 2}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, -2}, {3, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 0}, {0, 1}}; p2 = Polygon@{{1, 0}, {2, 0}, {1, 1}}; ! RegionDisjoint[p1, p2]
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Translate this program into Go but keep the logic exactly as in Mathematica.
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}}; p2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, 0}, {3, 2}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, -2}, {3, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 0}, {0, 1}}; p2 = Polygon@{{1, 0}, {2, 0}, {1, 1}}; ! RegionDisjoint[p1, p2]
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Write the same code in Go as shown below in Mathematica.
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}}; p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {5, 0}, {2.5, 5}}; p2 = Polygon@{{0, 4}, {2.5, -1}, {5, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, 0}, {3, 2}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 1}, {0, 2}}; p2 = Polygon@{{2, 1}, {3, -2}, {3, 4}}; ! RegionDisjoint[p1, p2] p1 = Polygon@{{0, 0}, {1, 0}, {0, 1}}; p2 = Polygon@{{1, 0}, {2, 0}, {1, 1}}; ! RegionDisjoint[p1, p2]
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Convert this Nim block to C, preserving its control flow and logic.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Rewrite this program in C while keeping its functionality equivalent to the Nim version.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Produce a functionally identical C# code for the snippet given in Nim.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Please provide an equivalent version of this Nim code in C#.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Produce a language-to-language conversion: from Nim to C++, same semantics.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Translate the given Nim code snippet into C++ without altering its behavior.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Produce a functionally identical Java code for the snippet given in Nim.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Translate the given Nim code snippet into Java without altering its behavior.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Generate an equivalent Python version of this Nim code.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Ensure the translated Python code behaves exactly like the original Nim snippet.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Write a version of this Nim function in VB with identical behavior.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Change the programming language of this snippet from Nim to Go without modifying what it does.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Rewrite this program in Go while keeping its functionality equivalent to the Nim version.
import strformat type Point = tuple[x, y: float] type Triangle = array[3, Point] func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})" func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}" func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[2].x * (t[0].y - t[1].y) func checkTriWinding(t: var Triangle; allowReversed: bool) = let det = t.det2D() if det < 0: if allowReversed: swap t[1], t[2] else: raise newException(ValueError, "Triangle has wrong winding direction.") func boundaryCollideChk(t: Triangle; eps: float): bool = t.det2D() < eps func boundaryDoesntCollideChk(t: Triangle; eps: float): bool = t.det2D() <= eps func triTri2D(t1, t2: var Triangle; eps = 0.0; allowReversed = false; onBoundary = true): bool = t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) let chkEdge = if onBoundary: boundaryCollideChk else: boundaryDoesntCollideChk for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t1[i], t1[j], t2[0]], eps) and chkEdge([t1[i], t1[j], t2[1]], eps) and chkEdge([t1[i], t1[j], t2[2]], eps): return false for i in 0..2: let j = (i + 1) mod 3 if chkEdge([t2[i], t2[j], t1[0]], eps) and chkEdge([t2[i], t2[j], t1[1]], eps) and chkEdge([t2[i], t2[j], t1[2]], eps): return false result = true when isMainModule: var t1: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] var t2: Triangle = [(0.0, 0.0), (5.0, 0.0), (0.0, 6.0)] echo t1, " and\n", t2 var overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (5.0, 0.0)] t2 = t1 echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, true, true) echo if overlapping: "overlap (reversed)\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (5.0, 0.0), (0.0, 5.0)] t2 = [(-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1[2] = (2.5, 5.0) t2 = [(0.0, 4.0), (2.5, -1.0), (5.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 1.0), (0.0, 2.0)] t2 = [(2.0, 1.0), (3.0, 0.0), (3.0, 2.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t2 = [(2.0, 1.0), (3.0, -2.0), (3.0, 4.0)] echo t1, " and\n", t2 overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" t1 = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] t2 = [(1.0, 0.0), (2.0, 0.0), (1.0, 1.1)] echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points collide" overlapping = triTri2D(t1, t2, 0, false, true) echo if overlapping: "overlap\n" else: "do not overlap\n" echo t1, " and\n", t2 echo "which have only a single corner in contact, if boundary points do not collide" overlapping = triTri2D(t1, t2, 0, false, false) echo if overlapping: "overlap\n" else: "do not overlap\n"
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Maintain the same structure and functionality when rewriting this code in C.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Write the same algorithm in C as shown in this Pascal implementation.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Rewrite the snippet below in C# so it works the same as the original Pascal code.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Convert the following code from Pascal to C#, ensuring the logic remains intact.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Translate this program into C++ but keep the logic exactly as in Pascal.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Translate this program into C++ but keep the logic exactly as in Pascal.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Transform the following Pascal implementation into Java, maintaining the same output and logic.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Port the provided Pascal code into Java while preserving the original functionality.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Preserve the algorithm and functionality while converting the code from Pascal to Python.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Change the following Pascal code into Python without altering its purpose.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Ensure the translated VB code behaves exactly like the original Pascal snippet.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Convert the following code from Pascal to VB, ensuring the logic remains intact.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Maintain the same structure and functionality when rewriting this code in Go.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Write the same code in Go as shown below in Pascal.
program TrianglesOverlap; } uses Math, SysUtils; type TCoordinate = double; const TOLERANCE = 1.0E-6; type TCoordinate = integer; const TOLERANCE = 0; type TVertex = record x, y : TCoordinate; end; function Vertex( x_in, y_in : TCoordinate) : TVertex; begin result.x := x_in; result.y := y_in; end; const SEP_NO_TEST = -1; SEP_NONE = 0; SEP_WEAK = 1; SEP_STRONG = 2; function EqualVertices( V, W : TVertex) : boolean; begin result := (Abs(V.x - W.x) <= TOLERANCE) and (Abs(V.y - W.y) <= TOLERANCE); end; function Det( P, Q, R : TVertex) : TCoordinate; begin result := Q.x*R.y - R.x*Q.y + R.x*P.y - P.x*R.y + P.x*Q.y - Q.x*P.y; end; function TrySides( L, M, N, P, Q, R : TVertex) : integer; var s, sMin, sMax: TCoordinate; H, K : TVertex; function TestSide( V, W : TVertex) : integer; var detP, detQ, detR, tMin, tMax : TCoordinate; begin result := SEP_NONE; detP := Det( V, W, P); detQ := Det( V, W, Q); detR := Det( V, W, R); tMin := Math.Min( Math.Min( detP, detQ), detR); tMax := Math.Max( Math.Max( detP, detQ), detR); if (tMin - sMax > TOLERANCE) or (sMin - tMax > TOLERANCE) then result := SEP_STRONG else if (tMin - sMax >= -TOLERANCE) or (sMin - tMax >= -TOLERANCE) then result := SEP_WEAK; end; begin sMin := 0; sMax := 0; s := Det( L, M, N); if (s <> 0) then begin if (s < 0) then sMin := s else sMax := s; result := TestSide( M, N); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( N, L)); if (result < SEP_STRONG) then result := Math.Max( result, TestSide( L, M)); end else begin H := L; K := M; if EqualVertices( H, K) then K := N; if EqualVertices( H, K) then result := SEP_NO_TEST else result := TestSide( H, K); end; end; function Algo_5( A, B, C, D, E, F : TVertex) : integer; begin result := TrySides( A, B, C, D, E, F); if (result < SEP_STRONG) then begin result := Math.Max( result, TrySides( D, E, F, A, B, C)); if (result = SEP_NO_TEST) then begin if EqualVertices( A, D) then result := SEP_WEAK else result := SEP_STRONG; end; end; end; procedure TestTrianglePair (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy : TCoordinate); var ovStr : string; begin case Algo_5( Vertex(Ax, Ay), Vertex(Bx, By), Vertex(Cx, Cy), Vertex(Dx, Dy), Vertex(Ex, Ey), Vertex(Fx, Fy)) of SEP_STRONG : ovStr := 'Disjoint'; SEP_NONE : ovStr := 'Overlap'; else ovStr := 'Borderline'; end; WriteLn( SysUtils.Format( '(%g,%g),(%g,%g),(%g,%g) and (%g,%g),(%g,%g),(%g,%g): %s', [Ax, Ay, Bx, By, Cx, Cy, Dx, Dy, Ex, Ey, Fx, Fy, ovStr])); end; begin TestTrianglePair( 0,0,5,0,0,5, 0,0,5,0,0,6); TestTrianglePair( 0,0,0,5,5,0, 0,0,0,5,5,0); TestTrianglePair( 0,0,5,0,0,5, -10,0,-5,0,-1,6); TestTrianglePair( 0,0,5,0,2.5,5, 0,4,2.5,-1,5,4); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,0,3,2); TestTrianglePair( 0,0,1,1,0,2, 2,1,3,-2,3,4); TestTrianglePair( 0,0,1,0,0,1, 1,0,2,0,1,1); end.
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Convert this Perl block to C, preserving its control flow and logic.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Port the provided Perl code into C while preserving the original functionality.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Maintain the same structure and functionality when rewriting this code in C++.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Preserve the algorithm and functionality while converting the code from Perl to C++.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Convert the following code from Perl to Python, ensuring the logic remains intact.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Transform the following Perl implementation into Python, maintaining the same output and logic.
use strict; use warnings; sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - $p2->{y}); } sub checkTriWinding { my $p1 = shift or die "14 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $allowReversed = shift; my $detTri = det2D($p1, $$p2, $$p3); if ($detTri < 0.0) { if ($allowReversed) { my $t = $$p3; $$p3 = $$p2; $$p2 = $t; } else { die "triangle has wrong winding direction"; } } return undef; } sub boundaryCollideChk { my $p1 = shift or die "33 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) < $eps; } sub boundaryDoesntCollideChk { my $p1 = shift or die "42 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n"; my $eps = shift; return det2D($p1, $p2, $p3) <= $eps; } sub triTri2D { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift; my $onBoundary = shift; checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed); checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed); my $chkEdge; if ($onBoundary) { $chkEdge = \&boundaryCollideChk; } else { $chkEdge = \&boundaryDoesntCollideChk; } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps) and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) { return 0; } } foreach my $i (0, 1, 2) { my $j = ($i + 1) % 3; if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps) and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) { return 0; } } return 1; } sub formatTri { my $t = shift or die "Missing triangle to format\n"; my $p1 = $t->[0]; my $p2 = $t->[1]; my $p3 = $t->[2]; return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})"; } sub overlap { my $t1 = shift or die "Missing first triangle to calculate with\n"; my $t2 = shift or die "Missing second triangle to calculate with\n"; my $eps = shift; my $allowReversed = shift or 0; my $onBoundary = shift or 1; unless ($eps) { $eps = 0.0; } if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) { return "overlap\n"; } else { return "do not overlap\n"; } } my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); @t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5}); @t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5}); @t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2}); @t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n"; @t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1}); @t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1}); print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n";
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Preserve the algorithm and functionality while converting the code from Racket to C.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Convert the following code from Racket to C, ensuring the logic remains intact.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Produce a language-to-language conversion: from Racket to C#, same semantics.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Change the programming language of this snippet from Racket to C# without modifying what it does.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Rewrite this program in C++ while keeping its functionality equivalent to the Racket version.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Translate the given Racket code snippet into C++ without altering its behavior.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Can you help me rewrite this code in Java instead of Racket, keeping it the same logically?
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Convert this Racket snippet to Java and keep its semantics consistent.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Convert this Racket snippet to Python and keep its semantics consistent.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Write a version of this Racket function in Python with identical behavior.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Transform the following Racket implementation into VB, maintaining the same output and logic.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Port the following code from Racket to VB with equivalent syntax and logic.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Please provide an equivalent version of this Racket code in Go.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Translate the given Racket code snippet into Go without altering its behavior.
#lang racket (define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3))) (define det-2D (match-lambda [`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))])) (define (assert-triangle-winding triangle allow-reversed?) (cond [(>= (det-2D triangle) 0) triangle] [allow-reversed? (match triangle [(list p1 p2 p3) (list p1 p3 p2)])] [else (error 'assert-triangle-winding "triangle is wound in wrong direction")])) (define (tri-tri-2d? triangle1 triangle2 #:ϵ (ϵ 0) #:allow-reversed? (allow-reversed? #f) #:on-boundary? (on-boundary? #t)) (define check-edge (if on-boundary? (λ (triangle) (< (det-2D triangle) ϵ)) (λ (triangle) (<= (det-2D triangle) ϵ)))) (define (inr t1 t2) (for*/and ((i (in-range 3))) (define t1.i (list-ref t1 i)) (define t1.j (list-ref t1 (modulo (add1 i) 3))) (not (for/and ((k (in-range 3))) (check-edge (list (list-ref t2 k) t1.i t1.j)))))) (let ( (tri1 (assert-triangle-winding triangle1 allow-reversed?)) (tri2 (assert-triangle-winding triangle2 allow-reversed?))) (and (inr tri1 tri2) (inr tri2 tri1)))) (module+ test (require rackunit) (define triangleses (for/list ((a.b (in-list '(((0 0 5 0 0 5) ( 0 0 5 0 0 6)) ((0 0 0 5 5 0) ( 0 0 0 5 5 0)) ((0 0 5 0 0 5) (-10 0 -5 0 -1 6)) ((0 0 5 0 2.5 5) ( 0 4 2.5 -1 5 4)) ((0 0 1 1 0 2) ( 2 1 3 0 3 2)) ((0 0 1 1 0 2) ( 2 1 3 -2 3 4)))))) (map (curry apply to-tri) a.b))) (check-equal? (for/list ((t1.t2 (in-list triangleses))) (define t1 (first t1.t2)) (define t2 (second t1.t2)) (define-values (r reversed?) (with-handlers ([exn:fail? (λ (_) (values (tri-tri-2d? t1 t2 #:allow-reversed? #t) #t))]) (values (tri-tri-2d? t1 t2) #f))) (cons r reversed?)) '((#t . #f) (#t . #t) (#f . #f) (#t . #f) (#f . #f) (#f . #f))) (let ((c1 (to-tri 0 0 1 0 0 1)) (c2 (to-tri 1 0 2 0 1 1))) (check-true (tri-tri-2d? c1 c2 #:on-boundary? #t)) (check-false (tri-tri-2d? c1 c2 #:on-boundary? #f))))
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Write a version of this Ruby function in C with identical behavior.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Write the same code in C as shown below in Ruby.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from Ruby to C#.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Transform the following Ruby implementation into C#, maintaining the same output and logic.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Ensure the translated C++ code behaves exactly like the original Ruby snippet.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Convert this Ruby snippet to C++ and keep its semantics consistent.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Convert this Ruby snippet to Java and keep its semantics consistent.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Rewrite this program in Java while keeping its functionality equivalent to the Ruby version.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Change the programming language of this snippet from Ruby to Python without modifying what it does.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Generate an equivalent Python version of this Ruby code.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Ensure the translated VB code behaves exactly like the original Ruby snippet.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Produce a functionally identical VB code for the snippet given in Ruby.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Produce a functionally identical Go code for the snippet given in Ruby.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Rewrite the snippet below in Go so it works the same as the original Ruby code.
require "matrix" def det2D(p1, p2, p3) return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1]) end def checkTriWinding(p1, p2, p3, allowReversed) detTri = det2D(p1, p2, p3) if detTri < 0.0 then if allowReversed then p2[0], p3[0] = p3[0], p2[0] p2[1], p3[1] = p3[1], p2[1] else raise "Triangle has incorrect winding" end end end def boundaryCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) < eps end def boundaryDoesntCollideChk(p1, p2, p3, eps) return det2D(p1, p2, p3) <= eps end def triTri2D(t1, t2, eps, allowReversed, onBoundary) checkTriWinding(t1[0], t1[1], t1[2], allowReversed) checkTriWinding(t2[0], t2[1], t2[2], allowReversed) if onBoundary then chkEdge = -> (p1, p2, p3, eps) { boundaryCollideChk(p1, p2, p3, eps) } else chkEdge = -> (p1, p2, p3, eps) { boundaryDoesntCollideChk(p1, p2, p3, eps) } end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t1[i], t1[j], t2[0], eps) and chkEdge.(t1[i], t1[j], t2[1], eps) and chkEdge.(t1[i], t1[j], t2[2], eps) then return false end end for i in 0..2 do j = (i + 1) % 3 if chkEdge.(t2[i], t2[j], t1[0], eps) and chkEdge.(t2[i], t2[j], t1[1], eps) and chkEdge.(t2[i], t2[j], t1[2], eps) then return false end end return true end def main t1 = [Vector[0,0], Vector[5,0], Vector[0,5]] t2 = [Vector[0,0], Vector[5,0], Vector[0,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[0,5], Vector[5,0]] t2 = [Vector[0,0], Vector[0,5], Vector[5,0]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, true, true)] t1 = [Vector[ 0,0], Vector[ 5,0], Vector[ 0,5]] t2 = [Vector[-10,0], Vector[-5,0], Vector[-1,6]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[ 5, 0], Vector[2.5,5]] t2 = [Vector[0,4], Vector[2.5,-1], Vector[ 5,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,0], Vector[3,2]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1, 1], Vector[0,2]] t2 = [Vector[2,1], Vector[3,-2], Vector[3,4]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, true)] t1 = [Vector[0,0], Vector[1,0], Vector[0,1]] t2 = [Vector[1,0], Vector[2,0], Vector[1,1]] print "Triangle: ", t1, "\n" print "Triangle: ", t2, "\n" print "overlap: %s\n\n" % [triTri2D(t1, t2, 0.0, false, false)] end main()
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Write the same code in C as shown below in Scala.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Generate an equivalent C version of this Scala code.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
#include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct { double x, y; } Point; double det2D(const Point * const p1, const Point * const p2, const Point * const p3) { return p1->x * (p2->y - p3->y) + p2->x * (p3->y - p1->y) + p3->x * (p1->y - p2->y); } void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) { double detTri = det2D(p1, p2, p3); if (detTri < 0.0) { if (allowReversed) { double t = p3->x; p3->x = p2->x; p2->x = t; t = p3->y; p3->y = p2->y; p2->y = t; } else { errno = 1; } } } bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) < eps; } bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) { return det2D(p1, p2, p3) <= eps; } bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) { bool(*chkEdge)(Point*, Point*, Point*, double); int i; checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed); if (errno != 0) { return false; } checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed); if (errno != 0) { return false; } if (onBoundary) { chkEdge = boundaryCollideChk; } else { chkEdge = boundaryDoesntCollideChk; } for (i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge(&t1[i], &t1[j], &t2[0], eps) && chkEdge(&t1[i], &t1[j], &t2[1], eps) && chkEdge(&t1[i], &t1[j], &t2[2], eps)) { return false; } } for (i = 0; i < 3; i++) { int j = (i + 1) % 3; if (chkEdge(&t2[i], &t2[j], &t1[0], eps) && chkEdge(&t2[i], &t2[j], &t1[1], eps) && chkEdge(&t2[i], &t2[j], &t1[2], eps)) return false; } return true; } int main() { { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {0, 0}, {5, 0}, {0, 6} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {0, 5}, {5, 0} }; Point t2[] = { {0, 0}, {0, 5}, {5, 0} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true)); } { Point t1[] = { {0, 0}, {5, 0}, {0, 5} }; Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} }; Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, 0}, {3, 2} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 1}, {0, 2} }; Point t2[] = { {2, 1}, {3, -2}, {3, 4} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true)); } { Point t1[] = { {0, 0}, {1, 0}, {0, 1} }; Point t2[] = { {1, 0}, {2, 0}, {1, 1} }; printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false)); } return EXIT_SUCCESS; }
Rewrite this program in C# while keeping its functionality equivalent to the Scala version.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Rewrite the snippet below in C# so it works the same as the original Scala code.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Port the following code from Scala to C++ with equivalent syntax and logic.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Maintain the same structure and functionality when rewriting this code in C++.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) chkEdge = BoundaryCollideChk; else chkEdge = BoundaryDoesntCollideChk; for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } for(int i=0; i<3; i++) { int j=(i+1)%3; if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Rewrite this program in Java while keeping its functionality equivalent to the Scala version.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Write a version of this Scala function in Java with identical behavior.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
import java.util.function.BiFunction; public class TriangleOverlap { private static class Pair { double first; double second; Pair(double first, double second) { this.first = first; this.second = second; } @Override public String toString() { return String.format("(%s, %s)", first, second); } } private static class Triangle { Pair p1, p2, p3; Triangle(Pair p1, Pair p2, Pair p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } @Override public String toString() { return String.format("Triangle: %s, %s, %s", p1, p2, p3); } } private static double det2D(Triangle t) { Pair p1 = t.p1; Pair p2 = t.p2; Pair p3 = t.p3; return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second); } private static void checkTriWinding(Triangle t, boolean allowReversed) { double detTri = det2D(t); if (detTri < 0.0) { if (allowReversed) { Pair a = t.p3; t.p3 = t.p2; t.p2 = a; } else throw new RuntimeException("Triangle has wrong winding direction"); } } private static boolean boundaryCollideChk(Triangle t, double eps) { return det2D(t) < eps; } private static boolean boundaryDoesntCollideChk(Triangle t, double eps) { return det2D(t) <= eps; } private static boolean triTri2D(Triangle t1, Triangle t2) { return triTri2D(t1, t2, 0.0, false, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) { return triTri2D(t1, t2, eps, allowedReversed, true); } private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) { checkTriWinding(t1, allowedReversed); checkTriWinding(t2, allowedReversed); BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk; Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3}; Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3}; for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false; } for (int i = 0; i < 3; ++i) { int j = (i + 1) % 3; if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false; } return true; } public static void main(String[] args) { Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0)); System.out.printf("%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0)); t2 = t1; System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2, 0.0, true)) { System.out.println("overlap (reversed)"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0)); t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1.p3 = new Pair(2.5, 5.0); t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0)); t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0)); System.out.printf("\n%s and\n%s\n", t1, t2); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0)); t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1)); System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points collide"); if (triTri2D(t1, t2)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } System.out.printf("\n%s and\n%s\n", t1, t2); System.out.println("which have only a single corner in contact, if boundary points do not collide"); if (triTri2D(t1, t2, 0.0, false, false)) { System.out.println("overlap"); } else { System.out.println("do not overlap"); } } }
Port the provided Scala code into Python while preserving the original functionality.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Change the programming language of this snippet from Scala to Python without modifying what it does.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
from __future__ import print_function import numpy as np def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("triangle has wrong winding direction") return trisq def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True): t1s = CheckTriWinding(t1, allowReversed) t2s = CheckTriWinding(t2, allowReversed) if onBoundary: chkEdge = lambda x: np.linalg.det(x) < eps else: chkEdge = lambda x: np.linalg.det(x) <= eps for i in range(3): edge = np.roll(t1s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t2s[0]))) and chkEdge(np.vstack((edge, t2s[1]))) and chkEdge(np.vstack((edge, t2s[2])))): return False for i in range(3): edge = np.roll(t2s, i, axis=0)[:2,:] if (chkEdge(np.vstack((edge, t1s[0]))) and chkEdge(np.vstack((edge, t1s[1]))) and chkEdge(np.vstack((edge, t1s[2])))): return False return True if __name__=="__main__": t1 = [[0,0],[5,0],[0,5]] t2 = [[0,0],[5,0],[0,6]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[0,5],[5,0]] t2 = [[0,0],[0,6],[5,0]] print (TriTri2D(t1, t2, allowReversed = True), True) t1 = [[0,0],[5,0],[0,5]] t2 = [[-10,0],[-5,0],[-1,6]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[5,0],[2.5,5]] t2 = [[0,4],[2.5,-1],[5,4]] print (TriTri2D(t1, t2), True) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,0],[3,2]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,1],[0,2]] t2 = [[2,1],[3,-2],[3,4]] print (TriTri2D(t1, t2), False) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = True), True) t1 = [[0,0],[1,0],[0,1]] t2 = [[1,0],[2,0],[1,1]] print (TriTri2D(t1, t2, onBoundary = False), False)
Rewrite this program in VB while keeping its functionality equivalent to the Scala version.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Please provide an equivalent version of this Scala code in VB.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
Module Module1 Class Triangle Property P1 As Tuple(Of Double, Double) Property P2 As Tuple(Of Double, Double) Property P3 As Tuple(Of Double, Double) Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double)) Me.P1 = p1 Me.P2 = p2 Me.P3 = p3 End Sub Function Det2D() As Double Return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P1.Item2 - P2.Item2) End Function Sub CheckTriWinding(allowReversed As Boolean) Dim detTri = Det2D() If detTri < 0.0 Then If allowReversed Then Dim a = P3 P3 = P2 P2 = a Else Throw New Exception("Triangle has wrong winding direction") End If End If End Sub Function BoundaryCollideChk(eps As Double) As Boolean Return Det2D() < eps End Function Function BoundaryDoesntCollideChk(eps As Double) As Boolean Return Det2D() <= eps End Function Public Overrides Function ToString() As String Return String.Format("Triangle: {0}, {1}, {2}", P1, P2, P3) End Function End Class Function TriTri2D(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional alloweReversed As Boolean = False, Optional onBoundary As Boolean = True) As Boolean t1.CheckTriWinding(alloweReversed) t2.CheckTriWinding(alloweReversed) Dim chkEdge = If(onBoundary, Function(t As Triangle) t.BoundaryCollideChk(eps), Function(t As Triangle) t.BoundaryDoesntCollideChk(eps)) Dim lp1 As New List(Of Tuple(Of Double, Double)) From {t1.P1, t1.P2, t1.P3} Dim lp2 As New List(Of Tuple(Of Double, Double)) From {t2.P1, t2.P2, t2.P3} For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp1(i), lp1(j), lp2(0))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(1))) AndAlso chkEdge(New Triangle(lp1(i), lp1(j), lp2(2))) Then Return False End If Next For i = 0 To 2 Dim j = (i + 1) Mod 3 If chkEdge(New Triangle(lp2(i), lp2(j), lp1(0))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(1))) AndAlso chkEdge(New Triangle(lp2(i), lp2(j), lp1(2))) Then Return False End If Next Return True End Function Sub Overlap(t1 As Triangle, t2 As Triangle, Optional eps As Double = 0.0, Optional allowReversed As Boolean = False, Optional onBoundary As Boolean = True) If TriTri2D(t1, t2, eps, allowReversed, onBoundary) Then Console.WriteLine("overlap") Else Console.WriteLine("do not overlap") End If End Sub Sub Main() Dim t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) Dim t2 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(0.0, 5.0), Tuple.Create(5.0, 0.0)) t2 = t1 Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2, 0.0, True) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(5.0, 0.0), Tuple.Create(0.0, 5.0)) t2 = New Triangle(Tuple.Create(-10.0, 0.0), Tuple.Create(-5.0, 0.0), Tuple.Create(-1.0, 6.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1.P3 = Tuple.Create(2.5, 5.0) t2 = New Triangle(Tuple.Create(0.0, 4.0), Tuple.Create(2.5, -1.0), Tuple.Create(5.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 1.0), Tuple.Create(0.0, 2.0)) t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, 0.0), Tuple.Create(3.0, 2.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t2 = New Triangle(Tuple.Create(2.0, 1.0), Tuple.Create(3.0, -2.0), Tuple.Create(3.0, 4.0)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Overlap(t1, t2) Console.WriteLine() t1 = New Triangle(Tuple.Create(0.0, 0.0), Tuple.Create(1.0, 0.0), Tuple.Create(0.0, 1.0)) t2 = New Triangle(Tuple.Create(1.0, 0.0), Tuple.Create(2.0, 0.0), Tuple.Create(1.0, 1.1)) Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points collide") Overlap(t1, t2) Console.WriteLine() Console.WriteLine("{0} and", t1) Console.WriteLine("{0}", t2) Console.WriteLine("which have only a single corner in contact, if boundary points do not collide") Overlap(t1, t2, 0.0, False, False) End Sub End Module
Change the following Scala code into Go without altering its purpose.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Change the following Scala code into Go without altering its purpose.
typealias Point = Pair<Double, Double> data class Triangle(var p1: Point, var p2: Point, var p3: Point) { override fun toString() = "Triangle: $p1, $p2, $p3" } fun det2D(t: Triangle): Double { val (p1, p2, p3) = t return p1.first * (p2.second - p3.second) + p2.first * (p3.second - p1.second) + p3.first * (p1.second - p2.second) } fun checkTriWinding(t: Triangle, allowReversed: Boolean) { val detTri = det2D(t) if (detTri < 0.0) { if (allowReversed) { val a = t.p3 t.p3 = t.p2 t.p2 = a } else throw RuntimeException("Triangle has wrong winding direction") } } fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0, allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean { checkTriWinding(t1, allowReversed) checkTriWinding(t2, allowReversed) val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk val lp1 = listOf(t1.p1, t1.p2, t1.p3) val lp2 = listOf(t2.p1, t2.p2, t2.p3) for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false } for (i in 0 until 3) { val j = (i + 1) % 3 if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false } return true } fun main(args: Array<String>) { var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0) println("$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0) t2 = t1 println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap") t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0) t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1.p3 = 2.5 to 5.0 t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0) t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0) println("\n$t1 and\n$t2") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0) t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1) println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points collide") println(if (triTri2D(t1, t2)) "overlap" else "do not overlap") println("\n$t1 and\n$t2") println("which have only a single corner in contact, if boundary points do not collide") println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap") }
package main import "fmt" type point struct { x, y float64 } func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) } type triangle struct { p1, p2, p3 point } func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) } func (t *triangle) det2D() float64 { return t.p1.x * (t.p2.y - t.p3.y) + t.p2.x * (t.p3.y - t.p1.y) + t.p3.x * (t.p1.y - t.p2.y) } func (t *triangle) checkTriWinding(allowReversed bool) { detTri := t.det2D() if detTri < 0.0 { if allowReversed { a := t.p3 t.p3 = t.p2 t.p2 = a } else { panic("Triangle has wrong winding direction.") } } } func boundaryCollideChk(t *triangle, eps float64) bool { return t.det2D() < eps } func boundaryDoesntCollideChk(t *triangle, eps float64) bool { return t.det2D() <= eps } func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool { t1.checkTriWinding(allowReversed) t2.checkTriWinding(allowReversed) var chkEdge func (*triangle, float64) bool if onBoundary { chkEdge = boundaryCollideChk } else { chkEdge = boundaryDoesntCollideChk } lp1 := [3]point{t1.p1, t1.p2, t1.p3} lp2 := [3]point{t2.p1, t2.p2, t2.p3} for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp1[i], lp1[j], lp2[0]} tri2 := &triangle{lp1[i], lp1[j], lp2[1]} tri3 := &triangle{lp1[i], lp1[j], lp2[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } for i := 0; i < 3; i++ { j := (i + 1) % 3 tri1 := &triangle{lp2[i], lp2[j], lp1[0]} tri2 := &triangle{lp2[i], lp2[j], lp1[1]} tri3 := &triangle{lp2[i], lp2[j], lp1[2]} if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) { return false } } return true } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func main() { t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}} fmt.Printf("%s and\n%s\n", t1, t2) overlapping := triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}} t2 = t1 fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, true, true) fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}} t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1.p3 = point{2.5, 5.0} t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}} t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}} fmt.Printf("\n%s and\n%s\n", t1, t2) overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}} t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}} fmt.Printf("\n%s and\n%s\n", t1, t2) println("which have only a single corner in contact, if boundary points collide") overlapping = triTri2D(t1, t2, 0.0, false, true) fmt.Println(iff(overlapping, "overlap", "do not overlap")) fmt.Printf("\n%s and\n%s\n", t1, t2) fmt.Println("which have only a single corner in contact, if boundary points do not collide") overlapping = triTri2D(t1, t2, 0.0, false, false) fmt.Println(iff(overlapping, "overlap", "do not overlap")) }
Write the same algorithm in C# as shown in this Ada implementation.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
using System; class SudokuSolver { private int[] grid; public SudokuSolver(String s) { grid = new int[81]; for (int i = 0; i < s.Length; i++) { grid[i] = int.Parse(s[i].ToString()); } } public void solve() { try { placeNumber(0); Console.WriteLine("Unsolvable!"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(this); } } public void placeNumber(int pos) { if (pos == 81) { throw new Exception("Finished!"); } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } public bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } public override string ToString() { string sb = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sb += (grid[i * 9 + j] + " "); if (j == 2 || j == 5) sb += ("| "); } sb += ('\n'); if (i == 2 || i == 5) sb += ("------+-------+------\n"); } return sb; } public static void Main(String[] args) { new SudokuSolver("850002400" + "720000009" + "004000000" + "000107002" + "305000900" + "040000000" + "000080070" + "017000000" + "000036040").solve(); Console.Read(); } }
Can you help me rewrite this code in C instead of Ada, keeping it the same logically?
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
#include <stdio.h> void show(int *x) { int i, j; for (i = 0; i < 9; i++) { if (!(i % 3)) putchar('\n'); for (j = 0; j < 9; j++) printf(j % 3 ? "%2d" : "%3d", *x++); putchar('\n'); } } int trycell(int *x, int pos) { int row = pos / 9; int col = pos % 9; int i, j, used = 0; if (pos == 81) return 1; if (x[pos]) return trycell(x, pos + 1); for (i = 0; i < 9; i++) used |= 1 << (x[i * 9 + col] - 1); for (j = 0; j < 9; j++) used |= 1 << (x[row * 9 + j] - 1); row = row / 3 * 3; col = col / 3 * 3; for (i = row; i < row + 3; i++) for (j = col; j < col + 3; j++) used |= 1 << (x[i * 9 + j] - 1); for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) if (!(used & 1) && trycell(x, pos + 1)) return 1; x[pos] = 0; return 0; } void solve(const char *s) { int i, x[81]; for (i = 0; i < 81; i++) x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0; if (trycell(x, 0)) show(x); else puts("no solution"); } int main(void) { solve( "5x..7...." "6..195..." ".98....6." "8...6...3" "4..8.3..1" "7...2...6" ".6....28." "...419..5" "....8..79" ); return 0; }
Please provide an equivalent version of this Ada code in C++.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
#include <iostream> using namespace std; class SudokuSolver { private: int grid[81]; public: SudokuSolver(string s) { for (unsigned int i = 0; i < s.length(); i++) { grid[i] = (int) (s[i] - '0'); } } void solve() { try { placeNumber(0); cout << "Unsolvable!" << endl; } catch (char* ex) { cout << ex << endl; cout << this->toString() << endl; } } void placeNumber(int pos) { if (pos == 81) { throw (char*) "Finished!"; } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } string toString() { string sb; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char c[2]; c[0] = grid[i * 9 + j] + '0'; c[1] = '\0'; sb.append(c); sb.append(" "); if (j == 2 || j == 5) sb.append("| "); } sb.append("\n"); if (i == 2 || i == 5) sb.append("------+-------+------\n"); } return sb; } }; int main() { SudokuSolver ss("850002400" "720000009" "004000000" "000107002" "305000900" "040000000" "000080070" "017000000" "000036040"); ss.solve(); return EXIT_SUCCESS; }
Port the provided Ada code into Go while preserving the original functionality.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
package main import "fmt" var puzzle = "" + "394 267 " + " 3 4 " + "5 69 2 " + " 45 9 " + "6 7" + " 7 58 " + " 1 67 8" + " 9 8 " + " 264 735" func main() { printGrid("puzzle:", puzzle) if s := solve(puzzle); s == "" { fmt.Println("no solution") } else { printGrid("solved:", s) } } func printGrid(title, s string) { fmt.Println(title) for r, i := 0, 0; r < 9; r, i = r+1, i+9 { fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8]) if r == 2 || r == 5 { fmt.Println("------+-------+------") } } } func solve(u string) string { d := newDlxObject(324) for r, i := 0, 0; r < 9; r++ { for c := 0; c < 9; c, i = c+1, i+1 { b := r/3*3 + c/3 n := int(u[i] - '1') if n >= 0 && n < 9 { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } else { for n = 0; n < 9; n++ { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } } } } d.search() return d.text() } type x struct { c *y u, d, l, r *x x0 *x } type y struct { x s int n int } type dlx struct { ch []y h *y o []*x } func newDlxObject(nCols int) *dlx { ch := make([]y, nCols+1) h := &ch[0] d := &dlx{ch, h, nil} h.c = h h.l = &ch[nCols].x ch[nCols].r = &h.x nh := ch[1:] for i := range ch[1:] { hi := &nh[i] ix := &hi.x hi.n = i hi.c = hi hi.u = ix hi.d = ix hi.l = &h.x h.r = ix h = hi } return d } func (d *dlx) addRow(nr []int) { if len(nr) == 0 { return } r := make([]x, len(nr)) x0 := &r[0] for x, j := range nr { ch := &d.ch[j+1] ch.s++ np := &r[x] np.c = ch np.u = ch.u np.d = &ch.x np.l = &r[(x+len(r)-1)%len(r)] np.r = &r[(x+1)%len(r)] np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np np.x0 = x0 } } func (d *dlx) text() string { b := make([]byte, len(d.o)) for _, r := range d.o { x0 := r.x0 b[x0.c.n] = byte(x0.r.c.n%9) + '1' } return string(b) } func (d *dlx) search() bool { h := d.h j := h.r.c if j == h { return true } c := j for minS := j.s; ; { j = j.r.c if j == h { break } if j.s < minS { c, minS = j, j.s } } cover(c) k := len(d.o) d.o = append(d.o, nil) for r := c.d; r != &c.x; r = r.d { d.o[k] = r for j := r.r; j != r; j = j.r { cover(j.c) } if d.search() { return true } r = d.o[k] c = r.c for j := r.l; j != r; j = j.l { uncover(j.c) } } d.o = d.o[:len(d.o)-1] uncover(c) return false } func cover(c *y) { c.r.l, c.l.r = c.l, c.r for i := c.d; i != &c.x; i = i.d { for j := i.r; j != i; j = j.r { j.d.u, j.u.d = j.u, j.d j.c.s-- } } } func uncover(c *y) { for i := c.u; i != &c.x; i = i.u { for j := i.l; j != i; j = j.l { j.c.s++ j.d.u, j.u.d = j, j } } c.r.l, c.l.r = &c.x, &c.x }
Transform the following Ada implementation into Java, maintaining the same output and logic.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
public class Sudoku { private int mBoard[][]; private int mBoardSize; private int mBoxSize; private boolean mRowSubset[][]; private boolean mColSubset[][]; private boolean mBoxSubset[][]; public Sudoku(int board[][]) { mBoard = board; mBoardSize = mBoard.length; mBoxSize = (int)Math.sqrt(mBoardSize); initSubsets(); } public void initSubsets() { mRowSubset = new boolean[mBoardSize][mBoardSize]; mColSubset = new boolean[mBoardSize][mBoardSize]; mBoxSubset = new boolean[mBoardSize][mBoardSize]; for(int i = 0; i < mBoard.length; i++) { for(int j = 0; j < mBoard.length; j++) { int value = mBoard[i][j]; if(value != 0) { setSubsetValue(i, j, value, true); } } } } private void setSubsetValue(int i, int j, int value, boolean present) { mRowSubset[i][value - 1] = present; mColSubset[j][value - 1] = present; mBoxSubset[computeBoxNo(i, j)][value - 1] = present; } public boolean solve() { return solve(0, 0); } public boolean solve(int i, int j) { if(i == mBoardSize) { i = 0; if(++j == mBoardSize) { return true; } } if(mBoard[i][j] != 0) { return solve(i + 1, j); } for(int value = 1; value <= mBoardSize; value++) { if(isValid(i, j, value)) { mBoard[i][j] = value; setSubsetValue(i, j, value, true); if(solve(i + 1, j)) { return true; } setSubsetValue(i, j, value, false); } } mBoard[i][j] = 0; return false; } private boolean isValid(int i, int j, int val) { val--; boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]; return !isPresent; } private int computeBoxNo(int i, int j) { int boxRow = i / mBoxSize; int boxCol = j / mBoxSize; return boxRow * mBoxSize + boxCol; } public void print() { for(int i = 0; i < mBoardSize; i++) { if(i % mBoxSize == 0) { System.out.println(" -----------------------"); } for(int j = 0; j < mBoardSize; j++) { if(j % mBoxSize == 0) { System.out.print("| "); } System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-"); System.out.print(' '); } System.out.println("|"); } System.out.println(" -----------------------"); } public static void main(String[] args) { int[][] board = { {8, 5, 0, 0, 0, 2, 4, 0, 0}, {7, 2, 0, 0, 0, 0, 0, 0, 9}, {0, 0, 4, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 7, 0, 0, 2}, {3, 0, 5, 0, 0, 0, 9, 0, 0}, {0, 4, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 8, 0, 0, 7, 0}, {0, 1, 7, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 3, 6, 0, 4, 0} }; Sudoku s = new Sudoku(board); System.out.print("Starting grid:\n"); s.print(); if (s.solve()) { System.out.print("\nSolution:\n"); s.print(); } else { System.out.println("\nUnsolvable!"); } } }
Transform the following Ada implementation into Python, maintaining the same output and logic.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
def initiate(): box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) box.append([33, 34, 35, 42, 43, 44, 51, 52, 53]) box.append([54, 55, 56, 63, 64, 65, 72, 73, 74]) box.append([57, 58, 59, 66, 67, 68, 75, 76, 77]) box.append([60, 61, 62, 69, 70, 71, 78, 79, 80]) for i in range(0, 81, 9): row.append(range(i, i+9)) for i in range(9): column.append(range(i, 80+i, 9)) def valid(n, pos): current_row = pos/9 current_col = pos%9 current_box = (current_row/3)*3 + (current_col/3) for i in row[current_row]: if (grid[i] == n): return False for i in column[current_col]: if (grid[i] == n): return False for i in box[current_box]: if (grid[i] == n): return False return True def solve(): i = 0 proceed = 1 while(i < 81): if given[i]: if proceed: i += 1 else: i -= 1 else: n = grid[i] prev = grid[i] while(n < 9): if (n < 9): n += 1 if valid(n, i): grid[i] = n proceed = 1 break if (grid[i] == prev): grid[i] = 0 proceed = 0 if proceed: i += 1 else: i -=1 def inputs(): nextt = 'T' number = 0 pos = 0 while(not(nextt == 'N' or nextt == 'n')): print "Enter the position:", pos = int(raw_input()) given[pos - 1] = True print "Enter the numerical:", number = int(raw_input()) grid[pos - 1] = number print "Do you want to enter another given?(Y, for yes: N, for no)" nextt = raw_input() grid = [0]*81 given = [False]*81 box = [] row = [] column = [] initiate() inputs() solve() for i in range(9): print grid[i*9:i*9+9] raw_input()
Write the same algorithm in VB as shown in this Ada implementation.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 ); begin solve( sudoku_ar ); end Sudoku;
Dim grid(9, 9) Dim gridSolved(9, 9) Public Sub Solve(i, j) If i > 9 Then For r = 1 To 9 For c = 1 To 9 gridSolved(r, c) = grid(r, c) Next c Next r Exit Sub End If For n = 1 To 9 If isSafe(i, j, n) Then nTmp = grid(i, j) grid(i, j) = n If j = 9 Then Solve i + 1, 1 Else Solve i, j + 1 End If grid(i, j) = nTmp End If Next n End Sub Public Function isSafe(i, j, n) As Boolean Dim iMin As Integer Dim jMin As Integer If grid(i, j) <> 0 Then isSafe = (grid(i, j) = n) Exit Function End If For c = 1 To 9 If grid(i, c) = n Then isSafe = False Exit Function End If Next c For r = 1 To 9 If grid(r, j) = n Then isSafe = False Exit Function End If Next r iMin = 1 + 3 * Int((i - 1) / 3) jMin = 1 + 3 * Int((j - 1) / 3) For r = iMin To iMin + 2 For c = jMin To jMin + 2 If grid(r, c) = n Then isSafe = False Exit Function End If Next c Next r isSafe = True End Function Public Sub Sudoku() Dim s(9) As String s(1) = "001005070" s(2) = "920600000" s(3) = "008000600" s(4) = "090020401" s(5) = "000000000" s(6) = "304080090" s(7) = "007000300" s(8) = "000007069" s(9) = "010800700" For i = 1 To 9 For j = 1 To 9 grid(i, j) = Int(Val(Mid$(s(i), j, 1))) Next j Next i Solve 1, 1 Debug.Print "Solution:" For i = 1 To 9 For j = 1 To 9 Debug.Print Format$(gridSolved(i, j)); " "; Next j Debug.Print Next i End Sub
Convert this AutoHotKey block to C, preserving its control flow and logic.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
#include <stdio.h> void show(int *x) { int i, j; for (i = 0; i < 9; i++) { if (!(i % 3)) putchar('\n'); for (j = 0; j < 9; j++) printf(j % 3 ? "%2d" : "%3d", *x++); putchar('\n'); } } int trycell(int *x, int pos) { int row = pos / 9; int col = pos % 9; int i, j, used = 0; if (pos == 81) return 1; if (x[pos]) return trycell(x, pos + 1); for (i = 0; i < 9; i++) used |= 1 << (x[i * 9 + col] - 1); for (j = 0; j < 9; j++) used |= 1 << (x[row * 9 + j] - 1); row = row / 3 * 3; col = col / 3 * 3; for (i = row; i < row + 3; i++) for (j = col; j < col + 3; j++) used |= 1 << (x[i * 9 + j] - 1); for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) if (!(used & 1) && trycell(x, pos + 1)) return 1; x[pos] = 0; return 0; } void solve(const char *s) { int i, x[81]; for (i = 0; i < 81; i++) x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0; if (trycell(x, 0)) show(x); else puts("no solution"); } int main(void) { solve( "5x..7...." "6..195..." ".98....6." "8...6...3" "4..8.3..1" "7...2...6" ".6....28." "...419..5" "....8..79" ); return 0; }
Translate the given AutoHotKey code snippet into C# without altering its behavior.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
using System; class SudokuSolver { private int[] grid; public SudokuSolver(String s) { grid = new int[81]; for (int i = 0; i < s.Length; i++) { grid[i] = int.Parse(s[i].ToString()); } } public void solve() { try { placeNumber(0); Console.WriteLine("Unsolvable!"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(this); } } public void placeNumber(int pos) { if (pos == 81) { throw new Exception("Finished!"); } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } public bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } public override string ToString() { string sb = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sb += (grid[i * 9 + j] + " "); if (j == 2 || j == 5) sb += ("| "); } sb += ('\n'); if (i == 2 || i == 5) sb += ("------+-------+------\n"); } return sb; } public static void Main(String[] args) { new SudokuSolver("850002400" + "720000009" + "004000000" + "000107002" + "305000900" + "040000000" + "000080070" + "017000000" + "000036040").solve(); Console.Read(); } }
Change the following AutoHotKey code into C++ without altering its purpose.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
#include <iostream> using namespace std; class SudokuSolver { private: int grid[81]; public: SudokuSolver(string s) { for (unsigned int i = 0; i < s.length(); i++) { grid[i] = (int) (s[i] - '0'); } } void solve() { try { placeNumber(0); cout << "Unsolvable!" << endl; } catch (char* ex) { cout << ex << endl; cout << this->toString() << endl; } } void placeNumber(int pos) { if (pos == 81) { throw (char*) "Finished!"; } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } string toString() { string sb; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char c[2]; c[0] = grid[i * 9 + j] + '0'; c[1] = '\0'; sb.append(c); sb.append(" "); if (j == 2 || j == 5) sb.append("| "); } sb.append("\n"); if (i == 2 || i == 5) sb.append("------+-------+------\n"); } return sb; } }; int main() { SudokuSolver ss("850002400" "720000009" "004000000" "000107002" "305000900" "040000000" "000080070" "017000000" "000036040"); ss.solve(); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from AutoHotKey to Java.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
public class Sudoku { private int mBoard[][]; private int mBoardSize; private int mBoxSize; private boolean mRowSubset[][]; private boolean mColSubset[][]; private boolean mBoxSubset[][]; public Sudoku(int board[][]) { mBoard = board; mBoardSize = mBoard.length; mBoxSize = (int)Math.sqrt(mBoardSize); initSubsets(); } public void initSubsets() { mRowSubset = new boolean[mBoardSize][mBoardSize]; mColSubset = new boolean[mBoardSize][mBoardSize]; mBoxSubset = new boolean[mBoardSize][mBoardSize]; for(int i = 0; i < mBoard.length; i++) { for(int j = 0; j < mBoard.length; j++) { int value = mBoard[i][j]; if(value != 0) { setSubsetValue(i, j, value, true); } } } } private void setSubsetValue(int i, int j, int value, boolean present) { mRowSubset[i][value - 1] = present; mColSubset[j][value - 1] = present; mBoxSubset[computeBoxNo(i, j)][value - 1] = present; } public boolean solve() { return solve(0, 0); } public boolean solve(int i, int j) { if(i == mBoardSize) { i = 0; if(++j == mBoardSize) { return true; } } if(mBoard[i][j] != 0) { return solve(i + 1, j); } for(int value = 1; value <= mBoardSize; value++) { if(isValid(i, j, value)) { mBoard[i][j] = value; setSubsetValue(i, j, value, true); if(solve(i + 1, j)) { return true; } setSubsetValue(i, j, value, false); } } mBoard[i][j] = 0; return false; } private boolean isValid(int i, int j, int val) { val--; boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]; return !isPresent; } private int computeBoxNo(int i, int j) { int boxRow = i / mBoxSize; int boxCol = j / mBoxSize; return boxRow * mBoxSize + boxCol; } public void print() { for(int i = 0; i < mBoardSize; i++) { if(i % mBoxSize == 0) { System.out.println(" -----------------------"); } for(int j = 0; j < mBoardSize; j++) { if(j % mBoxSize == 0) { System.out.print("| "); } System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-"); System.out.print(' '); } System.out.println("|"); } System.out.println(" -----------------------"); } public static void main(String[] args) { int[][] board = { {8, 5, 0, 0, 0, 2, 4, 0, 0}, {7, 2, 0, 0, 0, 0, 0, 0, 9}, {0, 0, 4, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 7, 0, 0, 2}, {3, 0, 5, 0, 0, 0, 9, 0, 0}, {0, 4, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 8, 0, 0, 7, 0}, {0, 1, 7, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 3, 6, 0, 4, 0} }; Sudoku s = new Sudoku(board); System.out.print("Starting grid:\n"); s.print(); if (s.solve()) { System.out.print("\nSolution:\n"); s.print(); } else { System.out.println("\nUnsolvable!"); } } }
Can you help me rewrite this code in Python instead of AutoHotKey, keeping it the same logically?
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
def initiate(): box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) box.append([33, 34, 35, 42, 43, 44, 51, 52, 53]) box.append([54, 55, 56, 63, 64, 65, 72, 73, 74]) box.append([57, 58, 59, 66, 67, 68, 75, 76, 77]) box.append([60, 61, 62, 69, 70, 71, 78, 79, 80]) for i in range(0, 81, 9): row.append(range(i, i+9)) for i in range(9): column.append(range(i, 80+i, 9)) def valid(n, pos): current_row = pos/9 current_col = pos%9 current_box = (current_row/3)*3 + (current_col/3) for i in row[current_row]: if (grid[i] == n): return False for i in column[current_col]: if (grid[i] == n): return False for i in box[current_box]: if (grid[i] == n): return False return True def solve(): i = 0 proceed = 1 while(i < 81): if given[i]: if proceed: i += 1 else: i -= 1 else: n = grid[i] prev = grid[i] while(n < 9): if (n < 9): n += 1 if valid(n, i): grid[i] = n proceed = 1 break if (grid[i] == prev): grid[i] = 0 proceed = 0 if proceed: i += 1 else: i -=1 def inputs(): nextt = 'T' number = 0 pos = 0 while(not(nextt == 'N' or nextt == 'n')): print "Enter the position:", pos = int(raw_input()) given[pos - 1] = True print "Enter the numerical:", number = int(raw_input()) grid[pos - 1] = number print "Do you want to enter another given?(Y, for yes: N, for no)" nextt = raw_input() grid = [0]*81 given = [False]*81 box = [] row = [] column = [] initiate() inputs() solve() for i in range(9): print grid[i*9:i*9+9] raw_input()
Preserve the algorithm and functionality while converting the code from AutoHotKey to VB.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
Dim grid(9, 9) Dim gridSolved(9, 9) Public Sub Solve(i, j) If i > 9 Then For r = 1 To 9 For c = 1 To 9 gridSolved(r, c) = grid(r, c) Next c Next r Exit Sub End If For n = 1 To 9 If isSafe(i, j, n) Then nTmp = grid(i, j) grid(i, j) = n If j = 9 Then Solve i + 1, 1 Else Solve i, j + 1 End If grid(i, j) = nTmp End If Next n End Sub Public Function isSafe(i, j, n) As Boolean Dim iMin As Integer Dim jMin As Integer If grid(i, j) <> 0 Then isSafe = (grid(i, j) = n) Exit Function End If For c = 1 To 9 If grid(i, c) = n Then isSafe = False Exit Function End If Next c For r = 1 To 9 If grid(r, j) = n Then isSafe = False Exit Function End If Next r iMin = 1 + 3 * Int((i - 1) / 3) jMin = 1 + 3 * Int((j - 1) / 3) For r = iMin To iMin + 2 For c = jMin To jMin + 2 If grid(r, c) = n Then isSafe = False Exit Function End If Next c Next r isSafe = True End Function Public Sub Sudoku() Dim s(9) As String s(1) = "001005070" s(2) = "920600000" s(3) = "008000600" s(4) = "090020401" s(5) = "000000000" s(6) = "304080090" s(7) = "007000300" s(8) = "000007069" s(9) = "010800700" For i = 1 To 9 For j = 1 To 9 grid(i, j) = Int(Val(Mid$(s(i), j, 1))) Next j Next i Solve 1, 1 Debug.Print "Solution:" For i = 1 To 9 For j = 1 To 9 Debug.Print Format$(gridSolved(i, j)); " "; Next j Debug.Print Next i End Sub
Write the same algorithm in Go as shown in this AutoHotKey implementation.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
package main import "fmt" var puzzle = "" + "394 267 " + " 3 4 " + "5 69 2 " + " 45 9 " + "6 7" + " 7 58 " + " 1 67 8" + " 9 8 " + " 264 735" func main() { printGrid("puzzle:", puzzle) if s := solve(puzzle); s == "" { fmt.Println("no solution") } else { printGrid("solved:", s) } } func printGrid(title, s string) { fmt.Println(title) for r, i := 0, 0; r < 9; r, i = r+1, i+9 { fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8]) if r == 2 || r == 5 { fmt.Println("------+-------+------") } } } func solve(u string) string { d := newDlxObject(324) for r, i := 0, 0; r < 9; r++ { for c := 0; c < 9; c, i = c+1, i+1 { b := r/3*3 + c/3 n := int(u[i] - '1') if n >= 0 && n < 9 { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } else { for n = 0; n < 9; n++ { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } } } } d.search() return d.text() } type x struct { c *y u, d, l, r *x x0 *x } type y struct { x s int n int } type dlx struct { ch []y h *y o []*x } func newDlxObject(nCols int) *dlx { ch := make([]y, nCols+1) h := &ch[0] d := &dlx{ch, h, nil} h.c = h h.l = &ch[nCols].x ch[nCols].r = &h.x nh := ch[1:] for i := range ch[1:] { hi := &nh[i] ix := &hi.x hi.n = i hi.c = hi hi.u = ix hi.d = ix hi.l = &h.x h.r = ix h = hi } return d } func (d *dlx) addRow(nr []int) { if len(nr) == 0 { return } r := make([]x, len(nr)) x0 := &r[0] for x, j := range nr { ch := &d.ch[j+1] ch.s++ np := &r[x] np.c = ch np.u = ch.u np.d = &ch.x np.l = &r[(x+len(r)-1)%len(r)] np.r = &r[(x+1)%len(r)] np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np np.x0 = x0 } } func (d *dlx) text() string { b := make([]byte, len(d.o)) for _, r := range d.o { x0 := r.x0 b[x0.c.n] = byte(x0.r.c.n%9) + '1' } return string(b) } func (d *dlx) search() bool { h := d.h j := h.r.c if j == h { return true } c := j for minS := j.s; ; { j = j.r.c if j == h { break } if j.s < minS { c, minS = j, j.s } } cover(c) k := len(d.o) d.o = append(d.o, nil) for r := c.d; r != &c.x; r = r.d { d.o[k] = r for j := r.r; j != r; j = j.r { cover(j.c) } if d.search() { return true } r = d.o[k] c = r.c for j := r.l; j != r; j = j.l { uncover(j.c) } } d.o = d.o[:len(d.o)-1] uncover(c) return false } func cover(c *y) { c.r.l, c.l.r = c.l, c.r for i := c.d; i != &c.x; i = i.d { for j := i.r; j != i; j = j.r { j.d.u, j.u.d = j.u, j.d j.c.s-- } } } func uncover(c *y) { for i := c.u; i != &c.x; i = i.u { for j := i.l; j != i; j = j.l { j.c.s++ j.d.u, j.u.d = j, j } } c.r.l, c.l.r = &c.x, &c.x }
Maintain the same structure and functionality when rewriting this code in C#.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
using System; class SudokuSolver { private int[] grid; public SudokuSolver(String s) { grid = new int[81]; for (int i = 0; i < s.Length; i++) { grid[i] = int.Parse(s[i].ToString()); } } public void solve() { try { placeNumber(0); Console.WriteLine("Unsolvable!"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(this); } } public void placeNumber(int pos) { if (pos == 81) { throw new Exception("Finished!"); } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } public bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } public override string ToString() { string sb = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sb += (grid[i * 9 + j] + " "); if (j == 2 || j == 5) sb += ("| "); } sb += ('\n'); if (i == 2 || i == 5) sb += ("------+-------+------\n"); } return sb; } public static void Main(String[] args) { new SudokuSolver("850002400" + "720000009" + "004000000" + "000107002" + "305000900" + "040000000" + "000080070" + "017000000" + "000036040").solve(); Console.Read(); } }
Produce a language-to-language conversion: from AWK to C++, same semantics.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
#include <iostream> using namespace std; class SudokuSolver { private: int grid[81]; public: SudokuSolver(string s) { for (unsigned int i = 0; i < s.length(); i++) { grid[i] = (int) (s[i] - '0'); } } void solve() { try { placeNumber(0); cout << "Unsolvable!" << endl; } catch (char* ex) { cout << ex << endl; cout << this->toString() << endl; } } void placeNumber(int pos) { if (pos == 81) { throw (char*) "Finished!"; } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } string toString() { string sb; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char c[2]; c[0] = grid[i * 9 + j] + '0'; c[1] = '\0'; sb.append(c); sb.append(" "); if (j == 2 || j == 5) sb.append("| "); } sb.append("\n"); if (i == 2 || i == 5) sb.append("------+-------+------\n"); } return sb; } }; int main() { SudokuSolver ss("850002400" "720000009" "004000000" "000107002" "305000900" "040000000" "000080070" "017000000" "000036040"); ss.solve(); return EXIT_SUCCESS; }
Keep all operations the same but rewrite the snippet in Python.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
def initiate(): box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) box.append([33, 34, 35, 42, 43, 44, 51, 52, 53]) box.append([54, 55, 56, 63, 64, 65, 72, 73, 74]) box.append([57, 58, 59, 66, 67, 68, 75, 76, 77]) box.append([60, 61, 62, 69, 70, 71, 78, 79, 80]) for i in range(0, 81, 9): row.append(range(i, i+9)) for i in range(9): column.append(range(i, 80+i, 9)) def valid(n, pos): current_row = pos/9 current_col = pos%9 current_box = (current_row/3)*3 + (current_col/3) for i in row[current_row]: if (grid[i] == n): return False for i in column[current_col]: if (grid[i] == n): return False for i in box[current_box]: if (grid[i] == n): return False return True def solve(): i = 0 proceed = 1 while(i < 81): if given[i]: if proceed: i += 1 else: i -= 1 else: n = grid[i] prev = grid[i] while(n < 9): if (n < 9): n += 1 if valid(n, i): grid[i] = n proceed = 1 break if (grid[i] == prev): grid[i] = 0 proceed = 0 if proceed: i += 1 else: i -=1 def inputs(): nextt = 'T' number = 0 pos = 0 while(not(nextt == 'N' or nextt == 'n')): print "Enter the position:", pos = int(raw_input()) given[pos - 1] = True print "Enter the numerical:", number = int(raw_input()) grid[pos - 1] = number print "Do you want to enter another given?(Y, for yes: N, for no)" nextt = raw_input() grid = [0]*81 given = [False]*81 box = [] row = [] column = [] initiate() inputs() solve() for i in range(9): print grid[i*9:i*9+9] raw_input()
Change the programming language of this snippet from AWK to VB without modifying what it does.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
Dim grid(9, 9) Dim gridSolved(9, 9) Public Sub Solve(i, j) If i > 9 Then For r = 1 To 9 For c = 1 To 9 gridSolved(r, c) = grid(r, c) Next c Next r Exit Sub End If For n = 1 To 9 If isSafe(i, j, n) Then nTmp = grid(i, j) grid(i, j) = n If j = 9 Then Solve i + 1, 1 Else Solve i, j + 1 End If grid(i, j) = nTmp End If Next n End Sub Public Function isSafe(i, j, n) As Boolean Dim iMin As Integer Dim jMin As Integer If grid(i, j) <> 0 Then isSafe = (grid(i, j) = n) Exit Function End If For c = 1 To 9 If grid(i, c) = n Then isSafe = False Exit Function End If Next c For r = 1 To 9 If grid(r, j) = n Then isSafe = False Exit Function End If Next r iMin = 1 + 3 * Int((i - 1) / 3) jMin = 1 + 3 * Int((j - 1) / 3) For r = iMin To iMin + 2 For c = jMin To jMin + 2 If grid(r, c) = n Then isSafe = False Exit Function End If Next c Next r isSafe = True End Function Public Sub Sudoku() Dim s(9) As String s(1) = "001005070" s(2) = "920600000" s(3) = "008000600" s(4) = "090020401" s(5) = "000000000" s(6) = "304080090" s(7) = "007000300" s(8) = "000007069" s(9) = "010800700" For i = 1 To 9 For j = 1 To 9 grid(i, j) = Int(Val(Mid$(s(i), j, 1))) Next j Next i Solve 1, 1 Debug.Print "Solution:" For i = 1 To 9 For j = 1 To 9 Debug.Print Format$(gridSolved(i, j)); " "; Next j Debug.Print Next i End Sub
Preserve the algorithm and functionality while converting the code from AWK to Go.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
package main import "fmt" var puzzle = "" + "394 267 " + " 3 4 " + "5 69 2 " + " 45 9 " + "6 7" + " 7 58 " + " 1 67 8" + " 9 8 " + " 264 735" func main() { printGrid("puzzle:", puzzle) if s := solve(puzzle); s == "" { fmt.Println("no solution") } else { printGrid("solved:", s) } } func printGrid(title, s string) { fmt.Println(title) for r, i := 0, 0; r < 9; r, i = r+1, i+9 { fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8]) if r == 2 || r == 5 { fmt.Println("------+-------+------") } } } func solve(u string) string { d := newDlxObject(324) for r, i := 0, 0; r < 9; r++ { for c := 0; c < 9; c, i = c+1, i+1 { b := r/3*3 + c/3 n := int(u[i] - '1') if n >= 0 && n < 9 { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } else { for n = 0; n < 9; n++ { d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, 243 + b*9 + n}) } } } } d.search() return d.text() } type x struct { c *y u, d, l, r *x x0 *x } type y struct { x s int n int } type dlx struct { ch []y h *y o []*x } func newDlxObject(nCols int) *dlx { ch := make([]y, nCols+1) h := &ch[0] d := &dlx{ch, h, nil} h.c = h h.l = &ch[nCols].x ch[nCols].r = &h.x nh := ch[1:] for i := range ch[1:] { hi := &nh[i] ix := &hi.x hi.n = i hi.c = hi hi.u = ix hi.d = ix hi.l = &h.x h.r = ix h = hi } return d } func (d *dlx) addRow(nr []int) { if len(nr) == 0 { return } r := make([]x, len(nr)) x0 := &r[0] for x, j := range nr { ch := &d.ch[j+1] ch.s++ np := &r[x] np.c = ch np.u = ch.u np.d = &ch.x np.l = &r[(x+len(r)-1)%len(r)] np.r = &r[(x+1)%len(r)] np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np np.x0 = x0 } } func (d *dlx) text() string { b := make([]byte, len(d.o)) for _, r := range d.o { x0 := r.x0 b[x0.c.n] = byte(x0.r.c.n%9) + '1' } return string(b) } func (d *dlx) search() bool { h := d.h j := h.r.c if j == h { return true } c := j for minS := j.s; ; { j = j.r.c if j == h { break } if j.s < minS { c, minS = j, j.s } } cover(c) k := len(d.o) d.o = append(d.o, nil) for r := c.d; r != &c.x; r = r.d { d.o[k] = r for j := r.r; j != r; j = j.r { cover(j.c) } if d.search() { return true } r = d.o[k] c = r.c for j := r.l; j != r; j = j.l { uncover(j.c) } } d.o = d.o[:len(d.o)-1] uncover(c) return false } func cover(c *y) { c.r.l, c.l.r = c.l, c.r for i := c.d; i != &c.x; i = i.d { for j := i.r; j != i; j = j.r { j.d.u, j.u.d = j.u, j.d j.c.s-- } } } func uncover(c *y) { for i := c.u; i != &c.x; i = i.u { for j := i.l; j != i; j = j.l { j.c.s++ j.d.u, j.u.d = j, j } } c.r.l, c.l.r = &c.x, &c.x }
Translate this program into C but keep the logic exactly as in BBC_Basic.
VDU 23,22,453;453;8,20,16,128 *FONT Arial,28 DIM Board%(8,8) Board%() = %111111111 FOR L% = 0 TO 9:P% = L%*100 LINE 2,P%+2,902,P%+2 IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4 LINE P%+2,2,P%+2,902 IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902 NEXT DATA " 4 5 6 " DATA " 6 1 8 9" DATA "3 7 " DATA " 8 5 " DATA " 4 3 " DATA " 6 7 " DATA " 2 6" DATA "1 5 4 3 " DATA " 2 7 1 " FOR R% = 8 TO 0 STEP -1 READ A$ FOR C% = 0 TO 8 A% = ASCMID$(A$,C%+1) AND 15 IF A% Board%(R%,C%) = 1 << (A%-1) NEXT NEXT R% GCOL 4 PROCshow WAIT 200 dummy% = FNsolve(Board%(), TRUE) GCOL 2 PROCshow REPEAT WAIT 1 : UNTIL FALSE END DEF PROCshow LOCAL C%,P%,R% FOR C% = 0 TO 8 FOR R% = 0 TO 8 P% = Board%(R%,C%) IF (P% AND (P%-1)) = 0 THEN IF P% P% = LOGP%/LOG2+1.5 MOVE C%*100+30,R%*100+90 VDU 5,P%+48,4 ENDIF NEXT NEXT ENDPROC DEF FNsolve(P%(),F%) LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%() DIM Q%(8,8) REPEAT Q%() = P%() FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF (D% AND (D%-1))=0 THEN M% = NOT D% FOR X% = 0 TO 8 IF X%<>C% P%(R%,X%) AND= M% IF X%<>R% P%(X%,C%) AND= M% NEXT FOR X% = C%DIV3*3 TO C%DIV3*3+2 FOR Y% = R%DIV3*3 TO R%DIV3*3+2 IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M% NEXT NEXT ENDIF NEXT NEXT Q%() -= P%() UNTIL SUMQ%()=0 M% = 10 FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF D%=0 M% = 0 IF D% AND (D%-1) THEN N% = 0 REPEAT N% += D% AND 1 D% DIV= 2 UNTIL D% = 0 IF N%<M% M% = N% : X% = C% : Y% = R% ENDIF NEXT NEXT IF M%=0 THEN = 0 IF M%=10 THEN = 1 D% = 0 FOR M% = 0 TO 8 IF P%(Y%,X%) AND (2^M%) THEN Q%() = P%() Q%(Y%,X%) = 2^M% C% = FNsolve(Q%(),F%) D% += C% IF C% IF F% P%() = Q%() : = D% ENDIF NEXT = D%
#include <stdio.h> void show(int *x) { int i, j; for (i = 0; i < 9; i++) { if (!(i % 3)) putchar('\n'); for (j = 0; j < 9; j++) printf(j % 3 ? "%2d" : "%3d", *x++); putchar('\n'); } } int trycell(int *x, int pos) { int row = pos / 9; int col = pos % 9; int i, j, used = 0; if (pos == 81) return 1; if (x[pos]) return trycell(x, pos + 1); for (i = 0; i < 9; i++) used |= 1 << (x[i * 9 + col] - 1); for (j = 0; j < 9; j++) used |= 1 << (x[row * 9 + j] - 1); row = row / 3 * 3; col = col / 3 * 3; for (i = row; i < row + 3; i++) for (j = col; j < col + 3; j++) used |= 1 << (x[i * 9 + j] - 1); for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) if (!(used & 1) && trycell(x, pos + 1)) return 1; x[pos] = 0; return 0; } void solve(const char *s) { int i, x[81]; for (i = 0; i < 81; i++) x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0; if (trycell(x, 0)) show(x); else puts("no solution"); } int main(void) { solve( "5x..7...." "6..195..." ".98....6." "8...6...3" "4..8.3..1" "7...2...6" ".6....28." "...419..5" "....8..79" ); return 0; }
Preserve the algorithm and functionality while converting the code from BBC_Basic to C#.
VDU 23,22,453;453;8,20,16,128 *FONT Arial,28 DIM Board%(8,8) Board%() = %111111111 FOR L% = 0 TO 9:P% = L%*100 LINE 2,P%+2,902,P%+2 IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4 LINE P%+2,2,P%+2,902 IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902 NEXT DATA " 4 5 6 " DATA " 6 1 8 9" DATA "3 7 " DATA " 8 5 " DATA " 4 3 " DATA " 6 7 " DATA " 2 6" DATA "1 5 4 3 " DATA " 2 7 1 " FOR R% = 8 TO 0 STEP -1 READ A$ FOR C% = 0 TO 8 A% = ASCMID$(A$,C%+1) AND 15 IF A% Board%(R%,C%) = 1 << (A%-1) NEXT NEXT R% GCOL 4 PROCshow WAIT 200 dummy% = FNsolve(Board%(), TRUE) GCOL 2 PROCshow REPEAT WAIT 1 : UNTIL FALSE END DEF PROCshow LOCAL C%,P%,R% FOR C% = 0 TO 8 FOR R% = 0 TO 8 P% = Board%(R%,C%) IF (P% AND (P%-1)) = 0 THEN IF P% P% = LOGP%/LOG2+1.5 MOVE C%*100+30,R%*100+90 VDU 5,P%+48,4 ENDIF NEXT NEXT ENDPROC DEF FNsolve(P%(),F%) LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%() DIM Q%(8,8) REPEAT Q%() = P%() FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF (D% AND (D%-1))=0 THEN M% = NOT D% FOR X% = 0 TO 8 IF X%<>C% P%(R%,X%) AND= M% IF X%<>R% P%(X%,C%) AND= M% NEXT FOR X% = C%DIV3*3 TO C%DIV3*3+2 FOR Y% = R%DIV3*3 TO R%DIV3*3+2 IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M% NEXT NEXT ENDIF NEXT NEXT Q%() -= P%() UNTIL SUMQ%()=0 M% = 10 FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF D%=0 M% = 0 IF D% AND (D%-1) THEN N% = 0 REPEAT N% += D% AND 1 D% DIV= 2 UNTIL D% = 0 IF N%<M% M% = N% : X% = C% : Y% = R% ENDIF NEXT NEXT IF M%=0 THEN = 0 IF M%=10 THEN = 1 D% = 0 FOR M% = 0 TO 8 IF P%(Y%,X%) AND (2^M%) THEN Q%() = P%() Q%(Y%,X%) = 2^M% C% = FNsolve(Q%(),F%) D% += C% IF C% IF F% P%() = Q%() : = D% ENDIF NEXT = D%
using System; class SudokuSolver { private int[] grid; public SudokuSolver(String s) { grid = new int[81]; for (int i = 0; i < s.Length; i++) { grid[i] = int.Parse(s[i].ToString()); } } public void solve() { try { placeNumber(0); Console.WriteLine("Unsolvable!"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(this); } } public void placeNumber(int pos) { if (pos == 81) { throw new Exception("Finished!"); } if (grid[pos] > 0) { placeNumber(pos + 1); return; } for (int n = 1; n <= 9; n++) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n; placeNumber(pos + 1); grid[pos] = 0; } } } public bool checkValidity(int val, int x, int y) { for (int i = 0; i < 9; i++) { if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) return false; } int startX = (x / 3) * 3; int startY = (y / 3) * 3; for (int i = startY; i < startY + 3; i++) { for (int j = startX; j < startX + 3; j++) { if (grid[i * 9 + j] == val) return false; } } return true; } public override string ToString() { string sb = ""; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sb += (grid[i * 9 + j] + " "); if (j == 2 || j == 5) sb += ("| "); } sb += ('\n'); if (i == 2 || i == 5) sb += ("------+-------+------\n"); } return sb; } public static void Main(String[] args) { new SudokuSolver("850002400" + "720000009" + "004000000" + "000107002" + "305000900" + "040000000" + "000080070" + "017000000" + "000036040").solve(); Console.Read(); } }