Passed
Push — master ( fbbe5c...a34811 )
by Arkadiusz
07:00
created

Point::getClosest()   B

Complexity

Conditions 4
Paths 4

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 22
Code Lines 12

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Clustering\KMeans;
6
7
use ArrayAccess;
8
9
class Point implements ArrayAccess
10
{
11
    /**
12
     * @var int
13
     */
14
    protected $dimension;
15
16
    /**
17
     * @var array
18
     */
19
    protected $coordinates = [];
20
21
    public function __construct(array $coordinates)
22
    {
23
        $this->dimension = count($coordinates);
24
        $this->coordinates = $coordinates;
25
    }
26
27
    public function toArray(): array
28
    {
29
        return $this->coordinates;
30
    }
31
32
    /**
33
     * @return int|mixed
34
     */
35
    public function getDistanceWith(self $point, bool $precise = true)
36
    {
37
        $distance = 0;
38
        for ($n = 0; $n < $this->dimension; ++$n) {
39
            $difference = $this->coordinates[$n] - $point->coordinates[$n];
40
            $distance += $difference * $difference;
41
        }
42
43
        return $precise ? sqrt((float) $distance) : $distance;
44
    }
45
46
    /**
47
     * @return mixed
48
     */
49
    public function getClosest(array $points)
50
    {
51
        $minPoint = null;
52
53
        foreach ($points as $point) {
54
            $distance = $this->getDistanceWith($point, false);
55
56
            if (!isset($minDistance)) {
57
                $minDistance = $distance;
58
                $minPoint = $point;
59
60
                continue;
61
            }
62
63
            if ($distance < $minDistance) {
64
                $minDistance = $distance;
65
                $minPoint = $point;
66
            }
67
        }
68
69
        return $minPoint;
70
    }
71
72
    public function getCoordinates(): array
73
    {
74
        return $this->coordinates;
75
    }
76
77
    /**
78
     * @param mixed $offset
79
     */
80
    public function offsetExists($offset): bool
81
    {
82
        return isset($this->coordinates[$offset]);
83
    }
84
85
    /**
86
     * @param mixed $offset
87
     *
88
     * @return mixed
89
     */
90
    public function offsetGet($offset)
91
    {
92
        return $this->coordinates[$offset];
93
    }
94
95
    /**
96
     * @param mixed $offset
97
     * @param mixed $value
98
     */
99
    public function offsetSet($offset, $value): void
100
    {
101
        $this->coordinates[$offset] = $value;
102
    }
103
104
    /**
105
     * @param mixed $offset
106
     */
107
    public function offsetUnset($offset): void
108
    {
109
        unset($this->coordinates[$offset]);
110
    }
111
}
112