Last active
December 12, 2015 00:59
-
-
Save gzoritchak/4687828 to your computer and use it in GitHub Desktop.
Solution en kotlin au dernier exercice de codestory 2012
This file contains 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
package codestory2013.gzoritchak.jajascript | |
class Flight(val id: String, val startHour: Int, val duration: Int, val price: Int){ | |
val endHour = startHour + duration | |
} | |
class Planning(val gain: Int = 0, val flights: List<Flight> = listOf()) { | |
fun plus(flight: Flight) = Planning(gain + flight.price, flights + flight) //Planning + Flight = Planning | |
} | |
fun findBestPlanning(flights: List<Flight>): Planning { | |
val flightsByEndHour = flights.groupBy { it.endHour } | |
val bestPlanningFor = hashMapOf( 0 to Planning() ) | |
val dayLong = flights.fold(0) { duration, flight -> | |
if (flight.endHour > duration) flight.endHour | |
else duration } | |
/** | |
* Recherche du meilleur planing pour une heure. | |
* Pour chaque vol atterrissant à cette heure, on crée un nouveau planning en ajoutant le vol au meilleur planning | |
* de son heure de départ. | |
* On compare ces plannings avec le meilleur planning de l'heure h-1 pour renvoyer celui qui offre le meilleur gain. | |
*/ | |
fun bestPlanningForHour(heure:Int): Planning { | |
val flightsForLandingHour = flightsByEndHour.get(heure) ?: linkedListOf<Flight>() | |
val plannings = linkedListOf(bestPlanningFor.get(heure-1)) | |
flightsForLandingHour.forEach { plannings.add(bestPlanningFor.get(it.startHour)!! + it) } | |
return plannings.sortBy { -it!!.gain }.first ?: Planning() //bug compilo? On ne devrait pas ajouter ?:Planning() | |
} | |
for (hour in 1..dayLong) { | |
bestPlanningFor.put(hour, bestPlanningForHour(hour)) | |
} | |
return bestPlanningFor.get(dayLong)!! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment