Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^2: Tree in perl

by saurabh2k26 (Initiate)
on Nov 17, 2014 at 15:02 UTC ( #1107426=note: print w/replies, xml ) Need Help??


in reply to Re: Tree in perl
in thread Tree in perl

I dont know where to start. I mean, after taking inputs, how to store them as vertex and edges. How to check the connecting edges.

Replies are listed 'Best First'.
Re^3: Tree in perl
by roboticus (Chancellor) on Nov 17, 2014 at 15:14 UTC

    saurabh2k26:

    As you can see from McA's and my code examples, there are plenty of ways to represent the data structures. For the code McA presented, you can check if a node exists via if (exists $vertices{$node}) { ... } and edges with if (exists $edges{$src}{$dst}) { ... }. In my example, I opted to use a two-level hash, where the first key is the source node and the second key is the destination. So in mine you'd test whether a node exists the same way as McA presented, but to check for the edge, you need to use if (exists $G{$src} and exists $G{$src}{$dst}) { ... }. (You can omit the first clause if you know that the source node exists, but if you're not certain, you need the first clause so that you don't accidentally create (through autovivification) new graph nodes. For example, if you add this line just before the print statement in my code:

    print "BAM!\n" if exists $G{25}{30};

    You'll find that node 25 gets added to your graph:

    { 1 => { 2 => 0, 3 => 0 }, 2 => { 3 => 0, 4 => 0 }, 3 => { 5 => 0 }, 4 => { 5 => 0 }, 5 => {}, 25 => {}, } Start: 1, End: 5

    Update: If I were going to store any significant data in the nodes, then I'd make it a three-level hash, where the second level would be {EDGES} to let you represent the graph structure, and other keys would hold the node-specific data. The data elements under the {EDGES} can hold edge-specific data, like so:

    my %G = ( 1=>{ EDGES=> { # Edges for node 1 2=>{ "Data for edge 1->2" }, 3=>{ "Data for edge 1->3" }, FOO=> { "a data element for node 1" }, BAR=> { "another data elemment for node 1" }, }, 2=> ... }

    If you use McA's method, you can just use the two hashes to hold the data, instead of adding a hash key layer.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1107426]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2022-08-14 18:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?