File tree 1 file changed +12
-0
lines changed
src/algorithms/sets/cartesian-product
1 file changed +12
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Generates Cartesian Product of two sets.
3
+ * @param {*[] } setA
4
+ * @param {*[] } setB
5
+ * @return {*[] }
6
+ */
1
7
export default function cartesianProduct ( setA , setB ) {
8
+ // Check if input sets are not empty.
9
+ // Otherwise return null since we can't generate Cartesian Product out of them.
2
10
if ( ! setA || ! setB || ! setA . length || ! setB . length ) {
3
11
return null ;
4
12
}
5
13
14
+ // Init product set.
6
15
const product = [ ] ;
7
16
17
+ // Now, let's go through all elements of a first and second set and form all possible pairs.
8
18
for ( let indexA = 0 ; indexA < setA . length ; indexA += 1 ) {
9
19
for ( let indexB = 0 ; indexB < setB . length ; indexB += 1 ) {
20
+ // Add current product pair to the product set.
10
21
product . push ( [ setA [ indexA ] , setB [ indexB ] ] ) ;
11
22
}
12
23
}
13
24
25
+ // Return cartesian product set.
14
26
return product ;
15
27
}
You can’t perform that action at this time.
0 commit comments