Forked from Isinlor/lazy-consecutive-biggest-product.php
Created
January 28, 2016 09:55
-
-
Save evancauwenberg/f9b3d9c22119deb89990 to your computer and use it in GitHub Desktop.
Get nth biggest product of two arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class IteratorsPriorityQueue extends SplPriorityQueue {} | |
function getNthIterator($n, $s, $nthA, $bList) { | |
for ($i=0; $i < $s; $i++) { | |
yield $nthA * $bList[$i]; | |
} | |
} | |
function getNextIteratorValue(Iterator $iterator) { | |
$iterator->key(); | |
$current = $iterator->current(); | |
$iterator->next(); | |
return $current; | |
} | |
function getNthBiggestProductGenerator($aList, $bList) { | |
$n = count($aList)*count($bList); | |
$aMin = min($n, count($aList)); | |
$bMin = min($n, count($bList)); | |
rsort($aList); | |
rsort($bList); | |
$iteratorsPriorityQueue = new IteratorsPriorityQueue; | |
$iteratorsPriorityQueue->setExtractFlags($iteratorsPriorityQueue::EXTR_BOTH); | |
for ($i=0; $i < $aMin; $i++) { | |
$iteratorsPriorityQueue->insert( | |
$nthIterator = getNthIterator($i, $bMin, $aList[$i], $bList), | |
getNextIteratorValue($nthIterator) | |
); | |
} | |
for ($i=0; $i < $n; $i++) { | |
$iteratorWithPriority = $iteratorsPriorityQueue->extract(); | |
$iterator = $iteratorWithPriority['data']; | |
$priority = $iteratorWithPriority['priority']; | |
if($iterator->valid()) { | |
$iteratorsPriorityQueue->insert($iterator, getNextIteratorValue($iterator)); | |
} | |
yield $priority; | |
} | |
} | |
$aList = array(3, 5, 24, 306, 48, 25, 25, 205); | |
$bList = array(73, 48, 25, 1, 2, 3, 508, 401, 2, 200); | |
$generator = getNthBiggestProductGenerator($aList, $bList); | |
$abList1 = []; | |
foreach ($generator as $value) { | |
$abList1[] = $value; | |
} | |
// Naive approach | |
$abList2 = []; | |
foreach($aList as $aKey => $a) { | |
foreach($bList as $bKey => $b) { | |
$abList2[] = $a*$b; | |
} | |
} | |
rsort($abList2); | |
var_dump($abList1 === $abList2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment