/** * Calculate all possible plant yields for current * un-bred candy cane plants * * @return $this */ private function calculateBreedYields() { $this->yields = []; $this->each(function (CandyCanePlant $plantA) { if ($plantA->hasBred()) { return; } $this->each(function (CandyCanePlant $plantB) use($plantA) { if ($plantA === $plantB || $plantB->hasBred()) { return; } $yieldA = $this->breederService->calculateYield($plantA, $plantB); $yieldB = $this->breederService->calculateYield($plantB, $plantA); $this->yields[$yieldA] = new PlantCouple($plantA, $plantB); $this->yields[$yieldB] = new PlantCouple($plantB, $plantA); }); }); krsort($this->yields); return $this; }
<?php /** * File index.php * * @author Edward Pfremmer <*****@*****.**> */ require_once 'vendor/autoload.php'; use PHPWeekly\Collection\CandyCanePlantCollection; use PHPWeekly\Service\CandyCanePlantBreederService; use PHPWeekly\Plant\CandyCanePlant; $breederService = new CandyCanePlantBreederService(); $plantCollection = new CandyCanePlantCollection([new CandyCanePlant(5), new CandyCanePlant(3), new CandyCanePlant(2)]); /* * To convert this to be able to calculate yield loss due to time this would * need to be called recursively. Each iteration representing 1 weeks time. * * Plant offspring would be pushed to a separate collection, each previous generation * plant's yield would be decremented by one with each iteration before mergine the * two collections back together for the next iteration. */ while ($couple = $plantCollection->getTopCouple()) { $offspring = $breederService->breed($couple->getFather(), $couple->getMother()); $plantCollection->push($offspring); } // calculate total yield $yield = $plantCollection->reduce(function ($result, CandyCanePlant $plant) { return $result + $plant->getYield(); }); // print results $plantCollection->each(function (CandyCanePlant $plant) {
public function testCalculateYield() { $father = new CandyCanePlant(5); $mother = new CandyCanePlant(3); $this->assertEquals(5 ** 3 % (5 + 3), $this->breederService->calculateYield($father, $mother)); }