global target; target = split("METHINKS IT IS LIKE A WEASEL", ""); charset = ["A":"Z", " "]; p = ones(length(charset), 1) ./ length(charset); parent = discrete_rnd(charset, p, length(target), 1); mutaterate = 0.1; C = 1000; function r = fitness(parent, target) r = sum(parent == target) ./ length(target); endfunction function r = mutate(parent, mutaterate, charset) r = parent; p = unifrnd(0, 1, length(parent), 1); nmutants = sum( p < mutaterate ); if (nmutants) s = discrete_rnd(charset, ones(length(charset), 1) ./ length(charset),nmutants,1); r( p < mutaterate ) = s; endif endfunction function r = evolve(parent, mutatefunc, fitnessfunc, C, mutaterate, charset) global target; children = []; for i = 1:C children = [children, mutatefunc(parent, mutaterate, charset)]; endfor children = [parent, children]; fitval = []; for i = 1:columns(children) fitval = [fitval, fitnessfunc(children(:,i), target)]; endfor [m, im] = max(fitval); r = children(:, im); endfunction function printgen(p, t, i) printf("%3d %5.2f %s\n", i, fitness(p, t), p'); endfunction i = 0; while( !all(parent == target) ) i++; parent = evolve(parent, @mutate, @fitness, C, mutaterate, charset); if ( mod(i, 1) == 0 ) printgen(parent, target, i); endif endwhile disp(parent');