Add cartesian product algorithm.

This commit is contained in:
Oleksii Trekhleb 2018-04-02 09:23:32 +03:00
parent 02806f7efa
commit 91011c18f4
4 changed files with 35 additions and 1 deletions

View File

@ -15,6 +15,7 @@
* Math
* [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

View File

@ -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]]);
});
});

View 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;
}