본문 바로가기

Javascript/DSA

Set Data Structure

About Set

 

집합이란 고유한 요소의 모임을 집합이라 한다.

[1,2,3,3] 3은 고유하지 않기때문에 집합이라 부를수 없다.

집합에는 순서가 없다.

[3,1,2,4] 는 집합 이다.

ADT Structure

method description
add(val) 추가
remove(val) 제거
has(val) 존제 여부 체크
clear() 초기화
size() 길이
values() 현재 담겨져 잇는 값
union() 합집합
intersection() 교집합
difference() 차집합

Implementation

class Set {
    constructor() {
        this.data = [];
    }

    add(val) {
        return this.has(val) ? console.log('val is exist') : this.data.push(val);
    }

    remove(val) {
        return this.has(val) ? this.data.splice(this.data.indexOf(val), 1) : console.log('val is no exist'); 
    }

    has(val) {
        return this.data.indexOf(val) >= 0 ? true : false;
    }

    clear() {
        this.data = [];
    }

    size() {
        return this.data.length;
    }

    values() {
        return this.data;
    }

    union(d_set) {
        let unionSet = new Set(),
            values, i;

        values = this.values();
        for (i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }

        values = d_set.values();
        for (i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }

        return unionSet;
    }

    intersection(d_set) {
        let intersectionSet = new Set(),
            values, i;

        values = this.values(); 

        for (i = 0; i < values.length; i++) {
            if (d_set.has(values[i])) {
                console.log(values[i]);
                intersectionSet.add(values[i]);
            }
        }

        return intersectionSet;
    }

    difference(d_set) {
        let differenceSet = new Set(),
            values, i;

        values = this.values();

        for (i = 0; i < values.length; i++) {
            if (!d_set.has(values[i])) {
                differenceSet.add(values[i]);
            }
        }

        return differenceSet;
    }

}

var seta = new Set();
var setb = new Set();

seta.add(1);
seta.add(2);
setb.add(2);
setb.add(3);

seta.union(setb);
seta.intersection(setb);
seta.difference(setb);

'Javascript > DSA' 카테고리의 다른 글

DSA end  (0) 2016.09.15
Search Algorithm  (0) 2016.09.15
Dynamic Programming & Greedy Algorithms  (0) 2016.09.11
Sorting Data Structure  (0) 2016.08.31
Graph Data Structure  (0) 2016.08.31