상세 컨텐츠

본문 제목

7. 셋 (set)

CS전공 지식/2. 자료구조와 알고리즘

by 본투비곰손 2023. 7. 13. 22:33

본문

728x90

셋(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
728x90

관련글 더보기