Skip to content

Instantly share code, notes, and snippets.

@deltam
Last active June 15, 2018 03:09
Show Gist options
  • Save deltam/3980410eb645d5b4ff1395321ff3b3a7 to your computer and use it in GitHub Desktop.
Save deltam/3980410eb645d5b4ff1395321ff3b3a7 to your computer and use it in GitHub Desktop.
汎用データ構造っぽいやつ
// どんな型の配列だろうが添字はintという発想から汎用データ構造みたいなのが作れないか試してみた
// 配列は削除が面倒なのでmapで任意の構造体を持つ
// intキー:任意の型でintキーだけデータ構造で管理しとく
// とりあえずStack
package main
import "fmt"
func main() {
fmt.Println("IndexStack")
is := NewIndexStack(10)
is.Push(0)
is.Push(1)
fmt.Println(is.Pop())
fmt.Println(is.Pop())
fmt.Println("StrStack")
ss := NewStrStack(10)
fmt.Println("size:", ss.Size())
ss.Push("A")
ss.Push("B")
ss.Push("C")
fmt.Println("size:", ss.Size())
fmt.Println(ss.Pop())
fmt.Println(ss.Pop())
fmt.Println(ss.Pop())
fmt.Println("size:", ss.Size())
// 自前の構造体を使える
fmt.Println("PointStack")
ps := NewPointStack(10)
fmt.Println("size:", ps.Size())
ps.Push(MyPoint{X: 10, Y: 10})
ps.Push(MyPoint{X: 20, Y: 20})
ps.Push(MyPoint{X: 30, Y: 30})
fmt.Println("size:", ps.Size())
fmt.Println(ps.Pop())
fmt.Println(ps.Pop())
fmt.Println(ps.Pop())
fmt.Println("size:", ps.Size())
}
// スタック本体
type IndexStack struct {
data []int
}
func NewIndexStack(cap int) IndexStack {
return IndexStack{
data: make([]int, 0, cap),
}
}
func (s *IndexStack) Push(i int) {
s.data = append(s.data, i)
}
func (s *IndexStack) Pop() int {
r := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
return r
}
func (s IndexStack) Size() int {
return len(s.data)
}
// string用スタック
type StrStack struct {
stk IndexStack
strs map[int]string
index int
}
func NewStrStack(cap int) StrStack {
return StrStack{
stk: NewIndexStack(cap),
strs: make(map[int]string),
index: 0,
}
}
func (s *StrStack) Push(str string) {
s.strs[s.index] = str
s.stk.Push(s.index)
s.index++
}
func (s *StrStack) Pop() string {
i := s.stk.Pop()
str := s.strs[i]
delete(s.strs, i)
return str
}
func (s StrStack) Size() int {
return s.stk.Size()
}
// 適当なオリジナルの構造体
type MyPoint struct {
X int
Y int
}
type PointStack struct {
stk IndexStack
points map[int]MyPoint
index int
}
func NewPointStack(cap int) PointStack {
return PointStack{
stk: NewIndexStack(cap),
points: make(map[int]MyPoint),
index: 0,
}
}
func (ps *PointStack) Push(p MyPoint) {
ps.points[ps.index] = p
ps.stk.Push(ps.index)
ps.index++
}
func (ps *PointStack) Pop() MyPoint {
i := ps.stk.Pop()
p := ps.points[i]
delete(ps.points, i)
return p
}
func (ps PointStack) Size() int {
return ps.stk.Size()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment