From 91011c18f40b2e9f2d3de095563eecc0e7b20d17 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Mon, 2 Apr 2018 09:23:32 +0300 Subject: [PATCH] Add cartesian product algorithm. --- README.md | 1 + .../__test__/cartesianProduct.test.js | 19 +++++++++++++++++++ .../cartesian-product/cartesian-product.js | 1 - .../cartesian-product/cartesianProduct.js | 15 +++++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/algorithms/math/cartesian-product/__test__/cartesianProduct.test.js delete mode 100644 src/algorithms/math/cartesian-product/cartesian-product.js create mode 100644 src/algorithms/math/cartesian-product/cartesianProduct.js diff --git a/README.md b/README.md index 401e0faf..63a02f2b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/algorithms/math/cartesian-product/__test__/cartesianProduct.test.js b/src/algorithms/math/cartesian-product/__test__/cartesianProduct.test.js new file mode 100644 index 00000000..f9154fa2 --- /dev/null +++ b/src/algorithms/math/cartesian-product/__test__/cartesianProduct.test.js @@ -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]]); + }); +}); diff --git a/src/algorithms/math/cartesian-product/cartesian-product.js b/src/algorithms/math/cartesian-product/cartesian-product.js deleted file mode 100644 index 8b137891..00000000 --- a/src/algorithms/math/cartesian-product/cartesian-product.js +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/algorithms/math/cartesian-product/cartesianProduct.js b/src/algorithms/math/cartesian-product/cartesianProduct.js new file mode 100644 index 00000000..61666819 --- /dev/null +++ b/src/algorithms/math/cartesian-product/cartesianProduct.js @@ -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; +}