Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^3: Tree in perl

by roboticus (Chancellor)
on Nov 17, 2014 at 15:14 UTC ( [id://1107429]=note: print w/replies, xml ) Need Help??


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

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://1107429]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-25 16:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found