Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evancauwenberg/f9b3d9c22119deb89990 to your computer and use it in GitHub Desktop.
Save evancauwenberg/f9b3d9c22119deb89990 to your computer and use it in GitHub Desktop.
Get nth biggest product of two arrays
<?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