Algorithm-Evolutionary

 view release on metacpan or  search on metacpan

lib/Algorithm/Evolutionary/Wheel.pm  view on Meta::CPAN

use strict;
use warnings;

=head1 NAME

Algorithm::Evolutionary::Wheel - Random selector of things depending on probabilities

=head1 SYNOPSIS

    my $wheel = new Algorithm::Evolutionary::Wheel( @probs );
    print $wheel->spin(); #Returns an element according to probabilities;

=head1 DESCRIPTION

Creates a "roulette wheel" for spinning and selecting stuff. It will
be used in several places; mainly in the
L<Algorithm::Evolutionary::Op::CanonicalGA>.  Take care that fitness
must be non-zero positives; since if they aren't, roulette wheel won't
work at all

=head1 METHODS

=cut

package Algorithm::Evolutionary::Wheel;
use Carp;

our ($VERSION) = ( '$Revision: 3.6 $ ' =~ / (\d+\.\d+)/ ) ;

=head2 new( @probabilites )

Creates a new roulette wheel. Takes an array of numbers, which need not be
normalized

=cut

sub new {
  my $class = shift;
  my @probs = @_;
  
  my $self;
  $self->{'_accProbs'} = [ 0 ];
  
  my $acc = 0;
  for ( @probs ) { $acc += $_;}
  croak "The sum of fitness is 0, can't use roulette wheel\n" if ! $acc;
  for ( @probs ) { $_ /= $acc;} #Normalizes array
  
  #Now creates the accumulated array
  my $aux = 0;  
  for ( @probs ) {
	push @{$self->{'_accProbs'}}, $_ + $aux;
	$aux += $_;
  }
  bless $self, $class;
  return $self;
}

=head2 spin( [$number_of_individuals = 1])

Returns an individual whose probability is related to its fitness

=cut

sub spin {
  my $self = shift;
  my $number_of_individuals = shift || 1;
  my $i = 0;
  my @rand;
  for my $n ( 1..$number_of_individuals ) {
    push @rand, rand();
  }
  my @individuals;
  for ( my $r=0; $r<= $#rand; $r++ ) {
    my $i = first( $rand[$r], $self->{'_accProbs'} );



( run in 0.647 second using v1.01-cache-2.11-cpan-ceb78f64989 )