Skip to content

Instantly share code, notes, and snippets.

@kubukoz
Last active December 18, 2015 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubukoz/f21e1cacfccfe983def0 to your computer and use it in GitHub Desktop.
Save kubukoz/f21e1cacfccfe983def0 to your computer and use it in GitHub Desktop.
package com.kubukoz.polskibus.domain
import scala.language.postfixOps
case class Matrix[T](data: List[T]*)(implicit ev1: Numeric[T]) {
final lazy val valid = {
require(data.forall(s => s.size == data.head.size), "All rows must have the same column amount")
true
}
import ev1._
val rows = data.size
val columns = data.head.size
def *(b: Matrix[T]): Option[Matrix[T]] = columns == b.rows match {
case true if valid && b.valid => Some(Matrix(data.indices map { i =>
b.data.head.indices map { j =>
(data.head.indices map { k =>
data(i)(k) * b.data(k)(j)
}) sum
} toList
}: _*))
case _ => None
}
override def toString: String = {
valid
data.map(_.mkString(" | ")).mkString("\n")
}
def x(another: Matrix[T]) = (rows == another.rows, columns == another.columns) match {
case (true, true) if valid && another.valid =>
Some(
Matrix(
data.indices.map { i =>
data(i).indices.map { j =>
data(i)(j) * another.data(i)(j)
} toList
}: _*
)
)
case _ => None
}
def \(another: T) = {
Matrix(data.init.toList ::: List(data.last ::: List(another)): _*)(ev1)
}
def \\(another: T) = {
Matrix(data.toList ::: List(List(another)): _*)(ev1)
}
}
object MatrixMultiplication {
def main(args: Array[String]) {
implicit def numericToMatrix[T](i: T)(implicit ev1: Numeric[T]): Matrix[T] = Matrix(i :: Nil)
val a =
1 \ 2 \\
2 \ 3
val b =
2 \ 3 \\
3 \ 4
println(a * b contains (
8 \ 11 \\
13 \ 18
))
println(a x b contains (
2 \ 6 \\
6 \ 12
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment