📗 self-study/📗 inflearn

[자료 구조와 알고리즘] 셋(Set)

천재강쥐 2023. 5. 21. 21:26

 

 

 

🔥 그림으로 쉽게 배우는 자료 구조와 알고리즘

 

셋(Set)

 

 

 

 

📍 셋(Set)

👉🏻 데이터의 중복을 허용하지 않는 자료 구조

👉🏻 해시 테이블을 이용한 자료 구조로 해시 셋이라고도 불림

 

👉🏻  Value를 사용하지 않고 Key만 사용하여 구현 

 

 

📍 셋(Set)의 추상 자료형

[ HashSet.mjs ]

ximport { HashTable } from './HashTable.mjs';

class HashSet {
    constructor() {
        this.hashTable = new HashTable();
    }

    add(data) {
        if(this.hashTable.get(data) == null) {
            this.hashTable.set(data, -1); // 아무 값이나 넣어도 상관은 없으나 예시로 -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 };
[ test_set.mjs ]

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("===== 데이터 제거 1 =====");
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()}`);

👉🏻 add(data): 데이터 삽입

👉🏻 isContain(data): 데이터 체크로 true/false 리턴

 

👉🏻 remove(data): key에 해당하는 데이터 제거 

 

👉🏻 clear(): 셋 비우기

 

👉🏻 isEmpty(): 셋이 비었는지 체크

 

👉🏻 printAll(): 모든 데이터 출력