Movatterモバイル変換


[0]ホーム

URL:


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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
xinzhe822 wants to merge6 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromxinzhe822:master
Open
Show file tree
Hide file tree
Changes fromall 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 deletionsMaths/CartesianProduct.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionsMaths/test/CartesianProduct.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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]])
})
})

[8]ページ先頭

©2009-2025 Movatter.jp