本文整理匯總了PHP中SplPriorityQueue::extract方法的典型用法代碼示例。如果您正苦於以下問題:PHP SplPriorityQueue::extract方法的具體用法?PHP SplPriorityQueue::extract怎麽用?PHP SplPriorityQueue::extract使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類SplPriorityQueue
的用法示例。
在下文中一共展示了SplPriorityQueue::extract方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。
示例1: find_routes
private function find_routes($org, $dest, &$flights)
{
$result = array();
$queue = new SplPriorityQueue();
foreach ($flights as $flight) {
if ($flight['org_id'] == $org) {
$route = new Route($this->route_opts);
$route->add_flight($flight);
array_push($this->id, $flight['flight_id']);
$queue->insert($route, $route->get_joy());
}
}
//BFS to find all routes that take < 10 hours
$count = 0;
while ($queue->count() > 0 && $count < $this->opts['max_results']) {
$cur_route = $queue->extract();
if ($cur_route->get_dest() == $dest) {
$result[] = $cur_route;
$count++;
continue;
}
foreach ($flights as $flight) {
if ($flight['org_id'] == $cur_route->get_dest() && $flight['e_depart_time'] > 30 * 60 + $cur_route->get_arrival_time()) {
$new_route = $cur_route->copy();
$new_route->add_flight($flight);
array_push($this->id, $flight['flight_id']);
if ($new_route->get_trip_time() < 24 * 60 * 60) {
$queue->insert($new_route, $new_route->get_joy());
}
}
}
}
return $result;
}
示例2: find_routes
private function find_routes($org, $dest, &$flights)
{
$result = array();
$queue = new SplPriorityQueue();
foreach ($flights as $flight) {
if ($flight['org_id'] == $org) {
$route = new Route($this->route_opts);
$num_seats = Flight::get_open_seats_on_flight($flight['flight_id'], $this->user);
$route->add_flight($flight, $num_seats);
$queue->insert($route, $route->get_joy());
}
}
//BFS to find all routes that take < 10 hours
$count = 0;
while ($queue->count() > 0 && $count < $this->opts['max_results']) {
$cur_route = $queue->extract();
if ($cur_route->get_dest() == $dest) {
$result[] = $cur_route;
$count++;
continue;
}
foreach ($flights as $flight) {
if (!array_key_exists($flight['dest_id'], $cur_route->visited) && $flight['org_id'] == $cur_route->get_dest() && $flight['e_depart_time'] > 30 * 60 + $cur_route->get_arrival_time()) {
$new_route = $cur_route->copy();
$num_seats = Flight::get_open_seats_on_flight($flight['flight_id'], $this->user);
$new_route->add_flight($flight, $num_seats);
if ($new_route->get_trip_time() < 24 * 60 * 60 && $new_route->seats >= $this->opts['passengers']) {
$queue->insert($new_route, $new_route->get_joy());
}
}
}
}
return $result;
}
示例3: encode
function encode($symb2freq)
{
$heap = new SplPriorityQueue();
// Instancia fila de prioridades utilizando max heap.
$heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
// define o modo de extração no caso extrai array com a prioridade
foreach ($symb2freq as $sym => $wt) {
$heap->insert(array($sym => ''), -$wt);
}
while ($heap->count() > 1) {
$lo = $heap->extract();
// extraio o minimo
$hi = $heap->extract();
// extraio o minimo
foreach ($lo['data'] as &$x) {
$x = '0' . $x;
}
foreach ($hi['data'] as &$x) {
$x = '1' . $x;
}
$heap->insert($lo['data'] + $hi['data'], $lo['priority'] + $hi['priority']);
}
$result = $heap->extract();
return $result['data'];
}
示例4: __construct
public function __construct()
{
$this->queue = new \SplPriorityQueue();
$this->timer = Loop\periodic(1, function () {
$time = time();
while (!$this->queue->isEmpty()) {
$key = $this->queue->top();
if (isset($this->expire[$key])) {
if ($time <= $this->expire[$key]) {
break;
}
unset($this->data[$key], $this->expire[$key], $this->ttl[$key]);
}
$this->queue->extract();
}
if ($this->queue->isEmpty()) {
$this->timer->stop();
}
});
$this->timer->stop();
$this->timer->unreference();
}
示例5: pop
/**
* @see QueueInterface::pop()
*/
public function pop()
{
if (!$this->innerQueue->isEmpty()) {
$eta = $this->innerQueue->top()->getEta();
if (!$eta || $eta->getTimestamp() <= time()) {
return $this->innerQueue->extract();
}
}
return false;
}
示例6: pop
/**
* {@inheritdoc}
*/
public function pop()
{
if (!$this->queue->isEmpty()) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
$priority = $this->queue->top();
if (time() + $priority[0] >= 0) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
return $this->queue->extract();
}
}
throw new NoItemAvailableException($this);
}
示例7: pop
/**
* {@inheritdoc}
*/
public function pop()
{
if ($this->queue->isEmpty()) {
return;
}
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
$priority = $this->queue->top();
if (time() + $priority[0] >= 0) {
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
return $this->queue->extract();
}
}
示例8: tick
/**
* 檢查是否有可執行的定時任務,有的話執行
* @return void
*/
protected function tick()
{
while (!$this->_scheduler->isEmpty()) {
$scheduler_data = $this->_scheduler->top();
$timer_id = $scheduler_data['data'];
$next_run_time = -$scheduler_data['priority'];
$time_now = microtime(true);
if ($time_now >= $next_run_time) {
$this->_scheduler->extract();
// 如果任務不存在,則是對應的定時器已經刪除
if (!isset($this->_task[$timer_id])) {
continue;
}
// 任務數據[func, args, flag, timer_interval]
$task_data = $this->_task[$timer_id];
// 如果是持續的定時任務,再把任務加到定時隊列
if ($task_data[2] === self::EV_TIMER) {
$next_run_time = $time_now + $task_data[3];
$this->_scheduler->insert($timer_id, -$next_run_time);
}
// 嘗試執行任務
try {
call_user_func_array($task_data[0], $task_data[1]);
} catch (\Exception $e) {
echo $e;
}
continue;
} else {
// 設定超時時間
$this->_selectTimeout = ($next_run_time - $time_now) * 1000000;
return;
}
}
$this->_selectTimeout = 100000000;
}
示例9: tick
/**
* Executes any pending timers. Returns the number of timers executed.
*
* @return int
*
* @internal
*/
public function tick() : int
{
$count = 0;
$time = microtime(true);
while (!$this->queue->isEmpty()) {
list($timer, $timeout) = $this->queue->top();
if (!$this->timers->contains($timer) || $timeout !== $this->timers[$timer]) {
$this->queue->extract();
// Timer was removed from queue.
continue;
}
if ($this->timers[$timer] > $time) {
// Timer at top of queue has not expired.
return $count;
}
// Remove and execute timer. Replace timer if persistent.
$this->queue->extract();
if ($timer->isPeriodic()) {
$timeout = $time + $timer->getInterval();
$this->queue->insert([$timer, $timeout], -$timeout);
$this->timers[$timer] = $timeout;
} else {
$this->timers->detach($timer);
}
// Execute the timer.
$timer->call();
++$count;
}
return $count;
}
示例10: tick
/**
* Tick for timer.
* @return void
*/
protected function tick()
{
while (!$this->_scheduler->isEmpty()) {
$scheduler_data = $this->_scheduler->top();
$timer_id = $scheduler_data['data'];
$next_run_time = -$scheduler_data['priority'];
$time_now = microtime(true);
if ($time_now >= $next_run_time) {
$this->_scheduler->extract();
if (!isset($this->_task[$timer_id])) {
continue;
}
// [func, args, flag, timer_interval]
$task_data = $this->_task[$timer_id];
if ($task_data[2] === self::EV_TIMER) {
$next_run_time = $time_now + $task_data[3];
$this->_scheduler->insert($timer_id, -$next_run_time);
}
call_user_func_array($task_data[0], $task_data[1]);
if (isset($this->_task[$timer_id]) && $task_data[2] === self::EV_TIMER_ONCE) {
$this->del($timer_id, self::EV_TIMER_ONCE);
}
continue;
} else {
$this->_selectTimeout = ($next_run_time - $time_now) * 1000000;
return;
}
}
$this->_selectTimeout = 100000000;
}
示例11: extract
public function extract()
{
$data = parent::extract();
$return = ["timer" => $data["data"], "time" => round(abs($data["priority"]) - microtime(true), 6), "tickAt" => abs($data["priority"])];
$return["time"] = $return["time"] >= 0 ? $return["time"] : 0;
return (object) $return;
}
示例12: calculate_score
function calculate_score()
{
global $score_board;
global $TOTAL_P_SCORE;
global $score_P_ratio;
$qCur = new SplPriorityQueue();
$qExpire = new SplPriorityQueue();
$total_p_score = $TOTAL_P_SCORE;
$multiplier = 0.01;
$qCur->setExtractFlags(SplPriorityQueue::EXTR_DATA);
$qExpire->setExtractFlags(SplPriorityQueue::EXTR_DATA);
foreach ($score_board as $k => $r) {
///// f_score
if (IsValidScoreboardEntry($k)) {
$score_board[$k]["func"] = $score_board[$k]["check_pattern"] * pow(0.9, $score_board[$k]["mem_error"]);
if ($score_board[$k]["mem_heap"] > 0) {
$score_board[$k]["func"] *= ($score_board[$k]["mem_heap"] - $score_board[$k]["heap_lost"]) / $score_board[$k]["mem_heap"];
}
if ($r["priority"] > 0) {
$qCur->insert($k, $r["priority"]);
}
} else {
$score_board[$k]["func"] = 0;
}
////// init p_score
$score_board[$k]["p_score"] = 0;
}
while ($qCur->valid() && $total_p_score > 0) {
while ($qCur->valid()) {
$idx = $qCur->extract();
$s = $score_board[$idx]["priority"] * $multiplier;
// alloted score in the scheduling cycle
if ($s > 100 - $score_board[$idx]["p_score"]) {
$s = 100 - $score_board[$idx]["p_score"];
}
$score_board[$idx]["p_score"] += $s;
$total_p_score -= $s;
if ($score_board[$idx]["p_score"] < 100) {
$qExpire->insert($idx, $score_board[$idx]["priority"]);
}
}
$qCur = $qExpire;
$qExpire = new SplPriorityQueue();
$qExpire->setExtractFlags(SplPriorityQueue::EXTR_DATA);
}
foreach ($score_board as $k => $r) {
$score_board[$k]["score"] = 100 * $score_board[$k]["func"] * (1 - $score_P_ratio + $score_board[$k]["p_score"] * $score_P_ratio / 100);
}
////////sort by score
$tmp = array();
foreach ($score_board as &$ma) {
$tmp[] =& $ma["score"];
}
array_multisort($tmp, SORT_DESC, $score_board);
}
示例13: find_path
/**
* Поиск самого дешёвого пути между двумя локациями
* Для поиска используется алгоритм Дейкстры
*
* @see http://www.sitepoint.com/data-structures-4/
*
* @param array $data Массив с локациями и ценой проезда между ними [][src, dst, cost]
* @param string $source Название исходного пункта
* @param string $target Название конечного пункта
*
* @return SplStack
*/
function find_path(array $data, $source, $target)
{
$graph = build_graph($data);
// массив лучших цен кратчайшего пути для каждой локации
$best_cost = [];
// массив предыдущих локаций для каждой локации
$prev_loc = array();
// очередь из необработанных локаций
$queue = new SplPriorityQueue();
foreach ($graph as $src => $dst) {
$best_cost[$src] = INF;
// изначальные значения цен бесконечны
$prev_loc[$src] = null;
// предыдущие локации неизвестны
foreach ($dst as $name => $cost) {
// используем цену как приоритет в очереди
$queue->insert($name, $cost);
}
}
// цена поездки в исходный пункт = 0
$best_cost[$source] = 0;
while (!$queue->isEmpty()) {
// получаем минимальную цену
$u = $queue->extract();
if (empty($graph[$u])) {
continue;
}
// обрабатываем доступные маршруты для локации
foreach ($graph[$u] as $v => $cost) {
// альтернативная цена для маршрута
$alt = $best_cost[$u] + $cost;
if ($alt < $best_cost[$v]) {
// обновляем минимальную цену для локации
$best_cost[$v] = $alt;
// добавляем локацию в массив предыдущих локаций
$prev_loc[$v] = $u;
}
}
}
// ищем дешёвый путь и складываем его в стек
$stack = new SplStack();
$u = $target;
$final_cost = 0;
// проходим в обратном порядке от пункта назначения к исходному пункту
while (isset($prev_loc[$u]) && $prev_loc[$u]) {
$stack->push($u);
$final_cost += $graph[$u][$prev_loc[$u]];
$u = $prev_loc[$u];
}
$stack->push($source);
return [$stack, $final_cost];
}
示例14: compileRoutes
/**
* {@inheritdoc}
*/
public final function compileRoutes(RouteCompiler $compiler, RoutingContext $context) : array
{
$parsed = new \SplPriorityQueue();
foreach ($this->routes as $route) {
foreach ($route->compile($compiler) as list($priority, $depth, $route, $regex, $mapping)) {
$parsed->insert(\array_merge([$regex, $depth, $priority, $route], $mapping), $priority);
}
}
$result = [];
while (!$parsed->isEmpty()) {
$result[] = $parsed->extract();
}
return $result;
}
示例15: _shortestPath
/**
* Поиск кратчайшего пути
* @see https://www.youtube.com/watch?v=UA6aV1XJCGg
*/
private function _shortestPath()
{
while (!$this->_nodeQueue->isEmpty()) {
$u = $this->_nodeQueue->extract();
if (!empty($this->_routes[$u])) {
foreach ($this->_routes[$u] as $v => $cost) {
$newCost = $this->_destinations[$u] + $cost;
if ($newCost < $this->_destinations[$v]) {
$this->_destinations[$v] = $newCost;
$this->_predecessors[$v] = $u;
}
}
}
}
}