Open20

# Golangでグラフ理論やってみる

vertexは頂点
edgeは頂点のペアなので辺

https://play.golang.org/p/N9QbASf6DEB

``````graph[3][4] = 1
graph[4][3] = 1
``````

todo ペアを作る部分を関数化する

なんかイメージしやすいように駅のダイアグラム的なノリで地名とか適当に入れてみた。

https://play.golang.org/p/UreybFJ9w5p

サンプルグラフの イメージはこんな感じ

``````	_________5,6
|    |   |
1---2    |
| X |    |
3---4----|
|________|
``````
``````func (g *glink) createVertexesPair(p []place) {
placeSetter := placeSet{}
for i := range p {
for j := i; j < len(p); j++ {
if j != i {
placeSetter.vertex1 = p[i]
placeSetter.vertex2 = p[j]
g.placeSets = append(g.placeSets, placeSetter)
}
}
}
}

func (g *glink) createEdge(p1 []place, p2 []place) {
placeSetter := placeSet{}
for i := range p1 {
for j := range p2 {
placeSetter.vertex1 = p1[i]
placeSetter.vertex2 = p2[j]
g.placeSets = append(g.placeSets, placeSetter)

}
}
}
``````

``````package main

import (
"fmt"
graph "github.com/Iovesophy/graph-go"
)

func main() {
samplePlace := []graph.Node{
graph.Node{ID: 1, Element: "place-A"},
graph.Node{ID: 2, Element: "place-B"},
graph.Node{ID: 3, Element: "place-C"},
graph.Node{ID: 4, Element: "place-D"},
}
sampleStation := []graph.Node{
graph.Node{ID: 5, Element: "station-A"},
graph.Node{ID: 6, Element: "station-B"},
}
NodeData: samplePlace,
BaseData: sampleStation,
}

fmt.Println(g.CreateVertexesPair())
fmt.Println(g.CreateEdge())
}

``````

IDはint
Elementはstring型しか使えなかったところをinterface型に置き換え全ての型に対応できるようにした

https://play.golang.org/p/XDfxWXtNN_m