in reply to Tell whether two strings differ at only one position
This:
use strict; use warnings; # @data contains the (chomped, lower-cased) entries # from a 70K dictionary file (2076 words beginning with 'j') my $count; # Or whatever: this can check algorithm validity foreach my $item ( @data ) { compare( $item, $_ ) and $count++ for @data; } print $count; sub compare { return 0 unless length $_[0] == length $_[1]; my $diff = 0; for ( 0 .. length $_[0] ) { $diff++ if substr( $_[0], $_, 1 ) ne substr( $_[1], $_, 1 ); return 0 if $diff > 1; } return 1; }
is very much faster than your original code.
Surprisingly(?), initial testing seems to show that it is also considerably faster than any of the replies you have hitherto received using bitwise XOR.
I haven't got the time to do any precise benchmarking at the moment: however, since you need the "fastest solution on Earth", I shall leave that up to you
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Tell whether two strings differ at only one position
by rg0now (Chaplain) on Aug 04, 2005 at 21:14 UTC | |
by BrowserUk (Patriarch) on Aug 05, 2005 at 03:00 UTC | |
by Your Mother (Archbishop) on Aug 05, 2005 at 01:34 UTC |