Retrieving root id in hierarchial data structure.

HI,
I have data arranged in tree having parent child relationship as below .But i need to retrieve the root in the tree.Please let me know how can i achieve this.
parent child
A B
B C
C D
D E
M N
N O
In the above case i need to get root element of tree through query i.e in my case it will be A and N.How can we achieve this

And why not 'M'?
I'm not sure about the exact requirement, but you could try to fiddle a bit with connect_by_root etc.:
SQL>  -- generating sample data:
SQL>  with t as (
  2   select 'A' p, 'B' c from dual union
  3   select 'B', 'C' from dual union
  4   select 'C', 'D' from dual union
  5   select 'D', 'E' from dual union
  6   select 'M', 'N' from dual union
  7   select 'N', 'O' from dual
  8   )
  9   --
10   -- actual query:
11   --
12   select connect_by_root(p) root_p
13   ,      ltrim(sys_connect_by_path(p, '/'), '/') scbp
14   ,      connect_by_isleaf
15   ,      level lvl
16   from   t
17   where  connect_by_isleaf = 1
18   connect by p = prior c
19   order siblings by p;
R SCBP       CONNECT_BY_ISLEAF        LVL
A A/B/C/D                    1          4
B B/C/D                      1          3
C C/D                        1          2
D D                          1          1
M M/N                        1          2
N N                          1          1

