Java code with tests - infinite loop?

后端 未结 1 838
余生分开走
余生分开走 2021-01-26 16:42

I try to get the relationship between people. However, when I run unit test, the test runs forever, it doesn\'t get the result and my CPU usage was high. Could someone see what\

相关标签:
1条回答
  • 2021-01-26 17:45
     for(i = 0, j = 0, name = ancestor; i < allRelations.size(); i++){
                if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
                    generationNum++;
                    ancestor = allRelations.get(i).get(1);
                    i = 0;
                    j = 1;
                }
                else if(ancestor.equals(allRelations.get(i).get(0)) && person.equals(allRelations.get(i).get(1))){
                    generationNum++;
                    j = 1;
                    break;
                }
            }
    

    here you have your faulty lines in your case your ancestor/name is "Martin Weasel" given relation for martin is "John Doe", but you are looking for mary smith so name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))) this is true and this i = 0; makes your loop starts from beginning

    what you could do, try to create object person ie class Person{ String name; List childrens; List parents; ... } then just do simple tree walker

    int SearchDown(Person person, String searchedRelation,int generation)
    {
    if person.getName().equals(searchedRelation())
    return generation;
    for (Person child: person.getChildren())
    {
    int generation = SearchDown(child, searchedRelation, generation+1);
    if (generation!=-1) return generation;
    }
    return -1;
    }
    

    etc...

    i'm really finding this way much easier to deal with all types of trees

    0 讨论(0)
提交回复
热议问题