Advertisement
Guest User

Scala Stuff

a guest
Mar 18th, 2014
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.60 KB | None | 0 0
  1. case class Capacity(cores: Int, ram: Int, bandWidth: Int) {
  2.   def +(other: Capacity) = Capacity(cores + other.cores, ram + other.ram, bandWidth + other.bandWidth)
  3.   def -(other: Capacity) = Capacity(cores - other.cores, ram - other.ram, bandWidth - other.bandWidth)
  4.   def >=(other: Capacity) = cores >= other.cores && ram >= other.ram && bandWidth >= other.bandWidth
  5. }
  6.  
  7. case class PhysicalServer(capacity: Capacity)
  8. case class VirtualServer(demand: Capacity)
  9.  
  10. case class ServerMapping(physicalServer: PhysicalServer, virtualServers: List[VirtualServer]) {
  11.   val remainingCapacity = physicalServer.capacity - virtualServers
  12.     .foldLeft(Capacity(0, 0, 0))((sum, next) => sum + next.demand)
  13.   def :+(vServer: VirtualServer) = ServerMapping(physicalServer, virtualServers :+ vServer)
  14. }
  15.  
  16. object FirstFit {
  17.   def apply(serverSpec: PhysicalServer, vServers: List[VirtualServer]): List[ServerMapping] = {
  18.     vServers.foldLeft(Nil: List[ServerMapping]) { (currentMappings, vServer) =>
  19.       // check current mappings, else add new
  20.       currentMappings.view.zipWithIndex.find(_._1.remainingCapacity >= vServer.demand)
  21.         .map(mapping => currentMappings.updated(mapping._2, mapping._1 :+ vServer))
  22.         .getOrElse(currentMappings :+ ServerMapping(serverSpec, List(vServer)))
  23.     }
  24.   }
  25. }
  26.  
  27. object ServerMapperApp extends App {
  28.   val virtualServers = List(
  29.     VirtualServer(Capacity(2, 3, 2)),
  30.     VirtualServer(Capacity(2, 4, 2)),
  31.     VirtualServer(Capacity(2, 3, 2))
  32.   )
  33.   val physicalServerSpec = PhysicalServer(Capacity(4, 6, 4))
  34.  
  35.   FirstFit(physicalServerSpec, virtualServers)
  36.     .foreach(println)
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement