dogCount; } public function setDogCount($count) { $this->dogCount = $count; } public function getCatCount() { return $this->catCount; } public function setCatCount($count) { $this->catCount = $count; } public function getMouseCount() { return $this->mouseCount; } public function setMouseCount($count) { $this->mouseCount = $count; } public function getTotalCount() { return $this->getDogCount() + $this->getCatCount() + $this->getMouseCount(); } public function getTotalCost() { return ($this->getDogCount() * 15) + $this->getCatCount() + ($this->getMouseCount() * 0.25); } /** * Generate a random set of counts, within reasonable constraints. */ public function randomize() { $this->setDogCount(rand(1,6)); $this->setCatCount(rand(1,85)); $this->setMouseCount(rand(1,336)); } /** * Return the fitness of this solution as a score * from 0 (worst) to 100 (perfect). * See: http://en.wikipedia.org/wiki/Fitness_function. */ public function getFitness() { // There must be at least one of each animal: if ($this->getDogCount() == 0 || $this->getCatCount() == 0 || $this->getMouseCount() == 0) return 0; $countError = abs(100 - $this->getTotalCount()); $amountError = abs(100 - $this->getTotalCost()); if ($countError > 50 || $amountError > 50) return 0; else return 100 - ($countError + $amountError); } /** * Set my attributes from those of my parents. * This is also known as breeding, crossover, or recombination. */ public function combine($dad, $mom) { $this->setDogCount(rand(0,1) == 0 ? $dad->getDogCount() : $mom->getDogCount()); $this->setCatCount(rand(0,1) == 0 ? $dad->getCatCount() : $mom->getCatCount()); $this->setMouseCount(rand(0,1) == 0 ? $dad->getMouseCount() : $mom->getMouseCount()); } /** * Mutate my attributes so that I'm not an exact clone of my parents. */ public function mutate() { $this->setDogCount(rand(0,2) == 0 ? rand(1,6) : $this->getDogCount()); $this->setCatCount(rand(0,2) == 0 ? rand(1,85) : $this->getCatCount()); $this->setMouseCount(rand(0,2) == 0 ? rand(1,336) : $this->getMouseCount()); } /** * Compare fitness levels for sorting. */ public function compareFitness($purchase1, $purchase2) { if ($purchase1->getFitness() == $purchase2->getFitness()) return 0; return ($purchase1->getFitness() > $purchase2->getFitness()) ? -1 : 1; } /** * Format myself in table form. */ public function printMe() { echo '
Dogs | Cats | Mice | Count | Cost | Fitness | '; echo '
---|---|---|---|---|---|
%d | ',$this->getDogCount()); printf('%d | ',$this->getCatCount()); printf('%d | ',$this->getMouseCount()); printf('%d | ',$this->getTotalCount()); printf('%.3f | ',$this->getTotalCost()); printf('%.3f | ',$this->getFitness()); echo '