標籤:java als type javascrip store log 最小 ons function
集合的實現
function Set () { this.dataStore = []; this.add = add; this.remove = remove; this.size = size; this.union = union; this.intersect = intersect; this.subset = subset; this.difference = difference; this.show = show; this.contains = contains;}function add (data) { if (this.dataStore.indexOf(data) < 0) { this.dataStore.push(data); return true; } else { return false; }}function remove (data) { let 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 true; } else { return false; }}function union (set) { let tempSet = new Set(); for (let i = 0; i < this.dataStore.length; ++i) { tempSet.add(this.dataStore[i]); } for (let i = 0; i < set.dataStore.length; ++i) { if (!tempSet.contains(set.dataStore[i])) { tempSet.dataStore.push(set.dataStore[i]); } } return tempSet;}function intersect (set) { let tempSet = new Set(); for (let i =0; i < this.dataStore.length; ++i) { if (set.contains(this.dataStore[i])) { tempSet.add(this.dataStore[i]); } } return tempSet;}function subset (set) { if (this.size() > set.size()) { return false; } else { for (let i = 0; i < this.dataStore.length; ++i) { if (!set.contains(this.dataStore[i])) { return false; } } } return true;}function size () { return this.dataStore.length;}function difference (set) { let tempSet = new Set(); for (let i = 0; i < this.dataStore.length; ++i) { if (!set.contains(this.dataStore[i])) { tempSet.add(this.dataStore[i]); } } return tempSet;}
練習一. 修改集合類,使裡面的元素按順序儲存。寫一段測試代碼來測試你的修改。
// 修改add方法function add (data) { if (this.dataStore.indexOf(data) < 0) { this.dataStore.push(data); // 排序 this.dataStore = this.dataStore.sort((a, b) => a - b); return true; } else { return false; }}// 樣本let s = new Set();s.add(23);s.add(3);s.add(2);s.add(24);s.add(73);console.log(s.show()); // [2, 3, 23, 24, 73]
二. 為集合類增加一個higher(element)方法,該方法返回比傳入元素大的元素中最小的那個。寫一段測試代碼來測試這個方法。
Set.prototype.higher = function (element) { let arr = []; for (let i = 0; i < this.dataStore.length; ++i) { if (this.dataStore[i] > element) { arr.push(this.dataStore[i]); } } return arr.sort((a, b) => a - b)[0];};// 樣本let s = new Set();s.add(23);s.add(3);s.add(2);s.add(24);s.add(73);console.log(s.higher(20)); // 23console.log(s.higher(60)); // 73
三. 為集合類增加一個lower(element)方法,該方法返回比傳入元素小的元素中最大的那個。寫一段測試代碼來測試這個方法。
Set.prototype.lower = function (element) { let arr = []; for (let i = 0; i < this.dataStore.length; ++i) { if (this.dataStore[i] < element) { arr.push(this.dataStore[i]); } } return arr.sort((a, b) => b - a)[0];};// 樣本let s = new Set();s.add(23);s.add(3);s.add(2);s.add(24);s.add(73);console.log(s.lower(20)); // 3console.log(s.lower(60)); // 24
JavaScript資料結構與演算法-集合練習