Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added CartesianProduct.js #1082

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Maths/CartesianProduct.js
Original file line number Diff line number Diff line change
@@ -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 }
21 changes: 21 additions & 0 deletions Maths/test/CartesianProduct.test.js
Original file line number Diff line number Diff line change
@@ -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]])
})
})