第九章(集合)

1,集合中的元素是無序的;

2,用來保存獨一無二的元素,比如一段文本中用到的單詞,先檢索有沒有在數組中出現再確定是否往數組中添加。

			function Set(){
				this.dataStore=[];//數組
				this.add=add;//增加
				this.remove=remove;//刪除
//				this.contains=contains;
				this.size=size;//大小
				this.union=union;//並集
				this.intersect=intersect;//交集
				this.subset=subset;//子集
				this.difference=difference;//補集
				this.show=show;//顯示集合
				this.contanins=contanins;
			}
			function add(data){
				if(this.dataStore.indexOf(data)>=0){
					return false;
				}
				else{
					this.dataStore.push(data);
					return true;
				}
			}
			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 contanins(data){
				if(this.dataStore.indexOf(data)>-1){
					return true;
				}
				else{
					return false;
				}
			}
			//並集
			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.contanins(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.contanins(this.dataStore[i])){
						tempSet.add(this.dataStore[i]);
					}
				}
				return tempSet;
			}
			//子集
			function subset(set){
				if(this.size()>set.size()){
					return false;
				}
				else{
					for(var member in this.dataStore){
						if(!set.contains(member)){
							return false;
						}
					}
					return true;
				}
			}
			//大小
			function size(){
				return this.dataStore.length;
			}
			//補集
			function difference(set){
				var tempSet=new Set();
				for(var i=0;i<this.dataStore.length;++i){
					if(!set.contanins(this.dataStore[i])){
						tempSet.add(this.dataStore[i]);
					}
				}
				return tempSet;
			}
			
			//主程序
			var seta=new Set();
			seta.add("zhangsan");
			seta.add("lisi");
			seta.add("wangwu");
			seta.add("maliu");
			
			var setb=new Set();
			setb.add("maliu");
			setb.add("qiqi");
			setb.add("basi");
			
			console.log("seta:"+seta.show());
			console.log("setb:"+setb.show());
			
			console.log("seta&setb:"+seta.union(setb).show());
			console.log("seta與setb的交集:"+seta.intersect(setb).show());
			console.log("seta是setb的子集嗎?:"+seta.subset(setb));
			console.log("seta在setb的補集:"+seta.difference(setb).show());


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章