Tree   Data  Structure

Hello Guys,
I am stuck in my project for a while and decided to contact you guys for ideas because am short of ideas how to get it done. This is the task: I have information like this from the server and have to create a tree structure from the information(data). The data from the server comes in this form:
APP               net       main
Account        net      main
Address        net      main
Person        net      OptelClient3
Person        net      ggggg
Person        net      show
Bindings    apple    parse
Bindings    apple    findProject
Bindings    apple    show
The positions of the columns is not fixed. The first column can become the second or the third depending on the preference of the user.
1)
The task is this:
In each row , the first data must be the parent of the second data, the second data must be the parent of the third data and if there appears to be a fourth data then it will be the child of the third and it follows like that......
I have to be able to build this tree structure whiles am looping over the information from the server.
*****Optional Requirement****
And if it is possible i must also be able to use the structure to create a table.
I have spent much time(weeks after weeks) doing it but its not working so am asking if someone can help me with ideas how to get this done or point me to a tutorial where i can have a deep understanding of how i can do it.
Thank for your help.

Thanks for your reply.
I have to implement the tree from the list i receive from the server. Each column belongs to the same class. For instance the first column will belong to a class called say "cHuman" and i will set the name attribute of each class to the names of the first column.
The second coulumn will belong to the same class say "cPackage"and i will set each to the names of the second column datas. This apply to the rest of the columns.
What am asking is simple. How can i build the tree dynamically so that the in each row, every data is parent to the next data. That is all what i want. What am doing is correct but i just need how to create the tree dynamically. Show me how to build trees dynamically from data.
Thanks.

