Skip to content

Instantly share code, notes, and snippets.

View hhariri's full-sized avatar

Hadi Hariri hhariri

View GitHub Profile
fun <T, R, C: MutableCollection<in R>> Iterable<T>.flatMapTo(result: C, transform: (T) -> Iterable<R>) : C
fun albumAndTrackLowerThanGivenSeconds_v2(durationInSeconds: Int, albums: List<Album>): List<Pair<String, String>> {
return albums.flatMap {
val album = it.title
it.tracks.filter {
it.durationInSeconds <= durationInSeconds
}.map {
Pair(album, it.title)
}
}
}
fun <T, R> Iterable<T>.flatMap(transform: (T)-> Iterable<R>) : List<R>
fun albumAndTrackLowerThanGivenSeconds_v1(durationInSeconds: Int, albums: List<Album>): List<Pair<String, String>> {
val list = arrayListOf<Pair<String, String>>()
albums.forEach {
val album = it.title
it.tracks.filter {
it.durationInSeconds <= durationInSeconds
}.map {
list.add(Pair(album, it.title))
}
fun nameAndTotalTime_v2(albums: List<Album>): List<Pair<String, Int>> {
return albums.map {
Pair(it.title, it.tracks.map { it.durationInSeconds }.reduce { x, y -> x +y })
}
}
fun sumOfInts(list: List<Int>): Int {
return list.reduce { (x, y) -> x + y}
}
fun nameAndTotalTime_v1(albums: List<Album>): List<Pair<String, Int>> {
return albums.map {
var total = 0
it.tracks.forEach {
total += it.durationInSeconds
}
Pair(it.title,total)
}
}
data class Track(val title: String, val durationInSeconds: Int)
val pinkFloyd = listOf(
Album("The Dark Side of the Moon", 1973, 2, 1,
listOf(Track("Speak to Me", 90),
Track("Breathe", 163),
Track("On he Run", 216),
Track("Time", 421),
Track("The Great Gig in the Sky", 276),
Track("Money", 382),
fun <T, R> Collection<T>.map(transform : (T) -> R) : List<R>
fun topUSandUK_hits_years_v2(albums: List<Album>): List<Int> {
return albums.filter {
(it.chartUK == 1 && it.chartUS == 1)
}.map {
it.year
}
}