in reply to Re^4: Find duplicate digits
in thread Find duplicate digits

Now that is a truly interesting result, especially as when I modified it slightly to add my own variant I got a storm of undefined value used warnings from the chomp;s in the foreach loops that don't have anything to chomp on. When I fixed that I obtained the following results. (Note that I've not validated the operation of the individual functions)

Rate regex hash gf regex 1.94/s -- -73% -78% hash 7.17/s 269% -- -17% gf 8.67/s 347% 21% --
use strict; use warnings; use Time::HiRes; use Benchmark ':all'; my @data = (1000..9999); cmpthese (-2, { hash => 'hash()', gf => 'gf()', regex => 'regex()', }); sub regex { my @keep; foreach my $line (@data) { chomp $line; for ( split //, $line ) { my @a = ($line =~ m/$_/g); if (@a == 2) { push @keep, $line; last; } } } } sub hash { my @keep; # numbers to keep foreach my $line (@data) { chomp $line; my %count; ++$count{$_} for split '', $line; push @keep, $line if grep { $_ == 2 } values %count } } sub gf { my @keep = grep {my %d; map {$d{$_}++} split ''; grep {$_ == 2} valu +es %d} @data; }

DWIM is Perl's answer to Gödel