Problem 223: ruby rewrite

This commit is contained in:
Ivan R. 2022-12-02 23:28:36 +05:00
parent a053af02d9
commit 20b5f3e546
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
6 changed files with 39 additions and 50 deletions

View file

@ -1 +0,0 @@
../template/Makefile

View file

@ -1,35 +0,0 @@
#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

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

View file

@ -1,12 +0,0 @@
#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,30 @@
def find_intersection(a, b)
a,b = b,a if a.min > b.min
return [a.max, b.max].min - b.min if a.max > b.min
0
end
# @param {Integer} ax1
# @param {Integer} ay1
# @param {Integer} ax2
# @param {Integer} ay2
# @param {Integer} bx1
# @param {Integer} by1
# @param {Integer} bx2
# @param {Integer} by2
# @return {Integer}
def compute_area(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2)
# Area of the first rectangle
a = (ax2 - ax1) * (ay2 - ay1)
# Area of the second rectangle
b = (bx2 - bx1) * (by2 - by1)
# Find intersection
x_intersection = find_intersection(ax1..ax2, bx1..bx2)
y_intersection = find_intersection(ay1..ay2, by1..by2)
a + b - x_intersection * y_intersection
end

View file

@ -0,0 +1,9 @@
require_relative 'main'
require 'test/unit'
class TestRectangleArea < Test::Unit::TestCase
def test_simple
assert_equal(45, compute_area(-3, 0, 3, 4, 0, -1, 9, 2))
assert_equal(16, compute_area(-2, -2, 2, 2, -2, -2, 2, 2))
end
end