Created
April 24, 2012 21:50
-
-
Save salzig/2484145 to your computer and use it in GitHub Desktop.
Scala Aufgabe 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package aufgabe5 | |
class Matrix[T](val xDim:Int, val yDim:Int, protected val data:Array[T])(implicit num : Numeric[T], m : Manifest[T]) { | |
val numeric = num | |
val manifest = m | |
def apply(x:Int, y:Int):T = | |
if (x < 0 || x >= xDim || y < 0 || y >= yDim) | |
numeric.zero | |
else | |
data(x+xDim*y) | |
def +(other:Matrix[T])= { | |
require (xDim == other.xDim && yDim == other.yDim) | |
new Matrix(xDim, yDim, data.zip(other.data).map((p) => num.plus(p._1,p._2))) | |
} | |
def -(other:Matrix[T])= { | |
require (xDim == other.xDim && yDim == other.yDim) | |
new Matrix(xDim, yDim, data.zip(other.data).map((p) => num.plus(p._1,p._2))) | |
} | |
override def toString = | |
"Matrix[%s](%s)" format (manifest, data.grouped(xDim).map( "(%s)" format _.mkString(", ") ).mkString(", ")) | |
} | |
object Matrix { | |
// Matrix(dim, *values) | |
def apply[T](dim:Int)(values:T*)(implicit num : Numeric[T], m : Manifest[T]) = | |
new Matrix(dim, dim, values.toIndexedSeq.padTo(dim*dim, num.zero).toArray) // true? | |
// Matrix(dim, func) | |
def apply[T](dim:Int, func:(Int,Int)=>T)(implicit num : Numeric[T], m : Manifest[T]):Matrix[T] = | |
new Matrix(dim, dim, Array.tabulate(dim,dim)(func).flatten) | |
// Matrix( array(array()) ) | |
def apply[T](values:Array[Array[T]])(implicit num : Numeric[T], m : Manifest[T]):Matrix[T]= | |
new Matrix(values.size, values.size, values.flatten) | |
} | |
// go out of my way | |
object Application { | |
def main(args:Array[String]) { | |
val mat01 = new Matrix(2,2,Array(1,2,3,4)) | |
val mat02 = new Matrix(2,2,Array(4,3,2,1)) | |
println(mat01) | |
println(mat02) | |
// println(Matrix(1)(true)) // <- compiliert nich | |
println(Matrix(3)(1, 2, 3)) | |
println(Matrix(3)(1.0, 2, 3)) | |
println(Matrix(2)(BigDecimal(2))) | |
println() | |
val mat1 = Matrix(5, (x, y) => if (x == y) 1 else 0) | |
val mat2 = Matrix(Array(Array(3, 2, 1), Array(0, 1, 0), Array(0, 0, 3))) | |
val mat3 = Matrix(1)(1.01) | |
println(mat1) | |
println(mat2) | |
println(mat3) | |
println() | |
println(mat1(0, 0)) | |
println(mat1(4, 0)) | |
println(mat1(4, 4)) | |
println(mat1(5, 5)) | |
println() | |
println(mat1 + mat1) | |
println(Matrix(3)(1, 2, 3) + mat2) | |
println(Matrix(3)(1, 2, 3) + mat2 + Matrix(3, (i, j) => i + j)) | |
println(mat3 + Matrix(1)(0)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment