insert() public method

public insert ( $item, $priority )
Ejemplo n.º 1
0
function calcShortestPaths(vertex $start, &$adjLists)
{
    // define an empty queue
    $q = new PriorityQueue();
    // push the starting vertex into the queue
    $q->insert($start, 0);
    $q->rewind();
    // mark the distance to it 0
    $start->distance = 0;
    // the path to the starting vertex
    $start->path = array($start->key);
    while ($q->valid()) {
        $vertex = $q->extract();
        $vertex->visited = 1;
        $list = $adjLists[$vertex->key];
        while ($list->valid()) {
            $item = $list->current();
            if (!$item['vertex']->visited) {
                if ($item['vertex']->distance > $vertex->distance + $item['distance']) {
                    $item['vertex']->distance = $vertex->distance + $item['distance'];
                    $item['vertex']->parent = $vertex;
                }
                $item['vertex']->path = array_merge($vertex->path, array($item['vertex']->key));
                $q->insert($item["vertex"], $item["vertex"]->distance);
            }
            $list->next();
        }
        $q->recoverFromCorruption();
        $q->rewind();
    }
}
Ejemplo n.º 2
0
 function Find($NodeStart, $NodeEnd)
 {
     $Queue = new PriorityQueue();
     // Open Nodes ordered based on F cost
     $Queue->setExtractFlags(PriorityQueue::EXTR_DATA);
     $Closed = 0;
     $Found = FALSE;
     $this->Debug = '';
     $this->Cache = array($NodeStart => array('G' => 0, 'F' => 0, 'Parent' => $NodeStart, 'Status' => STATUS_OPEN));
     $Queue->insert($NodeStart, $this->Cache[$NodeStart]['F']);
     while (!$Queue->isEmpty()) {
         $Node = $Queue->extract();
         if ($this->Cache[$Node]['Status'] == STATUS_CLOSED) {
             continue;
         }
         if ($Node == $NodeEnd) {
             $this->Cache[$Node]['Status'] = STATUS_CLOSED;
             $Found = TRUE;
             break;
         }
         if ($Closed > $this->Limit) {
             $this->Debug = 'Hit limit. (' . $this->Limit . ')';
             return NULL;
         }
         $Neighbours = $this->Graph->Neighbours($Node);
         foreach ($Neighbours as $Neighbour) {
             $G = $this->Cache[$Node]['G'] + $this->Graph->G($Node, $Neighbour);
             if (isset($this->Cache[$Neighbour]) && $this->Cache[$Neighbour]['Status'] && $this->Cache[$Neighbour]['G'] <= $G) {
                 continue;
             }
             $F = $G + $this->Graph->H($Neighbour, $NodeEnd);
             $this->Cache[$Neighbour] = array('G' => $G, 'F' => $F, 'Parent' => $Node, 'Status' => STATUS_OPEN);
             $Queue->insert($Neighbour, $F);
         }
         ++$Closed;
         $this->Cache[$Node]['Status'] = STATUS_CLOSED;
     }
     if ($Found) {
         $Path = array();
         $Node = $NodeEnd;
         while ($NodeStart != $Node) {
             $Path[] = $Node;
             $Node = $this->Cache[$Node]['Parent'];
         }
         $Path[] = $Node;
         return array_reverse($Path);
     }
     $this->Debug = 'Path not found, ran out of open nodes.';
     return NULL;
 }
 /**
  * {@inheritdoc}
  */
 public function calculate($start, $finish)
 {
     // check if the nodes exist
     if (!isset($this->nodes[$start])) {
         throw new \InvalidArgumentException("The starting node '" . $start . "' is not found");
     }
     if (!isset($this->nodes[$finish])) {
         throw new \InvalidArgumentException("The ending node '" . $finish . "' is not found");
     }
     $distances = [];
     $distances[$start] = 0;
     $visited = [];
     $previous = [];
     $queue = new PriorityQueue();
     $queue->insert($start, $distances[$start]);
     $queue->top();
     while ($queue->valid()) {
         $smallest = $queue->current();
         if ($smallest == $finish) {
             // trying to make path
             $path = array();
             while (isset($previous[$smallest])) {
                 $path[] = $smallest;
                 $smallest = $previous[$smallest];
             }
             $path[] = $start;
             return ['distance' => $distances[$finish], 'path' => array_reverse($path)];
         }
         if (isset($visited[$smallest])) {
             $queue->next();
             continue;
         }
         $visited[$smallest] = true;
         foreach ($this->nodes[$smallest] as $neighbor => $weight) {
             if (isset($visited[$neighbor])) {
                 continue;
             }
             $alt = $distances[$smallest] + $weight;
             if (!isset($distances[$neighbor]) || $alt < $distances[$neighbor]) {
                 $distances[$neighbor] = $alt;
                 $previous[$neighbor] = $smallest;
                 $queue->insert($neighbor, $alt);
             }
         }
         $queue->next();
     }
     // there is no available path if the graph is unconnected
     return null;
 }
Ejemplo n.º 4
0
 public function shortest_path($start, $finish)
 {
     $distances = array();
     $previous = array();
     $nodes = new PriorityQueue();
     foreach ($this->verticies as $vertex => $value) {
         if ($vertex === $start) {
             $distances[$vertex] = 0;
             $nodes->insert($vertex, 0);
         } else {
             $distances[$vertex] = PHP_INT_MAX;
             $nodes->insert($vertex, PHP_INT_MAX);
         }
         $previous[$vertex] = null;
     }
     $nodes->top();
     while ($nodes->valid()) {
         $smallest = $nodes->current();
         if ($smallest === $finish) {
             $path = array();
             while ($previous[$smallest]) {
                 $path[] = $smallest;
                 $smallest = $previous[$smallest];
             }
             $path[] = $start;
             $alt = $distances[$finish];
             $path['Разстояние'] = $alt;
             return array_reverse($path);
         }
         if ($smallest === null || $distances[$smallest] === PHP_INT_MAX) {
             break;
         }
         foreach ($this->verticies[$smallest] as $neighbor => $value) {
             $alt = $distances[$smallest] + $this->verticies[$smallest][$neighbor];
             if ($alt < $distances[$neighbor]) {
                 $distances[$neighbor] = $alt;
                 $previous[$neighbor] = $smallest;
                 $nodes->insert($neighbor, $alt);
             }
         }
         $nodes->next();
     }
     return $distances;
 }
Ejemplo n.º 5
0
 public function testQueue()
 {
     $queue = new PriorityQueue();
     $queue->insert('foo', 0);
     $queue->insert('test', 16);
     $queue->insert('bar', 8);
     $this->assertInstanceOf('Countable', $queue);
     $this->assertInstanceOf('IteratorAggregate', $queue);
     $this->assertEquals(3, $queue->count());
     $this->assertEquals(3, count($queue));
     $iterator = $queue->getIterator();
     $this->assertEquals('test', $iterator->current());
     $iterator->next();
     $this->assertEquals('bar', $iterator->current());
     $iterator->next();
     $this->assertEquals('foo', $iterator->current());
     $iterator->next();
     $this->assertEmpty($iterator->current());
 }
Ejemplo n.º 6
0
 /**
  * Add an entry into the queu
  * @param type $datum
  * @param type $priority
  */
 public function insert($name, $callback, $priority)
 {
     $name = trim((string) $name);
     if ('' == $name) {
         throw new \RuntimeException('No name provided for FilterQueue entry');
     }
     if (0 == $priority && $this->hasPriorityZeroFilter) {
         throw new \RuntimeException('Attempt to add duplicate priority-zero filter');
     }
     $datum = array('name' => $name, 'callback' => $callback);
     $this->priorityQueue->insert($datum, $priority);
     if (0 == $priority) {
         $this->hasPriorityZeroFilter = true;
     }
 }
