Skip to content

Instantly share code, notes, and snippets.

@pnf
Last active December 21, 2015 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pnf/6236029 to your computer and use it in GitHub Desktop.
Save pnf/6236029 to your computer and use it in GitHub Desktop.
Two algorithms for finding the longest anagram in a list of words.
die "Note that there are two different algorithms here. Don't expect it to run as is."
#!/usr/bin/perl
# ~0.15s on i7 1.7GHz
my @all;
my $m=0;
while(<>) {
$l = length($_);
$m = $l if $l>$m;
push @all,$_;
}
while ($m>0) {
my %c = ();
for (@all) {
next unless length($_)==$m;
#print "$n\n";
$s = join('',sort(split(//,$_)));
if( defined $c{$s}) {
chomp $_; chomp $c{$s};
print $c{$s}," ",$_,"\n";
exit;
}
$c{$s} = $_;
}
$m--;
}
#!/usr/bin/perl
# 0.08s on i7 1.7GHz
# See cribee here: https://gist.github.com/moretti/3bfd119787159021997d
my $m=0;
my %c = ();
my $a = "";
while(<>) {
$l = length($_);
next unless $l>$m;
$s = join('',sort(split(//,$_)));
if(defined $c{$s}) {
$m = $l;
chomp; chomp $c{$s};
$a = "$c{$s} $_";
%c = ();
} else {
$c{$s} = $_;
}
}
print $a,"\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment