Skip to content

Commit 2a12e9a

Browse files
myluckagainpedja4
authored andcommitted
BAEL-2151 (eugenp#5087)
BAEL-2151
1 parent 2274e39 commit 2a12e9a

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.linesintersection;
2+
3+
import java.awt.Point;
4+
import java.util.Optional;
5+
6+
public class LinesIntersectionService {
7+
8+
public Optional<Point> calculateIntersectionPoint(float m1, float b1, float m2, float b2) {
9+
10+
if (m1 == m2) {
11+
return Optional.empty();
12+
}
13+
14+
float x = (b2 - b1) / (m1 - m2);
15+
float y = m1 * x + b1;
16+
17+
Point point = new Point(Math.round(x), Math.round(y));
18+
19+
return Optional.of(point);
20+
}
21+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.baeldung.linesintersection;
2+
3+
import java.awt.Point;
4+
import java.util.Optional;
5+
6+
import org.junit.Test;
7+
import static org.junit.Assert.assertTrue;
8+
import static org.junit.Assert.assertFalse;
9+
import static org.junit.Assert.assertEquals;
10+
11+
public class LinesIntersectionServiceUnitTest {
12+
private LinesIntersectionService service = new LinesIntersectionService();
13+
14+
@Test
15+
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
16+
17+
float m1 = 0;
18+
float b1 = 0;
19+
float m2 = 1;
20+
float b2 = -1;
21+
22+
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
23+
24+
assertTrue(point.isPresent());
25+
assertEquals(point.get().x, 1);
26+
assertEquals(point.get().y, 0);
27+
}
28+
29+
@Test
30+
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
31+
float m1 = 1;
32+
float b1 = 0;
33+
float m2 = 1;
34+
float b2 = -1;
35+
36+
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
37+
38+
assertFalse(point.isPresent());
39+
}
40+
}

0 commit comments

Comments
 (0)