```>>>>> "R" == Robo  <robo / mars.com> writes:

R> Unfortunately my lack of knowledge in genetic and Perl means I couldn't
R> quite get the code working. When it runs, each generation doesn't seem
R> to improve. It would be great if someone could take a look, compare it
R> to the original Perl version and see where I've gone wrong, and the fix
R> require to get it working. The code's attached to this post.

First the P version seems wrong. Perhaps best if you find a better
algorithm.

At least there are some basic errors

R>  my @sorted_population = sort { \$a->{fitness}  \$b->{fitness} } @\$pop_ref;

<=>

missing

R>  my \$pop_size = scalar @\$population;  # population size
R>
R>  # create the weights array: select only survivors from the population,
R>  # then use map to have only the fitness come through
R>  my @weights = map { \$_->{fitness} } grep { \$_->{survived} } @\$population;
R>
R>  # if we have less than 2 survivors, we're in trouble
R>  die "Population size \$pop_size is too small" if \$pop_size < 2;

this algorithm seems wrong : be carefull with it

R>   \$count += \$weights->[\$i];
R>   \$sample = \$i if rand \$count [\$i];

rand(\$count) < \$weights->[\$i];

R>  }

unless (defined \$sample) {
\$sample = \$weights->[0];
}

R>  return \$sample;
R> }

For the ruby version : you have at least a problem with fitness

R> def fitness(dna)
R> 	dna / 256

dna / 256.0  # otherwise ruby can use integer /

R> end

R> #sample an array of weighted elements
R> def sample(weights)
R> 	count = sample = 0

R> 	weights.each_index do |i|
R> 		count += weights[i]
R> 		sample = i if rand(count[i]) != 0

rand(count) < weights[i]

R> 	end

Guy Decoux

```