Genetic Algorithms in Elixir: Chapter 9 (pg 151) - setting ID in struct default value sets same ID for all structs

On page 151, the id for each new Chromosome struct is set via a default value like:

defmodule Types.Chromosome do
  @enforce_keys :genes
  defstruct [:genes,
    id: Base.encode16(:crypto.strong_rand_bytes(64)),
    size: 0,
    fitness: 0,
    age: 0]
end

But this results in the same ID being used for all Chromosome structs, which can be seen if you run the code to inspect the graph as instructed on page 155.

Two approaches for solving this are either defining some kind of “initializer” function that is used each time you create a new Chromosome (rather than %Chromosome{genes: ...}, do Chromosome.new(genes, size, ...) – or, perhaps, make the id a computed value based on the genes of the chromosome? Of course, that has the side effect of making two chromosomes with identical genes get treated as the same thing – but “genetically speaking”, maybe that’s ok?

1 Like