C9 -- 集合
集合是一种包含不同元素的数据结构。
集合中的元素称为成员。
集合的两个最重要特性是:
- 集合中的成员是无序的。
- 集合中不允许相同元素存在。
1.集合的定义、操作和属性
1.1.1集合的定义
空集、全集、子集
1.2.对集合的操作
- 并集
- 交集
- 补集
2.Set类的实现
Set类的实现基于数组。
function Set(){
this.dataStore = [];
this.add = add;
this.remove = remove;
this.size = size;
this.intersect = intersect;
this.subset = subset;
this.union = union;
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){
if(this.dataStore.indexOf(data)>-1){
return false;
}else{
return true;
}
}
function union(set){
var tempSet = new Set();
for (var i = 0;i<this.dataStore.length;++i){
tempSet.add(this.dataStore[i]);
}
for (var i = 0;i<set.dataStore.length;++i){
if(!tempSet.contains(set.dataStore[i])){
tempSet.dataStore.push(set.dataStore[i]);
}
}
return tempSet;
}
function intersect(set){
var tempSet = new Set();
for(var i = 0;i<this.dataStore.length;++i){
if(set.contains(this.dataStore[i])){
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}
function size(){
return this.dataStore.length;
}
function subset(set){
if(this.size() > set.size()){
return false;
}
else{
for each(var member in this.dataStore){
if(!set.contains(member)){
return false;
}
}
}
return true;
}
function difference(set){
var tempSet = new Set();
for (var i=0;i<this.dataStore.length;++i){
if(!set.contains(this.dataStore[i])){
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}