in reply to Re: Unique Character Combinations
in thread Unique Character Combinations
even if results show your solution is still slightly more efficient (-2% / 5% scissor).use strict; use warnings; print join "\n", comb_thormod('A'..'R'); sub comb_thormod { my $c_out = []; permute_thormod( '', $_, $c_out, @_ ) for ( 0 .. $#_ ); return @$c_out; } sub permute_thormod { my ( $str, $depth, $c_out, @chars ) = @_; if ( !$depth-- ) { foreach (@chars) { push @$c_out, $str . $_; } } else { permute_thormod( $str . $chars[$_], $depth, $c_out, @chars[ ( $_ + 1 ) .. ($#chars) ] ) for ( 0 .. $#chars ); } }
#!/usr/bin/perl -w use strict; use Benchmark qw(cmpthese); my @range = 'A' .. 'D'; cmpthese(-1, { 'TedPride' => sub { comb_ted ( @range ) }, 'thor' => sub { comb_thor( @range ) }, 'thor-modified' => sub { comb_thormod ( @range ) }, } ); sub comb_thormod { my $c_out = []; permute_thormod( '', $_, $c_out, @_ ) for ( 0 .. $#_ ); return @$c_out; } sub permute_thormod { my ( $str, $depth, $c_out, @chars ) = @_; if ( !$depth-- ) { foreach (@chars) { push @$c_out, $str . $_; } } else { permute_thormod( $str . $chars[$_], $depth, $c_out, @chars[ ( $_ + 1 ) .. ($#chars) ] ) for ( 0 .. $#chars ); } } sub comb_thor { my @c_out = (); push @c_out, permute_thor( '', $_, @_ ) for ( 0 .. $#_ ); return @c_out; } sub permute_thor { my @results; my ( $str, $depth, @chars ) = @_; if ( !$depth-- ) { foreach (@chars) { push @results, $str . $_; } } else { push @results, permute_thor( $str . $chars[$_], $depth, @chars[ ( $_ + 1 ) .. ($#chars) ] ) for ( 0 .. $#chars ); } return @results; } BEGIN { my @c_out; sub comb_ted { @c_out = (); permute_ted('', $_, @_) for (0..$#_); return @c_out; } sub permute_ted { my ($str, $depth, @chars) = @_; if (!$depth--) { push @c_out, $str.$_ for @chars; } else { permute_ted($str.$chars[$_], $depth, @chars[($_+1)..($#cha +rs)]) for (0..$#chars); } } } __END__ poletti@flaviox ~/sviluppo/perl/tmp> perl thor-mod.pl Rate thor TedPride thor-modified thor 5430/s -- -11% -13% TedPride 6126/s 13% -- -2% thor-modified 6221/s 15% 2% -- poletti@flaviox ~/sviluppo/perl/tmp> perl thor-mod.pl Rate thor thor-modified TedPride thor 5428/s -- -13% -17% thor-modified 6221/s 15% -- -5% TedPride 6515/s 20% 5% --
Flavio (perl -e 'print(scalar(reverse("\nti.xittelop\@oivalf")))')
Don't fool yourself.
|
|---|