« blib/lib/Algorithm/Evolutionary/Fitness/Knapsack.pm
↑ Summary
blib/lib/Algorithm/Evolutionary/Fitness/Any.pm »
| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | |||
| 4 | use lib qw( ../../../../lib ); | ||
| 5 | |||
| 6 | =head1 NAME | ||
| 7 | |||
| 8 | Algorithm::Evolutionary::Fitness::Royal_Road - Mitchell's Royal Road function | ||
| 9 | |||
| 10 | =head1 SYNOPSIS | ||
| 11 | |||
| 12 | my $block_size = 4; | ||
| 13 | my $rr = Algorithm::Evolutionary::Fitness::Royal_Road->new( $block_size ); | ||
| 14 | |||
| 15 | =head1 DESCRIPTION | ||
| 16 | |||
| 17 | Royal Road function, adds block_size to fitness only when the block is complete | ||
| 18 | |||
| 19 | =head1 METHODS | ||
| 20 | |||
| 21 | =cut | ||
| 22 | |||
| 23 | package Algorithm::Evolutionary::Fitness::Royal_Road; | ||
| 24 | |||
| 25 | our ($VERSION) = ( '$Revision: 3.1 $ ' =~ / (\d+\.\d+)/ ) ; | ||
| 26 | |||
| 27 | use base qw(Algorithm::Evolutionary::Fitness::String); | ||
| 28 | |||
| 29 | =head2 new( $block_size ) | ||
| 30 | |||
| 31 | Creates a new instance of the problem, with the said block size. | ||
| 32 | |||
| 33 | =cut | ||
| 34 | |||
| 35 | sub new { | ||
| 36 | my $class = shift; | ||
| 37 | my ( $block_size ) = @_; | ||
| 38 | my $self = $class->SUPER::new(); | ||
| 39 | $self->{'_block_size'} = $block_size; | ||
| 40 | $self->initialize(); | ||
| 41 | return $self; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub _really_apply { | ||
| 45 | my $self = shift; | ||
| 46 | return $self->royal_road( @_ ); | ||
| 47 | } | ||
| 48 | |||
| 49 | =head2 royal_road( $string ) | ||
| 50 | |||
| 51 | Computes the royal road function with given block size. Results are | ||
| 52 | cached by default. | ||
| 53 | |||
| 54 | =cut | ||
| 55 | |||
| 56 | sub royal_road { | ||
| 57 | my $self = shift; | ||
| 58 | my $string = shift; | ||
| 59 | my $cache = $self->{'_cache'}; | ||
| 60 | |||
| 61 | if ( $cache->{$string} ) { | ||
| 62 | return $cache->{$string}; | ||
| 63 | } | ||
| 64 | |||
| 65 | my $fitness = 0; | ||
| 66 | my $block_size = $self->{'_block_size'}; | ||
| 67 | for ( my $i = 0; $i < length( $string ) / $block_size; $i++ ) { | ||
| 68 | my $block = 0; | ||
| 69 | if ( length( substr( $string, $i*$block_size, $block_size )) == $block_size ) { | ||
| 70 | $block=1; | ||
| 71 | for ( my $j = 0; $j < $block_size; $j++ ) { | ||
| 72 | $block &= substr( $string, $i*$block_size+$j, 1 ); | ||
| 73 | } | ||
| 74 | } | ||
| 75 | ( $fitness += $block_size ) if $block; | ||
| 76 | } | ||
| 77 | $cache->{$string} = $fitness; | ||
| 78 | return $cache->{$string}; | ||
| 79 | |||
| 80 | } | ||
| 81 | |||
| 82 | |||
| 83 | =head1 Copyright | ||
| 84 | |||
| 85 | This file is released under the GPL. See the LICENSE file included in this distribution, | ||
| 86 | or go to http://www.fsf.org/licenses/gpl.txt | ||
| 87 | |||
| 88 | =cut | ||
| 89 | |||
| 90 | "What???"; |