From 7de6c3cae374c0a5e3bcedecb6c0025473fc2fa4 Mon Sep 17 00:00:00 2001 From: Simon Bruder Date: Sun, 7 May 2023 19:24:48 +0200 Subject: [PATCH] u02: Implement sorting for 3 points --- u02/include/util.h | 3 +++ u02/src/tests.cpp | 25 +++++++++++++++++++++++++ u02/src/util.cpp | 21 +++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/u02/include/util.h b/u02/include/util.h index 6f84fb1..b1e1574 100644 --- a/u02/include/util.h +++ b/u02/include/util.h @@ -36,3 +36,6 @@ Transformation transformation_to_standard_case(int x0, int y0, int x1, int y1); std::tuple barycentric_coordinates(int x0, int y0, int x1, int y1, int x2, int y2, int xp, int yp); + +// Sorts the points of a triangle to be in ascending order (y0 < y1 < y2). +void sort_triangle_points(int &x0, int &y0, int &x1, int &y1, int &x2, int &y2); diff --git a/u02/src/tests.cpp b/u02/src/tests.cpp index 23dd8a7..ce03ca0 100644 --- a/u02/src/tests.cpp +++ b/u02/src/tests.cpp @@ -427,3 +427,28 @@ TEST_CASE("Barycentric coordinates (prop: Σ = 1)") { REQUIRE_THAT(b1 + b2 + b3, WithinRel(1.0, 1e-4)); } + +TEST_CASE("Sort triangle points") { + int x0 = 10, y0 = 60, x1 = 50, y1 = 90, x2 = 40, y2 = 30; + sort_triangle_points(x0, y0, x1, y1, x2, y2); + REQUIRE(x0 == 40); + REQUIRE(y0 == 30); + REQUIRE(x1 == 10); + REQUIRE(y1 == 60); + REQUIRE(x2 == 50); + REQUIRE(y2 == 90); +} + +TEST_CASE("Sort triangle points (prop: y0 < y1 < y2)") { + int x0 = GENERATE(take(3, random(-100, 100))); + int y0 = GENERATE(take(3, random(-100, 100))); + int x1 = GENERATE(take(3, random(-100, 100))); + int y1 = GENERATE(take(3, random(-100, 100))); + int x2 = GENERATE(take(3, random(-100, 100))); + int y2 = GENERATE(take(3, random(-100, 100))); + + sort_triangle_points(x0, y0, x1, y1, x2, y2); + + REQUIRE(y0 <= y1); + REQUIRE(y1 <= y2); +} diff --git a/u02/src/util.cpp b/u02/src/util.cpp index 4bfdac7..3c991b3 100644 --- a/u02/src/util.cpp +++ b/u02/src/util.cpp @@ -159,3 +159,24 @@ std::tuple barycentric_coordinates(int x0, int y0, int x1, return {b1, b2, b3}; } + +void sort_triangle_points(int &x0, int &y0, int &x1, int &y1, int &x2, + int &y2) { + // Bubble sort is not really ideal in general. + // It could be changed to use a more efficient algorithm, + // but for only 3 values, it should suffice. + // Moreover, implementing sorting on an array/vector of tuples + // is probably more overhead. + if (y0 > y1) { + std::swap(x0, x1); + std::swap(y0, y1); + } + if (y0 > y2) { + std::swap(x0, x2); + std::swap(y0, y2); + } + if (y1 > y2) { + std::swap(x1, x2); + std::swap(y1, y2); + } +}