셋(Set)
데이터의 중복을 허용하지 않는 자료 구조
해시테이블을 사용하기 때문에 해시 셋이라고도 한다.
해시 테이블을 사용 하여 해시 셋을 구현
import { HashTable } from './HashTable.mjs';
class HashSet {
constructor() {
this.hashTable = new HashTable();
}
add(data) {
if (this.hashTable.get(data) == null) {
this.hashTable.set(data, -1);
}
}
isContain(data) {
return this.hashTable.get(data) != null;
}
remove(data) {
this.hashTable.remove(data);
}
clear() {
for (let i = 0; i < this.hashTable.arr.length; i++) {
this.hashTable.arr[i].clear();
}
}
isEmpty() {
let empty = true;
for (let i = 0; i < this.hashTable.arr.length; i++) {
if (this.hashTable.arr[i].count > 0) {
empty = false;
break;
}
}
return empty;
}
printAll() {
for (let i = 0; i < this.hashTable.arr.length; i++) {
let currentNode = this.hashTable.arr[i].head;
while (currentNode != null) {
console.log(currentNode.data.key);
currentNode = currentNode.next;
}
}
}
}
export { HashSet };
아래와 같이 테스트 한다.
import { HashSet } from './HashSet.mjs';
let hashSet = new HashSet();
console.log(`isEmpty: ${hashSet.isEmpty()}`);
console.log('===== 데이터 삽입 =====');
hashSet.add(1);
hashSet.add(1);
hashSet.add(123);
hashSet.add(512);
hashSet.printAll();
console.log(`isEmpty: ${hashSet.isEmpty()}`);
console.log('===== 데이터 체크1 =====');
console.log(`isContain: ${hashSet.isContain(1)}`);
console.log('===== 데이터 제거 =====');
hashSet.remove(1);
hashSet.printAll();
console.log(`isEmpty: ${hashSet.isEmpty()}`);
console.log('===== 데이터 체크2 =====');
console.log(`isContain: ${hashSet.isContain(1)}`);
console.log('===== clear =====');
hashSet.clear();
hashSet.printAll();
console.log(`isEmpty: ${hashSet.isEmpty()}`);
λ node test_HashSet.mjs
isEmpty: true
===== 데이터 삽입 =====
1
512
123
isEmpty: false
===== 데이터 체크1 =====
isContain: true
===== 데이터 제거 =====
512
123
isEmpty: false
===== 데이터 체크2 =====
isContain: false
===== clear =====
isEmpty: true
9. 정렬 - 버블 정렬, 선택정렬,삽입정렬,병합정렬,퀵정렬 (0) | 2023.07.17 |
---|---|
8. 알고리즘 - 재귀 (0) | 2023.07.14 |
6. 해시 테이블(HashTable) (0) | 2023.07.12 |
5. 덱(deque) (0) | 2023.07.11 |
4. 큐(Queue) (0) | 2023.07.10 |