TU-Programmieren_2/exercise8/task3.c
2025-04-09 10:22:44 +02:00

55 lines
2.2 KiB
C

#include "task3.h" // task3_count_inside, task3_common_bbox
#include "task2.h" // struct Vec2d, struct BBox, struct Circle
#include <stdbool.h> // for bool (true/false)
/// @brief Count the number of Circles fully contained inside a bounding box
/// @param box Bounding box
/// @param circles Array of Circles
/// @param size Length of the 'circles' array
/// @return Number of circles fully contained inside 'box'
unsigned int task3_count_inside(const struct BBox* box, const struct Circle circles[], unsigned int size) {
unsigned int count = 0;
for (unsigned int i = 0; i < size; i++) {
const struct Circle* circle = &circles[i];
// Check if circle center is within box boundaries
bool inside_x = (circle->c.x - circle->r >= box->min.x) && (circle->c.x + circle->r <= box->max.x);
bool inside_y = (circle->c.y - circle->r >= box->min.y) && (circle->c.y + circle->r <= box->max.y);
if (inside_x && inside_y) {
count++;
}
}
return count;
}
/// @brief Generates the smallest bounding box containing a sequence of circles
/// @param circles Array of Circles
/// @param size Length of the 'circles' array (Assertion: size >= 1)
/// @return Smallest bounding box containing all circles
struct BBox task3_common_bbox(const struct Circle circles[], unsigned int size) {
struct BBox res;
// Initialize with first circle's data (assuming at least one circle)
res.min.x = circles[0].c.x - circles[0].r;
res.min.y = circles[0].c.y - circles[0].r;
res.max.x = circles[0].c.x + circles[0].r;
res.max.y = circles[0].c.y + circles[0].r;
for (unsigned int i = 1; i < size; i++) {
const struct Circle* circle = &circles[i];
// Update minimum bounds if circle's center falls outside current box
if (circle->c.x - circle->r < res.min.x) {
res.min.x = circle->c.x - circle->r;
}
if (circle->c.y - circle->r < res.min.y) {
res.min.y = circle->c.y - circle->r;
}
// Update maximum bounds if circle's edge falls outside current box
if (circle->c.x + circle->r > res.max.x) {
res.max.x = circle->c.x + circle->r;
}
if (circle->c.y + circle->r > res.max.y) {
res.max.y = circle->c.y + circle->r;
}
}
return res;
}