Completed
Push — master ( e15c58...b150a8 )
by Changwan
07:08
created

Vector::equal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Math\LinearAlgebra;
3
4
use InvalidArgumentException;
5
use Closure;
6
7
class Vector
8
{
9
    /**
10
     * @param int $size
11
     * @return static
12
     */
13 1
    public static function zeros($size)
14
    {
15 1
        return new static(array_pad([], $size, 0));
16
    }
17
18
    /** @var array */
19
    protected $items;
20
21 6
    public function __construct(array $items)
22
    {
23 6
        $this->items = $items;
24 6
    }
25
26
    /**
27
     * @return string
28
     */
29 1
    public function __toString()
30
    {
31 1
        return "Vector(" . implode(", ", $this->items) . ")";
32
    }
33
34
    /**
35
     * @param \Wandu\Math\LinearAlgebra\Vector $other
36
     * @return number
37
     */
38 2
    public function dot(Vector $other)
39
    {
40 2
        $this->checkCalculatable($other);
41 2
        $result = 0;
42 2
        foreach ($other->items as $key => $value) {
43 2
            $result += $value * $this->items[$key];
44 2
        }
45 2
        return $result;
46
    }
47
48
    /**
49
     * @param \Wandu\Math\LinearAlgebra\Vector $other
50
     * @return \Wandu\Math\LinearAlgebra\Vector
51
     */
52 1
    public function add(Vector $other)
53
    {
54 1
        $this->checkCalculatable($other);
55
        return $other->map(function ($item, $key) {
56 1
            return $item + $this->items[$key];
57 1
        });
58
    }
59
60 3
    protected function checkCalculatable(Vector $other)
61
    {
62 3
        if (count($this->items) !== count($other->items)) {
63
            throw new InvalidArgumentException('vector size is difference.');
64
        }
65 3
    }
66
67
    /**
68
     * @param \Wandu\Math\LinearAlgebra\Vector $other
69
     * @return bool
70
     */
71 2
    public function equal(Vector $other)
72
    {
73 2
        return $this->items === $other->items;
74
    }
75
76
    /**
77
     * @param number $other
78
     * @return \Wandu\Math\LinearAlgebra\Vector
79
     */
80
    public function multiplyWithScalar($other)
81
    {
82 1
        return $this->map(function ($item) use ($other) {
83 1
            return $item * $other;
84 1
        });
85
    }
86
87
    /**
88
     * @param \Closure $handler
89
     * @return \Wandu\Math\LinearAlgebra\Vector
90
     */
91 2
    public function map(Closure $handler)
92
    {
93 2
        $new = [];
94 2
        foreach ($this->items as $key => $item) {
95 2
            $new[$key] = $handler->__invoke($item, $key);
96 2
        }
97 2
        return new Vector($new);
98
    }
99
}
100