您的位置:首页 > 理论基础 > 数据结构算法

JavaScript数据结构与算法-集合练习

2018-01-20 23:49 302 查看

集合的实现

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)); // 23
console.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)); // 3
console.log(s.lower(60)); // 24

JavaScript数据结构与算法-集合练习

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: