hakeの日記

Windows環境でプログラミングの勉強をしています。

Go言語 - Set(集合)

本日からGo言語の使用環境は、go version go1.5.1 windows/amd64 です。


Goでsetを扱う方法を見てSet型を作成してみました。

package main

import (
	"fmt"
)

type Set struct{
	m         map[string]struct{}
}

func NewSet(ss ...string) *Set {
	set := &Set{}
	set.m  = make(map[string]struct{})
	if len(ss) > 0 {
		for _, i := range ss {
			set.m[i] = struct{}{}
		}
	}
	return set
}

func (self *Set)Add(ss ...string) {
	if len(ss) > 0 {
		for _, i := range ss {
			self.m[i] = struct{}{}
		}
	}
}

func (self *Set)Delete(k string) {
	delete(self.m, k)
}

func (self *Set)Len() int {
	return len(self.m)
}

func (self *Set)Include(k string) bool {
	_, b := self.m[k]
	return b
}

func (self *Set)Union(other *Set) {
	self.Add(other.Elements()...)
}

func (self *Set)Intersection(other *Set) *Set {
	r := NewSet()
	for k,_ := range other.m {
		if self.Include(k) {
			r.Add(k)
		}
	}
	return r
}


func (self *Set)Elements() []string {
	r := make([]string, self.Len(), self.Len())
	var i int = 0
	for k,_ := range self.m {
		r[i] = k
		i++
	}
	return r
}



func main() {

	s := NewSet("A", "B")
	fmt.Println(s.Elements())         //-> [B A]
	s.Add("C", "D")
	fmt.Println(s.Elements())         //-> [A B C D]
	s.Delete("A")
	fmt.Println(s.Elements())         //-> [C D B]
	fmt.Println(s.Len())              //-> 3
	fmt.Println(s.Include("B"))       //-> true
	fmt.Println(s.Include("Z"))       //-> false

	s.Union(NewSet("D", "E", "F"))  // s ∪ other
	fmt.Println(s.Elements())         //-> [C D F E B]

	u := s.Intersection(NewSet("A", "B", "C"))  // s ∩ other
	fmt.Println(u.Elements())         //-> [B C]


}