How to calculate the center of a rectangle in Scala

1 Answer

0 votes
object RectangleCenter {

  case class Point(x: Double, y: Double)

  case class Rectangle(topLeft: Point, bottomRight: Point)

  def getCenter(rect: Rectangle): Point = {
    val centerX = (rect.topLeft.x + rect.bottomRight.x) / 2.0
    val centerY = (rect.topLeft.y + rect.bottomRight.y) / 2.0
    
    Point(centerX, centerY)
  }

  def main(args: Array[String]): Unit = {
    val rect = Rectangle(Point(10.0, 20.0), Point(110.0, 70.0))
    val center = getCenter(rect)
    
    println(f"Center of the rectangle: (${center.x}%.2f, ${center.y}%.2f)")
  }
}


 
/*
run:

Center of the rectangle: (60.00, 45.00)

*/

 



answered Jun 23, 2025 by avibootz

Related questions

1 answer 112 views
1 answer 107 views
1 answer 89 views
1 answer 82 views
2 answers 109 views
...