This commit is contained in:
GrosSacASacs 2024-07-17 10:38:06 +09:00 committed by GitHub
commit c082a7052d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 2 deletions

View File

@ -16,4 +16,12 @@ describe('cartesianProduct', () => {
expect(product1).toEqual([[1, 1]]);
expect(product2).toEqual([[1, 3], [1, 5], [2, 3], [2, 5]]);
});
it('should return an empty set if one or both of the source is empty', () => {
const product1 = cartesianProduct([], [1, 2, 3]);
const product2 = cartesianProduct([], []);
expect(product1).toEqual([]);
expect(product2).toEqual([]);
});
});

View File

@ -5,14 +5,17 @@
* @return {*[]}
*/
export default function cartesianProduct(setA, setB) {
// Check if input sets are not empty.
// Check if input sets are not non-arrays.
// Otherwise return null since we can't generate Cartesian Product out of them.
if (!setA || !setB || !setA.length || !setB.length) {
if (!setA || !setB) {
return null;
}
// Init product set.
const product = [];
if (!setA.length || !setB.length) {
return 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) {