Skip to content

Instantly share code, notes, and snippets.

View hhariri's full-sized avatar

Hadi Hariri hhariri

View GitHub Profile
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 topUSandUK_hits_years_v2(albums: List<Album>): List<Int> {
return albums.filter {
(it.chartUK == 1 && it.chartUS == 1)
}.map {
it.year
}
}
fun <T, R> Collection<T>.map(transform : (T) -> R) : List<R>
fun topUSandUK_hits_years_v1(albums: List<Album>): List<Int> {
val hits = albums.filter {
(it.chartUK == 1 && it.chartUS == 1)
}
val years = ArrayList<Int>()
hits.forEach {
years.add(it.year)
}
return years;
}
fun <T> Collection<T>.filter(predicate: (T) -> Boolean) : List<T>
fun topUSandUK_v4(albums: List<Album>): List<Album> {
return albums.filter {
(it.chartUK == 1 && it.chartUS == 1)
}
}
fun topUSandUK_v3(albums: List<Album>): List<Album> {
val hits = arrayListOf<Album>()
albums.forEach {
if (it.chartUK == 1 && it.chartUS == 1) {
hits.add(it)
}
}
return hits;
}
fun topUSandUK_v2(albums: List<Album>): List<Album> {
val hits = arrayListOf<Album>()
for (album in albums) {
if (album.chartUK == 1 && album.chartUS == 1) {
hits.add(album)
}
}
return hits;
}