Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added CartesianProduct.js #1082

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

Open
xinzhe822 wants to merge 6 commits into TheAlgorithms:master
base: master
Choose a base branch
Loading
from xinzhe822:master
Open
Show file tree
Hide file tree
Changes from 4 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
24 changes: 24 additions & 0 deletions Maths/CartesianProduct.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @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 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
}

export { cartesianProduct }
21 changes: 21 additions & 0 deletions Maths/test/CartesianProduct.test.js
View file Open in desktop
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]])
})
})

AltStyle によって変換されたページ (->オリジナル) /