0

I have a tree that looks like the following (a simple example, can be a variable size).

1 (root)
|---------------------------------|
1-1                              1-2
|------------|                    |--------------|
1-1-1     1-1-2                  1-2-1          1-2-2

I've written a Java class to generate this tree based on NumberOfSiblings (horizontal) and NumberOfChildren (vertical). I'm now looking to write a class that will generate the path of a given entry in the tree, for example:

Entry: 1-1-1
Path: /1/1-1/1-1-1

I believe that I need some sort of recursive method that will count the number of dashes and take off the last part of the entry (not always length() - 2 though as it could be 10-10-10).

This is the method that will generate the tree:

public static void generateCatalog(String parent, int siblings, int children, int level) {
    for (int a = 1; a <= siblings; a++) {
        String child = parent + "-" + a;
        System.out.println(child);
        if (level <= children) {
            level++;
            generateCatalog(child, siblings, children, level);
            level--;
        }
    }
}

I've been trying something like this to generate the path but it does not work very well.

public static void getPath(String category, String path) {
    System.out.println("Category: " + category);
    System.out.println("Current path: " + path);
    int numberOfDashes = category.length() - category.replace("-", "").length();
    System.out.println("Number of dashes: " + numberOfDashes);
    while (numberOfDashes > 1) {
        path = category + "/" + category.substring(0, category.length() - 2);
        getPath(category, path);
    }
    System.out.println("New path: " + path);
}

Could someone please tell me the best way to do this?

1
  • No need to add the tags to the questions. I removed it for you ;-) Commented Jul 2, 2013 at 13:42

1 Answer 1

1

Instead of

path = category + "/" + category.substring(0, category.length() - 2);

Try

int endIndex = category.lastIndexOf("-");
if(endIndex != -1)  {
     path = category + "/" + category.subString(0, endIndex);
}

Not sure what you want to do if there aren't any dashes, but just stick that in an else block.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.