aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2019-09-16 00:08:04 +0100
committerGitHub <noreply@github.com>2019-09-16 00:08:04 +0100
commitc1d944c6bc5f633f87e1f6acb593ca7cb86ecb04 (patch)
tree255f82b37bd30a10ac9a4c612465465f6168ddb5
parenta6f1fbb2210c4d89c998dcebfb44ec9600db39a1 (diff)
parent8c54783b03b0defa0b60b0496d2abec07f599f51 (diff)
downloadperlweeklychallenge-club-c1d944c6bc5f633f87e1f6acb593ca7cb86ecb04.tar.gz
perlweeklychallenge-club-c1d944c6bc5f633f87e1f6acb593ca7cb86ecb04.tar.bz2
perlweeklychallenge-club-c1d944c6bc5f633f87e1f6acb593ca7cb86ecb04.zip
Merge pull request #632 from jaldhar/challenge-025
Challenge 25 task 1 by Jaldhar H. Vyas.
-rwxr-xr-xchallenge-025/jaldhar-h-vyas/perl5/ch-1.pl66
1 files changed, 66 insertions, 0 deletions
diff --git a/challenge-025/jaldhar-h-vyas/perl5/ch-1.pl b/challenge-025/jaldhar-h-vyas/perl5/ch-1.pl
new file mode 100755
index 0000000000..002b00665b
--- /dev/null
+++ b/challenge-025/jaldhar-h-vyas/perl5/ch-1.pl
@@ -0,0 +1,66 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use 5.010;
+
+sub graph {
+ my ($words) = @_;
+ my %graph;
+
+ for my $word (@{$words}) {
+ my $lastLetter = substr $word, -1, 1;
+ for my $other (@{$words}) {
+ if ((substr $other, 0, 1) eq $lastLetter && $other ne $word) {
+ push @{$graph{$word}}, $other;
+ }
+ }
+ }
+
+ return \%graph;
+}
+
+sub traverse {
+ my ($graph, $word, $path) = @_;
+
+ if (scalar grep /$word/, @{$path}) {
+ return $path;
+ }
+
+ my $pathCopy = [ @{$path} ];
+ push @{$pathCopy}, $word;
+
+ my $longest = $pathCopy;
+ foreach my $neighbor (@{$graph->{$word}}) {
+ my $p = traverse($graph, $neighbor, $pathCopy);
+ if (scalar @{$p} > scalar @{$longest}) {
+ $longest = $p;
+ }
+ }
+ $path = $longest;
+
+ return $path;
+}
+
+my @words = qw/
+ audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
+ cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig
+ gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
+ kricketune landorus ledyba loudred lumineon lunatone machamp magnezone
+ mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena
+ porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede
+ scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga
+ trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull
+ yamask
+/;
+
+my $g = graph(\@words);
+
+my $longestPath = [];
+for my $word (keys %{$g}) {
+ my $path = traverse($g, $word, []);
+ if (scalar @{$path} > scalar @{$longestPath}) {
+ $longestPath = $path;
+ }
+}
+
+say join q{ }, @{$longestPath};