/* CS:2820 Object Oriented Software Development Spring 2015 The University of Iowa Instructor: Cesare Tinelli */ // Elaboration on the vector 'Vec' class seen in the discussion sections abstract class Vec { val length : Int def apply(i : Int) : Double def ++(other : Vec) : Vec def +(other : Vec) : Vec // General implementation of '*' using 'apply' def *(other : Vec) : Double = { var p = 0.0 for (i <- 0 to length - 1) p = p + this(i) * other(i) p } // General implementation of 'toString' using 'apply' override def toString : String = { var s = "<" + this(0) for (j <- 1 to length - 1) s = s + ", " + this(j) s + ">" } // General implementation of 'equals' using 'apply' override def equals(other : Any) : Boolean = // 'this' and 'other' are equal iff // 'other' is a 'Vec' and has exactly the same elements as 'this' other match { case o : Vec => if (o.length == length) return false for (j <- 0 to length - 1) if (this(j) != o(j)) return false true case _ => false } } class DenseVec protected (protected val elems : Array[Double]) extends Vec { val length = elems.length def this(d : Double) = this(Array(d)) def apply(i : Int) = elems(i) def ++(other : Vec) : Vec = { val r = new Array[Double](length + other.length) for (i <- 0 to length - 1) r(i) = this(i) for (i <- 0 to other.length - 1) r(length + i) = other(i) new DenseVec(r) } def +(other : Vec) : Vec = { require(other.length == length) val r = new Array[Double](length) for (i <- 0 to length - 1) r(i) = this(i) + other(i) new DenseVec(r) } } class SparseVec protected ( protected val elems : List[(Int, Double)], val length : Int ) extends Vec { private def startList(d : Double) = if (d == 0) Nil else List((0, d)) def this(d : Double) = this(if (d == 0) Nil else List((0, d)), 1) def apply(i : Int) : Double = { for ( (p, v) <- elems ) if (p == i) return v 0.0 } def ++(other : Vec) : Vec = { var e = elems for ( i <- 0 to other.length ) { val v = other(i) if (v != 0) e = (length + i, v) :: e } new SparseVec( e, length + other.length ) } def +(other : Vec) : Vec = { var e = List[(Int,Double)]() for ( i <- 0 to length - 1 ) { val s = this(i) + other(i) if ( s != 0 ) e = (i, s) :: e } new SparseVec( e , length ) } } // a few test examples /* val dv1 = new DenseVec(1) val dv2 = new DenseVec(3.4) val dv3 = new DenseVec(5.5) val dv4 = dv1 ++ dv2 ++ dv3 val dv5 = dv1 ++ dv1 ++ dv2 val dv6 = dv4 + dv5 val dv7 = dv4 * dv5 val sv1 = new SparseVec(1) val sv2 = new SparseVec(3.4) val sv3 = new SparseVec(5.5) val sv4 = sv1 ++ sv2 ++ sv3 val sv5 = sv1 ++ sv1 ++ sv2 val sv6 = sv4 + sv5 val sv7 = sv4 * sv5 val v1 = dv1 ++ sv2 val v2 = dv1 ++ sv2 ++ dv2 val v2 = dv1 + sv2 + dv2 */