/*
* 数据结构——集合
* 集合(set)是一种包含不同元素的数据结构。集合中的元素称为成员。两个特点:1、成员是无序的 2、集合不能存在相同的成员
*
* 定义:
* 1、不包含任何成员的集合称为空集,全集则是包含一切可能成员的集合
* 2、如果两个集合的成员完全相同,则称两个集合相等
* 3、如果一个集合中所有的成员都属于另外一个集合,则前一集合称为后一集合的子集
* */
function add(data) {
if (this.dataStore.indexOf(data) === -1) {
this.dataStore.push(data);
return true;
}
return false;
}
function remove(data) {
var index = this.dataStore.indexOf(data);
if (index > -1) {
this.dataStore.splice(index,1);
return true;
}
return false;
}
function show() {
console.log(this.dataStore);
}
function size() {
return this.dataStore.length;
}
function contains(data) {
return this.dataStore.indexOf(data) > -1;
}
//并集操作
function union(set) {
var tempSet = new Set();
for (var i = 0 ; i < this.dataStore.length; i++) {
tempSet.add(this.dataStore[i]);
}
for(var j = 0; j < set.dataStore.length; j++) {
if (!tempSet.contains(set.dataStore[j])) {
tempSet.add(set.dataStore[j])
}
}
return tempSet;
}
//交集操作 a.intersect(b) b相对a的交集
function intersect(set) {
var tempSet = new Set();
for(var i = 0 ; i < set.dataStore.length; i++) {
if (this.contains(set.dataStore[i])) {
tempSet.add(set.dataStore[i])
}
}
return tempSet;
}
//是否是子集判断 a.subset(b) b是否是a的子集
function subset(set) {
if (this.size() < set.size()) {
return false;
}
for(var i = 0; i < set.size(); i++) {
if (!this.contains(set.dataStore[i])) {
return false;
}
}
return true;
}
//补集操作 a.difference(b) b相对于a的补集
function difference(set) {
var tempSet = new Set();
for(var i = 0; i< this.size();i++) {
if (!set.contains(this.dataStore[i])) {
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}
function Set() {
this.dataStore = [];
this.add = add;
this.remove = remove;
this.size = size;
this.contains = contains;
this.union = union;
this.intersect = intersect;
this.subset = subset;
this.difference = difference;
this.show = show;
}
var s = new Set();
s.add("1");
s.add("2");
s.add("3");
var dmp = new Set();
dmp.add("1");
dmp.add("4");
dmp.add("5");
dmp.add("6");
var c = s.union(dmp);
console.log(c);
var i = s.intersect(dmp);
console.log(i);
console.log(s.subset(i));
console.log(s.difference(i))