Skip to content

Instantly share code, notes, and snippets.

@gzoritchak
Last active December 12, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gzoritchak/4687828 to your computer and use it in GitHub Desktop.
Save gzoritchak/4687828 to your computer and use it in GitHub Desktop.
Solution en kotlin au dernier exercice de codestory 2012
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