reset password
Author Message
rabbott
Posts: 1649
Posted 20:36 Feb 11, 2014 |

Thanks again to Amata for send me my files!

Regarding the SpaceShip race problem, which we talked about Monday, I like the insight underlying Sherry's solution. It isn't necessary to propagate the SpaceShips; all one needs are the times when the passings occur. Rather than look through all the times, though, one can just look at the pairs of SpaceShips that will pass each other and compute the times of passings.

def race(ships: Vector[(Int, Int)]): Seq[(Double, Int, Int)] = {
    val spaceShips =  ships.zipWithIndex.map { case ( (pos, vel), id) => (id + 1, pos, vel) }
    val passings =
      for {
        ship_1_Index <- (0 until spaceShips.length - 1)
        (id1, pos1, vel1) = spaceShips(ship_1_Index)
        ship_2_Index <- (ship_1_Index + 1 until spaceShips.length).toVector
        (id2, pos2, vel2) = spaceShips(ship_2_Index)
        if (vel1 > vel2)    // Ship 1 must be going faster than ship 2 or it won't pass.
        passingInstant = ((pos2 - pos1):Double) / (vel1 - vel2)
      } yield (passingInstant, id1, id2)
      passings.sortBy { _._1 }  // Order the passings by when they occur
  }

One of the things that I like about this solution is that it took multiple minds. This also uses Jeff's trick to zipWithIndex and than increment the index to get the ship id.

 

Last edited by rabbott at 20:54 Feb 11, 2014.