Last active
June 5, 2020 12:16
-
-
Save eugene70/392ed77fde811391cf15724b20f410f6 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 ch1 | |
case class Container(group: Set[Char], n: Int, x: Double) | |
object Container { | |
def apply(key: Char): Container = Container(Set(key), 1, 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.n | |
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 n1 = container1.n + container2.n | |
val z = (container1.x * container1.n + container2.x * container2.n) / n1 | |
val group1 = container1.group ++ container2.group | |
World(group1.foldLeft(containers){ case (containers, memberKey) => | |
val container1 = containers(memberKey) | |
containers.updated(memberKey, container1.copy(group = group1, n = n1, 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 ch1 | |
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