Created
June 10, 2023 01:44
-
-
Save tiagofaustino/8f96baf3db23d5ddfb11b91046a7cf89 to your computer and use it in GitHub Desktop.
Curso Kotlin Puzzle 02
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.collections.List | |
fun List<Int>.produto(): Int { | |
var product = 1 | |
for (element in this) { | |
product *= element | |
} | |
return product | |
} | |
fun processarDespesas(despesas: List<Int>, numeroEntradas: Int): Int? { | |
val combinations = despesas.combinacao(numeroEntradas) | |
for (combination in combinations) { | |
if (combination.sum() == 2020) { | |
return combination.produto() | |
} | |
} | |
return null | |
} | |
fun <T> List<T>.combinacao(numeroEntradas: Int): Sequence<List<T>> { | |
if (numeroEntradas > size) return emptySequence() | |
if (numeroEntradas == 0) return sequenceOf(emptyList()) | |
return drop(1).combinacao(numeroEntradas - 1).map { listOf(first()) + it } + drop(1).combinacao(numeroEntradas) | |
} | |
fun main() { | |
val despesas = listOf(1721, 979, 366, 299, 675, 1456) | |
var numeroEntradas = 2 | |
var resultado = processarDespesas(despesas, numeroEntradas) | |
println("Produto de $numeroEntradas entradas = $resultado") | |
numeroEntradas = 3 | |
resultado = processarDespesas(despesas, numeroEntradas) | |
println("Produto de $numeroEntradas entradas = $resultado") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment