Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.82 KB | None | 0 0
  1. package ru.jcorp.coins
  2.  
  3. import java.util.Date
  4. import collection.Set
  5. import collection.mutable
  6.  
  7. object Runner {
  8.  
  9.   class CoinsCounter(components: Set[Int]) {
  10.     val cache: mutable.Map[Int, Set[Map[Int, Int]]] = mutable.Map()
  11.     var cacheLimit = 0
  12.  
  13.     def add(map: Map[Int, Int], i: Int): Map[Int, Int] = {
  14.       val option = map.get(i)
  15.       map + (i -> (if (None == option) 1 else option.get + 1))
  16.     }
  17.  
  18.     def decompose(value: Int) : Set[Map[Int, Int]] = value match {
  19.       case 0 => Set(Map[Int, Int]())
  20.       case t if (t < 0) => Set()
  21.       case t if (cache.contains(t)) => cache(value)
  22.       case _ => {
  23.  
  24.         def getVariants(subtracted: Int): Set[Map[Int, Int]] = {
  25.           val remain: Int = value - subtracted
  26.           val variants: Set[Map[Int, Int]] = decompose(remain)
  27.           if ((variants.size > 0) && ((cacheLimit > cache.size) || (cacheLimit <= 0)))
  28.             cache.put(remain, variants)
  29.           val result: Set[Map[Int, Int]] = variants.map(variant => add(variant, subtracted))
  30.           result
  31.         }
  32.  
  33.         val variants: Set[Set[Map[Int, Int]]] = components.map(component => getVariants(component))
  34.         ((Set[Map[Int, Int]]() /: variants)(_ ++ _))
  35.       }
  36.     }
  37.  
  38.     def setCacheLimit(value : Int) = {
  39.       cacheLimit = value
  40.       this
  41.     }
  42.  
  43.     def getCacheLimit = cacheLimit
  44.   }
  45.  
  46.   def main(args: Array[String]) {
  47.  
  48.     print("Sum: ")
  49.     val sum = readInt()
  50.  
  51.     print("Coins: ")
  52.     var coins = Set[Int]()
  53.     readLine().split(' ').foreach( f => { coins += f.toInt } )
  54.     println()
  55.  
  56.     val now = new Date()
  57.     val counts = new CoinsCounter(coins).setCacheLimit(720).decompose(sum)
  58.     println("Time: " + (new Date().getTime - now.getTime) + " ms")
  59.     println()
  60.  
  61.     for {variant <- counts} {
  62.       print(variant)
  63.       println()
  64.     }
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement