2014-01-09 2 views
0

그래서 저는 스칼라를 배웠고 배열을 기반으로 벡터 클래스를 만들고 2 개의 벡터를 더하기 위해 더하기와 빼기 연산자를 만들려고했습니다. 이것이 내가 지금까지 한 일이다. 누구든지 다른 길이의 벡터에 추가 할 때 더 짧은 길이의 배열에 "0"을 추가하여 더 긴 길이의 벡터와 길이가 같도록 만드는 방법을 알아낼 수 있습니까? 마찬가지로 (1, 2, 3)(1, 2)이 같은 (2, 4, 3)스칼라에 배열 요소 추가

class Wektor(private val s: Array[Double]){ 
     class LengthNotEqualException(msg:String) extends Exception(msg) 
     def get(index: Int):Double= s(index) 
     def +(that: Wektor):Wektor= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
      { 
      val temp= new Array[Double](this.s.length) 
      var i:Int= 0 
       for(i <- 0 until this.s.length) 
      { 
       temp(i)= this.s(i) + that.get(i) 
      } 
      new Wektor(temp) // zwraca nowy Wektor będący sumą danych wektorów 
      } 
     def -(that: Wektor):Wektor= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
      { 
      val temp= new Array[Double](this.s.length) 
      var i= 0 
       for(i <- 0 until this.s.length) 
      { 
       temp(i)= this.s(i) - that.get(i) 
      } 
      new Wektor(temp) // zwraca nowy Wektor będący różnicą danych wektorów 
      } 
     def *+(that:Wektor):Double= 
      if(this.s.length != that.s.length) 
        throw new LengthNotEqualException("Wektory roznej dlugosci") 
      else 
       { 
        var result:Double= 0 
        var i:Int = 0 
        for(i <- 0 until this.s.length) 
        { 
       result= result + this.s(i) * that.get(i) 
        } 
        result  // zwracany iloczyn skalarny 
       } 
     override def toString():String={ 
      var result:String="Wektor: [" 
      var i:Int= 0 
      for(i <- 0 until this.s.length) 
      { 
        result= result + this.s(i) + " " 
      } 
      result = result + "]" 
      result  // zwracana wartosc 
     } 
} 

val test= new Wektor(Array[Double](1, 2, 3,5)) 
val test2= new Wektor(Array[Double](2, 2, 2)) 
val suma= test + test2 
val roznica= test - test2 
val iloczyn= test *+ test2 
println(suma) 
println(roznica) 
println(iloczyn) 

답변

4

사용 zipAll를 반환해야합니다 추가

case class Wektor(inner: IndexedSeq[Double]) { 
    def +(that: Wektor) = 
    Wektor(this.inner.zipAll(that.inner, 0.0, 0.0).map{case (a, b) => a+b}) 
    def -(that: Wektor) = 
    Wektor(this.inner.zipAll(that.inner, 0.0, 0.0).map{case (a, b) => a-b}) 
    def *+(that: Wektor) = 
    this.inner.zipAll(that.inner, 1.0, 1.0).map{case (a, b) => a*b}.sum 

    override def toString() = inner.mkString("Wektor: [", " ", "]") 
} 

val a = Wektor((1 to 5).map{_.toDouble}) 
// Wektor: [1.0 2.0 3.0 4.0 5.0] 
val b = Wektor((1 to 3).map{_.toDouble}) 
// Wektor: [1.0 2.0 3.0] 

a + b 
// Wektor: [2.0 4.0 6.0 4.0 5.0] 

a - b 
// Wektor: [0.0 0.0 0.0 4.0 5.0] 

a *+ b 
// 23.0 
+0

니스, 난 그런 방법은 존재 몰랐다. 심지어 C#'IEnumerable '확장에 추가했습니다. –