/** * Merge an array of arrays so that the result is in sorted order. * * @param array $arrays * @return array */ function mergeSortedArrays(array $arrays) { if (empty($arrays)) { return []; } $heads = array_fill(0, count($arrays), 0); $minHeap = new \SplMinHeap(); $result = []; // Insert the first value from each sorted array into the min heap for ($i = 0; $i < count($arrays); $i++) { if (!empty($arrays[$i])) { $minHeap->insert([$arrays[$i][0], $i]); $heads[$i] = 1; } } while (!$minHeap->isEmpty()) { $smallestArray = $arrays[$minHeap->top()[1]]; $smallestHead = $heads[$minHeap->top()[1]]; $result[] = $minHeap->top()[0]; // If the smallest array has more values, put the next one into the heap if ($smallestHead < count($smallestArray)) { $minHeap->insert([$smallestArray[$smallestHead], $minHeap->top()[1]]); $heads[$minHeap->top()[1]] += 1; } $minHeap->extract(); } return $result; }
<?php $h = new SplMinHeap(); try { $h->top(); } catch (Exception $e) { echo $e->getMessage(); }
<?php /** * A kulcsot nem tartja meg */ $data = [2, 4, 1, 76, 42, 23, 0, 10, 2]; $heap = new SplMinHeap(); foreach ($data as $v) { $heap->insert($v); } printf("TOP: %s\n", $heap->top()); foreach ($heap as $k => $v) { printf("%s => %s\n", $k, $v); } $heap = new SplMaxHeap(); foreach ($data as $v) { $heap->insert($v); } printf("TOP: %s\n", $heap->top()); foreach ($heap as $k => $v) { printf("%s => %s\n", $k, $v); }
<?php $h = new SplMinHeap(); $h->insert(5); // top doesn't take any args, lets see what happens if we give it one $h->top('bogus');
/** * Uses the chi-squared feature selection algorithm to rank features by * informativeness, and return a map from old feature indices to new ones. * * @param object $features full feature set * @return array associative array mapping a subset of the original feature * indices to new indices */ function select(Features $features) { $n = $features->numFeatures(); $selected = new SplMinHeap(); $allowed = isset($this->max) ? min($this->max, $n) : $n; $labels = array(-1, 1); /* Start with 1, since 0 is dedicated to the constant intercept term; <= $n because n is the last feature. */ for ($j = 1; $j <= $n; $j++) { $max_chi2 = 0.0; foreach ($labels as $label) { /* t = term present l = document has label n = negation */ $stats = $features->varStats($j, $label); list($t_l, $t_nl, $nt_l, $nt_nl) = $stats; $num = $t_l * $nt_nl - $t_nl * $nt_l; $den = ($t_l + $t_nl) * ($nt_l + $nt_nl); $chi2 = $den != 0 ? $num * $num / $den : INF; if ($chi2 > $max_chi2) { $max_chi2 = $chi2; } } /* Keep track of top features in a heap, as we compute informativeness. */ if ($allowed > 0) { $selected->insert(array($max_chi2, $j)); $allowed -= 1; } else { list($other_chi2, $_) = $selected->top(); if ($max_chi2 > $other_chi2) { $selected->extract(); $selected->insert(array($max_chi2, $j)); } } } return $this->buildMap($selected); }
public final function getCoreExtension() { return self::$extMinHeap->top(); }