Ai
1 Star 0 Fork 0

ubuntuvim/algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Set.js 2.50 KB
一键复制 编辑 原始数据 按行查看 历史
ubuntuvim 提交于 2015-07-15 10:58 +08:00 . save to git...
/**
* 集合类 Set
* 元素无序但是不能有相同的元素
*/
function Set() {
this.dataStore = [];
this.empty = empty;
this.remove = remove;
this.add = add;
this.clear = clear;
this.displayAll = displayAll;
this.union = union;
this.contains = contains; //判断集合是否存在某个元素
this.intersection = intersection; // 获取两个集合的交集
}
/**
* 判断集合是否为空
* @return true-空;false-非空
*/
function empty() {
return this.dataStore == 0;
}
// 新增元素
function add(e) {
if (this.dataStore.indexOf(e) < 0) { //先判断要新增的元素是否已经存在
this.dataStore.push(e);
return true;
} else {
return false;
}
}
// 清空集合
function clear() {
delete this.dataStore;
this.dataStore = [];
}
// 删除元素
function remove(e) {
// 先判断要删除的元素是否存在
var pos = this.dataStore.indexOf(e); //找到删除的元素的位置
if (pos > -1) { //存在
this.dataStore.splice(pos, 1);
return true;
} else {
return false;
}
}
// 显示集合的所有元素
function displayAll() {
print(this.dataStore);
}
/**
* 判断某个元素是否存在在集合中
* @return true-存在;false-不存在
*/
function contains(e) {
return this.dataStore.indexOf(e) > -1;
}
// 合并2个集合
function union(set) {
// 不能直接使用 this 否则会修改了 this 本身的元素
var tmpSet = new Set();
for (var i = 0; i < this.dataStore.length; i++) {
tmpSet.add(this.dataStore[i]);
}
var inLen = set.dataStore.length;
// 先判断要合并的集合的元素是否已经存在了,存在的不再添加到集合中
for (var i = 0; i < inLen; i++) {
if (!tmpSet.contains(set.dataStore[i])) {
tmpSet.add(set.dataStore[i]);
}
}
return tmpSet;
}
// 取得两个集合的交集
function intersection(set) {
var tmp = new Set();
// 返回两个集合中相同的元素
for (var i = 0; i < this.dataStore.length; i++) {
if (this.contains(set.dataStore[i])) {
tmp.add(set.dataStore[i]);
}
}
return tmp;
}
// 测试
var set1 = new Set();
// cis.clear();
set1.add("NBA");
set1.add("Curry");
set1.add("James");
set1.add("Kobe");
print("集合1:");
set1.displayAll();
var set2 = new Set();
// dmp.clear();
set2.add("Duncan");
set2.add("Curry");
set2.add("Jordan");
print("集合2:");
set2.displayAll();
var tmp = new Set();
tmp= set1.union(set2);
// it.clear();
print("合并后:");
tmp.displayAll();
// set1.displayAll();
print("\n获取交集: ");
var its = set1.intersection(set2);
its.displayAll();
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/ubuntuvim/algorithm.git
git@gitee.com:ubuntuvim/algorithm.git
ubuntuvim
algorithm
algorithm
master

搜索帮助