3 ms·
Its 50%. For 3 passengers the seating possibilities are {123,213,231,321}, so 3 gets to sit on seat 3 50% of the time. For 4 passengers the seating possibilit
by dxbydt 15y ago
Its 50%.
For 3 passengers the seating possibilities are
{123,213,231,321}, so 3 gets to sit on seat 3 50% of the time.
For 4 passengers the seating possibilities are
{1234,2134,2314,2341,2431,3241,3214,4231}, so 4 gets to sit on seat 4 50% of the time.
From there you can do a proof by induction.
If you like code:
----
import util.{Random=>rng}
import collection.mutable.ArrayBuffer
object passengers {
def main(args:Array[String]) = {
val n = args(0).toInt
val simulations = args(1).toInt
val happyLast = (1 to simulations).map(_=> {
val seats = ArrayBuffer.fill[Int](n+1)(0)
val taken = new ArrayBuffer[Int]
val all = (1 to n).toSeq
val seat = rng.shuffle(all).head
seats(seat) = 1
taken += seat
(2 to n).foreach( p=> {
val seat = seats(p) match {
case 0=> p
case x=> rng.shuffle(all.diff(taken)).head
}
seats(seat) = p
taken += seat
})
seats(n) == n
})
println( happyLast.filter(x=>x).size*1.0d/simulations )
}
}
-----
>scala -cp classes passengers 100 100000
>0.4997
- lgieron 15y agoMinor comment from a Scala fan - on that last line you could have used: happyLast.count(_ == true) instead of: happyLast.filter(x=>x).size
- graphene 15y agoshouldn't that be {123, 213, 312, 321}? ie 231 is not possible since after 1 randomly decides to sit at 3, 2 has no reason to go sit in seat 1. This doesn't change the answer to the problem though I think.
- dxbydt 15y agouh, nope. xyz => 1 sits on seat x, 2 on seat y, 3 on seat z So the only possibilities are: 123: 1 sits on seat 1, 2 on seat 2, 3 on seat 3 213: 1 sits on seat 2, 2 on seat 1, 3 on seat 3 231: 1 sits on seat 2, 2 on seat 3, 3 on seat 1 321: 1 sits on seat 3, 2 on seat 2, 3 on seat 1 passenger 3 is happy twice out of 4, hence 50% In the code, the happyLast variable counts the number of times the last passenger is happy ( happy == when he gets his assigned seat)
- graphene 15y agoah, right, I read it as xyz => seat 1 is occupied by passenger x, seat 2 by y and seat 3 by z