mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 15:11:16 +08:00
Add comments to Cartesian Product function.
This commit is contained in:
parent
243be8f2d1
commit
2382225e03
@ -1,15 +1,27 @@
|
||||
/**
|
||||
* Generates Cartesian Product of two sets.
|
||||
* @param {*[]} setA
|
||||
* @param {*[]} setB
|
||||
* @return {*[]}
|
||||
*/
|
||||
export default function cartesianProduct(setA, setB) {
|
||||
// Check if input sets are not empty.
|
||||
// Otherwise return null since we can't generate Cartesian Product out of them.
|
||||
if (!setA || !setB || !setA.length || !setB.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Init product set.
|
||||
const product = [];
|
||||
|
||||
// Now, let's go through all elements of a first and second set and form all possible pairs.
|
||||
for (let indexA = 0; indexA < setA.length; indexA += 1) {
|
||||
for (let indexB = 0; indexB < setB.length; indexB += 1) {
|
||||
// Add current product pair to the product set.
|
||||
product.push([setA[indexA], setB[indexB]]);
|
||||
}
|
||||
}
|
||||
|
||||
// Return cartesian product set.
|
||||
return product;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user