- 集合是一种包含不同元素的数据结构
- 集合成员是无序的,集合成员不能重复
- 集合有,空集、交集、并集、补集
function Set() {
this.store = [];
this.add = add;
this.remove = remove;
this.size = size;
this.union = union;
this.intersect = intersect;
this.difference = difference;
this.show = show;
this.subset = subset;
}
let add = function(data) {
if (this.store.indexOf(data) === -1) {
this.store.push(data);
}
};
let remove = function(data) {
var index = this.store.indexOf(data);
if (index > 0) {
this.store.splice(index, 1);
}
};
let size = function() {
return this.store.length;
};
// 并集
let union = function(set) {
var s = new Set();
for (var i = 0; i < this.store.length; i++) {
s.add(this.store[i]);
}
for (var i = 0; i < set.store.length; i++) {
var index = s.store.indexOf(set.store[i]);
if (index === -1) {
s.add(set.store[i]);
}
}
return s;
};
// 交集
let intersect = function(set) {
var s = new Set();
for (var i = 0; i < set.store.length; i++) {
if (this.store.indexOf(set.store[i]) !== -1) {
s.add(set.store[i]);
}
}
return s;
};
// 补集
let difference = function(set) {
var s = new Set();
for (var i = 0; i < this.store.length; i++) {
var index = set.store.indexOf(this.store[i]);
if (index === -1) {
s.add(this.store[i]);
}
}
return s;
};
let show = function() {
return this.store.toString();
};
// 是否是子集
let subset = function(set) {
if (set.size() > this.size()) {
return false;
} else {
for (var i = 0; i < set.store.length; i++) {
if (this.store.indexOf(set.store[i]) === -1) {
return false;
}
}
return true;
}
};
var s = new Set();
s.add(1);
s.add(2);
s.add(3);
s.add(4);
s.add(5);
console.log(s.show());
s.remove(2);
console.log(s.show());
var s2 = new Set();
s2.add(11);
s2.add(11);
s2.add(22);
s2.add(33);
s2.add(1);
s2.add(5);
console.log("s2-》", s2.show());
console.log("并集", s.union(s2).show());
console.log("交集", s.intersect(s2).show());
console.log("s2相对s补集(s有的,s2没有)", s.difference(s2).show());
var s3 = new Set();
s3.add(11);
s3.add(1);
s3.add(22);
s3.add(22);
s3.add(1);
console.log(s3.show());
console.log("s3是s2的子集", s2.subset(s3));