From 2a12e9abd42822c1b7a3ddf321b975fe68907f35 Mon Sep 17 00:00:00 2001 From: myluckagain Date: Thu, 30 Aug 2018 03:56:21 +0500 Subject: [PATCH] BAEL-2151 (#5087) BAEL-2151 --- .../LinesIntersectionService.java | 21 ++++++++++ .../LinesIntersectionServiceUnitTest.java | 40 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java create mode 100644 core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java b/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java new file mode 100644 index 0000000000..e4fed5a22e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linesintersection/LinesIntersectionService.java @@ -0,0 +1,21 @@ +package com.baeldung.linesintersection; + +import java.awt.Point; +import java.util.Optional; + +public class LinesIntersectionService { + + public Optional 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); + } +} diff --git a/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java b/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java new file mode 100644 index 0000000000..90c93fe050 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/linesintersection/LinesIntersectionServiceUnitTest.java @@ -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 = 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 = service.calculateIntersectionPoint(m1, b1, m2, b2); + + assertFalse(point.isPresent()); + } +}