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.
J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html
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
Matrix(List(List())).saddlePoints should be(Set())
}
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
col <- list.head.indices
transposed = list.transpose
if list(row).max == list(row)(col) && transposed(col).min == list(row)(col)
} yield (row, col)).toSet
}
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,449 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments