Test Setup Failed
Pull Request — master (#348)
by Pol
05:57 queued 03:49
created

Distance   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 50
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A distance() 0 13 1
A deltas() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Math\Distance;
6
7
use Phpml\Exception\InvalidArgumentException;
8
use Phpml\Math\Distance as DistanceInterface;
9
10
/**
11
 * Class Distance
12
 */
13
abstract class Distance implements DistanceInterface
14
{
15
    /**
16
     * @var float|int
17
     */
18
    public $norm = 2;
19
20
    /**
21
     * Distance constructor.
22
     */
23
    public function __construct(float $norm = 3.0)
24
    {
25
        $this->norm = $norm;
26
    }
27
28
    /**
29
     * @throws InvalidArgumentException
30
     */
31
    public function distance(array $a, array $b): float
32
    {
33
        $norm = $this->norm;
34
35
        return array_sum(
36
            array_map(
37
                function ($a) use ($norm) {
38
                    return $a ** $norm;
39
                },
40
                $this->deltas($a, $b)
41
            )
42
        ) ** (1 / $norm);
43
    }
44
45
    /**
46
     * @throws InvalidArgumentException
47
     */
48
    protected function deltas(array $a, array $b): array
49
    {
50
        if (count($a) !== count($b)) {
51
            throw new InvalidArgumentException('Size of given arrays does not match');
52
        }
53
54
        return array_map(
55
            function ($a, $b) {
56
                return abs($a - $b);
57
            },
58
            $a,
59
            $b
60
        );
61
    }
62
}
63