DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Carl has posted 4 posts at DZone. View Full User Profile

Genetic Algorithm In J

10.15.2006
| 1792 views |
  • submit to reddit
        
-------------  Beginning of class  pga.ijs   -------------------
coclass'pga'
create=:3 : 0
genes=: ? 4 $ 100  NB. 4 random integers 0-99
)
getgenes =: 3 : 'genes'
setgenes =: 3 : 'genes=:y.'
matewith=: 3 : 0
other=. y.
mine=. ((#genes) % 2) ? (#genes) NB. crossover
childgene=. getgenes__other '' NB. copy others intially
child=. conew 'pga'
setgenes__child ((mine { genes) (mine }) childgene)
child
)
perform =: 3 : 0 NB. dummy problem
+/ genes
)
destroy=:codestroy
-------------  End of of class  pga.ijs   ----------------------
-------------  beginning of script ga.ijs ----------------------
NB. genetic algorithm 
NB. needs pga class
NB. define a dummy target to measure fitness against
targetvalue =:  500  
fitness=: 3 : 0
object=. y.
1000 * %(targetvalue - perform__object '')
)

load jpath '~user\classes\pga.ijs'


top =: 4 : '(i.y.) { \: (fitness each x.)'  NB. pop top 10 returns the 10 fittest

pair=: 3 : 0  NB. pick two random ga objects, mate them, and return the child
pop=. y.
mom=. > (?#pop) { pop NB. must unbox!
dad=. > (?#pop) { pop NB.  # is length of boxed list
matewith__mom dad
)

NB.  pop evolve generations returns the fittest ga after 
NB. sifting the top 25 ga's
evolve=: 4 : 0
pop=. x.
n=. y.
for_k. i.n do.
kpop=.  3 : 'pop' NB. not sure if necessary to do here
newgen=.  (pair@kpop) each i.100  NB. create 100 children
best=.  (newgen top 25) { newgen NB. find the indices of the best, then select the corresponding objects
pop=. best,best,best,best  NB. not really necessary?
end.
>0{best  NB. return best
)
NB. usage  
load jpath '~user\ga.ijs'
average =: +/%#
pop=: conew&'pga' each i.100   NB. create 100 boxed ga objects
fitness each pop  NB. should show a boxed list of fitness values
average ; fitness each pop  NB. shows average fitness

fred=: pop evolve 100
fitness fred
uberfred=: pop evolve 1000

NB. the fitness values increase pretty slowly which is disappointing
NB. probably needs some mutation :)
-------------    end of script ga.ijs     ----------------------