Find the intersection of two lines: Difference between revisions

Content deleted Content added
No edit summary
Scala solution added
Line 760: Line 760:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C#}}
{{trans|C#}}
<lang scala>// version 1.1.2
<lang kotlin>// version 1.1.2


class PointF(val x: Float, val y: Float) {
class PointF(val x: Float, val y: Float) {
Line 1,185: Line 1,185:
</lang>
</lang>
{{out}}
{{out}}
<pre>Line y = 5.0x + -20.0 intersects line y = 0.4x + 3.0 at #<struct Point x=5.0, y=5.0>.
<pre>Line y = 5.0x + -20.0 intersects line y = 0.4x + 3.0 at #<struct Point x=5.0, y=5.0>.</pre></lang>
=={{header|Scala}}==
</pre>
<lang Scala>object Intersection extends App {
val (l1, l2) = (LineF(PointF(4, 0), PointF(6, 10)), LineF(PointF(0, 3), PointF(10, 7)))


def findIntersection(l1: LineF, l2: LineF): PointF = {
val a1 = l1.e.y - l1.s.y
val b1 = l1.s.x - l1.e.x
val c1 = a1 * l1.s.x + b1 * l1.s.y

val a2 = l2.e.y - l2.s.y
val b2 = l2.s.x - l2.e.x
val c2 = a2 * l2.s.x + b2 * l2.s.y

val delta = a1 * b2 - a2 * b1
// If lines are parallel, intersection point will contain infinite values
PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
}

def l01 = LineF(PointF(0f, 0f), PointF(1f, 1f))
def l02 = LineF(PointF(1f, 2f), PointF(4f, 5f))

case class PointF(x: Float, y: Float) {
override def toString = s"{$x, $y}"
}

case class LineF(s: PointF, e: PointF)

println(findIntersection(l1, l2))
println(findIntersection(l01, l02))

}</lang>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/DAqMtEx/0 (JavaScript)]
or by [https://scastie.scala-lang.org/WQOqakOlQnaBRFBa1PuRYw Scastie (JVM)].
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl 6}}
{{trans|Perl 6}}