コード例 #1
0
 public function testInterviewQuestionA()
 {
     /*
        The sum of all natural numbers below 10 that are multiples of 3 or 5 are 23 (3 + 5 + 6 + 9)
        Write a php script that will find the sum of all the multiples of 3 or 5 below 1000. The script
        should run from command line and put the result on screen. We will judge this task based on
        simplicity, efficiency and cleverness of the code.
     */
     $limit = 1000;
     $values = range(0, $limit);
     $a = 3;
     $b = 5;
     $fnFilterMaker = function ($a, $b) {
         return function ($v) use($a, $b) {
             return $v % $a == 0 || $v % $b == 0;
         };
     };
     // test: sum of multiples of 3 or 5 below 10 is 23 (3 + 5 + 6 + 9)
     $this->assertTrue(Sequence::make(range(0, 9))->filter($fnFilterMaker(3, 5))->reduce(0, FnGen::fnSum()) == 23);
     $filteredValues = Sequence::make($values)->filter($fnFilterMaker($a, $b))->to_a();
     $this->assertArrayHasKey($a, $filteredValues);
     $this->assertArrayHasKey($b, $filteredValues);
     $this->assertArrayNotHasKey($a * $b + 1, $filteredValues);
     $valuesOnly = array_values($filteredValues);
     $subsetA = range(0, $limit, $a);
     $subsetB = range(0, $limit, $b);
     $this->assertTrue($subsetA == array_values(array_intersect($valuesOnly, $subsetA)));
     $this->assertTrue($subsetB == array_values(array_intersect($valuesOnly, $subsetB)));
     $this->assertTrue(!count(array_diff($valuesOnly, $subsetA, $subsetB)));
 }
コード例 #2
0
ファイル: FnReduceTest.php プロジェクト: revinate/sequence
 public function testFnSum()
 {
     $range = range(0, 100);
     $this->assertEquals(array_sum($range), Sequence::make($range)->reduce(0, FnGen::fnSum()));
     $fruit = array(array('name' => 'apple', 'count' => 1), array('name' => 'orange', 'count' => 5), array('name' => 'apple', 'count' => 3), array('name' => 'banana', 'count' => 9));
     $this->assertEquals(18, Sequence::make($fruit)->reduce(0, FnReduce::fnSum(FnGen::fnPluck('count', 0))));
 }
コード例 #3
0
ファイル: FnSequenceTest.php プロジェクト: revinate/sequence
 public function testInject()
 {
     $fsFilterApples = FnSequence::make()->filter(FnGen::fnCallChain(FnGen::fnPluck('name'), FnGen::fnIsEqual('apple')));
     $fsFilterBananas = FnSequence::make()->filter(FnGen::fnCallChain(FnGen::fnPluck('name'), FnGen::fnIsEqual('banana')));
     $fsExtractCounts = FnSequence::make()->map(FnGen::fnPluck('count'));
     $fnSum = FnSequence::make()->reduceBounded(0, FnGen::fnSum());
     $fnAppleCounter = FnSequence::make()->inject($fsFilterApples)->inject($fsExtractCounts)->append($fnSum);
     $fnBananaCounter = FnSequence::make()->inject($fsFilterBananas)->inject($fsExtractCounts)->append($fnSum);
     $this->assertEquals(21, $fnAppleCounter(TestData::$fruit));
     $this->assertEquals(25, $fnBananaCounter(TestData::$fruit));
 }