集合的特点是不包含重复元素,集合的元素通常无顺序之分。在系统编程中集合很常用,但是并非所有语言都原生支持集合。
集合的三条理论:
- 不包含任何元素的集合为空集
- 两个集合包含的元素完全一样,则它们相等
- 集合A是集合B的子集,如果A的所有元素都在B中出现
集合的三种基本操作: - Union,两个集合的并
- Intersection,两个集合的交
- Difference,两个集合的差
集合的js实现:
function Set() {
this.dataStore = [ ];
// operations
this.add = add;
this.remove = remove;
this.size = size;
this.union = union;
this.intersect = intersect;
this.subset = subset;
this.difference = difference;
this.show = show;
}
function add(data) {
if (this.dataStore.indexOf(data) < 0) {
this.dataStore.push(data);
return true;
}
else {
return false;
}
}
function remove(data) {
var pos = this.dataStore.indexOf(data);
if (pos > -1) {
this.dataStore.splice(pos, 1);
return true;
}
else {
return false;
}
}
function show() {
return this.dataStore;
}
function contains(data) {
return this.dataStore.indexOf(data) > -1 ;
}
function union(set) {
var tmp = new Set();
for each (var e in this.dataStore) {
tmp.add(e);
}
for each (var e in set) {
if (!tmp.contains(e)) {
tmp.push(e);
}
}
return tmp;
}
function subset(set) {
if (this.size() > set.size()) {
return false;
}
else {
for each (var e in this.dataStore) {
if (!set.contains(e)) {
return false;
}
}
}
return true;
}
function size() {
return this.dataStore.length;
}
// 返回 this - set
function difference(set) {
var tmp = new Set();
for each (var e1 in this.dataStore) {
if (!set.contains(e1)) tmp.add(e1);
}
return tmp;
}