Thread Eindeutige Liste aller Zeichen im String (32 answers)
Opened by roli at 2008-03-11 18:39

pq
 2008-03-13 00:58
#106991 #106991
User since
2003-08-04
12209 Artikel
Admin1
[Homepage]
user image
and the winner is...
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
sub hash1 { 
    my %seen;
    $seen{$_}++ for ( split( //, $string ) );
    my $res = join( '', sort keys %seen );
    return $res;
}

sub hash2 { 
    my $res = $string;
    my %seen;
    $res =~ s/(.)/$seen{$1}++ ? "" : $1/gse;
    return $res;
}

sub joinsplit1 {  
    my $res = join '', split /(.)\1+/, join('', sort( split('', $string )));
}   
    
sub hash3 {
    my $res = join "", sort keys %{ { map{ $_ => 1 } split //, $string } };
}

sub join_tr {
    my $res = join("",sort(split("",$string)));
    $res =~ tr/0-9a-zA-Z//s;
    return $res;
}

use Benchmark;
timethese($ARGV[0] || 100, {
    hash1 => \&hash1,
    hash2 => \&hash2,
    hash3 => \&hash3,
    joinsplit1 => \&joinsplit1,
    join_tr => \&join_tr,
});

Code: (dl )
1
2
3
4
5
6
Benchmark: timing 40000 iterations of hash1, hash2, hash3, join_tr, joinsplit1...
hash1: 1 wallclock secs ( 1.23 usr + 0.00 sys = 1.23 CPU) @ 32520.33/s (n=40000)
hash2: 1 wallclock secs ( 1.11 usr + 0.00 sys = 1.11 CPU) @ 36036.04/s (n=40000)
hash3: 2 wallclock secs ( 1.55 usr + 0.00 sys = 1.55 CPU) @ 25806.45/s (n=40000)
join_tr: 1 wallclock secs ( 0.73 usr + 0.00 sys = 0.73 CPU) @ 54794.52/s (n=40000)
joinsplit1: 1 wallclock secs ( 0.94 usr + 0.00 sys = 0.94 CPU) @ 42553.19/s (n=40000)
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wiki:Wie frage ich & perlintro Wiki:brian's Leitfaden für jedes Perl-Problem

View full thread Eindeutige Liste aller Zeichen im String