Last active
June 5, 2020 12:18
-
-
Save tong92/02ae40970ad0615cf3879d35ee7e5fab to your computer and use it in GitHub Desktop.
ch1.scala
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
case class Container(amount: Double = 0.0, connects: Set[Int] = Set()) { | |
def getAmount: Double = amount | |
def addWater(water: Double): Container = copy(amount = water + amount) | |
} | |
case class ContainerWorld(containers: List[Container] = Nil) { | |
def addWater(index: Int, water: Double): ContainerWorld = { | |
ContainerWorld(containers.updated(index, containers(index).addWater(water))) | |
} | |
def connect(a: Int, b: Int): ContainerWorld = { | |
val containerA = containers(a) | |
val containerB = containers(b) | |
if (containerA == containerB) { | |
return this | |
} | |
val newAmount = containerA.amount * containerA.connects.size + containerB.amount * containerB.connects.size | |
val newConnects = containerA.connects ++ containerB.connects | |
val newContainer = Container(newAmount / newConnects.size, newConnects) | |
ContainerWorld(containers.map { container => | |
if (container == containerA || container == containerB) { | |
newContainer | |
} else { | |
container | |
} | |
}) | |
} | |
def newContainer(): ContainerWorld = { | |
ContainerWorld(containers :+ Container(0, Set(containers.size))) | |
} | |
} | |
object Main extends App { | |
var world = ContainerWorld() | |
world = world.newContainer().newContainer().newContainer().newContainer() | |
println(world) | |
world = world.addWater(0, 12).addWater(1, 8).addWater(3, 3) | |
println(world) | |
world = world.connect(0, 1) | |
println(world) | |
world = world.connect(0, 1) | |
println(world) | |
world = world.connect(2, 1) | |
println(world) | |
world = world.connect(0, 3) | |
println(world) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment