Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Nim implementation into Go, maintaining the same output and logic.
type Point = tuple x: float y: float func shoelace(points: openArray[Point]): float = var leftSum, rightSum = 0.0 for i in 0..<len(points): var j = (i + 1) mod len(points) leftSum += points[i].x * points[j].y rightSum += points[j].x * points[i].y 0.5 * abs(leftSum - rightSum) var points = [(3.0, 4.0), (5.0, 11.0), (12.0, 8.0), (9.0, 5.0), (5.0, 6.0)] echo shoelace(points)
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Please provide an equivalent version of this Perl code in C.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Generate an equivalent C version of this Perl code.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Produce a language-to-language conversion: from Perl to C#, same semantics.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Translate the given Perl code snippet into C# without altering its behavior.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Keep all operations the same but rewrite the snippet in C++.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Convert this Perl block to C++, preserving its control flow and logic.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Translate this program into Java but keep the logic exactly as in Perl.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Rewrite the snippet below in Java so it works the same as the original Perl code.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Keep all operations the same but rewrite the snippet in Python.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Change the programming language of this snippet from Perl to Python without modifying what it does.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Change the programming language of this snippet from Perl to VB without modifying what it does.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Change the following Perl code into VB without altering its purpose.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Maintain the same structure and functionality when rewriting this code in Go.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Port the provided Perl code into Go while preserving the original functionality.
use strict; use warnings; use feature 'say'; sub area_by_shoelace { my $area; our @p; $ $area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1; $area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1; return abs $area/2; } my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [3,4], [5,11], [12,8], [9,5], [5,6] ); say area_by_shoelace( [ [3,4], [5,11], [12,8], [9,5], [5,6] ] ); say area_by_shoelace( @poly ); say area_by_shoelace( \@poly );
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Produce a language-to-language conversion: from Racket to C, same semantics.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Write the same code in C as shown below in Racket.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Translate this program into C# but keep the logic exactly as in Racket.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Keep all operations the same but rewrite the snippet in C#.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Please provide an equivalent version of this Racket code in C++.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Change the programming language of this snippet from Racket to C++ without modifying what it does.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Write the same algorithm in Java as shown in this Racket implementation.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Port the following code from Racket to Java with equivalent syntax and logic.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Convert this Racket block to Python, preserving its control flow and logic.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Rewrite this program in Python while keeping its functionality equivalent to the Racket version.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Transform the following Racket implementation into VB, maintaining the same output and logic.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Translate the given Racket code snippet into VB without altering its behavior.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Write the same algorithm in Go as shown in this Racket implementation.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Translate this program into Go but keep the logic exactly as in Racket.
#lang racket/base (struct P (x y)) (define (area . Ps) (define (A P-a P-b) (+ (for/sum ((p_i Ps) (p_i+1 (in-sequences (cdr Ps) (in-value (car Ps))))) (* (P-a p_i) (P-b p_i+1))))) (/ (abs (- (A P-x P-y) (A P-y P-x))) 2)) (module+ main (area (P 3 4) (P 5 11) (P 12 8) (P 9 5) (P 5 6)))
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Convert the following code from REXX to C, ensuring the logic remains intact.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Transform the following REXX implementation into C, maintaining the same output and logic.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Produce a functionally identical C# code for the snippet given in REXX.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Can you help me rewrite this code in C# instead of REXX, keeping it the same logically?
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Rewrite this program in C++ while keeping its functionality equivalent to the REXX version.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Can you help me rewrite this code in C++ instead of REXX, keeping it the same logically?
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Keep all operations the same but rewrite the snippet in Java.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Port the following code from REXX to Java with equivalent syntax and logic.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Keep all operations the same but rewrite the snippet in Python.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Convert the following code from REXX to Python, ensuring the logic remains intact.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Write the same algorithm in VB as shown in this REXX implementation.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Keep all operations the same but rewrite the snippet in VB.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Transform the following REXX implementation into Go, maintaining the same output and logic.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Change the programming language of this snippet from REXX to Go without modifying what it does.
parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" A= 0; @= space($, 0) do #=1 until @==''; parse var @ '(' x.# "," y.# ')' "," @ end z= #+1; y.0= y.#; y.z= y.1 do j=1 for #; jm= j-1; jp= j+1; A= A + x.j*(y.jm - y.jp) end say 'polygon area of ' # " points: " $ ' is ───► ' abs(A/2)
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Port the provided Ruby code into C while preserving the original functionality.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Translate the given Ruby code snippet into C without altering its behavior.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Change the following Ruby code into C# without altering its purpose.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Produce a functionally identical C# code for the snippet given in Ruby.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Transform the following Ruby implementation into C++, maintaining the same output and logic.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Generate a C++ translation of this Ruby snippet without changing its computational steps.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Translate the given Ruby code snippet into Java without altering its behavior.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Transform the following Ruby implementation into Python, maintaining the same output and logic.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Rewrite the snippet below in Python so it works the same as the original Ruby code.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Please provide an equivalent version of this Ruby code in VB.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Write a version of this Ruby function in VB with identical behavior.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Convert this Ruby snippet to Go and keep its semantics consistent.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Produce a language-to-language conversion: from Ruby to Go, same semantics.
Point = Struct.new(:x,:y) do def shoelace(other) x * other.y - y * other.x end end class Polygon def initialize(*coords) @points = coords.map{|c| Point.new(*c) } end def area points = @points + [@points.first] points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2) end end puts Polygon.new([3,4], [5,11], [12,8], [9,5], [5,6]).area
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Produce a functionally identical C code for the snippet given in Scala.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Port the provided Scala code into C while preserving the original functionality.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Ensure the translated C# code behaves exactly like the original Scala snippet.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Preserve the algorithm and functionality while converting the code from Scala to C#.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Please provide an equivalent version of this Scala code in C++.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Port the following code from Scala to C++ with equivalent syntax and logic.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Translate the given Scala code snippet into Java without altering its behavior.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Convert the following code from Scala to Java, ensuring the logic remains intact.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Keep all operations the same but rewrite the snippet in Python.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Port the provided Scala code into Python while preserving the original functionality.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Preserve the algorithm and functionality while converting the code from Scala to VB.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Produce a functionally identical VB code for the snippet given in Scala.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Preserve the algorithm and functionality while converting the code from Scala to Go.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Generate an equivalent Go version of this Scala code.
class Point(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun shoelaceArea(v: List<Point>): Double { val n = v.size var a = 0.0 for (i in 0 until n - 1) { a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y } return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 } fun main(args: Array<String>) { val v = listOf( Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) ) val area = shoelaceArea(v) println("Given a polygon with vertices at $v,") println("its area is $area") }
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Translate this program into C but keep the logic exactly as in Swift.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Translate this program into C but keep the logic exactly as in Swift.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,"r"); fscanf(fp,"%d",&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,"%lf %lf",&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf("\nUsage : %s <full path of polygon vertices file>",argV[0]); else printf("The polygon area is %lf square units.",shoelace(argV[1])); return 0; }
Transform the following Swift implementation into C#, maintaining the same output and logic.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Convert this Swift block to C#, preserving its control flow and logic.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
using System; using System.Collections.Generic; namespace ShoelaceFormula { using Point = Tuple<double, double>; class Program { static double ShoelaceArea(List<Point> v) { int n = v.Count; double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2; } return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0; } static void Main(string[] args) { List<Point> v = new List<Point>() { new Point(3,4), new Point(5,11), new Point(12,8), new Point(9,5), new Point(5,6), }; double area = ShoelaceArea(v); Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v)); Console.WriteLine("its area is {0}.", area); } } }
Produce a functionally identical C++ code for the snippet given in Swift.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Write a version of this Swift function in C++ with identical behavior.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Port the provided Swift code into Java while preserving the original functionality.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Preserve the algorithm and functionality while converting the code from Swift to Java.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
import java.util.List; public class ShoelaceFormula { private static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private static double shoelaceArea(List<Point> v) { int n = v.size(); double a = 0.0; for (int i = 0; i < n - 1; i++) { a += v.get(i).x * v.get(i + 1).y - v.get(i + 1).x * v.get(i).y; } return Math.abs(a + v.get(n - 1).x * v.get(0).y - v.get(0).x * v.get(n - 1).y) / 2.0; } public static void main(String[] args) { List<Point> v = List.of( new Point(3, 4), new Point(5, 11), new Point(12, 8), new Point(9, 5), new Point(5, 6) ); double area = shoelaceArea(v); System.out.printf("Given a polygon with vertices %s,%n", v); System.out.printf("its area is %f,%n", area); } }
Produce a functionally identical Python code for the snippet given in Swift.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Produce a functionally identical Python code for the snippet given in Swift.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
>>> def area_by_shoelace(x, y): "Assumes x,y points go around the polygon in one direction" return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1])) -sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2 >>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)] >>> x, y = zip(*points) >>> area_by_shoelace(x, y) 30.0 >>>
Convert this Swift block to VB, preserving its control flow and logic.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Can you help me rewrite this code in VB instead of Swift, keeping it the same logically?
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
Option Base 1 Public Enum axes u = 1 v End Enum Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i)(u) * s(i + 1)(v) - s(i + 1)(u) * s(i)(v) Next i End If shoelace = Abs(t) / 2 End Function Public Sub polygonal_area() Dim task() As Variant task = [{3,4;5,11;12,8;9,5;5,6}] Dim tcol As New Collection For i = 1 To UBound(task) tcol.Add Array(task(i, u), task(i, v)) Next i Debug.Print shoelace(tcol) End Sub
Translate the given Swift code snippet into Go without altering its behavior.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Change the programming language of this snippet from Swift to Go without modifying what it does.
import Foundation struct Point { var x: Double var y: Double } extension Point: CustomStringConvertible { var description: String { return "Point(x: \(x), y: \(y))" } } struct Polygon { var points: [Point] var area: Double { let xx = points.map({ $0.x }) let yy = points.map({ $0.y }) let overlace = zip(xx, yy.dropFirst() + yy.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) let underlace = zip(yy, xx.dropFirst() + xx.prefix(1)).map({ $0.0 * $0.1 }).reduce(0, +) return abs(overlace - underlace) / 2 } init(points: [Point]) { self.points = points } init(points: [(Double, Double)]) { self.init(points: points.map({ Point(x: $0.0, y: $0.1) })) } } let poly = Polygon(points: [ (3,4), (5,11), (12,8), (9,5), (5,6) ]) print("\(poly) area = \(poly.area)")
package main import "fmt" type point struct{ x, y float64 } func shoelace(pts []point) float64 { sum := 0. p0 := pts[len(pts)-1] for _, p1 := range pts { sum += p0.y*p1.x - p0.x*p1.y p0 = p1 } return sum / 2 } func main() { fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8}, {9, 5}, {5, 6}})) }
Convert this Ada snippet to C# and keep its semantics consistent.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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); } } }
Generate an equivalent C# version of this Ada code.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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); } } }
Generate an equivalent C version of this Ada code.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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 Ada.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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; }
Can you help me rewrite this code in C++ instead of Ada, keeping it the same logically?
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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;} }
Produce a functionally identical C++ code for the snippet given in Ada.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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 the following code from Ada to Go, ensuring the logic remains intact.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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 this program in Go while keeping its functionality equivalent to the Ada version.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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")) }
Preserve the algorithm and functionality while converting the code from Ada to Java.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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"); } } }
Port the provided Ada code into Java while preserving the original functionality.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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"); } } }
Transform the following Ada implementation into Python, maintaining the same output and logic.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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 Python code behaves exactly like the original Ada snippet.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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)
Please provide an equivalent version of this Ada code in VB.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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
Rewrite the snippet below in VB so it works the same as the original Ada code.
WITH Ada.Text_IO; USE Ada.Text_IO; PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float; FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RETURN Float IS ((B (1) - A (1)) * (U (0) - A (0)) + (A (0) - B (0)) * (U (1) - A (1))); BEGIN RETURN Aff (M) * Aff (N) >= 0.0; END Same_Side; FUNCTION In_Side (T1 , T2 : Triangle) RETURN Boolean IS (FOR ALL V IN Vertex => (FOR Some P OF T2 => Same_Side (T1 (V + 1), T1 (V + 2), T1 (V), P))); FUNCTION Overlap (T1, T2 : Triangle) RETURN Boolean IS (In_Side (T1, T2) AND THEN In_Side (T2, T1)); FUNCTION "+" (T : Triangle_Vertices) RETURN Triangle IS ((T (0), T (1)), (T (2), T (3)), (T (4), T (5))); PROCEDURE Put (T1, T2 : Triangle_Vertices) IS BEGIN Put_Line (Overlap (+T1, +T2)'Img); END Put; BEGIN Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (0.0, 0.0, 5.0, 0.0, 0.0, 6.0)); Put ((0.0, 0.0, 0.0, 5.0, 5.0, 0.0), (0.0, 0.0, 0.0, 5.0, 5.0, 0.0)); Put ((0.0, 0.0, 5.0, 0.0, 0.0, 5.0), (-10.0, 0.0, -5.0, 0.0, -1.0, 6.0)); Put ((0.0, 0.0, 5.0, 0.0, 2.5, 5.0), (0.0, 4.0, 2.5, -1.0, 5.0, 4.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, 0.0, 3.0, 2.0)); Put ((0.0, 0.0, 1.0, 1.0, 0.0, 2.0), (2.0, 1.0, 3.0, -2.0, 3.0, 4.0)); Put ((0.0, 0.0, 1.0, 0.0, 0.0, 1.0), (1.0, 0.0, 2.0, 0.0, 1.0, 1.0)); 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
Write a version of this AutoHotKey function in C with identical behavior.
TrianglesIntersect(T1, T2){ counter := 0 for i, Pt in T1 counter += PointInTriangle(Pt, T2) for i, Pt in T2 counter += PointInTriangle(Pt, T1) counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.2],[t2.2,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.2,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.2,t2.3]) ? 1 : 0 return (counter>3)  } PointInTriangle(pt, Tr){ v1 := Tr.1, v2 := Tr.2, v3 := Tr.3 d1 := sign(pt, v1, v2) d2 := sign(pt, v2, v3) d3 := sign(pt, v3, v1) has_neg := (d1 < 0) || (d2 < 0) || (d3 < 0) has_pos := (d1 > 0) || (d2 > 0) || (d3 > 0) return !(has_neg && has_pos) } sign(p1, p2, p3){ return (p1.1 - p3.1) * (p2.2 - p3.2) - (p2.1 - p3.1) * (p1.2 - p3.2) } LinesIntersect(L1, L2){ x1 := L1[1,1], y1 := L1[1,2] x2 := L1[2,1], y2 := L1[2,2] x3 := L2[1,1], y3 := L2[1,2] x4 := L2[2,1], y4 := L2[2,2] x := ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) y := ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) if (x<>"" && y<>"") && isBetween(x, x1, x2) && isBetween(x, x3, x4) && isBetween(y, y1, y2) && isBetween(y, y3, y4) return 1 } isBetween(x, p1, p2){ return !((x>p1 && x>p2) || (x<p1 && x<p2)) }
#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; }
Change the programming language of this snippet from AutoHotKey to C without modifying what it does.
TrianglesIntersect(T1, T2){ counter := 0 for i, Pt in T1 counter += PointInTriangle(Pt, T2) for i, Pt in T2 counter += PointInTriangle(Pt, T1) counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.2]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.2],[t2.2,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.1,t1.3],[t2.2,t2.3]) ? 1 : 0 counter += LinesIntersect([t1.2,t1.3],[t2.2,t2.3]) ? 1 : 0 return (counter>3)  } PointInTriangle(pt, Tr){ v1 := Tr.1, v2 := Tr.2, v3 := Tr.3 d1 := sign(pt, v1, v2) d2 := sign(pt, v2, v3) d3 := sign(pt, v3, v1) has_neg := (d1 < 0) || (d2 < 0) || (d3 < 0) has_pos := (d1 > 0) || (d2 > 0) || (d3 > 0) return !(has_neg && has_pos) } sign(p1, p2, p3){ return (p1.1 - p3.1) * (p2.2 - p3.2) - (p2.1 - p3.1) * (p1.2 - p3.2) } LinesIntersect(L1, L2){ x1 := L1[1,1], y1 := L1[1,2] x2 := L1[2,1], y2 := L1[2,2] x3 := L2[1,1], y3 := L2[1,2] x4 := L2[2,1], y4 := L2[2,2] x := ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) y := ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) if (x<>"" && y<>"") && isBetween(x, x1, x2) && isBetween(x, x3, x4) && isBetween(y, y1, y2) && isBetween(y, y3, y4) return 1 } isBetween(x, p1, p2){ return !((x>p1 && x>p2) || (x<p1 && x<p2)) }
#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; }