Skip to content

Instantly share code, notes, and snippets.

@thiagolenz
Created July 21, 2023 20:14
Show Gist options
  • Select an option

  • Save thiagolenz/191dba439989ad8aa32f1fbae6d81797 to your computer and use it in GitHub Desktop.

Select an option

Save thiagolenz/191dba439989ad8aa32f1fbae6d81797 to your computer and use it in GitHub Desktop.
Exemplo Básico sobre recursividade
/**
==== ÁRVORE GENEALÓGICA ===
Vovô Eugênio
- Matheus
- Pedrinho
- Valentina
- Mariana
- Bruno
- Patricia
- Helena
*/
data class Pessoa(
val nome: String,
val filhos: List<Pessoa>
)
fun criarArvore(): Pessoa {
val pedrinho = Pessoa(nome = "Pedrinho", filhos = listOf())
val valentina = Pessoa(nome = "Valentina", filhos = listOf())
val matheus = Pessoa(nome = "Matheus", filhos = listOf(pedrinho, valentina))
val bruno = Pessoa(nome = "Bruno", filhos = listOf())
val helena = Pessoa(nome = "Helena", filhos = listOf())
val patricia = Pessoa(nome = "Patricia", filhos = listOf(helena))
val mariana = Pessoa(nome = "Mariana", filhos = listOf(bruno, patricia))
val vovo = Pessoa(nome = "Eugenio", filhos = listOf(matheus, mariana))
return vovo
}
/**
* Para mostrar as cores mais evidentes
*/
val green = "\u001b[32m"
val reset = "\u001b[0m"
fun imprimirPessoaRecursiva (pessoa: Pessoa, nivel: Int) {
var printText = ""
for (i in 0..nivel) {
printText = "$printText-"
}
println("$printText Pessoa: ${pessoa.nome}")
pessoa.filhos.forEach { filho ->
imprimirPessoaRecursiva(filho, nivel + 1)
}
println(green + "======== Fim Execução Pessoa: ${pessoa.nome} ======" + reset)
}
fun main () {
val vovo = criarArvore()
imprimirPessoaRecursiva(vovo, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment