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

Distance::distance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
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 = 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