集合的特點(diǎn)是不包含重復(fù)元素,集合的元素通常無順序之分。在系統(tǒng)編程中集合很常用,但是并非所有語言都原生支持集合。
集合的三條理論:
- 不包含任何元素的集合為空集
- 兩個(gè)集合包含的元素完全一樣,則它們相等
- 集合A是集合B的子集,如果A的所有元素都在B中出現(xiàn)
集合的三種基本操作: - Union,兩個(gè)集合的并
- Intersection,兩個(gè)集合的交
- Difference,兩個(gè)集合的差
集合的js實(shí)現(xiàn):
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;
}