Test Setup Failed
Pull Request — master (#348)
by Pol
06:51
created

Distance   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 0
loc 61
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
     * @param float $norm
23
     */
24
    public function __construct(float $norm = 3.0)
25
    {
26
        $this->norm = $norm;
27
    }
28
29
    /**
30
     * @param array $a
31
     * @param array $b
32
     *
33
     * @return float
34
     *
35
     * @throws InvalidArgumentException
36
     */
37
    public function distance(array $a, array $b): float
38
    {
39
        $norm = $this->norm;
40
41
        return array_sum(
42
                array_map(
43
                    function ($a) use ($norm) {
44
                        return $a**$norm;
45
                    },
46
                    $this->deltas($a, $b)
47
                )
48
            ) ** (1 / $norm);
49
    }
50
51
    /**
52
     * @param array $a
53
     * @param array $b
54
     *
55
     * @return array
56
     *
57
     * @throws InvalidArgumentException
58
     */
59
    protected function deltas(array $a, array $b): array
60
    {
61
        if (count($a) !== count($b)) {
62
            throw new InvalidArgumentException('Size of given arrays does not match');
63
        }
64
65
        return array_map(
66
            function ($a, $b) {
67
                return abs($a - $b);
68
            },
69
            $a,
70
            $b
71
        );
72
    }
73
}
74