🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉 # SergiiVlasiuk's solution

## to Saddle Points in the Scala Track

Published at Aug 25 2019 · 0 comments
Instructions
Test suite
Solution

Detect saddle points in a matrix.

So say you have a matrix like so:

``````    0  1  2
|---------
0 | 9  8  7
1 | 5  3  2     <--- saddle point at (1,0)
2 | 6  6  7
``````

It has a saddle point at (1, 0).

It's called a "saddle point" because it is greater than or equal to every element in its row and less than or equal to every element in its column.

A matrix may have zero or more saddle points.

Your code should be able to provide the (possibly empty) list of all the saddle points for any given matrix.

Note that you may find other definitions of matrix saddle points online, but the tests for this exercise follow the above unambiguous definition.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

For more detailed info about the Scala track see the help page.

## Source

J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

``````import org.scalatest.{Matchers, FunSuite}

/** @version 1.1.0 */
class SaddlePointsTest extends FunSuite with Matchers {

test("Can identify single saddle point") {
Matrix(List(List(9, 8, 7), List(5, 3, 2), List(6, 6, 7))).saddlePoints should be(
Set((1, 0)))
}

test("Can identify that empty matrix has no saddle points") {
pending
}

test("Can identify lack of saddle points when there are none") {
pending
Matrix(List(List(1, 2, 3), List(3, 1, 2), List(2, 3, 1))).saddlePoints should be(
Set())
}

test("Can identify multiple saddle points") {
pending
Matrix(List(List(4, 5, 4), List(3, 5, 5), List(1, 5, 4))).saddlePoints should be(
Set((0, 1), (1, 1), (2, 1)))
}

test("Can identify saddle point in bottom right corner") {
pending
Matrix(List(List(8, 7, 9), List(6, 7, 6), List(3, 2, 5))).saddlePoints should be(
Set((2, 2)))
}
}``````
``````case class Matrix(list: List[List[Int]]) {
val saddlePoints: Set[(Int, Int)] = (for {
row <- list.indices
transposed = list.transpose
if list(row).max == list(row)(col) && transposed(col).min == list(row)(col)
} yield (row, col)).toSet
}``````