Counting of all members of FamilyTree

165 views Asked by At

I'm working on one of my first projects in Kotlin - FamilyTree. I have class Person, which contains fields: "name", "age", "mother", "father" and array of "siblings". After initializing all members, now I have to count all of them, and here is my problem.

Let's make it simpler: forget about siblings, only father, and mother. Given the fact that all members connected by links on their mother, father, I thought that the best decision is to use a recursive function. I'm checking if I have a mother if I have one - I increment the counter and checking if SHE has mother if she has - I increment the counter and checking if HER MOTHER has mother if HER MOTHER has father, ... Doing some kind of binary search tree. The code of it is below:

class Person(...) {    
  var amountOfAllRelatives = 0

    fun countAmountOfAllRelatives() {
        this.mother?.let {
            amountOfAllRelatives++
            it.countAmountOfAllRelatives()
        }
        this.father?.let {
            amountOfAllRelatives++
            it.countAmountOfAllRelatives()
        }
        this.siblings?.let {
            it.forEach {
                amountOfAllRelatives++
                it.countAmountOfAllRelatives()
            }
        }
    }
}

It doesn't work - every time the result is 0, because every time I call the function "CountOfAllRelatives", it nullifies the counter.

I create the companion object that adds every new Person to the list, so it easy to count, but it's not the right solution, because this list is not part of the instance, it's part of the class.

I guess I can solve it by using loops, it'll be simple to write but not easy to read. Maybe you can prompt me on how to fix function with recursion?

I added this part of the project on Github: https://github.com/RomanMetelov/FamilyTree.git

Thanks for your time and have a nice day!

1

There are 1 answers

0
rMetelov On

Problem solved: if you want to add all members to one list or count them, you should call this function with parameter-link on your instance

class Person(...) { 

var amountOfAllRelatives = 0
var listOfRelatives: MutableList<Person> = mutableListOf<Person>()

fun createListRelativesOf(person: Person) {
    //tree traversal, form a list of all relatives and counting of them
    this.mother?.let {
        person.listOfRelatives.add(it)
        person.amountOfAllRelatives++
        it.createListRelativesOf(person)
    }
    this.father?.let {
        person.listOfRelatives.add(it)
        person.amountOfAllRelatives++
        it.createListRelativesOf(person)
    }
    this.siblings?.let {
        it.forEach {
            person.listOfRelatives.add(it)
            person.amountOfAllRelatives++
            it.createListRelativesOf(person)
        }
    }
}

}

I'll also commit the changes in Github project