Skip to content

Instantly share code, notes, and snippets.

@alienscience
Created April 26, 2019 14:09
Show Gist options
  • Save alienscience/d0689af8e79015838922892f3616dd40 to your computer and use it in GitHub Desktop.
Save alienscience/d0689af8e79015838922892f3616dd40 to your computer and use it in GitHub Desktop.
final case class Matrix(s: String) {
private val matrix = fromString3(s)
def row(r: Int): Vector[Int] = {
matrix(r)
}
def column(c: Int): Vector[Int] = {
matrix.map(_(c))
}
private def fromString(s: String): Vector[Vector[Int]] = {
val rowStrings = s.split("\n")
rowStrings.map { rowString =>
val numStrings = rowString.split(" ")
numStrings.map(_.toInt).toVector
}.toVector
}
private def fromString2(s: String): Vector[Vector[Int]] = {
for {
rowString <- s.split("\n").toVector
numStrings = rowString.split(" ").toVector
numVector = numStrings.map(_.toInt)
} yield numVector
}
private def fromString3(s: String): Vector[Vector[Int]] = {
splitWith("\n", splitWith(" ", _.toInt))(s)
}
private def splitWith[T](splitter: String, fn: String => T)(
s: String): Vector[T] = {
s.split(splitter)
.toVector
.map(fn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment