Created
June 5, 2020 12:33
-
-
Save eugene70/d058c246f72660c54230fa8a8b5d7751 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ch2 | |
case class Container(group: Set[Char], x: Double) | |
object Container { | |
def apply(key: Char): Container = Container(Set(key), 0) | |
} | |
case class World(containers: Map[Char, Container]) { | |
def getAmount(key: Char): Double = containers(key).x | |
def addWater(key: Char, amount: Double): World = { | |
val container = containers(key) | |
val y = amount / container.group.size | |
World(container.group.foldLeft(containers) { case (containers, memberKey) => | |
val container1 = containers(memberKey) | |
containers.updated(memberKey, container1.copy(x = container1.x + y)) | |
}) | |
} | |
def connectTo(key1: Char, key2: Char): World = { | |
val container1 = containers(key1) | |
val container2 = containers(key2) | |
val group1 = container1.group ++ container2.group | |
val z = (container1.x * container1.group.size + container2.x * container2.group.size) / group1.size | |
World(group1.foldLeft(containers){ case (containers, memberKey) => | |
val container1 = containers(memberKey) | |
containers.updated(memberKey, container1.copy(group = group1, x = z)) | |
}) | |
} | |
override def toString: String = containers.keys.toList.sorted.map(getAmount).mkString(" ") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ch2 | |
object UseCase { | |
def main(args: Array[String]): Unit = { | |
val world = World(Map( | |
'a' -> Container('a'), | |
'b' -> Container('b'), | |
'c' -> Container('c'), | |
'd' -> Container('d'), | |
)) | |
val world1 = world | |
.addWater('a', 12) | |
.addWater('d', 8) | |
.connectTo('a', 'b') | |
println(world1) | |
val world2 = world1.connectTo('b', 'c') | |
println(world2) | |
val world3 = world2.connectTo('b', 'd') | |
println(world3) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment