Skip to content
Snippets Groups Projects
Commit aa4de7d7 authored by joel.vonderwe's avatar joel.vonderwe
Browse files

Collections exos

parent d8643d22
Branches
No related tags found
No related merge requests found
package ch.hepia.tpscala
/* Implémentez les fonctions suivantes.
*/
object Collect {
case class Album( title: String, artist: String, year: Int )
case class Duration( minutes: Int, seconds: Int )
case class Track( title: String, duration: Duration )
val albums = List(
Album( "Mit Gas", "Tomahawk", 2003 ),
Album( "Pork Soda", "Primus", 1993 ),
Album( "Brown Album", "Primus", 1997 ),
Album( "Distraction Pieces", "Scroobius Pip", 2011 )
)
val tracks = Map(
"Mit Gas" -> List(
Track( "Mayday", Duration( 3, 32 ) )
),
"Pork Soda" -> List(
Track( "DMV", Duration( 4, 58 ) ),
Track( "Mr. Krinkle", Duration( 5, 27 ) )
),
"Brown Album" -> List(
Track( "Fisticuffs", Duration( 4, 25 ) ),
Track( "Camelback Cinema", Duration( 4, 0 ) ),
Track( "Kalamazoo", Duration( 3, 31 ) )
),
"Distraction Pieces" -> List(
Track( "Let 'Em Come", Duration( 4, 25 ) ),
Track( "Domestic Silence", Duration( 3, 58 ) )
)
)
/* Retourne la liste de morceaux associés à un artiste */
def tracksOf( artist: String ): List[Track] = {
albums.filter(_.artist == artist).flatMap( a => tracks(a.title))
}
/* Retourne la liste de tous les morceaux de moins de 4 minutes */
def shortTracks: List[Track] = {
tracks.flatMap(t => t._2).filter(t => t.duration.minutes < 4).toList
}
/* Retourne les titres des morceaux antérieurs à une année */
def titlesBefore( year: Int ): List[String] = {
albums.flatMap(a => if (a.year < year) tracks(a.title) else List()).map(_.title)
}
/* Calcule la durée totale de tous les morceaux disponibles.
REMARQUE: on veut que les secondes soient inférieures à 60 mais les
minutes peuvent dépasser ce total.
*/
def totalDuration: Duration = {
var m = 0
var s = 0
tracks.flatMap(_._2).foreach(t => {
m += t.duration.minutes
s += t.duration.seconds
})
Duration(m + s/60, s % 60)
}
}
package ch.hepia.tpscala
import org.scalatest.funsuite.AnyFunSuite
import Collect._
class Collect6Suite extends AnyFunSuite {
test( "tracksOf" ) {
assert( tracksOf("Justin Bieber").isEmpty )
assert( tracksOf("Tomahawk") == List( Track( "Mayday", Duration( 3, 32 ) ) ) )
assert( tracksOf("Primus").size == 5 )
}
test( "shortTracks" ) {
assert(
shortTracks.toSet == Set(
Track( "Mayday", Duration( 3, 32 ) ),
Track( "Kalamazoo", Duration( 3, 31 ) ),
Track( "Domestic Silence", Duration( 3, 58 ) )
)
)
}
test( "titlesBefore" ) {
assert( titlesBefore( 1928 ).size == 0 )
assert( titlesBefore( 2020 ).size == 8 )
assert(
titlesBefore( 2000 ).toSet == Set(
"DMV",
"Mr. Krinkle",
"Fisticuffs",
"Camelback Cinema",
"Kalamazoo"
)
)
}
test( "totalDuration" ) {
assert( totalDuration == Duration( 34, 16 ) )
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment