-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPheromoneMatrix.php
76 lines (61 loc) · 1.88 KB
/
PheromoneMatrix.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace App\Module\TSP\Application\Problem;
use App\Module\TSP\Domain\Constant;
use Ramsey\Collection\Map\AbstractTypedMap;
use Ramsey\Collection\Map\TypedMap;
use UnexpectedValueException;
/**
* @extends AbstractTypedMap<string, TypedMap<string, float>>
*/
class PheromoneMatrix extends AbstractTypedMap
{
/**
* @param string[] $locations
*/
public static function createFromLocations(
array $locations,
float $initialValue = Constant::DEFAULT_PHEROMONE_INITIAL_VALUE,
): self {
$matrix = new self();
foreach ($locations as $a) {
$cols = new TypedMap('string', 'float');
$matrix->put($a, $cols);
foreach ($locations as $b) {
$cols->put($b, $initialValue);
}
}
return $matrix;
}
public function getKeyType(): string
{
return 'string';
}
public function getValueType(): string
{
return TypedMap::class;
}
public function getPheromone(string $a, string $b): float
{
$this->checkPheromoneExists($a, $b);
return $this->get($a)->get($b);
}
public function updatePheromone(string $a, string $b, float $value): void
{
$this->checkPheromoneExists($a, $b);
$this->get($a)->put($b, $value);
}
public function increasePheromone(string $a, string $b, float $increaseValue): void
{
$value = $this->getPheromone($a, $b);
$this->updatePheromone($a, $b, $value + $increaseValue);
}
private function checkPheromoneExists(string $a, string $b): void
{
if (!$this->containsKey($a)) {
throw new UnexpectedValueException(sprintf('Not found matrix row %s', $a));
}
if (!$this->get($a)->containsKey($b)) {
throw new UnexpectedValueException(sprintf('Not found matrix cell %s : %s', $a, $b));
}
}
}