Ejemplo n.º 7
0
<?php

$GLOBALS['client'] = 'Tests';
echo "<p>Starting PriorityQueue test.</p>";
echo "New PriorityQueue, ";
$pq = new PriorityQueue();
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (1, 'one') into pq, ";
$pq->insert(1, 'one');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (2, 'two') into pq, ";
$pq->insert(2, 'two');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Insert (0, 'zero') into pq, ";
$pq->insert(0, 'zero');
echo "done.";
$pq->renderInternalRepresentation();
echo "<br>";
echo "Top of pq: ";
var_dump($pq->top());
$pq->renderInternalRepresentation();
echo "<br>";
echo "Pop pq: ";
var_dump($pq->pop());
$pq->renderInternalRepresentation();
Ejemplo n.º 8
0
    }
    function toString()
    {
        $retStr = "";
        $cnt = count($this->dataStore);
        for ($i = 0; $i < $cnt; ++$i) {
            $retStr .= $this->dataStore[$i]->name . " номер: " . $this->dataStore[$i]->priority . "\n";
        }
        return $retStr . "\n";
    }
}
$bank = new PriorityQueue();
$clients = ["Пупкин", "Сумкин", "Корзинкина", "Морковкин", "Зайцев"];
shuffle($clients);
foreach ($clients as $p => $client) {
    $bank->insert(new Client($client, $p + 1), $p + 1);
}
print $bank->toString();
$current = $bank->extract();
print "Обслуживается: " . $current->name . "\n";
print "Ожидают очереди:\n";
print $bank->toString();
exit;
$current = $bank->extract();
print "Обслуживается: " . $current->name . "\n";
print "Ожидают очереди:\n";
print $bank->toString();
$current = $bank->extract();
print "Обслуживается: " . $current->name . "\n";
print "Ожидают очереди:\n";
print $bank->toString();
Ejemplo n.º 9
0
                            // CMD: <1 digit priority><1 digit reserved><1 digit reserved>
                            $cmd = strtok($data[intval($s)], ',');
                            $data[intval($s)] = strtok(' ');
                            $completed->insert(intval($cmd[0]), $val);
                            $ch = curl_init($val);
                            curl_setopt($ch, CURLOPT_AUTOREFERER, true);
                            curl_setopt($ch, CURLOPT_FAILONERROR, true);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                            curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
                            //curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
                            curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);
                            //curl_setopt($ch, CURLOPT_STDERR, $fp);
                            curl_setopt($ch, CURLOPT_USERAGENT, $CONFIG['user_agent']);
                            // TODO: look into CURLOPT_RANGE
                            $curl_stack->insert(0, $ch);
                            Error::generate('debug', "Received: {$val}");
                            fputs($fp, "Daemon {$GLOBALS['client']} received {$val}\r\n");
                            $n_reqs_recvd++;
                            if (!$data[intval($s)]) {
                                $data[intval($s)] = '';
                            }
                        } while (strchr($data[intval($s)], ' '));
                    }
                }
            }
        }
        profiling_end('IPC');
    }
}
end:
Ejemplo n.º 10
0
 function calcDistances($start)
 {
     // define an empty queue
     $q = new PriorityQueue();
     // push the starting vertex into the queue
     $q->insert($start, 0);
     $q->rewind();
     // mark the distance to it 0
     $start->distance = 0;
     while ($q->valid()) {
         $t = $q->extract();
         $t->visited = 1;
         foreach ($t->getRelations() as $key => $relation) {
             foreach ($relation as $object) {
                 if (!$object->visited) {
                     if ($object->distance > $t->distance + 1) {
                         $object->distance = $t->distance + 1;
                         $object->parent = $t;
                     }
                     $q->insert($object, $object->distance);
                 }
             }
         }
         $q->recoverFromCorruption();
         $q->rewind();
     }
 }