Problem 223: Rectangle area

This commit is contained in:
Ivan R. 2022-11-17 16:56:24 +05:00
parent 16ef234336
commit 3b34f9a82a
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
5 changed files with 77 additions and 0 deletions

View file

@ -0,0 +1,14 @@
all: lib.o main.o
gcc -Wall -o bin lib.o main.o
lib.o: lib.c
gcc -c -Wall lib.c
main.o: main.c
gcc -c -Wall main.c
run:
./bin
clean:
rm *.o bin

View file

@ -0,0 +1,35 @@
#include "lib.h"
int _findIntersection(int a_start, int a_end, int b_start, int b_end) {
// aaaa
// bbbb
if (a_end > b_start && a_start <= b_start && a_end <= b_end)
return a_end - b_start;
// aa
// bbbbbb
if (a_start >= b_start && a_end <= b_end)
return a_end - a_start;
// aaaa
// bbbb
if (a_start >= b_start && a_start < b_end && a_end >= b_end)
return b_end - a_start;
// aaaaa
// bb
if (b_start >= a_start && b_end <= a_end)
return b_end - b_start;
return 0;
}
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// Area of the first rectangle
int a = (ax2 - ax1) * (ay2 - ay1);
// Area of the second rectangle
int b = (bx2 - bx1) * (by2 - by1);
// Find intersection
int x_intersection = _findIntersection(ax1, ax2, bx1, bx2);
int y_intersection = _findIntersection(ay1, ay2, by1, by2);
return a + b - x_intersection * y_intersection;
}

View file

@ -0,0 +1,2 @@
#pragma once
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2);

View file

@ -0,0 +1,12 @@
#include <stdio.h>
#include "lib.h"
int main() {
int res1 = computeArea(-3, 0, 3, 4, 0, -1, 9, 2);
printf("Test 1: %d\n", res1 == 45);
int res2 = computeArea(-2, -2, 2, 2, -2, -2, 2, 2);
printf("Test 2: %d\n", res2 == 16);
return 0;
}

View file

@ -0,0 +1,14 @@
# 223. Rectangle area
[Leetcode](https://leetcode.com/problems/rectangle-area/)
Given the coordinates of two rectilinear rectangles in a 2D plane,
return the total area covered by the two rectangles.
The first rectangle is defined by its
bottom-left corner (ax1, ay1) and its
top-right corner (ax2, ay2).
The second rectangle is defined by its
bottom-left corner (bx1, by1) and its
top-right corner (bx2, by2).