function generateInitialPopulation($ingredients, $count) { $pop = array(); for ($x = 0; $x < $count; $x++) { $solution = array(); $remaining = 100; foreach ($ingredients as $name => $ingredient) { $amount = rand(0, $remaining); $solution[$name] = $amount; $remaining -= $amount; } $solution['score'] = calculateFitness($solution, $ingredients); $pop[] = $solution; } return $pop; }
echo "\nCalculation\n"; echo calculateChromo($population[0]); echo "\nFitness\n"; echo calculateFitness($population[0], $target);*/ /*$crossresult = crossover($population[0], $population[1]); print_r($crossresult);*/ /*$new = mutate($population[0]); echo $new;*/ // Try to find the solution $found = false; $iterations = 0; while (!$found) { $totalfitness = 0; // test and update the fitness of every chromosome in the population for ($i = 0; $i < $POP_SIZE; $i++) { $fitness[$i] = calculateFitness($population[$i], $target); $totalfitness += $fitness[$i]; } // check to see if we have found any solutions (fitness will be 999) for ($i = 0; $i < $POP_SIZE; $i++) { if ($fitness[$i] == 999) { echo "Found a solution after " . $iterations . " iterations !!\n"; printChromo($population[$i]); $found = true; break; } } // create a new population by selecting two parents at a time and creating offspring // by applying crossover and mutation. Do this until the desired number of offspring // have been created. $temppop = array();