Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.65 KB | None | 0 0
  1. /**
  2.   * Created by Roman on 18.03.17.
  3.   */
  4. class Binary private (n: Int, l:List[Int]) {
  5.     private val container: List[Int] = if (l == Nil) this.construct(List[Int](), n) else l
  6.  
  7.     private val sum:(List[Int], List[Int], List[Int], Int) => List[Int] = {
  8.         case (Nil, Nil, res, 0) => res
  9.         case (Nil, Nil, res, r) => r%2::res
  10.         case (x::a, Nil, res, r) => sum(a, Nil, (x+r)%2::res, (x+r)/2)
  11.         case (Nil, x::b, res, r) => sum(Nil, b, (x+r)%2::res, (x+r)/2)
  12.         case (x1::a, x2::b, res, r) => sum(a, b, (x1+x2+r)%2::res, (x1+x2+r)/2)
  13.     }
  14.  
  15.     private def construct(l:List[Int], n:Int): List[Int] = (l, n) match {
  16.         case (_, 0) => l
  17.         case (l:List[Int], n:Int) => construct((n & 1)::l, n >> 1)
  18.     }
  19.  
  20.     private def this(container:List[Int]) = {
  21.         this(0, container)
  22.     }
  23.  
  24.     def this(n:Int) = {
  25.         this(n, Nil)
  26.     }
  27.  
  28.     def + (o: Binary): Binary = {
  29.         new Binary(this.sum(this.container.reverse, o.container.reverse, List[Int](), 0))
  30.     }
  31.  
  32.     def << (n: Int): Binary = {
  33.         new Binary(this.container:::List.fill(n)(0))
  34.     }
  35.  
  36.     def * (o: Binary): Binary = {
  37.         this.container.reverse.zipWithIndex.foldLeft(new Binary(0)) { (prod:Binary, z:(Int, Int)) => {
  38.             if (z._1 == 1) prod + (o << z._2) else prod
  39.         }}
  40.     }
  41.  
  42.     def intValue:Int = {
  43.         this.container.reverse.zipWithIndex.foldLeft(0) { (s:Int, z:(Int, Int)) => s + (z._1 * (1 << z._2))}
  44.     }
  45. }
  46.  
  47.  
  48. object Main {
  49.     def main(args: Array[String]): Unit = {
  50.         val a = new Binary(12)
  51.         val b = new Binary(12)
  52.         val c = a * b
  53.         print(c.intValue)
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement