in reply to Speeding permutation counting
Instead of breaking your strings up and then having to iterate the characters, you can use bitwise-string operations to process the characters in parallel and then use tr/// to count the results. This results in a 10x speed up over your original:
#! perl -slw use strict; use Benchmark::Timer; my $T = new Benchmark::Timer; use Math::Random::MT qw[ rand srand ]; our $S ||= 1; our $B ||= 32; our $N ||= 1000; srand( 1 ); my @strings = map { unpack 'b'. $B, rand( 2**32 ) } 1 .. $N; my $label = "$N strings of $B bits (srand:$S)"; $T->start( $label ); for my $i ( 0 .. $#strings ) { for my $j ( $i+1 .. $#strings ) { print join "\t", $i, $j, ( $strings[ $i ] | $strings[ $j ] ) =~ tr[0][0], ## 0 +0 ( ~$strings[ $i ] & $strings[ $j ] ) =~ tr[\1][\1], ## 0 +1 ( $strings[ $i ] & ~$strings[ $j ] ) =~ tr[\1][\1], ## 1 +0 ( $strings[ $i ] & $strings[ $j ] ) =~ tr[1][1]; ## 1 +1 } } $T->stop( $label ); $T->report; __END__ ## Original foreach my $string (@strings) { my @items = split //, $string; $string = \@items; } for ( my $i = 0 ; $i < @strings ; $i++ ) { for ( my $j = $i + 1 ; $j < @strings ; $j++ ) { my ( $c00, $c01, $c10, $c11 ) = ( 0, 0, 0, 0 ); for ( my $k = 0 ; $k < @{ $strings[$i] } ; $k++ ) { $c00++ if ${$strings[$i]}[$k] == 0 && ${$strings[$j]}[$k] == 0; $c01++ if ${$strings[$i]}[$k] == 0 && ${$strings[$j]}[$k] == 1; $c10++ if ${$strings[$i]}[$k] == 1 && ${$strings[$j]}[$k] == 0; $c11++ if ${$strings[$i]}[$k] == 1 && ${$strings[$j]}[$k] == 1; } print join( "\t", $i, $j, $c00, $c01, $c10, $c11 ), "\n"; } } c:\test>627253 >nul 1 trial of 1000 strings of 32 bits (srand:1) (40.336s total) c:\test>627253 >nul 1 trial of 1000 strings of 32 bits (srand:1) (40.477s total) ## Bitwise + tr/// c:\test>627253 >nul 1 trial of 1000 strings of 32 bits (srand:1) (4.711s total) c:\test>627253 >nul 1 trial of 1000 strings of 32 bits (srand:1) (4.696s total)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Speeding permutation counting
by albert (Monk) on Jul 18, 2007 at 15:40 UTC | |
|
Re^2: Speeding permutation counting
by Limbic~Region (Chancellor) on Jul 20, 2007 at 15:02 UTC | |
by albert (Monk) on Jul 21, 2007 at 23:38 UTC |