53 lines
1.3 KiB
Plaintext
53 lines
1.3 KiB
Plaintext
global target;
|
|
target = split("METHINKS IT IS LIKE A WEASEL", "");
|
|
charset = ["A":"Z", " "];
|
|
p = ones(length(charset), 1) ./ length(charset);
|
|
parent = discrete_rnd(length(target), charset, p)';
|
|
mutaterate = 0.01;
|
|
|
|
C = 100;
|
|
|
|
function r = fitness(parent, thetarget)
|
|
r = sum(parent == thetarget) ./ length(thetarget);
|
|
endfunction
|
|
|
|
function r = mutate(parent, therate, charset)
|
|
r = parent;
|
|
p = unifrnd(0, 1, length(parent), 1);
|
|
nmutants = sum( p < therate );
|
|
if (nmutants)
|
|
s = discrete_rnd(nmutants, charset, ones(length(charset), 1) ./ length(charset))';
|
|
r( p < therate ) = 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, 20) == 0 )
|
|
printgen(parent, target, i);
|
|
endif
|
|
endwhile
|
|
disp(parent');
|