Skip to content

Instantly share code, notes, and snippets.

@wibus-wee
Last active July 11, 2022 09:19
Show Gist options
  • Save wibus-wee/512507f0b872b20f930b25bce3d86db9 to your computer and use it in GitHub Desktop.
Save wibus-wee/512507f0b872b20f930b25bce3d86db9 to your computer and use it in GitHub Desktop.
const collection1 = [ 1, 2, 3, 4 ];
const collection2 = [ 1, 2, 3, 4, 5 ];
// 比较两个集合的长度
// 如果集合1的长度小于集合2的长度,意味着集合1有可能是集合2的子集(如果集合1的元素都在集合2中)
// 反之,意味着集合1有可能是集合2的父集(如果集合2的元素都在集合1中)
// 但是无论如何,判断长度后都需要判断是否有交集
function compareLength(collection1, collection2) {
if (collection1.length < collection2.length) {
return -1;
} else if (collection1.length > collection2.length) {
return 1;
} else if (collection1.length === collection2.length) {
return 0;
} else {
throw new Error('compareLength error');
}
}
// 判断交集,如果有交集,那么就需要判断是否是真子集or子集
// 无非就是查看集合1中的元素是否有在集合2中
function haveIndex(collection1, collection2) {
let result = false;
for (let i = 0; i < collection1.length; i++) {
//如果在集合2中找到了集合1的元素,那么就有交集 indexOf 是查找元素的位置,如果找不到返回-1
if (collection2.indexOf(collection1[i]) !== -1) { // collection2 的长度大于集合1的长度
result = true;
break;
}
}
return result;
}
// 判断是否有交集
// 交集有两种情况:
// 1. 集合1与集合2相同,集合1与集合2有交集
// 2. 集合1与集合2不相同,集合1与集合2有交集,那这个情况就需要考虑谁是谁的子集
// 如果他们都没有交集,那么就是不相交,啥也不是
// 需要注意的真子集和子集的区别:
// 子集就是一个集合中的全部元素是另一个集合中的元素,有可能与另一个集合相等
// 真子集就是一个集合中的元素全部是另一个集合中的元素,但不存在相等
function hasIntersect(collection1, collection2) {
// 先判断长度
if (compareLength(collection1, collection2) === 0) { //长度相等
// 因为长度相等,因此不需要判断是否是真子集or子集,绝对是真子集
return haveIndex(collection1, collection2) ? "子集" : "啥也不是";
} else if (compareLength(collection1, collection2) === -1) { // 1<2
return haveIndex(collection1, collection2) ? "真子集" : "啥也不是";
} else if (compareLength(collection1, collection2) === 1) { // 1>2
return haveIndex(collection2, collection1) ? "父集" : "啥也不是";
}
return "啥也不是";
}
console.log("collection1: " + collection1)
console.log("collection2: " + collection2)
console.log("子集情况: " +
"collection1 是 collection2 的" + hasIntersect(collection1, collection2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment