in reply to Re: Determining uniqueness in a string.
in thread Determining uniqueness in a string.

Oops, formatting necesse est!

Its only now that I saw the other solutions. I didn't time it, but regex should be to much overhead. Is that correct?

sub uni{ my ($s) = shift; my @a; for $i (0..9) { $j = int(substr($s,$i,1)); if ($a[$j]) {return( 0 )}; $a[$j] = 1;} return 1; } print uni("1902356784");

Replies are listed 'Best First'.
Re^3: Determining uniqueness in a string.
by gam3 (Curate) on Oct 02, 2005 at 05:25 UTC
    Regex seems to be faster.
    use Inline C; use Benchmark qw( cmpthese ) ; my $digits = '1234567891'; my $bob = { u1 => sub { return uniq($digits); }, u2 => sub { my @l = (); for my $x (split '', $digits) { if ($l[$x]++) { return 1; } } return 0; }, u3 => sub { my @l = (); my $max = length($digits); for (my $i=0; $i < $max; $i++) { $x = substr($digits,$i,1); if ($l[$x]++) { return 1; } } return 0; }, u4 => sub { return $digits !~ /(.).*\1/ ? 0:1; }, }; print "u1: ", $bob->{u1}->(), "\n"; print "u2: ", $bob->{u2}->(), "\n"; print "u3: ", $bob->{u3}->(), "\n"; print "u4: ", $bob->{u4}->(), "\n"; cmpthese( -5, $bob); __END__ Rate u2 u3 u4 u1 u2 19725/s -- -10% -90% -95% u3 21847/s 11% -- -89% -94% u4 204817/s 938% 838% -- -44% u1 367282/s 1762% 1581% 79% -- __C__ int uniq(char* name) { int bob[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int max = strlen(name); int x; for (x = 0; x < max; x++) { if (bob[name[x]-'0']++) { return 1; } } return 0; }
    -- gam3
    A picture is worth a thousand words, but takes 200K.