Similar Messages

  • Open ended data structure for retrieving SQL data

    I have a flex project that reads data from a database and
    sends it to my flex app to display in a chart. I need to do this in
    Actionscript since I have to dynamically create different charts
    based on the database definitions. Up til now, I have inserted the
    data for each series into a separate
    ArrayList(java)/ArrayCollection(flex) in this way:
    BindingUtils.bindProperty(lineSeries, "dataProvider", series,
    "pointList");
    lineSeries.xField="point1";
    lineSeries.yField="point2";
    The series variable is a custom Actionscript/Java object
    which contains an ArrayCollection called pointList. And the array
    is made up of custom DataObjects with two fields, point1 &
    point2.
    But in the new paradigm, I'd basically like to create a big
    array of arrays similar to a database table and then just point the
    xField to one column, and the yField to another column. Anyway, it
    seems like the problem is that my point1 and point2 in the current
    implementation are variable names, but with this new dynamic
    structure, I won't be able to create variables on the fly. So how
    do I let flex know to look at column 3, for example for the yField?
    The attached code is from the Flex documentation and is an example
    of what I'd like to emulate (except I need to do it in
    actionscript). I'd like to be able to select "month" or "amount",
    etc. But coming from the Java side, there is no way for me to name
    the array contained in each column.

    I guess I wasn't clear enough. I am actually serializing a
    java object and mapping it to an actionscript object via blazeDS. I
    know about how the objects translate, for example for
    ArrayCollections in flex, I use ArrayLists in java. The problem is
    that I'm not sure how to get the associative aspects of the arrays
    in flex into my java data structures in a way that will translate
    to the way flex can define arrays, such as Month:"January".
    It seems that in flex, you can create an Array and assign it
    an element like {month:"January", amount:"450"} and it will create
    an Object with variables for month and amount. But I don't know how
    to do this on the fly in Java (or in Actionscript for that matter)
    when I have no way of knowing beforehand how many variables my
    object will need. Each series will need an x and y, though usually
    the x will be dates which are the same for each series. So if I had
    10 series sharing an axis, I'd need 11 variables in my object-
    date, series1, series 2...series 10.

  • Data Structure Needed

    *** PLEASE DO NOT REPLY TO THIS POSTING UNLESS
    *** YOU KNOW EXACTLY WHAT I AM TALKING ABOUT
    *** AND HAVE SOLUTION AT THE READY.
    *** NO SWING TREE FYIs PLEASE...doesn't apply.
    *** NO UI JAVASCRIPTS .. I HAVE THOSE.
    I need a properly constructed multiway
    (m-way, general, n-ary, etc.) data structure
    implementation that uses non-ui
    dependent/associated classes. This is know as the
    first child/next sibling data structure used in
    Filesystems (similiar to a BTree).
    I am using many delimited strings, similiar to a
    directory/file structure path but the string is a
    software project hierarchy.
    [a string is structured like this]
    root|branch|...|branch|leaf
    [Process]
    1) the strings are fetched from DB by servlet.
    2) servlet feeds strings into data structure
    to eliminate duplicates and place in proper location.
    3) servlet uses contents of data structure to
    construct links that are coupled with the infamous
    ui-tree script.
    If you know your data structures and have an implementation
    that won't take me 6 days to modify for it to work I would
    appreciate your assistance. I am creating on my own as we
    speak but one from a more experienced java programmer would
    be better.
    Thank You,
    Kevin

    Sounds like one hell of a frustrated programmer over there - all those capitals an'all..
    If I understand you correctly, I don't think you'd take six days to implement this; just split your string by the separator;
    String[] split(String path, char sep, char esc) {
      String[] result = new String[0];
      int o = 0;
      int i; for (i=0; i<path.length(); ++i) {
        char c = path.charAt(i);
        if (c == esc) {
          ++i;
          continue;
        if (c == sep) {
          String substring = path.substring(o, i);
          String[] newresult = new String[result.length+1];
          System.arraycopy(result, 0, newresult, 0, result.length);
          newresult[result.length] = substring;
          result = newresult;
          o = i+1;
    }Then have a java.util.Hashtable as root, with all names in it pointers to either more Hashtables (nodes), or Strings (leaves). If it really does not get anymore complex than that (data associated with leaves, for example), you don't really have to use anything more complex than 'instanceof' here.
    Then start looping over all your String[] split paths, retrieve all nodes, if it's a String and you have a child for it, then convert it to a Hashtable, it it's a Hashtable trod along, if it isn't there create a String (unless you know you have an extra child, in which case you create a Hashtable).
    When you're ready to retrieve, just enumerate your root Hashtable, casting to String all the keys, examining all the values; if they are Hashtable, then recurse. If they're Strings, do your Thing (TM).

  • Simple Transformation to deserialize an XML file into ABAP data structures?

    I'm attempting to write my first simple transformation to deserialize
    an XML file into ABAP data structures and I have a few questions.
    My simple transformation contains code like the following
    <tt:transform xmlns:tt="http://www.sap.com/transformation-templates"
                  xmlns:pp="http://www.sap.com/abapxml/types/defined" >
    <tt:type name="REPORT" line-type="?">
      <tt:node name="COMPANY_ID" type="C" length="10" />
      <tt:node name="JOB_ID" type="C" length="20" />
      <tt:node name="TYPE_CSV" type="C" length="1" />
      <tt:node name="TYPE_XLS" type="C" length="1" />
      <tt:node name="TYPE_PDF" type="C" length="1" />
      <tt:node name="IS_NEW" type="C" length="1" />
    </tt:type>
    <tt:root name="ROOT2" type="pp:REPORT" />
        <QueryResponse>
        <tt:loop ref="ROOT2" name="line">
          <QueryResponseRow>
            <CompanyID>
              <tt:value ref="$line.COMPANY_ID" />
            </CompanyID>
            <JobID>
              <tt:value ref="$line.JOB_ID" />
            </JobID>
            <ExportTypes>
              <tt:loop>
                <ExportType>
                   I don't know what to do here (see item 3, below)
                </ExportType>
              </tt:loop>
            </ExportTypes>
            <IsNew>
              <tt:value ref="$line.IS_NEW"
              map="val(' ') = xml('false'), val('X') = xml('true')" />
            </IsNew>
          </QueryResponseRow>
          </tt:loop>
        </QueryResponse>
        </tt:loop>
    1. In a DTD, an element can be designated as occurring zero or one
    time, zero or more times, or one or more times. How do I write the
    simple transformation to accommodate these possibilities?
    2. In trying to accommodate the "zero or more times" case, I am trying
    to use the <tt:loop> instruction. It occurs several layers deep in the
    XML hierarchy, but at the top level of the ABAP table. The internal
    table has a structure defined in the ABAP program, not in the data
    dictionary. In the simple transformation, I used <tt:type> and
    <tt:node> to define the structure of the internal table and then
    tried to use <tt:loop ref="ROOT2" name="line"> around the subtree that
    can occur zero or more times. But every variation I try seems to get
    different errors. Can anyone supply a working example of this?
    3. Among the fields in the internal table, I've defined three
    one-character fields named TYPE_CSV, TYPE_XLS, and TYPE_PDF. In the
    XML file, I expect zero to three elements of the form
    <ExportType exporttype='csv' />
    <ExportType exporttype='xls' />
    <ExportType exporttype='pdf' />
    I want to set field TYPE_CSV = 'X' if I find an ExportType element
    with its exporttype attribute set to 'csv'. I want to set field
    TYPE_XLS = 'X' if I find an ExportType element with its exporttype
    attribute set to 'xls'. I want to set field TYPE_PDF = 'X' if I find
    an ExportType element with its exporttype attribute set to 'pdf'. How
    can I do that?
    4. For an element that has a value like
    <ErrorCode>123</ErrorCode>
    in the simple transformation, the sequence
    <ErrorCode>  <tt:value ref="ROOT1.CODE" />  </ErrorCode>
    seems to work just fine.
    I have other situations where the XML reads
    <IsNew value='true' />
    I wanted to write
    <IsNew>
            <tt:value ref="$line.IS_NEW"
            map="val(' ') = xml('false'), val('X') = xml('true')" />
           </IsNew>
    but I'm afraid that the <tt:value> fails to deal with the fact that in
    the XML file the value is being passed as the value of an attribute
    (named "value"), rather than the value of the element itself. How do
    you handle this?

    Try this code below:
    data  l_xml_table2  type table of xml_line with header line.
    W_filename - This is a Path.
      if w_filename(02) = '
        open dataset w_filename for output in binary mode.
        if sy-subrc = 0.
          l_xml_table2[] = l_xml_table[].
          loop at l_xml_table2.
            transfer l_xml_table2 to w_filename.
          endloop.
        endif.
        close dataset w_filename.
      else.
        call method cl_gui_frontend_services=>gui_download
          exporting
            bin_filesize = l_xml_size
            filename     = w_filename
            filetype     = 'BIN'
          changing
            data_tab     = l_xml_table
          exceptions
            others       = 24.
        if sy-subrc <> 0.
          message id sy-msgid type sy-msgty number sy-msgno
                     with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        endif.

  • How to load 3.x hierarchy data source from a certain level ?

    Hi all,
    I have an old 3.x hierarchy data souce which has a structure like below :
       Level 0 :  root node
                  Level 1:  Product Category
                      Level 2: Product Line
                          Level 3: Product
                              Level 4 : Product Version
    each level has independent infoobject for it.
    The hierarchy was initially constructed for the infoobject on the level 4 'Product Version'.
    Now here comes anther requriement, we also want to have a hierarchy for 'Product' and try to reuse the datasource.
    So the question is , is it possible to extract from the same data source, while just update the hierarchy for 'Product ' starting from the level 3 (up to level 0)?
    PS: i can't migrate the data souce to 7.X, because the source system doesn't support.
    I hope I made my question clearly.
    Really apprericated that you can give me a hint.
    Thanks,
    Amon

    Finally I solved this problem myself.
    there are many mays if you want to realize the requirement, only if you change your way of thinking, don't be stuck your mind with the thought we have to use the original data source coming from the source system.
      I'd like to introduce 2 ways I am thinking of:
    1. use the SAP standard program 'Z_SAP_HIERARCHY_DOWNLOAD' to save the hierarchy as a .csv file, then you can refer to http://scn.sap.com/community/data-warehousing/bw/blog/2012/01/08/bw-730-hierarchy-loading-becomes-easier-with-the-help-of-new-framework
    however this didn't work for me, because the program might be outdated in my working environment BW7.4, though I did some bugfix for this program , the output file seems with some errors.
    2. since the hierarchy for the 4th level infoobject has been successfully updated in my case, we can use it as the data provider directly . Here is the general dataflow : 4th level infoobject hierarchy -> DSO -> target infoobject hierarchy (3rd level infoobject) .
    for this DSO strucure, you should also refer to the link above, the structure is just like the EXCEL file provided. but you should be aware of adding external characteristics in the data fields of your DSO if there is external characteristics in your hierarchy.
    in the transformation of 'source infoobject hierarchy' , you should select 'hierarchy (one segment)' as the subtype of hierarchy.
    in the transoformation of 'DSO -> target infoobject' , you should map the source and target carefully , especially for the segment 'Structure' , you should make sure the field 0H_HIERNODE and the external chars. have proper value filled.

  • Path based data structure

    I need to create a path based data structure which not only will map path keys to values, but also allow me to specify a partial path and retrieve a listing of all keys that 'descend' from that path. The values for each path will be various primitive and Collecions values. I'm implementing this as a generic data cache, so access time is critical.
    I was thinking of designing my own, but was wondering if the API might come with something useful that does most of this work already? I'd want a solution that draws from the J2SE rather than additional libraries.
    Mark McKay
    http://www.kitfox.com

    If I understand you correctly you're looking for some tree like, or some directory like
    structure? You could use a Map for a single path component, storing all the keys
    and their associated sub-path components. The values for each path component
    could be stored in a List (or a Set if you don't want duplicates). Something like this:public class PathComponent {
       private static PathComponent root= new PathComponent();
       public static PathComponent getRoot() { return root; }
       private Map subDirs= new HashMap();
       private List values= new LinkedList();
       private PathComponent getPath(String[] path, int depth) {
          if (depth == path.length)
             return this;
          PathComponent sub= subDirs.get(path[depth++]);
          return (sub == null)?null:sub.getPath(path, depth);
       public PathComponent getPath(String[] path) { return getPath(path, 0); }
       public List getValues() { return values; }
       // etc. etc.
    }kind regards,
    Jos

  • I have hierarchy data in R/3 side how will i load that data from R/3 to BW

    Hi all,
    i have my hierarchy data in the R/3 side how will i load that data from  R/3 to BW side
    Regard
    Kiran Kumar

    Hi Kiran,
    Here is the procedure:
    1.      In the Data Warehousing Workbench under Modeling, select the InfoSource tree.
    2.      Select the InfoSource (with direct update) for the InfoObject, to which you want to load the hierarchy.
    3.      Choose Additional Functions® Create Transfer Rules from the context menu of the hierarchy table object for the InfoObject. The Assign Source System dialog box appears.
    4.      Select the source system from which the hierarchy is to be loaded. The InfoSource maintenance screen appears.
    ○       If the DataSource only supports the transfer method IDoc, then only the transfer structure is displayed (tab page DataSource/Transfer Structure).
    ○       If the DataSource also supports transfer method PSA, you can maintain the transfer rules (tab page Transfer Rules).
    If it is possible and useful, we recommend that you use the transfer method PSA and set the indicator Expand Leaf Values and Node InfoObjects. You can then also load hierarchies with characteristics whose node name has a length >32.
    5.      Save your entries and go back. The InfoSource tree for the Data Warehousing Workbench is displayed.
    6.      Choose Create InfoPackage from the context menu (see Maintaining InfoPackages). The Create InfoPackage dialog box appears.
    7.      Enter the description for the InfoPackage. Select the DataSource (data element Hierarchies) that you require and confirm your entries.
    8.      On the Tab Page: Hierarchy Selection, select the hierarchy that you want to load into your BI system.
    Specify if the hierarchy should be automatically activated after loading or be marked for activation.
    Select an update method (Full Update, Insert Subtree, Update Subtree).
    If you want to load a hierarchy from an external system with BAPI functionality, make BAPI-specific restrictions, if necessary.
    9.      If you want to load a hierarchy from a flat file, maintain the tab page: external data.
    10.      Maintain the tab page: processing.
    11.      Maintain the tab page: updating.
    12.      To schedule the InfoPackage, you have the following options:
    ○       (Manually) in the scheduler, see Scheduling InfoPackages
    ○       (Automatically) using a process chain (see Loading Hierarchies Using a Process Chain)
    When you upload hierarchies, the system carries out a consistency check, making sure that the hierarchy structure is correct. Error messages are logged in the Monitor. You can get technical details about the error and how to correct it in the long text for the respective message.
    For more info visit this help pages on SAP Help:
    http://help.sap.com/saphelp_nw04s/helpdata/en/80/1a6729e07211d2acb80000e829fbfe/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/3d/320e3d89195c59e10000000a114084/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/80/1a6729e07211d2acb80000e829fbfe/frameset.htm
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/4dae0795-0501-0010-cc96-fe3a9e8959dc
    Cheers,
    Habeeb

  • How to import Hierarchy Data in MDM 7.1

    Hi All,
        I am trying to import the hierarchy data to SAP MDM 7.1
    I have the data in the Excel sheet in the following structure
    Parent Code   Parent Name   Child Code   Child Name
    A1                  Printer              P1               Inkjet
    A1                  Printer              P2               Canon
    P1                   inkjet                Q1               Model - XXX
    P2                   Canon              Q2              Model - YYY
    In MDM i have 2 fields in the hierarchy table Code and Name as display fields.
    I tried to do partition of fields, combine fields as per the Import documentation. But i was not able to import the hierarchy.
    I have also seen some papers on SDN for Hierarchy import, but none of them talk about 2 display fields in the hierarchy table.
    Can anyone help me to import the data to MDM.
    Thanks,
    Priya.

    Hi Priya.
    You have three level hierarchy in your example
        A1    !     Printer
             P1   !    inkjet
                Q1   !    Model - XXX
    Parent Code ! Parent Name  ! Child Code ! Child Name
    in your import manager
    select "Partition Field/value" Tab
    In source partition window select  your "Parent code" filed
    press add
    select  your "Parent name" filed
    press add
    in window "Partition by:" select "Parent name" and "Parent code"  fields  and press "Combine" button
    for next fields you sould repeat previous steps
    then  select "Map Fields/values"
    find  in Field mapping Source field:  "Parent code [Partition]"
    map it to "Code"
    in "Values conversion mapping" window
    select all walues and press "Add" button then Add as Child
    More about import hierarchy:
    http://www.sdn.sap.com/irj/scn/index?rid=/library/uuid/b07849c7-3a5b-2b10-7586-c431d300a578
    Regards
    Kanstantsin

  • DELETE  HIERARCHY DATA,CONNECT BY  SQL/PLSQ

    Hi
    Please help with the logic!
    I am trying to delete the data from the hierarchy table data(TABLE1) based on another table(TABLE2),For this i am using 2 cursors (get_ssn and get_max),
    problem is with deleting the hierarchy data, there are several levels (few of them upto 10 levels), i have to delete from top to bottom level of the hierarchy structure
    the first cursor returns the hierarchy structure
    level ssn report_to baid
    1
    2
    3
    1
    2
    1
    2
    3
    4
    my plan is to pull the max of the level and delete it, loop the max value and decrement it by 1 in every iteration and delete the rows, below is the rough logic,
    please help me building up the logic
    declare
    lev eweb.level%TYPE;
    i = number :=0;
    cursor get_ssn is --> this cursor is getting ssn based on simple join between two tables
    select level, ssn, report_to, baid
    from TABLE1
    where ssn not in ( select e.ssn
    from TABLE1 e, TABLE2 s
    where e.ssn = s.ssn)
    start with ssn in (select e.ssn
    from TABLE1 e)
    connect by prior report_to=baid;
    cursor get_max is --> pulling the max of level
    select max(level)
    from eweb
    where ssn not in ( select e.ssn
    from TABLE1 e, TABLE2 s
    where e.ssn = s.ssn)
    start with ssn in (select e.ssn
    from TABLE1 e)
    connect by prior report_to=baid;
    BEGIN
    for i in get_ssn
    loop i := i+1;
    Delete from eweb --> here im trying to delete rows by using max(level)-i, in 1st iteration it takes the max value, in next iteration it will be max -1..........
    where level = get_max-i
    END LOOP;
    end for loop;
    END;
    Edited by: user8884944 on Jun 23, 2010 11:34 AM

    A few remarks
    1 The subject line was shouted by using all caps. This must be considered rude
    2 The introduction discusses 2 tables, yet the code deals with 3, and only from the third table data is deleted
    3 no CREATE TABLE statements were posted, nor sample data
    4 if you can put a constraint on the affected column, using on cascade delete, everything will be deleted automagically.
    With this little information, no help is possible. We can not see what each statement does, the comments don't tell anything, and we can also not see what it is expected to do in terms of logics, as the statements are almost certainly wrong.
    Sybrand Bakker
    Senior Oracle DBA

  • Data structure for web-based discussion forum

    Hello all. I have begun work on a discussion board forum but have not yet decided upon a data structure for the hierarchy of messages to be left on a board. Any one have any thoughts or experience in this matter? My first thought was to implement a basic linked list in which every reply to a message would be a new child of a node. This would require I use recursion in some areas for counting and finding messages but I was also thinking that this way I can store each thread object in a simple fashion using serialization.
    SJ

    THE STANDARS DIRECTORY STRUCTURE IS :-
    PROJECT FOLDER
    |
    |---------->WEB-INF
    |------> web.xml file
    |-------> classes (folder to keep java files)
    |-------> lib (folder to keep jar files)

  • 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

  • Implementing a Graph Data Structure

    First time posting here, I was introduced to LabVIEW while participating in FIRST.
    I was reading about Graph Data Structures, and wanted to see if I could use them in LabVIEW, as it looked like a good way to relate information. Unfortunately, it appears that the straight forward way that I attempted will not work. I tried creating a typedef which consisted of a cluster of two elements, an array of linked nodes and an array of edge weights. Alas, I found you can't have recursive data types, as the array of linked nodes in the typedef needed to be the same as the typedef. I know why this is after a bit of searching, but I was wondering if there was a way to get around this. From my research, it seems like using a root class and a child class is one possible, but advanced way of doing it.
    I am currently thinking of just representing the linked nodes of a node as an array of index numbers which you can use to get the referenced nodes from the graph array. This means that the graph array cannot be sorted or otherwise modified so that the index numbers won't work, you can only add objects onto the end. Is this thinking right, or is there a different way to go about this?
    Solved!
    Go to Solution.

    Not an easy problem, as recursion is not native to LV programming (much less than any other language I used except assembler).
    But the solution to your index number problem is to use 'keys'. Each node should have a unique key (number), so you can adress it (search for the key) even if the array is sorted in some way.
    Again, it is not native to LV. This means, that you need to program the logic other languages use for that on your own (pseudo-pointers, handles, keys, hashes).
    From a practical side: I would not implement the graph in LV itself but access a graph from some other source (data base?) via an interface (ActiveX, .NET). To learn a bit more about how to do it, try playing around with the tree control (it is a limited graph).
    Felix
    www.aescusoft.de
    My latest community nugget on producer/consumer design
    My current blog: A journey through uml

  • Relationship between Dynamic Memory Heap and Heap Data Structure

    This question is not strictly related to Java, but rather to programming in general, and I tend to get better answers from this community than any where else.
    Somehow, my school and industry experience have somehow not given me the opportunity to explore and understand heaps (the data structure), so I'm investigating them now, and in particular, I've been looking at applications. I know they can be used for priority queues, heap sorts, and shortest path searches. However, I would have thought that, obviously, there must be some sort of relationship between the heap data structure, and the dynamic memory heap. Otherwise, I can think of no good reason why the dynamic memory heap would be named "heap". Surprisingly, after searching the web for 90 minutes or so, I've seen vague references, but nothing conclusive (trouble seems to be that it's hard to get Google to understand that I'm using the word "heap" in two different contexts, and similarly, it would not likely understand that web authors would use the word in two different contexts).
    The Java Virtual Machine Spec is silent on the subject, as "The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements."
    I've seen things like:
    [of dynamic memory] "All the blocks of a particular size are kept in a sorted linked list or tree (I extrapolate that sorted tree could imply heap)"
    [of dynamic memory] "The free and reserved areas of memory are maintained in a data structure similar to binary trees called a heap"
    [of dynamic memory] "This is not related to the heap data structure"
    [of dynamic memory] "Not to be confused with the data structure known as a "heap"
    [of data structure] "Not to be confused with the dynamic memory pool, often known as TheHeap"
    At this point, I've come to surmise that some (but not all) memory management algorithms use heaps to track which (pages? blocks? bytes?) of memory are used, and which are not. However, the point of a heap is to store data so that the max (or min) key is at the root of the heap. But we might want to allocate memory of different sizes at different times, so it wouldn't make sense to key on the amount of available memory in a particular region of the free store.
    I must assume then that there would be a different heap maintained for each size of memory block that can be allocated, and the key must have something to do with the attractiveness of the particular memory block in the heap (perhaps the lowest address, resulting, hopefully, in growing the free store space less often, leaving more space for the stack to grow, or perhaps keyed based on the fragmentation, to hopefully result in less fragmentation, and therefore more efficient use of the memory space, or perhaps based on page boundaries, keeping as much data in the same page as possible, etc).
    So at this point, I have a few questions I've been unable to resolve completely:
    1. Am I correct that the heap was so named because (perhaps at one point in time), a heap is/was commonly used to track the available memory in the free store?
    2. If so, would it be correct that there would be a heap per standard block size?
    3. Also, at what level of granularity would a heap typically be used (memory page, memory blocks, individual words (4-bytes))?
    4. What would be the most likely property one would use as a key. That is, what makes the root item on the heap ideal?
    5. Would a industrial strength system like the jvm use a (perhaps modified or tuned) heap for this sort of task, or would this typically be too naive for an real world solution today?
    Any insight would be awesome!
    Thanks,
    A.

    jschell wrote:
    I think you are not only mixing terms but domains.
    For starters the OS allocs memory. Applications, regardless of language, request memory from the OS and use it in various ways.
    There are many variations of the term "heap" like the following.
    [http://en.wikipedia.org/wiki/Heap_(data_structure)]
    [http://en.wikipedia.org/wiki/Dynamic_memory_allocation]
    A java VM will request memory from the OS (from a 'heap') and use it in its application 'heap' (C/C++) and then create the Java 'heap'. There can be variations of that along the way that can and likely will include variations of how each heap is used, potentially code that creates its own heap, and potentially other allocators which use something which is not a heap.This last part, I find a bit confusing. By "use something which is not a heap", do you mean the heap data structure, or the dynamic memory pool meaning of heap? If the former, then you would be implying that it would be common for a heap data structure to be used to manage the heap dynamic memory pool. If the latter, what would this "something which is not a heap" be? The best definition of "heap" I've found simply states that it is a pool of memory that can be dynamically allocated. If there is some other way of allocating dynamic memory, then it would suggest that the previous definition of "heap" is incomplete.
    >
    So to terms.
    1. Am I correct that the heap was so named because (perhaps at one point in time), a heap is/was commonly used to track the available memory in the free store?Which 'heap'? The VM one? It is probably named that because the implementors of the Sun VM were familar with how C++ and Smalltalk allocated memory.Okay, but that begs the question, was the heap in C++ and/or Smalltalk so named for the above queried reason?
    >
    2. If so, would it be correct that there would be a heap per standard block size?Not sure what you are referring to but probably a detail of the implementation. And since there are different levels the question doesn't mean much.
    However OS allocations are always by block if that helps. After that it requires making the question much, much more specific.
    3. Also, at what level of granularity would a heap typically be used (memory page, memory blocks, individual words (4-bytes))?Again not specific enough. A typical standard implementation of heap could not be at the word level. And it is unlikely, but not impossible, that variations would support word size allocations.
    The VM heap might use word boundaries (but not size), where the application heap certainly does (word boundary.)My understanding of it is that the application would request blocks from the OS, and then something like malloc would manage the memory within the allocated blocks. malloc (or whatever equivalent Java uses) would have to keep track of the memory it has allocated somehow, and I would think it would have to do this at the word level, since it's most commonly going to allocate memory at the word level to be references to other objects, etc.
    So I guess my question here would really be, if the dynamic memory heap is so named because there has been a memory management strategy that relied upon a heap data structure (which I've found no proof, but have found some suggestive literature), then would that probably have applied at the OS Page Fault level, tracking allocated blocks, or would that have applied at the malloc level, allocating individual words as necessary?
    >
    4. What would be the most likely property one would use as a key. That is, what makes the root item on the heap ideal?"Key" is not a term that will apply in this discussion.
    You appear to be referring to strategies for effective allocation of memory such as allocations from different regions by size comparison.
    It is possible that all levels might use such an allocator. General purpose applications do not sort allocations though (as per your one reference that mentions 'key'.) Sorry, I got the term "key" from an article I read regarding heaps, that indicates that a "key" is used to sort the elements, which I guess would be a more generalized way to make a heap than assuming a natural ordering on the elements in the heap. I'm not sure if the terminology is standard.
    >
    5. Would a industrial strength system like the jvm use a (perhaps modified or tuned) heap for this sort of task, or would this typically be too naive for an real world solution today?Again too indefinite. The Sun VM uses a rather complicated allocator, the model for which originated after years of proceeding research certainly in Smalltalk and in Lisp as well, both commercially and academically.
    I am sure the default is rules driven either explicitly or implicitly as well. So it is self tuning.
    There are command line options that allow you to change how it works as well.I guess perhaps I could attempt to clarify my initial question a bit.
    There is a 1:1 correspondence between the runtime stack, and a stack data structure. That is, when you call a function, it pushes a stack frame onto the runtime stack. When you return from a function, it pops a stack frame from the runtime stack. This is almost certainly the reasons the runtime stack is named as it is.
    The question is, is there or has there ever been a 1:1 correspondence between some aspect of the dynamic memory heap or how it is managed, and a heap data structure? If so, it would explain the name, but I'm a bit puzzled as to how a heap data structure would be of assistance in creating or managing the dynamic memory heap. If not, on the other hand, then does anybody know where the name "heap" came from, as it applies to the dynamic memory pool?
    A.

  • About data structure

    hi all,
    here i do have another data structure related question where is concerning the JTree i have asked before this. how do i define/design the data structure that will suite my JTree application?
    my JTree will take many information as the data that it has at most 4 level including the root. the data may pass from the server, and it may be not in order, how do i do that?
    thanks a lot

    hmm... i have modify a bit of the data structure class as describe below:
    i have done all of the JTree part of my applet, except now only headache problem is that how do i gonna define my JTree data structure efficiently? i mean that there are many possible of data that will pass through the applet to create my JTree, there may be not in order though, so how can i define a suitable data structure to handle the data that coming in to the JTree?
    what i have done so far is that i have created a class (consider the data object) to handle the data, whereby the server will pass the data according to the class structure, which then i get the data from there and create my JTree node. in the data object, for sure i put a parameter that will detect the level of the tree node, where i can successfully put it in the JTree, but is there any other better way?
    thank you

  • Bit shifting tricks and speeding up data structure

    I'm pretty new to working directly with bits, but it is a lot of fun. I'm converting a javascript data structure to Flash.
    So I'm thinking that Math.floor(uint/32) is the same as uint >> 5, right?
    And that uint % 32 is the same as uint & 31 ? Evidently this works for modulos that are powers of 2, what a cool trick.
    Using both of those cut the time needed for storing and retrieving data about in half.
    But it is still takes about three times longer that just using the native Object. This is in reference to my previous post http://forums.adobe.com/message/5001353#5001353 but that didn't get very far.
    So if anybody has any suggestions on how else to speed this up it would be very helpful:
    package {
              public class BloomFilter {
                        private var _m:uint;
                        private var _k:int;
                        private var _locations:Vector.<uint>;
                        public var _buckets:Vector.<uint>;
                        public function BloomFilter(m:uint,k:int) {
                                  _m=m;
                                  _k=k;
                                  _locations=new Vector.<uint>  ;
                                  _buckets=new Vector.<uint>  ;
                                  var n:uint=Math.ceil(m/32);
                                  var i:int=-1;
                                  while (++i<n) {
                                            _buckets[i]=0;
                        private function hash(v:String) {
                                  var i:int=-1;
                                  var X:uint;
                                  var a,b:uint;
                                  a=fnv_1a(v);
                                  b=fnv_1a_b(a);
                                  X=a%_m;
                                  while (++i<_k) {
                                            _locations[i]=X<0? (X+_m) : X;
                                            X=(X+b)%_m;
                        public function add(v:String) {
                                  hash(v);
                                  var i:int=-1;
                                  while (++i<_k) {
                                            _buckets[_locations[i]>>5]|=1<<(_locations[i]&31);
                        public function test(v:String):Boolean {
                                  hash(v);
                                  var i:int=-1;
                                  var b:uint;
                                  while (++i<_k) {
                                            b=_locations[i];
                                             if ((_buckets[b>>5] & (1 << (b&31))) === 0) {
                                                      return false;
                                  return true;
                        // Fowler-Noll-Vo hash
                        private function fnv_1a(v:String):uint {
                                  var n:int=v.length;
                                  var a:uint=2166136261;
                                  var c,d:uint;
                                  var i:int=-1;
                                  while (++i<n) {
                                            c=v.charCodeAt(i);
                                            if (d=c&0xff000000) {
                                                      a^=d>>24;
                                                      a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
                                            if (d=c&0xff0000) {
                                                      a^=d>>16;
                                                      a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
                                            if (d=c&0xff00) {
                                                      a^=d>>8;
                                                      a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
                                            a^=c&0xff;
                                            a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
                                  a+=a<<13;
                                  a^=a>>7;
                                  a+=a<<3;
                                  a^=a>>17;
                                  a+=a<<5;
                                  return a&0xffffffff;
                        // One additional iteration of FNV
                        private function fnv_1a_b(a:uint):uint {
                                  a+=(a<<1) + (a<<4) + (a<<7) + (a<<8)+ (a<<24);
                                  a+=a<<13;
                                  a^=a>>7;
                                  a+=a<<3;
                                  a^=a>>17;
                                  a+=a<<5;
                                  return a&0xffffffff;

    the math shortcuts, as mentioned above, have a greater benefit.  (and thanks.  yes, that's from a book i wrote,
    Flash Game Development: In A Social, Mobile and 3D World
    Math Class Shortcuts
    These methods actually do provide a benefit and that benefit can be significant even without needing millions of operations to realize. They are listed in alphabetical order starting with Math.abs. (See support files/Chapter 07/math_class/Math.abs_v_conditional.fla, support files/Chapter 07/math_class/Math.floor_v_int.fla etc.)
    Math.abs
    Using
    x = (y<0) ? -y: y;
    instead of
    x = Math.abs(y)
    is about twice as fast. Unless you are using millions of Math.abs operations, you should not expect a noticeable benefit from using the inline code. In addition, the inline code is cumbersome.
    var xx:int;
    var n:int = 10000000;
    var n2:int = n/2;
    var i:int;
    var startTime:int = getTimer();
    //// Math.abs duration: 1016
    for(i=0;i<n;i++){
           xx = Math.abs(n2-i);
    trace("Math.abs duration:",getTimer()-startTime);
    // conditional duration: 445
    startTime = getTimer();
    for(i=0;i<n;i++){
            xx = (n2-i<0) ? i-n2 : n2-i;
    trace("conditional duration:",getTimer()-startTime);
    Math.ceil and Math.floor
    Using
    x = int(y);
    Instead of
    x = Math.floor(y); // y>=0
    x = Math.ceil(y); // y<=0
    Is about twice as fast. Unless you are using millions of Math.floor operations (with non-negative numbers), you should not expect a noticeable benefit.
    var i:int;
    var n:int = 10000000;
    var xx:int;
    var startTime:int = getTimer();
    // Math.floor duration: 1105
    for(i=0;i<n;i++){
           xx = Math.floor(i/n);
    trace("Math.floor duration:",getTimer()-startTime);
    // int duration: 479
    startTime = getTimer();
    for(i=0;i<n;i++){
           xx = int(i/n);
    trace("int duration:",getTimer()-startTime);
    Math.max
    Using
    x = (i>j) ? i : j;
    instead of
    x = Math.max(i,j);
    is about twice as fast.
    This shortcut is also cumbersome but has the greatest benefit (along with Math.min) of all those listed in this section. Notice the difference in time required to execute the code blocks and how few iterations are needed to demonstrate that difference.
    var xx:int;
    var n:int = 1000;
    var i:int;
    var j:int;
    var startTime:int;
    // Math.max duration: 109
    startTime = getTimer();
    for(i=n-1;i>=0;i--){
           for(j=n-1;j>-0;j--){
                  xx = Math.max(i,j);
    trace("Math.max duration:",getTimer()-startTime);
    // conditional duration 43
    startTime = getTimer();
    for(i=n-1;i>=0;i--){
           for(j=n-1;j>-0;j--){
                   xx = (i>j) ? i : j;
    trace("conditional duration",getTimer()-startTime);
    Math.min
    Using
    x = (i<j) ? i : j;
    instead of
    x = Math.min(i,j);
    is about twice as fast.
    This shortcut is also cumbersome but has the greatest benefit (along with Math.max) of all those listed in this section. Notice the difference in time required to execute the code blocks and how few iterations are needed to demonstrate that difference.
    var xx:int;
    var n:int = 1000;
    var i:int;
    var j:int;
    var startTime:int;
    // Duration Math.min 121
    startTime = getTimer();
    for(i=0;i<n;i++){
           for(j=0;j<n;j++){
                  xx = Math.min(i,j);
    trace("Duration Math.min",getTimer()-startTime);
    // Duration conditional 43
    startTime = getTimer();
    for(i=0;i<n;i++){
           for(j=0;j<n;j++){
                   xx = (i<j) ? i : j;
    trace("Duration conditional",getTimer()-startTime);
    Math.pow
    It is two to three times faster to explicitly multiply a number variable compared to using Math.pow. That benefit even extends a little beyond integer exponents because Math.sqrt(i) is about twice as fast as Math.pow(i,.5).
    var i:int;
    var n:int = 10000000;
    var xx:int;
    var startTime:int;
    // exp .5: 2020, exp 2: 1533, exp 3: 1617, exp 4: 1427, exp 5: 1381, exp 10: 1391
    startTime = getTimer();
    for(i=0;i<n;i++){
           xx = Math.pow(i,.5);
    trace("Duration Math.pow",getTimer()-startTime);
    // exp .5: 1064, exp 2: 427, exp 3: 778, exp 4: 557, exp 5: 501, exp 10: 586
    startTime = getTimer();
    for(i=0;i<n;i++){
           xx = Math.sqrt(i);
    trace("Duration iteration",getTimer()-startTime);

Maybe you are looking for