Here's an alternative (diploid) approach for you genetic algorithm:

ord=: a. i.]
chr=: a.{~]

fitness=: [: +/"1 [: | -"1

evol=: (2 :0)
:
 'epsilon psize growth'=.m
 goal=. n i.x
 genepool=. psize$,.&.|:n i.y
 glen=. {:$genepool
 mutations=.(0#~3*glen*#n),(1#~#n),(_1#~#n),i.#n
 grow=. growth*psize
 0 goal track n genepool
 while.1 do.
   goal track n genepool
   children=.(?grow$1+glen) (({. {.), (}. {:))"_1 (?(grow,2)$psize){genepool
   children=.genepool,(#n)|children+mutations{~?($children)$#mutations
   cost=.goal fitness children
   ok=.epsilon >: cost
   if. 1 e.ok do.
     1 goal track n children
     n{~ ~. (ok#children) /: ok#cost return.
   end.
   genepool=. psize {. children /: cost
 end.
)

track=:2 :0
  gCount=:gCount+1
  if.1e4<gCount do. 1 m track n y throw.end. NB. safety valve
:
  if.0=x do.gCount=:0 end.
  min=.</\cost=<./cost=.m fitness y
  1!:2&2 'gen ',(":gCount),'(',(":min#cost),') ',,n{~min#y
)



Example use:
   (] 0 2 30 evol (chr 32+i.95) [:chr 32+[:?95$~#) 'A perfect creature!'
gen 0(549) Ya;ev}X^A)bG:zR)e{N
gen 60(0) A perfect creature!
A perfect creature!

Note that this runs somewhat faster if the references to track are
commented out.

Note that this returns a list of possible answers.  (Of course, this list will
be length 1 when an exact match is returned.)

FYI,

-- 
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to