Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Tree in perl

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


in reply to Tree in perl

saurabh2k26:

You don't really need external modules to handle problems like this. It's pretty simple to represent graphs and trees with the basic perl data structures:

$ cat foo.pl #!/usr/bin/env perl use strict; use warnings; use Data::Dump qw(pp); my $t = <DATA>; my ($nV, $nE) = split /\s+/,$t; # read graph my %G; my ($src, $dst); while (<DATA>) { next if /^\s+$/; ($src, $dst) = split /\s+/; last if !$nE--; $G{$src}{$dst}=0; $G{$dst} = {} if ! exists $G{$dst}; } print pp(\%G),"\nStart: $src, End: $dst\n\n"; __DATA__ 5 6 1 2 2 3 2 4 4 5 1 3 3 5 1 5 $ perl foo.pl { 1 => { 2 => 0, 3 => 0 }, 2 => { 3 => 0, 4 => 0 }, 3 => { 5 => 0 }, 4 => { 5 => 0 }, 5 => {}, } Start: 1, End: 5

Since your data was a graph, I used a hash to represent the data. If you had a tree, you could use nested array references. Once you read it in, it's just a matter of adding the algorithm you want to try.

...roboticus

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

Replies are listed 'Best First'.
Re^2: Tree in perl
by saurabh2k26 (Initiate) on Nov 17, 2014 at 15:57 UTC

    Thanks, i tried this and it works and i am getting to understand it. But again, Data::Dump is not allowed in programming contests. Can you update your code without using Data::Dump

      saurabh2k26:

      I just used Data::Dump to print the data structure to the screen. You don't need it at all, but I needed it or you wouldn't see what data structure was created. Once you understand the data structure and create your algorithm, you can present the results any way you like.

      ...roboticus

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

      You wanted to get a starting point. You got one, no two.

      Do you want to win a contest or do you want to learn Perl?

      Regards
      McA

        syntax error at t.pl line 11, near "+ }"
        I am trying to removing syntax error from your code, but no success. Can you check it.
      A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-03-19 11:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found