Skip to content

Instantly share code, notes, and snippets.

@Isinlor
Last active January 28, 2016 14:29
Show Gist options
  • Save Isinlor/1aa484a20730210a2916 to your computer and use it in GitHub Desktop.
Save Isinlor/1aa484a20730210a2916 to your computer and use it in GitHub Desktop.
Lazy generate consecutive biggest products of two arrays
<?php
function getAListProductIterator($aList, $aListSize, $bValue, $bIndex) {
for ($aIndex=0; $aIndex < $aListSize; $aIndex++) {
yield [
'product' => $aList[$aIndex] * $bValue,
'aIndex' => $aIndex,
'bIndex' => $bIndex
];
}
}
function getConsecutiveBiggestProducts($aList, $bList) {
$aListSize = count($aList);
$bListSize = count($bList);
$n = $bListSize*$aListSize;
rsort($aList);
rsort($bList);
$aIteratorsPriorityQueue = new SplPriorityQueue;
for ($bIndex=0; $bIndex < $bListSize; $bIndex++) {
$bValue = $bList[$bIndex];
$aIteratorsPriorityQueue->insert(
getAListProductIterator($aList, $aListSize, $bValue, $bIndex),
$aList[0] * $bValue
);
}
for ($i=0; $i < $n; $i++) {
$aIterator = $aIteratorsPriorityQueue->extract();
yield $aIterator->current();
$aIterator->next();
if($aIterator->valid()) {
$aIteratorsPriorityQueue->insert(
$aIterator,
$aIterator->current()['product']
);
}
}
}
$aList = array(3, 5, 24, 306, 48, 25, 25, 205);
$bList = array(0, 73, 48, 25, 1, 2, 3, 508, 401, 2, 200);
$abList1 = [];
foreach (getConsecutiveBiggestProducts($aList, $bList) as $value) {
$abList1[] = $value['product'];
}
// 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