diff --git a/Maths/CartesianProduct.js b/Maths/CartesianProduct.js new file mode 100644 index 0000000000..65eb2f0ce8 --- /dev/null +++ b/Maths/CartesianProduct.js @@ -0,0 +1,23 @@ +/** + * @function cartesianProduct + * @description Generate Cartesian Product of Two Sets. + * @param {*[]} setA -First set + * @param {*[]} setB -Second set + * @return {*[]} -Cartesian Product of setA and setB + */ +const cartesianProduct = (setA, setB) => { + // Check if input sets are not empty. + if (!setA || !setB || !setA.length || !setB.length) { + return [] + } + const product = [] + + for(let elementA of setA){ + for(let elementB of setB){ + product.push([ elementA, elementB]) + } + } + return product +} + +export { cartesianProduct } diff --git a/Maths/test/CartesianProduct.test.js b/Maths/test/CartesianProduct.test.js new file mode 100644 index 0000000000..e5db00a6b6 --- /dev/null +++ b/Maths/test/CartesianProduct.test.js @@ -0,0 +1,21 @@ +import { cartesianProduct } from '../CartesianProduct' + +describe('cartesianProduct', () => { + it('should return null if 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]) + const product3 = cartesianProduct([1, 2], [3, 4]) + + expect(product1).toEqual([[1, 1]]) + expect(product2).toEqual([[1, 3], [2, 3]]) + expect(product3).toEqual([[1, 3], [1, 4], [2, 3], [2, 4]]) + }) +})