Test Setup Failed
Pull Request — master (#348)
by Pol
02:57
created

Distance::deltas()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 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;
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
        $power = function (float $value) use ($norm) {
36
            return $value ** $norm;
37
        };
38
39
        return array_sum(
40
            array_map(
41
                $power,
42
                $this->deltas($a, $b)
43
            )
44
        ) ** (1 / $norm);
45
    }
46
47
    /**
48
     * @throws InvalidArgumentException
49
     */
50
    protected function deltas(array $a, array $b): array
51
    {
52
        if (count($a) !== count($b)) {
53
            throw new InvalidArgumentException('Size of given arrays does not match');
54
        }
55
56
        return array_map(
57
            function ($a, $b) {
58
                return abs($a - $b);
59
            },
60
            $a,
61
            $b
62
        );
63
    }
64
}
65