Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to sum the corners of a matrix in Scala

2 Answers

0 votes
object MatrixCorners {

  /**
   * Returns the sum of the four corner elements of a matrix.
   *
   * Example matrix:
   *
   * 1  2  3  4
   * 5  6  7  8
   * 9 10 11 12
   *
   * Corners:
   * 1  (top-left)
   * 4  (top-right)
   * 9  (bottom-left)
   * 12 (bottom-right)
   *
   * Sum = 1 + 4 + 9 + 12 = 26
   */
  def sumCorners(matrix: Array[Array[Int]]): Int = {
    // Return 0 if the matrix is empty.
    if (matrix.isEmpty || matrix(0).isEmpty) {
      return 0
    }

    val rows = matrix.length
    val cols = matrix(0).length

    // Add the four corner elements.
    matrix(0)(0) +
    matrix(0)(cols - 1) +
    matrix(rows - 1)(0) +
    matrix(rows - 1)(cols - 1)
  }

  def main(args: Array[String]): Unit = {
    val matrix = Array(
      Array(1, 2, 3, 4),
      Array(5, 6, 7, 8),
      Array(9, 10, 11, 12)
    )

    println(s"Sum of corners: ${sumCorners(matrix)}")
  }
}


/*
run:

Sum of corners: 26

*/

 



answered 4 days ago by avibootz
0 votes
object MatrixCorners {

  /**
   * Returns the sum of the four corner elements of a matrix.
   *
   * Example matrix:
   *
   * 1  2  3  4
   * 5  6  7  8
   * 9 10 11 12
   *
   * Corners:
   * 1  (top-left)
   * 4  (top-right)
   * 9  (bottom-left)
   * 12 (bottom-right)
   *
   * Sum = 1 + 4 + 9 + 12 = 26
   */
def sumCorners(matrix: Array[Array[Int]]): Int = {
  if (matrix.isEmpty || matrix(0).isEmpty) {
    return 0
  }

  val rows = matrix.length
  val cols = matrix(0).length

  // Store the coordinates of the corners.
  val corners = Set(
    (0, 0),
    (0, cols - 1),
    (rows - 1, 0),
    (rows - 1, cols - 1)
  )

  // Sum the values at the unique corner positions.
  corners.map { case (r, c) => matrix(r)(c) }.sum
}

  def main(args: Array[String]): Unit = {
    val matrix = Array(
      Array(1, 2, 3, 4),
      Array(5, 6, 7, 8),
      Array(9, 10, 11, 12)
    )

    println(s"Sum of corners: ${sumCorners(matrix)}")
  }
}


/*
run:

Sum of corners: 26

*/

 



answered 4 days ago by avibootz
...