Set

김_리트리버·2020년 10월 1일
0

Data Structure

목록 보기
2/3

집합

사전적정의
= 유일하게 구분되는 원소들의 모임

IT 정의
= 중복되지 않고 정렬되지 않은 데이터들의 모임

사용이유
= 유사한 자료들을 중복없이 쉽게 관리하려고

사용방법

function Set() {
  var items = {}

  // add, remove , has, clear, size, values,

  Set.prototype.has = function (value) {
    // argument 로 받은 값이 현재 집합에 있는 지 여부를 리턴함
    return value in items
  }

  Set.prototype.add = function (value) {
    // 전달인자로 받은 값이 현재 집합에 없으면
    // 받은 값을 키로 객체에 넣는다.
    if (!this.has(value)) {
      items[value] = value
      return true
    }

    return false
  }

  Set.prototype.remove = function (value) {
    if (this.has(value)) {
      delete items[value]
      return true
    }

    return false
  }

  Set.prototype.clear = function () {
    items = {}
  }

  Set.prototype.size = function () {
    return Object.keys(items).length
  }

  Set.prototype.values = function () {
    return Object.keys(items)
  }

  // 집합연산

  /* 1. 합집합
  
  A ∪ B

  A 집합에 있거나 B 집합에 있는 요소들의 집합을 리턴 
  */

  Set.prototype.union = function (otherSet) {
    let unionSet = new Set()

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

    for (let i; i < otherSetValues.length; i++) {
      unionSet.add(otherSetValues[i])
    }

    return unionSet
  }
  /* 2. 교집합
  
  A ∩ B

  A 집합에도 있고 B 집합에도 있는 요소들의 집합을 리턴 
  */
  Set.prototype.intersection = function (otherSet) {
    let intersectionSet = new Set()

    let currentValues = this.values()
    // let otherSetValues = otherSet.values()
    for (let i = 0; i < currentValues.length; i++) {
      if (otherSet.has(currentValues[i])) {
        intersectionSet.add(currentValues[i])
      }
    }

    return intersectionSet
  }

  /* 3. 차집합
  
  A - B

  A 집합에만 있고 B 집합에는 없는 요소들의 집합을 리턴
   
  */

  Set.prototype.difference = function (otherSet) {
    let differenceSet = new Set()
    let currentValues = this.values()
    for (let i = 0; i < currentValues.length; i++) {
      if (!otherSet.has(currentValues[i])) {
        differenceSet.add(currentValues[i])
      }
    }

    return differenceSet
  }

  /* 4. 부분집합
  
  A ⊂ B

  집합 A 의 요소들을 집합 B 가 전부가지고 있는지 여부를 리턴   
   
  */
  Set.prototype.subset = function (otherSet) {
    if (this.size() > otherSet.size()) {
      return false
    } else {
      let currentValues = this.values()
      for (let i = 0; i < currentValues.length; i++) {
        if (!otherSet.has(currentValues[i])) {
          return false
        }
      }

      return true
    }
  }
}

profile
web-developer

0개의 댓글