mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-13 06:23:00 +08:00
Add cartesian product algorithm.
This commit is contained in:
parent
02806f7efa
commit
91011c18f4
@ -15,6 +15,7 @@
|
|||||||
|
|
||||||
* Math
|
* Math
|
||||||
* [Fibonacci Number](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/fibonacci)
|
* [Fibonacci Number](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/fibonacci)
|
||||||
|
* [Cartesian Product](https://github.com/trekhleb/javascript-algorithms/tree/master/src/algorithms/math/cartesian-product)
|
||||||
|
|
||||||
## Running Tests
|
## Running Tests
|
||||||
|
|
||||||
|
@ -0,0 +1,19 @@
|
|||||||
|
import cartesianProduct from '../cartesianProduct';
|
||||||
|
|
||||||
|
describe('cartesianProduct', () => {
|
||||||
|
it('should return null if there is not enough info for calculation', () => {
|
||||||
|
const product1 = cartesianProduct([1], null);
|
||||||
|
const product2 = cartesianProduct([], null);
|
||||||
|
|
||||||
|
expect(product1).toBeNull();
|
||||||
|
expect(product2).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should calculate the product of two sets', () => {
|
||||||
|
const product1 = cartesianProduct([1], [1]);
|
||||||
|
const product2 = cartesianProduct([1, 2], [3, 5]);
|
||||||
|
|
||||||
|
expect(product1).toEqual([[1, 1]]);
|
||||||
|
expect(product2).toEqual([[1, 3], [1, 5], [2, 3], [2, 5]]);
|
||||||
|
});
|
||||||
|
});
|
15
src/algorithms/math/cartesian-product/cartesianProduct.js
Normal file
15
src/algorithms/math/cartesian-product/cartesianProduct.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
export default function cartesianProduct(setA, setB) {
|
||||||
|
if (!setA || !setB || !setA.length || !setB.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = [];
|
||||||
|
|
||||||
|
for (let indexA = 0; indexA < setA.length; indexA += 1) {
|
||||||
|
for (let indexB = 0; indexB < setB.length; indexB += 1) {
|
||||||
|
product.push([setA[indexA], setB[indexB]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return product;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user