Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Tree in perl

by McA (Priest)
on Nov 17, 2014 at 15:04 UTC ( [id://1107427]=note: print w/replies, xml ) Need Help??


in reply to Tree in perl

This should help you over the first hurdle. At the end of the following snippet you have two hashes to start with. One hash describes the edges and the other the vertices found. Putting these informations into hashes let you access them by node/vertex number quite easily:

#!/usr/bin/perl use strict; use warnings; use 5.010; use Data::Dumper; my $VERY_BIG_NUM = 2_000_000_000; my @problem = grep { $_ !~ /^\s*#/ and $_ !~ /^\s*$/ } map { chomp; $_ + } <DATA>; die "ERROR: Problem description incomplete." unless(@problem >= 3); my ($num_of_vertices, $num_of_edges) = split / /, shift @problem; die "ERROR: Not enough vertices given." unless($num_of_vertices and $num_of_vertices > 1); die "ERROR: No edge given." unless($num_of_edges); die "ERROR: Number of edges not equal to declare numberd $num_of_edges + of edges." if(@problem - 1 != $num_of_edges); # Get the problem to solve my ($start_vertex, $end_vertex) = split / /, pop @problem; say "Problem with $num_of_vertices vertices and $num_of_edges edges"; say "Determine shortes path from vertex $start_vertex to $end_vertex"; # read the remaining edges my %vertices; my %edges; foreach my $edge (@problem) { my ($start, $end) = split / /, $edge; $edges{$start}->{$end} = { 'weight' => 1, }; $edges{$end}->{$start} = $edges{$start}->{$end}; foreach my $node ($start, $end) { $vertices{$node} = { 'predecessor' => undef, 'distance' => $node == $start_vertex ? 0 : $VERY_BIG_NUM, }; } } say "Vertices: " . Dumper(\%vertices); say "Edges: " . Dumper(\%edges); __DATA__ 5 6 1 2 2 3 2 4 4 5 1 3 3 5 1 5

We all - at least me - will be interested to see how your algorithms will be implemented.

Regards
McA

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-26 00:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found