about summary refs log tree commit diff stats
path: root/go/mermaid-graph.go
blob: d40bf9ed4938810d6e253d3cb4b8f9961d488362 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

type Graph struct {
	adjacencyList map[int][]int
}

func NewGraph() *Graph {
	return &Graph{adjacencyList: make(map[int][]int)}
}

func (g *Graph) addEdge(node1, node2 int) {
	g.adjacencyList[node1] = append(g.adjacencyList[node1], node2)
	g.adjacencyList[node2] = append(g.adjacencyList[node2], node1)
}

func generateConnectedGraph(n int) *Graph {
	rand.Seed(time.Now().UnixNano())
	graph := NewGraph()

	// Start with node 0
	for i := 1; i < n; i++ {
		// Connect the new node i to a random existing node
		existingNode := rand.Intn(i)
		graph.addEdge(i, existingNode)
	}

	return graph
}

func generateMermaid(graph *Graph) string {
	var sb strings.Builder

	sb.WriteString("graph TD;\n")

	visited := make(map[string]bool)

	for node, edges := range graph.adjacencyList {
		for _, edge := range edges {
			// Ensure each edge is only printed once
			if !visited[fmt.Sprintf("%d-%d", node, edge)] && !visited[fmt.Sprintf("%d-%d", edge, node)] {
				sb.WriteString(fmt.Sprintf("    %d --> %d;\n", node, edge))
				visited[fmt.Sprintf("%d-%d", node, edge)] = true
			}
		}
	}

	return sb.String()
}

func main() {
	graph := generateConnectedGraph(100)
	mermaid := generateMermaid(graph)

	fmt.Println(mermaid)
}