Skip to content

Instantly share code, notes, and snippets.

@SAReyes
Created June 14, 2015 13:11
Show Gist options
  • Save SAReyes/8993d40e01946fa48de3 to your computer and use it in GitHub Desktop.
Save SAReyes/8993d40e01946fa48de3 to your computer and use it in GitHub Desktop.
My scala approach
object Main {
val l1 = List(1, 8, 2, 15, 6, 7, 8, 12, 12)
val l2 = List(1, 8, 2, 15, 6, 7, 8, 12)
val l3 = List(1, 8, 2, 15, 6, 7, 8, 12, 12, 12)
def evenAndGTFive(i: Int) = i > 5 && i % 2 == 0
def magic(l: List[Int]) = {
println(
s"""
|Lista original : $l
|Filtramos pares y mayores que 5 : ${l.filter(evenAndGTFive)}
|Agrupamos repeticiones : ${l.filter(evenAndGTFive).groupBy(e => e).toList}
|Ordenamos : ${l.filter(evenAndGTFive).groupBy(e => e).toList.sortBy(_._1)}
|Eliminamos el par mas grande : ${l.filter(evenAndGTFive).groupBy(e => e).toList.sortBy(_._1).dropRight(1)}
|FlatMap : ${l.filter(evenAndGTFive).groupBy(e => e).toList.sortBy(_._1).dropRight(1).flatMap(_._2)}
|Resultado : ${l.filter(evenAndGTFive).groupBy(e => e).toList.sortBy(_._1).dropRight(1).flatMap(_._2).product}
""".stripMargin)
}
def main(args: Array[String]) {
magic(l1)
magic(l2)
magic(l3
)
}
}

Output

Lista original                   : List(1, 8, 2, 15, 6, 7, 8, 12, 12)
Filtramos pares y mayores que 5  : List(8, 6, 8, 12, 12)
Agrupamos repeticiones           : List((8,List(8, 8)), (12,List(12, 12)), (6,List(6)))
Ordenamos                        : List((6,List(6)), (8,List(8, 8)), (12,List(12, 12)))
Eliminamos el par mas grande     : List((6,List(6)), (8,List(8, 8)))
FlatMap                          : List(6, 8, 8)
Resultado                        : 384

Lista original                   : List(1, 8, 2, 15, 6, 7, 8, 12)
Filtramos pares y mayores que 5  : List(8, 6, 8, 12)
Agrupamos repeticiones           : List((8,List(8, 8)), (12,List(12)), (6,List(6)))
Ordenamos                        : List((6,List(6)), (8,List(8, 8)), (12,List(12)))
Eliminamos el par mas grande     : List((6,List(6)), (8,List(8, 8)))
FlatMap                          : List(6, 8, 8)
Resultado                        : 384

Lista original                   : List(1, 8, 2, 15, 6, 7, 8, 12, 12, 12)
Filtramos pares y mayores que 5  : List(8, 6, 8, 12, 12, 12)
Agrupamos repeticiones           : List((8,List(8, 8)), (12,List(12, 12, 12)), (6,List(6)))
Ordenamos                        : List((6,List(6)), (8,List(8, 8)), (12,List(12, 12, 12)))
Eliminamos el par mas grande     : List((6,List(6)), (8,List(8, 8)))
FlatMap                          : List(6, 8, 8)
Resultado                        : 384
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment