集合(Set)
特性:是由一組無順序且不重複的項目組成的。
可想成沒有重複的元素,也沒有順序概念的陣列。
(聯集、交集、差集、子集)
聯集: 對於給定兩集合,回傳一個包含兩個集合中"所有"元素的新集合
交集: 對於給定兩集合,回傳一個包含兩個集合中"共有"元素的新集合
差集: 對於給定兩集合,回傳一個包含所有存在第一個集合但不存在於第二集合的元素集合
子集: 驗證給定集合是否為另一個集合的子集
http://blog.kdchang.cc/2016/09/23/javascript-data-structure-algorithm-set/
建立集合類別和方法
function Set() {
var items = {};
this.add(value) {};
this.remove(value) {};
this.has(value) {};
this.clear() {};
this.size() {};
this.values() {};
}
has(value):判斷是否元素在集合中,若有回傳 true,反之傳回 false
this.has = function(value) {
return items.hasOwnProperty(value);
}
add(value):新增元素到集合
this.add = function(value) {
if(!this.has(value)) {
items[value] = value;
return true;
}
return false;
}
remove(value):刪除元素
this.remove = function(value) {
if(this.has(value)) {
delete items[value];
return true;
}
return false;
};
clear():移除集合所有元素
this.clear = function() {
items = {};
}
size():回傳集合元素數量
this.size = function() {
return this.values().length;
}
values():回傳集合所有值
this.values = function() {
return Object.keys(items);
}
範例:
const set = new Set();
set.add(12);
console.log(set.values());
console.log(set.has(12));
console.log(set.size());
set.add(7);
set.remove(12);
set.add(1);
console.log(set.has(12));
console.log(set.values());
console.log(set.size());
聯集
this.union = function(otherSet) {
let unionSet = new Set();
let values = this.values();
for(var i = 0; i < values.length; i++) {
unionSet.add(values[i]);
}
values = otherSet.values();
for(let j = 0; j < values.length; j++) {
unionSet.add(values[j]);
}
return unionSet.values();
}
交集
this.intersection = function(otherSet) {
let intersectionSet = new Set();
let values = this.values();
for(let i = 0; i < values.length; i++) {
if(otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
return intersectionSet;
}
差集
this.difference = function(otherSet) {
let differenceSet = new Set();
let values = this.values();
for(let i = 0; i < values.length; i++) {
if(!otherSet.has(values[i])) {
differenceSet.add(values[i]);
}
}
return differenceSet.values();
}
子集
this.subSet = function(otherSet) {
if(this.size() > otherSet.size()) {
return false;
} else {
let values = this.values();
for(let i = 0; i < values.length; i++) {
if(!otherSet.has(values[i])) {
return false;
}
}
return true;
}
}