/* * 數據結構——集合 * 集合(set)是一種包含不一樣元素的數據結構。集合中的元素稱爲成員。兩個特色:一、成員是無序的 二、集合不能存在相同的成員 * * 定義: * 一、不包含任何成員的集合稱爲空集,全集則是包含一切可能成員的集合 * 二、若是兩個集合的成員徹底相同,則稱兩個集合相等 * 三、若是一個集合中全部的成員都屬於另一個集合,則前一集合稱爲後一集合的子集 * */ 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))