0

I am struggling to implement an algorithm that seems rather easy... So I have 5 or less Objects, each with say different name. I need to find all permutations of these 5 or less objects. I tried to use tree-like structure where each element has 1 parent and n<=5 children. I am using ArrayList to store the child elements. I think what I need is recursion but I am not sure how it should be done.

Here's some of my code

public class Tree {
    private ArrayList<Tree> children = new ArrayList<>();
    private Tree parent = null;
    private String data;

    public Tree(String data) {
        this.data = data;
    }

public ArrayList<Tree> addChild(ArrayList<Tree> childrenPased) {
    ArrayList<Tree> childrenToUse = (ArrayList<Tree>) childrenPased.clone();
    childrenToUse.remove(this);
    ArrayList allParents = this.getAllParents();

    childrenToUse.removeAll(allParents);
    childrenToUse.removeAll(children);
    if(childrenToUse.size() > 0) {
        for(Tree child : childrenToUse) {
            children.add(child);
            child.parent = this;
        }
    }

    return children;
}
public ArrayList<Tree> getAllParents(){
    ArrayList<Tree> allParents = new ArrayList<>();
    Tree tempParrent = this.parent;

    if(tempParrent != null){
        allParents.add(tempParrent);
        tempParrent = this.parent.getParent();
        while(tempParrent != null){
            allParents.add(tempParrent);
            tempParrent = tempParrent.parent;
        }

    }

    return allParents;
}

To use this I just made 5 (essentially 4) nested for loops to add children via the above method to the value returned in the outer for loop. The results I am looking for is 120 (5*4*3*2*1) permutations of these 5 elements. Of course stored somehow so I can retrieve them and compare them after.

There should be some logic in my logic and how I deal with the problem, I would love if someone could put me in the right direction, I guess possibly using recursion...?

Viktor1926
  • 48
  • 1
  • 2
  • 11

0 Answers0