Algorithm-Evolve

 view release on metacpan or  search on metacpan

examples/StringEvolver.pm  view on Meta::CPAN

package StringEvolver;
use strict;
use Algorithm::Evolve::Util ':str';
our $VERSION = '0.03';

our %configs;

sub import {
    my $class = shift;
    
    %configs = (
        gene_length    => 20,
        alphabet       => [0,1],
        reference_gene => '1' x 20,
        mutation_rate  => 0.05,
        crossover_pts  => 2,
        @_
    );
}

sub new {
    my $pkg = shift;
    my $string = shift
        || str_random($configs{gene_length}, $configs{alphabet});
    return bless { _gene => $string }, $pkg;
}

sub crossover {
    my ($pkg, $s1, $s2) = @_;
    return map { $pkg->new($_) } 
           str_crossover($s1->gene, $s2->gene, $configs{crossover_pts});
}

sub fitness {
    my $self = shift;
    return str_agreement($configs{reference_gene}, $self->gene);
}

sub mutate {
    my $self = shift;
    $self->gene(
        str_mutate($self->gene, $configs{mutation_rate}, $configs{alphabet})
    );
}

sub gene {
    my $self = shift;
    $self->{_gene} = shift if @_;
    return $self->{_gene};
}

1;
__END__

=head1 NAME

StringEvolver - A generic base critter class for use with Algorithm::Evolve

=head1 SYNOPSIS

  package StringCritters;
  use StringEvolver gene_length => 50,
                    alphabet => ['A' .. 'F'],
                    ...;
  our @ISA = ('StringEvolver');
  ## StringCritters is now a valid critter class

  sub foo_method {
      my $self = shift;
      $self->{foo}++;   ## You can add object attributes
  }
  
  sub fitness {
      my $self = shift;

      ## You can override the default inherited methods to suit the
      ## task at hand
  }

You can use this class as a base class any time your representation is a
string gene.

=head1 USE ARGUMENTS

=over



( run in 1.205 second using v1.01-cache-2.11-cpan-39bf76dae61 )