Skip to content

Commit

Permalink
feat: add vector\add()
Browse files Browse the repository at this point in the history
  • Loading branch information
Yogarine committed Feb 8, 2025
1 parent c276412 commit 86cc6b0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
},
"autoload": {
"files": [
"src/array.php"
"src/array.php",
"src/vector.php"
],
"psr-4": {
"empaphy\\maphematics\\": "src/"
Expand Down
34 changes: 34 additions & 0 deletions src/vector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace empaphy\maphematics\vector;

use empaphy\maphematics\array;

/**
* Add two or more vectors together.
*
* ⎡ a ⎤ ⎡ x ⎤ ⎡ a + x ⎤
* ⎢ b ⎥ + ⎢ y ⎥ = ⎢ b + y ⎥
* ⎣ c ⎦ ⎣ z ⎦ ⎣ c + z ⎦
*
* @param array<int|float> $vector
* @param array<int|float> ...$vectors
* @return array<int|float>
*/
function add(array $vector, array ...$vectors): array
{
$vectors = [$vector, ...$vectors];
$length = array\check_lengths(...$vectors);
$count = \count($vectors);
$result = \array_fill(0, $length, 0);

for ($i = 0; $i < $length; $i++) {
for ($j = 0; $j < $count; $j++) {
$result[$i] += $vectors[$j][$i];
}
}

return $result;
}
19 changes: 19 additions & 0 deletions tests/Unit/VectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/**
* Vector tests.
*
* @noinspection StaticClosureCanBeUsedInspection
*/

use empaphy\maphematics\vector;

describe('vector\add', function () {
it('works', function ($vector, $vectors, $expected) {
expect(vector\add($vector, ...$vectors))->toBe($expected);
})->with([
'two vectors' => [[3, -5], [[2, 1]], [3 + 2, -5 + 1]],
'three vectors' => [[1, 2], [[3, 5], [7, 11]], [1 + 3 + 7, 2 + 5 + 11]],
'vectors with floats' => [[3.0, -5.0], [[2.0, 1.0]], [3.0 + 2.0, -5.0 + 1.0]],
]);
});

0 comments on commit 86cc6b0

Please sign in to comment.