PHP code example of darvin / genetic-algorithm

1. Go to this page and download the library: Download darvin/genetic-algorithm library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

darvin / genetic-algorithm example snippets


$config = new \Darvin\GeneticAlgorithm\Settings\DefaultSettings();
$algorithm = new Algorithm($config);

$algorithm->setPart("individual:gene", function (Gene $gene) {
    $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-+,. ');
    $gene->value($characters[rand(0, count($characters)-1)]);
});

$algorithm->setPart("fitness", function (Individual $individual) use ($solution) {
    $fitness = 0;
    for ($i=0; $i < $individual->genomeSize() && $i < count($solution); $i++) {
        $char_diff=abs(ord($individual->getGene($i)->value) - ord($solution[$i]));
        $fitness+=$char_diff;
    }
    return $fitness;
});

$algorithm->setPart("event:listen:algorithmStart", function (Algorithm $algorithm) {
    echo "Algorithm start.\n";
});

$algorithm->setPart("event:listen:newSolutionFound", function (Algorithm $algorithm) {
    echo "New solution found!";
});