|
| 1 | +package ScalaPlayground.Lift |
| 2 | + |
| 3 | +// https://www.codewars.com/kata/58905bfa1decb981da00009e |
| 4 | + |
| 5 | +import ScalaPlayground.Lift.Direction.{Down, Up} |
| 6 | + |
| 7 | +import scala.collection.immutable.ListMap |
| 8 | +import scala.collection.mutable |
| 9 | + |
| 10 | +type Floor = Int |
| 11 | +enum Direction { case Up, Down } |
| 12 | + |
| 13 | +case class Person(position: Floor, destination: Floor) { |
| 14 | + require(position != destination, "source and destination floor cannot be the same") |
| 15 | + |
| 16 | + val desiredDirection: Direction = (position, destination) match |
| 17 | + case _ if destination > position => Up |
| 18 | + case _ if destination < position => Down |
| 19 | + |
| 20 | + def matchesDirection(lift: Lift): Boolean = desiredDirection == lift.direction |
| 21 | + def isBelow(lift: Lift): Boolean = position < lift.position |
| 22 | + def isAbove(lift: Lift): Boolean = position > lift.position |
| 23 | +} |
| 24 | + |
| 25 | +case class Lift( |
| 26 | + var position: Floor, |
| 27 | + var direction: Direction, |
| 28 | + people: mutable.Queue[Person], |
| 29 | + capacity: Int |
| 30 | +) { |
| 31 | + private def isFull: Boolean = people.size == capacity |
| 32 | + def hasRoom: Boolean = !isFull |
| 33 | + def hasPeople: Boolean = people.nonEmpty |
| 34 | + def isEmpty: Boolean = people.isEmpty |
| 35 | + def accepts(person: Person): Boolean = hasRoom && person.desiredDirection == direction |
| 36 | + |
| 37 | + def nearestPassengerTarget: Option[Floor] = |
| 38 | + people.filter(_.matchesDirection(this)).map(_.destination).minByOption(floor => Math.abs(floor - position)) |
| 39 | + |
| 40 | + def turn(): Unit = direction = direction match |
| 41 | + case Up => Down |
| 42 | + case Down => Up |
| 43 | +} |
| 44 | + |
| 45 | +case class Building(floors: ListMap[Floor, mutable.Queue[Person]]) { |
| 46 | + def isEmpty: Boolean = floors.values.forall(_.isEmpty) |
| 47 | + def hasPeople: Boolean = !isEmpty |
| 48 | + |
| 49 | + private def peopleGoing(direction: Direction): List[Person] = |
| 50 | + floors.values.flatMap(queue => queue.filter(_.desiredDirection == direction)).toList |
| 51 | + |
| 52 | + def lowestFloorGoingUp(lift: Lift): Option[Floor] = |
| 53 | + peopleGoing(Up).filter(_.isBelow(lift)).map(_.position).minOption |
| 54 | + |
| 55 | + def highestFloorGoingDown(lift: Lift): Option[Floor] = |
| 56 | + peopleGoing(Down).filter(_.isAbove(lift)).map(_.position).maxOption |
| 57 | + |
| 58 | + def nearestRequestInSameDirection(lift: Lift): Option[Floor] = |
| 59 | + lift.direction match |
| 60 | + case Up => peopleGoing(Up).filter(_.isAbove(lift)).map(_.position).minOption |
| 61 | + case Down => peopleGoing(Down).filter(_.isBelow(lift)).map(_.position).maxOption |
| 62 | +} |
| 63 | + |
| 64 | +case class State(building: Building, lift: Lift, stops: mutable.ListBuffer[Floor]) { |
| 65 | + def toPrintable: String = { |
| 66 | + val sb = new StringBuilder() |
| 67 | + |
| 68 | + sb.append(s"${stops.length} stops: ${stops.mkString(", ")}\n") |
| 69 | + |
| 70 | + building.floors.toSeq.reverse.foreach { case (floor, queue) => |
| 71 | + sb.append(s"| $floor | ${queue.reverse.map(_.destination).mkString(", ").padTo(20, ' ')} |") |
| 72 | + |
| 73 | + // draw the lift if it is on the current level |
| 74 | + if lift.position == floor |
| 75 | + then sb.append(s" | ${lift.people.map(_.destination).mkString(", ").padTo(15, ' ')} |") |
| 76 | + |
| 77 | + sb.append('\n') |
| 78 | + } |
| 79 | + |
| 80 | + sb.toString() |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +// Excuse the name. Dinglemouse.theLift() is how the function is called in the Codewars test suite |
| 85 | +object Dinglemouse { |
| 86 | + def theLift(queues: Array[Array[Int]], capacity: Int): Array[Int] = { |
| 87 | + val floors: ListMap[Int, mutable.Queue[Person]] = |
| 88 | + queues.zipWithIndex |
| 89 | + .map { case (queue, index) => |
| 90 | + (index, queue.map(destination => Person(position = index, destination = destination)).to(mutable.Queue)) |
| 91 | + } |
| 92 | + .to(ListMap) |
| 93 | + |
| 94 | + val lift = Lift(position = 0, Direction.Up, people = mutable.Queue.empty, capacity) |
| 95 | + val building = Building(floors) |
| 96 | + |
| 97 | + val initialState = State(building = building, lift = lift, stops = mutable.ListBuffer.empty) |
| 98 | + val finalState = LiftLogic.simulate(initialState) |
| 99 | + |
| 100 | + finalState.stops.toArray |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +object LiftLogic { |
| 105 | + def simulate(initialState: State): State = { |
| 106 | + var state = initialState |
| 107 | + |
| 108 | + state.stops += state.lift.position // register initial position as the first stop |
| 109 | + println(state.toPrintable) // draw the initial state of the lift |
| 110 | + |
| 111 | + val State(building, lift, _) = state |
| 112 | + |
| 113 | + while building.hasPeople || lift.hasPeople || lift.position > 0 do |
| 114 | + state = step(state) |
| 115 | + println(state.toPrintable) |
| 116 | + |
| 117 | + state |
| 118 | + } |
| 119 | + |
| 120 | + private def step(state: State): State = { |
| 121 | + // Destructure state into convenient variables |
| 122 | + val State(building, lift, stops) = state |
| 123 | + |
| 124 | + val maxFloor = building.floors.keys.maxOption.getOrElse(0) |
| 125 | + |
| 126 | + // Always force the lift into a valid direction |
| 127 | + lift.direction = lift.position match |
| 128 | + case 0 => Up |
| 129 | + case p if p == maxFloor => Down |
| 130 | + case _ => lift.direction |
| 131 | + |
| 132 | + // Off-board people who reached their destination |
| 133 | + lift.people.dequeueAll(_.destination == lift.position) |
| 134 | + |
| 135 | + // get current floor queue |
| 136 | + val queue = building.floors(lift.position) |
| 137 | + |
| 138 | + // Transfer people from floor queue into lift |
| 139 | + while lift.hasRoom && queue.exists(lift.accepts) do |
| 140 | + val person = queue.dequeueFirst(lift.accepts).get |
| 141 | + lift.people.enqueue(person) |
| 142 | + |
| 143 | + val oldPosition = lift.position |
| 144 | + val (nextPosition, nextDirection) = getNextPositionAndDirection(building, lift) |
| 145 | + |
| 146 | + // Set the new values |
| 147 | + lift.direction = nextDirection |
| 148 | + lift.position = nextPosition |
| 149 | + |
| 150 | + // Register the stop. I added the extra condition because of a bug |
| 151 | + // by which the lift sometimes takes two turns for the very last move 🤔 |
| 152 | + if oldPosition != nextPosition then stops += nextPosition |
| 153 | + |
| 154 | + state |
| 155 | + } |
| 156 | + |
| 157 | + private def getNextPositionAndDirection(building: Building, lift: Lift): (Floor, Direction) = |
| 158 | + List( // Build a list of primary targets |
| 159 | + lift.nearestPassengerTarget, // request from passenger already on the lift |
| 160 | + building.nearestRequestInSameDirection(lift) // request from people [waiting in AND going to] the same direction |
| 161 | + ).flatten // turn list of options into list of Integers |
| 162 | + .minByOption(floor => Math.abs(floor - lift.position)) // get Some floor with the lowest distance, or None |
| 163 | + .match |
| 164 | + case Some(floor) => (floor, lift.direction) // return requested floor, keep direction |
| 165 | + case None => // otherwise choose a new target |
| 166 | + lift.direction match |
| 167 | + case Up => upwardsNewTarget(building, lift) // look for people above going downwards |
| 168 | + case Down => downwardsNewTarget(building, lift) // look for people below going upwards |
| 169 | + |
| 170 | + private def downwardsNewTarget(building: Building, lift: Lift): (Floor, Direction) = |
| 171 | + building.lowestFloorGoingUp(lift) match |
| 172 | + case Some(lowest) => (lowest, Up) |
| 173 | + case None => (building.highestFloorGoingDown(lift).getOrElse(0), Down) |
| 174 | + |
| 175 | + private def upwardsNewTarget(building: Building, lift: Lift): (Floor, Direction) = |
| 176 | + building.highestFloorGoingDown(lift) match |
| 177 | + case Some(highest) => (highest, Down) |
| 178 | + case None => (building.lowestFloorGoingUp(lift).getOrElse(0), Up) |
| 179 | +} |
0 commit comments