Last active
December 21, 2015 02:38
-
-
Save pnf/6236029 to your computer and use it in GitHub Desktop.
Two algorithms for finding the longest anagram in a list of words.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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