Skip to content

Instantly share code, notes, and snippets.

@desbo
Created July 9, 2017 21:14
Show Gist options
  • Save desbo/3e095b2393901a3364fddf91bef323c3 to your computer and use it in GitHub Desktop.
Save desbo/3e095b2393901a3364fddf91bef323c3 to your computer and use it in GitHub Desktop.
random donations
import scala.util.Random
// http://www.decisionsciencenews.com/2017/06/19/counterintuitive-problem-everyone-room-keeps-giving-dollars-random-others-youll-never-guess-happens-next/
case class Person(var balance: Int) {
def receive(amount: Int): Unit = {
balance = balance + 1
}
def give(amount: Int, other: Person): Unit = {
if (balance > 0) {
other.receive(amount)
balance = balance - 1
}
}
override def toString: String = s"£$balance"
}
class World(population: Int, iterations: Int, startingBalance: Int, giftAmount: Int) {
val people: List[Person] = (1 to population).map(_ => Person(startingBalance)).toList
def run(): Unit = {
for {
i <- (1 to iterations)
person <- people
others = people diff List(person)
other = others(Random.nextInt(others.size))
} person.give(giftAmount, other)
}
override def toString: String = people.sortBy(_.balance).toString
}
object Main extends App {
val world = new World(
population = 100,
iterations = 10000,
startingBalance = 100,
giftAmount = 1
)
world.run()
println(world)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment