views:

393

answers:

2

First yes, this is a homework project for my Perl class. I am not looking for the answer (although that would be sweet). As I understand it I need to use a BFS and a regular expression to organize my data for use. I need some direction on this one. How do I use a BFS? Do I use a massive stack and go through each item in the stack? Should I use a giant hash table? Has anyone worked on this problem? How did you go about doing it? I just need some direction is all. Is this similar to a BST? Is this possible without using the graph module? Is this possible using hash values?

+5  A: 

See Graph.

#!/usr/bin/perl

use autodie;
use strict; use warnings;

use Graph;
use Graph::TransitiveClosure::Matrix;

my $dat = 'kevin-bacon.dat';

my $kbg = Graph->new(undirected => 1);

open my $kbf, '<', $dat;

my %movies;

while ( my $line = <$kbf> ) {
    last unless $line =~ /\S/;
    chomp $line;
    my ($u, $m, $v) = split /;/, $line;
    $kbg->add_edge($u, $v);
    $movies{"$u|$v"} = $movies{"$v|$u"} = $m;
}

my $tcm = Graph::TransitiveClosure::Matrix->new($kbg,
    path_length => 1,
    path_vertices => 1,
);

my ($u, $v) = ('Kevin Bacon', 'Yelena Maksimova');

if ( my $n = $tcm->path_length($u, $v) ) {
    printf "%d degrees of separation between %s and %s\n", $n, $u, $v;
}

my @path = $tcm->path_vertices($u, $v);

for my $i ( 0 .. @path - 2 ) {
    my ($u, $v) = @path[$i, $i + 1];
    print qq{$u - $v: $movies{"$u|$v"}\n};
}

Using kevin-bacon.dat from the Boost project:

3 degrees of separation between Kevin Bacon and Yelena Maksimova
Kevin Bacon - Elisabeth Shue: Hollow Man (2000)
Elisabeth Shue - Lev Prygunov: Saint, The (1997)
Lev Prygunov - Yelena Maksimova: Bezottsovshchina (1976)
Sinan Ünür
+6  A: 

This isn't an answer, but it's hints towards your answer.

You are best served by first looking up what a Breadth First Search is in a graph.

Also, if you have not been given a regular expression, you may consider the tokenizing problem and look that up. Possibly that won't be needed. Check the assignment and see if you can just slurp in some information.

Paul Nathan