BAEL-2151
This commit is contained in:
myluckagain 2018-08-30 03:56:21 +05:00 committed by Predrag Maric
parent 2274e39392
commit 2a12e9abd4
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.linesintersection;
import java.awt.Point;
import java.util.Optional;
public class LinesIntersectionService {
public Optional<Point> calculateIntersectionPoint(float m1, float b1, float m2, float b2) {
if (m1 == m2) {
return Optional.empty();
}
float x = (b2 - b1) / (m1 - m2);
float y = m1 * x + b1;
Point point = new Point(Math.round(x), Math.round(y));
return Optional.of(point);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.linesintersection;
import java.awt.Point;
import java.util.Optional;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
public class LinesIntersectionServiceUnitTest {
private LinesIntersectionService service = new LinesIntersectionService();
@Test
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
float m1 = 0;
float b1 = 0;
float m2 = 1;
float b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertTrue(point.isPresent());
assertEquals(point.get().x, 1);
assertEquals(point.get().y, 0);
}
@Test
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
float m1 = 1;
float b1 = 0;
float m2 = 1;
float b2 = -1;
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
assertFalse(point.isPresent());
}
}