Created
July 9, 2017 21:14
-
-
Save desbo/3e095b2393901a3364fddf91bef323c3 to your computer and use it in GitHub Desktop.
random donations
This file contains hidden or 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
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