simpleGA.rkt 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #lang racket
  2. ;; A simple genetic algorithm
  3. ;; Computer Exercise #1 from Intro to GA by Mitchell
  4. ;;
  5. ;; Uses:
  6. ;; - fitness-proportionate selection
  7. ;; - routlette-wheel sampling
  8. ; The population is stored as a single list of popsize*chromlen elements
  9. (require math)
  10. ; population size and individual chromosome length
  11. (define popsize 100)
  12. (define chromlen 100)
  13. ; single-point crossover rate
  14. (define p-cross 0.7)
  15. ; bitwise mutation rate
  16. (define p-mutate 0.001)
  17. ; Fitness assessment is the number of 1's in the population member
  18. (define (fitness member)
  19. (/ (sum member)
  20. (length member)))
  21. ; Flip a chromosome to its opposite
  22. (define (flip-chrom val)
  23. (if (eq? val 1) 0 1))
  24. ; mutate
  25. ; because of the way the population is stored and that mutations happen after
  26. ; offspring are produced, we can mutate the whole list together
  27. (define (mutate pop)
  28. (for/list ([i pop])
  29. ((λ (chrom)
  30. (if (<= (random) p-mutate)
  31. (flip-chrom i)
  32. i))
  33. i)))
  34. ; Initialize a random population.
  35. (define (initpop)
  36. (for/list ([i (in-range (* popsize chromlen))])
  37. (random-integer 0 2)))