master
neil 2012-10-29 15:32:04 -04:00
parent cf07dd0f64
commit 34483307b2
3 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,47 @@
package DDG::Goodie::FindAnagrams;
use DDG::Goodie;
use File::Slurp qw(read_file write_file);
use File::ShareDir::ProjectDistDir;
use JSON;
use Data::Dumper;
zci is_cached => 1;
triggers start => "fingali";
handle remainder => sub {
if ($_ eq ""){
return "No Anagrams Found."
}
my $json = read_file(share('words.json'), { binmode => ':raw' }) or die("Unable to open words file");
my %wordHash = %{decode_json($json)};
#print Dumper(\%wordHash);
# Format string to look like hash key by making it lowercase then splitting the string into chars, sort them and finally join back into sorted string
my $sorted_string = join("",sort(split(//,lc($_))));
my @resultArray = ();
if (exists $wordHash{$sorted_string}) {
push(@resultArray, @{$wordHash{$sorted_string}});
} else {
return "No Anagrams Found.";
}
my $index = 0;
$index++ until $resultArray[$index] eq $_;
splice(@resultArray, $index, 1);
my $result_string = join(",",@resultArray);
return (($result_string eq "") ? "No Anagrams Found!" : $result_string);
};
1;

View File

@ -0,0 +1,42 @@
#!/usr/local/bin/perl
#
# Anagram Generator
#
use utf8;
use JSON::XS qw(encode_json decode_json);
use File::Slurp qw(read_file write_file);
# open file
open(FILE, "/usr/share/dict/words") or die("Unable to open file");
# read file into an array
my %dict = ();
while (my $line = <FILE>) {
chomp $line;
# get last two letters of word. the unix words file has man duplicated possessive words with the 's appended which do not serve our purpose for anagram finding.
$amt = substr($line, -2);
unless ($amt eq '\'s'){
$lcline = lc($line);
## Spliting the string with no delimeter.
$sorted_string = join("",sort(split("",$lcline)));
if (exists $dict{$sorted_string}) {
push @{$dict{$sorted_string}}, $line;
}
else {
push @{$dict{$sorted_string}}, $line;
}
}
}
# close file
close(FILE);
my $json = encode_json \%dict;
write_file('words.json', { binmode => ':raw' }, $json);

File diff suppressed because one or more lines are too long