Skip to content

Instantly share code, notes, and snippets.

@tong92
Last active June 5, 2020 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tong92/02ae40970ad0615cf3879d35ee7e5fab to your computer and use it in GitHub Desktop.
Save tong92/02ae40970ad0615cf3879d35ee7e5fab to your computer and use it in GitHub Desktop.
ch1.scala
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