Similar Messages

  • Trees Data Structures in Java

    Hi all !
    Currently I�m developing a Java software that requires a Tree data structure. Searching through Java API I�ve found classes like TreeMap and TreeSet, but although these classes seens to use tree structure behind what they really provide are linear data structure, not a tree data structure. My question is if there is a public and free Java tree data structure that permits to do activities such as:
    - Search for a particular node (efficiently)
    - Insert children to any node
    - Maintain one Object in each node
    Simple like this ! It must have something like this in Java, but I just can�t find it and I�m just too lazy to implement it :) ! Anyone can help me ?
    Thanks in advance !

    Mel,
    I�ve seen javax.swing.tree.TreeModel and its seens more like an implementation of Control in swing MVC (Model Vision Control) swing paradigm for JTree. It has listeners generated for manipulation events for example. It uses javax.swing.tree.DefaultMutableTreeNode for its nodes, and maybe I could use this class for the nodes of my tree since it has many useful operations. However still I miss a node searching operation that this class doesn�t have.
    Yes my problem is a simple Tree, but it is simple now and it might become much more complex, demanding more operations on the tree and specially efficient searching algorithms. Thats why I�m looking for a complete solution and I prefer something that is already done and well tested :) !
    Thanks for your tip !

  • 3750x Stack UTIL-3-TREE: Data structure error--attempt to remove an unthreaded node from a tree

    A Cisco Stack 3750X switch report the following error message:
    %UTIL-3-TREE: Data structure error--attempt to remove an unthreaded node from a tree.
    every minute +-20 sec
    Cisco IOS Software, C3750E Software (C3750E-IPBASEK9-M), Version 15.0(2)SE4, RELEASE SOFTWARE (fc1)
    analog bug: https://tools.cisco.com/bugsearch/bug/CSCsz93221

    WS-C3750G-24PS-E C3750-IPBASEK9-M version 12.2(53)SE2
    After implementing 802.1x with Avaya IP phones
    %UTIL-3-TREE: Data structure error--attempt to remove an unthreaded node from a tree
    Port then fails authentication and goes into vl-err-dis

  • What Tree Data Structures does Java Include?

    Hello,
    I have been reading about several tree data structures like a binary search tree, self-balancing bst, minimum spanning tree, red-black tree, AVL tree, etc... Are there data structures in Java represent the various trees, or is implementation of the ds left to user?
    Eric

    "Java" can be termed the "Java Language". The language does not have trees.
    In more general usage "Java" can refer to a standard, desktop, delivered VM which includes the standard Java API. The types that you are asking about would be found in the following package.
    [http://java.sun.com/javase/6/docs/api/java/util/package-summary.html]
    "Java" could also refer to any other commonly available implementations. In that case probably anything that can be implemented has been implemented somewhere. Googling works.

  • Is there a Java API for Tree data structure?

    Hi,
    I am wondering is there any Java API to work on Tree based data structure.
    I could read in some forums / sites that teach me how to create tree based objects using collection.
    But I wanted to know is there any core java API that can be used directly for tree based operations. (like binary tree or other type of trees)
    Please comment on this doubt.

    Headed using google and other stuff not found one.
    Suggestion: Why not start building the one, its a good idea to do that, isn't it.

  • Tree Data Type for top-down travelling

    I need a tree data structure to represent a category-subcategory. Only algorithm I need is to find all children from a given node. What is the effective constructure of such tree?
    Thanks.

    The only reason they post is they know somebody will
    do their homework for them. The point being, don'tdo
    it for them. The ultimate point being -- you don't
    want to work with someone that got through theircomp
    sci degree by posting to forums (and copying from
    others), but it actually happens. I had a friend in
    college that got his degree this way, and to his
    graduating day -- he couldn't get 3 lines of code to
    coplile (yes, that means ever.)Come on, I don't believe for a minute that you can
    cheat your way to a masters degree by getting "help"
    from forums. And if you can it's the university that's
    to blame.I never said it was a Master in CS.. BS in CS.
    You say you won't do homework for people. Why not? if
    you find a question interesting why not do it and post
    if with a full explanation and full source code. A
    forum is a public environment. What you do here is
    there for everyone to see. By doing this you actually
    help universities stop potential cheating. It's
    somewhat counter-intiutive but this is how it works.Plagiarism is still cheating, and I believe it is taking credit for work you did not do: copying from a forum, public of not, is still cheating. In ancient times (when I was in college) they used to expell you for turning in other people's work (if you were caught).
    Also what do you know about this person you suspect is
    posting homework for the purpose of cheating. Nothing.
    It can be an isolated person who really has no one
    else to ask.In a University, college, or even HS environment there are always other people to ask--and that is how the system there works.
    Also why is helping someone with homework so
    especially awful. I would rather not help someone with
    work related problems. Why should I help someone for
    free to do something they've been hired to do and get
    paid to do?What is the differenct? When you get the degree you are certified by a major institution of learning to know the materials covered in the coursework you completed. Employers used to assume becasue you have a degree you actually knew a little about the subject. Not any more!!! I wish you could see the millions of dollars each year that are wasted screening unqualified people that have degrees and the millions of dollars wasted trying to work with the ones that made it through the interviews because you did assume they knew at least the basics of the course work for the degree. (I speak here from experience.) We have had to make much more rigorous testing for our candidates to screen out the unqualified--basically you have to take an aggregate final to get into the interview process.
    Also I find cheaters who makes it to a job quite
    benign. There are other types I dislike more, like the
    psychopats and the bullies to name a few.If I have 10 workers and 8 of them cheated their way through college and do not have the problem solving, imagination, and skills needed to be productive and I have 2 "bullies" that give me the world on a silver platter when ever I ask them to do something... guess who is going to get the raises and promotions.
    My conclusion is that you should post at forums only
    if it gives YOU something.I support free information, and I share knowlege and ideas freely and try to cultivate an environment that other will do so too. I have to put a limit there when students want HW done--it is their assignment to do it, they are graded not only on correctness, but also on imagination, problem solving. Do it for them and you weaken the system and eventually the industry.
    As I have said in forums before: Cheating at college level and getting your degree when you are unqualified now costs millions in dollars that have to passed on to the general public to maintain normal operation. Does cheating hurt? Believe it or not, it cost you dollars out of your pocket each and every day.

  • Build XML for Custom Nested Accordian (like Tree View Structure) for SharePoint List Data

    Expected output in Xml:
    <?xml version="1.0" encoding="utf-8" ?>
    - <TopRoot>
    - <Root id="1" Name="Department">
    - <Type id="2" Name="IT">
    - <SubType id="3" Name="Technology">
      <SubSubType id="4" Name="Sharepoint" />
      <SubSubType id="5" Name="ASP.NET" />
      <SubSubType id="6" Name="HTML 5" />
      </SubType>
      </Type>
    </Root>
    </TopRoot>
    List Details:
    list details for storing category / sub category data and code to build tree structure for the same.
    1.Create Custom List named “CategoryDetails”:
    2.Create Column “Category Name” of type single line of text. Make it as required field and check Yes for Enforce Unique values.
    3.Create column “Parent Category” of type lookup. under Additional Column Settings.
    Get information dropdown, select “CategoryDetails”.
    4.Choice column ["SRTypeName"] 1.Root,2.SRTYPE,3.SubSRTYPE, 4.SUBSUBSRTYPE
    In this column dropdown, select “Category Name”:  
    Referance:
    http://www.codeproject.com/Tips/627580/Build-Tree-View-Structure-for-SharePoint-List-Data    -fine but don't want tree view just generate xml string
    i just follwed above link it work perferfectly fine for building tree view but i don't want server control.
    Expected Result:
    My ultimate goal is to generate xml string like above format without building tree view.
    I want to generate xml using web service and using xml i could convert into nested Tree View Accordian in html.
    I developed some code but its not working to generate xml /string.
    My modified Code:
    public const string DYNAMIC_CAML_QUERY =
            "<Where><IsNull><FieldRef Name='{0}' /></IsNull></Where>";
            public const string DYNAMIC_CAML_QUERY_GET_CHILD_NODE =
            "<Where><Eq><FieldRef Name='{0}' /><Value Type='LookupMulti'>{1}</Value></Eq></Where>";
            protected void Page_Load(object sender, EventArgs e)
                if (!Page.IsPostBack)
                 string TreeViewStr= BuildTree();
                 Literal1.Text = TreeViewStr;
            StringBuilder sbRoot= new StringBuilder();
            protected string BuildTree()
                SPList TasksList;
                SPQuery objSPQuery;
                StringBuilder Query = new StringBuilder();
                SPListItemCollection objItems;
                string DisplayColumn = string.Empty;
                string Title = string.Empty;
                string[] valueArray = null;
                try
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb web = site.OpenWeb())
                            TasksList = SPContext.Current.Web.Lists["Service"];
                            if (TasksList != null)
                                objSPQuery = new SPQuery();
                                Query.Append(String.Format(DYNAMIC_CAML_QUERY, "Parent_x0020_Service_x0020_Id"));
                                objSPQuery.Query = Query.ToString();
                                objItems = TasksList.GetItems(objSPQuery);
                                if (objItems != null && objItems.Count > 0)
                                    foreach (SPListItem objItem in objItems)
                                        DisplayColumn = Convert.ToString(objItem["Title"]);
                                        Title = Convert.ToString(objItem["Title"]);
                                        int rootId=objItem["ID"].ToString();
                                        sbRoot.Append("<Root id="+rootId+"
    Name="+Title+">");
                                        string SRAndSUBSRTpe = CreateTree(Title, valueArray,
    null, DisplayColumn, objItem["ID"].ToString());
                                        sbRoot.Append(SRAndSUBSRTpe);
                                        SRType.Clear();//make SRType Empty
                                        strhtml.Clear();
                                    SRType.Append("</Root>");
                catch (Exception ex)
                    throw ex;
                return SRType.ToString();
             StringBuilder strhtml = new StringBuilder();
            private string CreateTree(string RootNode, string[] valueArray,
          List<SPListItem> objNodeCollection, string DisplayValue, string KeyValue)
                try
                    strhtml.Appends(GetSRType(KeyValue, valueArray, objNodeCollection);
                catch (Exception ex)
                    throw ex;
                return strhtml;
            StringBuilder SRType = new StringBuilder();
            private string GetSRType(string RootNode,
            string[] valueArray, List<SPListItem> objListItemColn)
                SPQuery objSPQuery;
                SPListItemCollection objItems = null;
                List<SPListItem> objNodeListItems = new List<SPListItem>();
                objSPQuery = new SPQuery();
                string objNodeTitle = string.Empty;
                string objLookupColumn = string.Empty;
                StringBuilder Query = new StringBuilder();
                SPList objTaskList;
                SPField spField;
                string objKeyColumn;
                string SrTypeCategory;
                try
                    objTaskList = SPContext.Current.Web.Lists["Service"];
                    objLookupColumn = "Parent_x0020_Service_x0020_Id";//objTreeViewControlField.ParentLookup;
                    Query.Append(String.Format
                    (DYNAMIC_CAML_QUERY_GET_CHILD_NODE, objLookupColumn, RootNode));
                    objSPQuery.Query = Query.ToString();
                    objItems = objTaskList.GetItems(objSPQuery);
                    foreach (SPListItem objItem in objItems)
                        objNodeListItems.Add(objItem);
                    if (objNodeListItems != null && objNodeListItems.Count > 0)
                        foreach (SPListItem objItem in objNodeListItems)
                            RootNode = Convert.ToString(objItem["Title"]);
                            objKeyColumn = Convert.ToString(objItem["ID"]);
                            objNodeTitle = Convert.ToString(objItem["Title"]);
                            SrTypeCategory= Convert.ToString(objItem["SRTypeName"]);
                           if(SrTypeCategory =="SRtYpe")
                              SRType.Append("<Type  id="+objKeyColumn+" Name="+RootNode+ ">");
                             if (!String.IsNullOrEmpty(objNodeTitle))
                              SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
                          if(SrTypeCategory =="SRSubTYpe")
                              SRType.Append("<SRSubType  id="+objKeyColumn+" Name="+RootNode+
    ">");  
                             if (!String.IsNullOrEmpty(objNodeTitle))
                              SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
                          if(SrTypeCategory =="SubSubTYpe")
                              SRType.Append("<SubSubType  id="+objKeyColumn+" Name="+RootNode +"
    ></SubSubType");  
                        SRType.Append("</SubType>");
                        SRType.Append("</Type>");
                catch (Exception ex)
                    throw ex;
                return SRType.ToString();
                // Call method again (recursion) to get the child items

    Hi,
    According to your post, my understanding is that you want to custom action for context menu in "Site Content and Structure" in SharePoint 2010.
    In "SiteManager.aspx", SharePoint use MenuItemTemplate class which represent a control that creates an item in a drop-down menu.
    For example, to create or delete the ECB menu for a list item in
    "Site Content and Structure", we can follow the steps below:
    To add the “My Like” menu, we can add the code below:      
    <SharePoint:MenuItemTemplate
    UseShortId=false
    id="OLListItemLike"
    runat="server"
    Text="My Like"
    ImageUrl="/_layouts/images/DelItem.gif"
    ClientOnClickNavigateUrl="https://www.google.com.hk/"
    />
    To remove the “Delete” menu, we can comment the code below:
    <SharePoint:MenuItemTemplate
    UseShortId=false
    id="OLListItemDelete"
    runat="server"
    Text="<%$Resources:cms,SmtDelete%>"
    ImageUrl="/_layouts/images/DelItem.gif"
    ClientOnClickScript="%SmtObjectDeleteScript%"
    />            
    The result is as below:
    More information:
    MenuItemTemplate Class (Microsoft.SharePoint.WebControls)
    MenuItemTemplate.ClientOnClickScript property (Microsoft.SharePoint.WebControls)
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Is timesten still using T-tree as data structure?

    I just come across this paper - http://www.memdb.com/paper.pdf , this researcher do some experiments and showing that using concurrent B-tree algorithm is actually faster than T-tree operation. How do you think about this paper? Do you think actually he is using a inefficient algorithm to access T-tree? Or, Timesten already know the limitation of T-tree and have changed the internal data-structure?

    Yes, we are aware of the comparisons between T-Trees, concurrent B-trees etc. At the moment TimesTen still uses T-trees but this may change in the future :-)
    Chris

  • Access rights in case of a tree-like structure, with inheritance

    Hello,
    the project I've just started to work on should include an easy way (from the user's point of view) to grant/revoke access rights on a tree-like structure with inheritance.
    Basically we are working for several international companies who want to use our application to watch/manage some of their web projects - each project belongs to one company and consisting of several 'campaigns' in several countries (there can be several campaigns per country, but each campaign belongs to exactly one country).
    From our point of view this is a tree-like structure, with a 'root' node at the top level, 'companies' at the first level, 'countries' at the second level, 'campaigns' at the third level, and modules of our application (for example a module to display overall stats of the campaing, and so on) at the fourth level. There could be (and probably will be) some more levels, but that's not important at this point - it will always be a tree-like structure.
    The customer's reqirements are natural - the administrators should be able to grant/revoke access to 'subtrees' of this structure. For example the top managers should be able to see all the data related to their company, the local managers should be able to see all the data related to their company in the country they work in, etc. On the other hand the relular employees should not see some of the modules (with details about clients of the company).
    I wonder whether this can be solved using JAAS in an elegant and flexible manner - from the documents / whitepapers / tutorials I've seen till now it seems to me it seems to me not too suitable.
    All the data will be stored in relational database (Oracle, and in some cases PostgreSQL), and it would be nice to have the access rights stored in the same way (but it's not required). We have some ideas how to solve that using a single table containing paths in the tree, but at this point it's only an idea (not a single line of code written).
    We are sure somebody has already to solve such a problem - maybe using JAAS, maybe some other technology - and we don't want to reinvent a wheel. Do you have an idea how to solve this (using JAAS or something else)?

    Well, I forgot to explain what the 'inheritance' means ...
    We do not want to set the access right on each node of the tree - we prefer (as well as the users) to set/store only as much information as needed. We'd like the nodes to inherit the access rights from their parent nodes. For example we'd like granting access to particular project to mean granting access to all campaigns in all countries (related to the project), without the need to set and store these rights for each of the campaigns/countries.

  • What's the easiest way to move app data and data structures to a server?

    Hi guys,
    I've been developing my app locally with Apex 4.2 and Oracle 11g XE on Windows 7. It's getting close to the time to move the app to an Oracle Apex server. I imagine Export/Import is the way to move the app. But what about the app tables and data (those tables/data like "customer" and "account" created specifically for the app)? I've been using a data modeling tool, so I can run a DDL script to create the data structures on the server. What is the easiest way to move the app data to the server? Is there a way to move both structures and data in one process?
    Thanks,
    Kim

    There's probably another way to get here, but, in SQL Developer, on the tree navigation, expand the objects down to your table, right click, then click EXPORT.. there you will see all the options. This is a tedious process and it sucks IMO, but yeah, it works. It sucks mostly because 1) it's one table at a time, 2) if your data model is robust and has constraints, and sequences and triggers, then you'll have to disable them all for the insert, and hope that you can re-enable constraints, etc without a glitch (good luck, unless you have only a handful of tables)
    I prefer using the oracle command line EXP to export an entire schema, then on the target server I use IMP to import the schema. That way, it's near exact. This makes life messy if you develop more than one application in a single schema, and I've felt that pain -- however -- it's a whole lot easier to drop tables and other objects than it is to create them! (thus, even if the process of EXP/IMP moved more than you wanted to "move".. just blow away what you don't want on the target after the fact..)
    You could use oracle's datapump method too.
    Alternatively, what can be done, IF you have access to both servers from your SQL developer instance (or if you can tnsping them both already from the command line, you can use SQL*PLUS), is run a script that will identify your apex apps' objects (usually by prefix to object names, like EBA_PROJ_%, etc) and do all the manual work for you. I've created a script that does exactly this so that I can move data from dev to prod servers over a dblink. It's tricky because of the order that must be executed to disable constraints and then re-enable them, and of course, trickier if you don't consistently prefix ALL of your "application objects"... (tables, views, triggers, sequences, functions, procs, indexes, etc)

  • Dictionary Structure---data structure of Dictionary

    I don't know how to build a data structure of dictionary...
    somebody said it's was built by binary tree. but I don't know how.
    somebody helps me????
    thanks for reading my topic

    A dictionary is not a tree/hierarchical structure. Have you ever opened a dictionary before?! If you have even once, you already know the structure of a dictionary. Now, how to build that in Java is another question. I'm not sure of your requirements but you could start by creating an object that represents a single term, it's definitions, usages, etc. Then you can create a List of them (and sort them alphabetically). Simple enough?

  • Efficient data structure to implement simple text editor?

    I was given this problem in an interview:
    What data structure would you use to implement a simple text editor that does these 4 functions:
    a) goto(line number)
    b) insert(char input,location)
    c) delete(location)
    d) printAll() //print entire file
    Given that i'm such a newb, i was stumped. I came up with making a 2d array that would allow for o(1) time for goto, but o(n) for everything else (shifting everything in the array). there were other downfalls too dealing with space issues and such, but he wanted me to optimize this data structure. I then came up with a linked list of arrays, but that had similar problems.
    But thinking about it further is driving me a little crazy so I'm wondering if you guys have any suggestions on how to answer this question...
    one thing that came to mind after is to implement the data structure as a binary tree, where each node contains
    class Node
    char theChar
    int position; // ie 0 = first character in the file, and 81 could be the first character in the 2nd line
    node left,right,parent;
    }so how it works is the cursor would know where the location was so i would know where to delete and insert within the tree.
    insert {
         //search for location to insert after (log n)
           //create new character node and append to current node
         //increment position for all subsequent children
    delete(x) {
         search for x position
         if found, remove node and decrement position value for all children
    goto(line #) {
         return line # * 80 (or whatever max length for a single line)
    }the major problem i see here is balancing the tree after every insert/delete
    Thanks in advance.

    One of many great things emacs has given us is the gap buffer:
    http://en.wikipedia.org/wiki/Gap_buffer
    To see a Java implementation of this you can look in the Java SDK source. The document model (I forget exactly what its called), used in Swing uses a gap buffer.

  • Implement a program by using data structure

    i've learn link-list,b-tree,red black tree,hash table. now it's time for me to implement a program using any one of these. i've no idea about how to start, and what kind of program should i write? what kind of program use data structure? i want some simple example program to make me understand. can anyone help me?
    thank 4 u r time,
    makio

    what sort of program do use data structure? let's say
    i want to use binary search on data , how can i?As nasch said: pretty much any program uses data structures.
    Okay, let's say you want to try binary search. You could do that on an array, on a singly linked list, on a doubly linked list, probably on others that I can't think of right now.
    If you just want practice using the data structures you've learned, then why not write a binary search over several different ones? That will give you a feel for how they differ in usage and performance.
    Or, you can just pick any kind of program that interests you. Unless it's trivially small and simple, there will probably be a use for one or more of the data strux you've learned.
    A chat program needs data structures to hold curently connected users, ongoing conversations, maybe a queue for messages waiting to be sent.
    A card game needs to be able to search to see if a given card is in a given hand. Needs to hold all the cards in a deck that has to be shuffled. Dealing is like popping off a stack.
    A database of students and their courses might want to keep something in an ordered tree--by last name for instance.
    What applications interest you?

  • Tree Like structures

    Dear All,
    I am working on some tree like structures querys.
    I am strucked up with one tricky concept.
    My Data is like as given below
    EMPNO MGR
    1
    2 1
    3 1
    4 2
    5 4
    Now my requirement states that I should display the date as given below
    1
    1 2
    1 2 4
    1 2 4 5
    Can anyone help me in designing a query.
    Appreciate your help on this.
    Thanks,
    Madhu K.

    If more levels are there then it should populate under different columns like col5 ..... That's fine, that's how it will work.
    There are only 4 levels above because that's just how the sample data is.
    1 2 3 4You'd think people could give suggestions that get you over the hard bit and then you do some work for anything that's not exactly right.
    SQL> ed
    Wrote file afiedt.buf
      1  WITH DATA AS(
      2   SELECT 1 a,0 b FROM dual UNION
      3   SELECT 2,1 FROM dual UNION
      4   SELECT 3,1 FROM dual UNION
      5   SELECT 4,2 FROM dual UNION
      6   SELECT 5,4 FROM dual UNION
      7   SELECT 6,5 FROM dual
      8  )
      9  SELECT SUBSTR(SYS_CONNECT_BY_PATH (a,' '),2) scbp
    10  FROM DATA
    11  CONNECT BY PRIOR a=b
    12  START WITH a=1
    13* ORDER BY 1
    SQL> /
    SCBP
    1
    1 2
    1 2 4
    1 2 4 5
    1 2 4 5 6
    1 3
    6 rows selected.
    SQL>

  • Looking for an efficient data structur & search algorithm

    Hi all
    i have a list of digits (international phone network prefixes) with some hundreds to some thousends entries. An entry may be in the form
    ^00[1-9]{1}[0-9]{0,7}$
    I.e. this might be 001, 0041, 00317545, 00317548, 00317549 and so on. Regarding the last three examples, it might even be that there is an additonal 0031754.
    What i need a a data structur that allows to match these prefixes against a phonenumber.
    I.e. if i have the phonennumber 001123456789 it would match the prefix 001. If i had 00317549111 it would match 00317549.
    The easiest way would be to but all prefixes into an Vector or similar and loop over all entries, trying to match the phonenumber with startsWith(). But this wouldn't always result in a absolutely perfect match, since, i.e. for the phonenumber 00317549111 the check against the prefix 0031754 would return a match even if there was a more specific match with the prefix 00317549. But more than that, this simple algorithm is not very efficient.
    So i am looking for a more efficient way/pattern to do this. I thought about a kind of tree structure, starting with 00 in the top level, than provding [1-9] in the second level, and [0-9] from third level on. Then on every node it would either store if there is a matching prefix on that level, or if there is a prefix starting with that digits on a lower level or if there is no prefix on that level or any lower.
    I.e. when i have the phonenumber 00317549111 it would start at the top level with 00. That would be ok. On the next level it would check if there is a node for digit 3. If there is, it would go one level deeper and check if there is a node for digit 1. If yes, again it would go one level deeper to check if there is a node for digit 7. If that algorithm comes to a level where, for the request digit, it get's a prefix indicator rather than a node indicator, the algortihm would know, that a matching prefix was found and that there is no more specifig match on deeper levels.
    One thing i forgot to mention - the prefixes might be read once during startup/init and there it might take some time for building up the datastructur - i don't care about that. But, when running, then the maching process should be as efficient as possible, that's the most important point for me.
    What do you think about a pattern like this? Could this be efficient? Do you see other patterns, that might be easier to implement and that might be faster/need less memory?
    Thanks a lot for your help.
    Cheers, Frank

    I would really have gone for your first approach. With mperemsky5's approach you have the loop with (potential) n iterations (Let n be the length of the number) and in each iteration to compute the hash-code for the string which again takes time proportional to the strings length.
    The tree approach takes time equal to the length of the prefix and is imho not more complicated.
    Perhaps this way:
    public class DigitTree
      private class Node {
           private Object content;
           private Node[] children = new Node[10];
      private Node root = new Node();
      public DigitTree() {
      public void addPrefix(String prefix, Object value) {
           char[] numberChars = prefix.toCharArray();
           Node node = root;
           for (int i=0; i<numberChars.length; i++) {
                int number = numberChars[i] - '0';
                if (node.children[number] == null) node.children[number] = new Node();
                node = node.children[number];
           node.content = value;
      public Object match(String phonenumber) {
           char[] numberChars = prefix.toCharArray();
           Node node = root;
           for (int i=0; i<numberChars.length; i++) {
                int number = numberChars[i] - '0';
                if (node.children[number] == null) return code.content;
                node = node.children[number];
           return node.content;
    }The method addPrefix lets you add a prefix to the tree. The content-Object can hold a String or whatever to identify the prefix. If your data is not complete (i.e. if there are numbers for which no prefix exists) you might want to initialize the content-object of a node with a default value (e.g. "not found").
    The method match lets you look up a prefix for a given number and returns the Object associated with the prefix..
    The code was not tested.
    Greetings
    Thomas

Maybe you are looking for

  • The screen goes black for about 1/2 a second.

    The screen goes black for about 1/2 a second. Is it time to panic?

  • Why two FLOAT values are stored differently?

    Curious as to why two FLOAT values are stored differently. Inserting two FLOAT values one with value of 99E9 and the other with 12E-9. Value for 99E9 was stored in the database as 99000000000 and 12E-9 was stored in the database as 1.2E-8. Why were t

  • Condition Classification - Changed

    Hi All, I have created a PO and posting of excise invoice is also done. Now I have changed "TAX CONDITION CLASSIFICATIONS" in SPRO as shown below (tax settings for India) I have added the following condition types (AFTER POSTING THE EXCISE INVOICE) i

  • Kinds of packages.......???

    Hi, In java we are using basically four types of packages .. like java.. javax.. com... org... why sun separate the com and org packages from the java,javax.......?? and what is the real functionalities and the difference among them..... can anybody

  • So, there's no plugin to keep Library up-to-date?

    The other day, I posted a question if there is any way to keep Library up-to-date. I've got 2 replies. One person said there's no such way, and the other person told me a Javascript file that removes dead files from Library. But he said he didn't kno