├── go.mod
├── go.sum
├── node_chain
├── node_chain.go
└── node_chain_test.go
├── linked_list
├── enumerator.go
├── linked_list.go
└── linked_list_test.go
├── .gitignore
├── avl_tree
├── avl_tree_test.go
└── avl_tree.go
├── graph
├── graph_test.go
└── graph.go
├── README.md
├── queue
├── queue.go
└── queue_test.go
├── dijkstra
├── priority_queue.go
├── dijkstra.go
└── dijkstra_test.go
├── stack
├── stack.go
└── stack_test.go
├── heap
├── heap.go
└── heap_test.go
├── sort
├── sort_test.go
└── sort.go
├── binary_tree
├── binary_tree.go
└── binary_tree_test.go
└── LICENSE
/go.mod:
--------------------------------------------------------------------------------
1 | module fun_with_algorithms_and_data_structures
2 |
3 | go 1.20
4 |
5 | require golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1
6 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw=
2 | golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
3 |
--------------------------------------------------------------------------------
/node_chain/node_chain.go:
--------------------------------------------------------------------------------
1 | package node_chain
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | type Node[T any] struct {
9 | Value T
10 | Next *Node[T]
11 | }
12 |
13 | func (n *Node[value]) String() string {
14 | var sb strings.Builder
15 | fmt.Fprintf(&sb, "%v", n.Value)
16 |
17 | curr := n
18 | for curr.Next != nil {
19 | curr = curr.Next
20 | fmt.Fprintf(&sb, " %v", curr.Value)
21 | }
22 |
23 | return sb.String()
24 | }
25 |
--------------------------------------------------------------------------------
/linked_list/enumerator.go:
--------------------------------------------------------------------------------
1 | package linked_list
2 |
3 | type Enumerator[T any] struct {
4 | Current *Node[T]
5 | List *LinkedList[T]
6 | }
7 |
8 | func (e *Enumerator[T]) getNext() *Node[T] {
9 | if e.Current == nil {
10 | e.Current = e.List.Head
11 | } else {
12 | temp := e.Current.Next
13 | e.Current = temp
14 | }
15 | return e.Current
16 | }
17 |
18 | func (l *LinkedList[T]) enumerator() Enumerator[T] {
19 | return Enumerator[T]{
20 | List: l,
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # If you prefer the allow list template instead of the deny list, see community template:
2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3 | #
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Dependency directories (remove the comment below to include it)
18 | # vendor/
19 |
20 | # Go workspace file
21 | go.work
22 |
--------------------------------------------------------------------------------
/avl_tree/avl_tree_test.go:
--------------------------------------------------------------------------------
1 | package avl_tree
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestRandomDataIsInOrder(t *testing.T) {
8 | tree := NewAVLTree[int]()
9 |
10 | tree.Add(98)
11 | tree.Add(22)
12 | tree.Add(14)
13 | tree.Add(72)
14 | tree.Add(44)
15 | tree.Add(25)
16 | tree.Add(63)
17 |
18 | want := []int{14, 22, 25, 44, 63, 72, 98} // ordered slice
19 | got := tree.InOrder()
20 |
21 | if len(got) != len(want) {
22 | t.Errorf("got slice of size %d, want size %d ", len(got), len(want))
23 | } else {
24 | for i, v := range got {
25 | if want[i] != got[i] {
26 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/graph/graph_test.go:
--------------------------------------------------------------------------------
1 | package graph
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestTraverseGraph(t *testing.T) {
8 |
9 | nodeA := NewNode("A")
10 | nodeB := NewNode("B")
11 | nodeC := NewNode("C")
12 | nodeD := NewNode("D")
13 | nodeE := NewNode("E")
14 | nodeF := NewNode("F")
15 | nodeG := NewNode("G")
16 |
17 | nodeA.AddEdge(&nodeB, 3)
18 | nodeA.AddEdge(&nodeC, 3)
19 |
20 | nodeB.AddEdge(&nodeC, 6)
21 | nodeB.AddEdge(&nodeD, 5)
22 |
23 | nodeC.AddEdge(&nodeD, 11)
24 | nodeC.AddEdge(&nodeE, 8)
25 |
26 | nodeD.AddEdge(&nodeE, 2)
27 | nodeD.AddEdge(&nodeF, 10)
28 | nodeD.AddEdge(&nodeG, 2)
29 |
30 | nodeE.AddEdge(&nodeG, 5)
31 | nodeF.AddEdge(&nodeG, 3)
32 |
33 | labels := BreadthFirst[string](&nodeA)
34 | numEdges := 12
35 |
36 | if len(labels) != numEdges {
37 | t.Errorf("want %d labels from %d edges, got %d", numEdges, numEdges, len(labels))
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Fun With Algorithms and Data Structures in Go
2 |
3 | _"Algorithms + Data Structures = Programs" - Niklaus Wirth_
4 |
5 | NB: This code isn't at all production ready. It's intended for educational purposes only.
6 |
7 | ## Data Structures
8 | * [Node Chain](node_chain/node_chain.go)
9 | * [Linked List](linked_list/linked_list.go)
10 | * [Stack](stack/stack.go)
11 | * [Queue](queue/queue.go)
12 | * [Binary Tree](binary_tree/binary_tree.go)
13 | * [AVL Tree](avl_tree/avl_tree.go)
14 | * [Heap](heap/heap.go)
15 | * [Graph](graph/graph.go)
16 |
17 | ## Algorithms
18 | * [Sorting](sort/sort.go)
19 | * [Bubble Sort](sort/sort.go#L5)
20 | * [Insertion Sort](sort/sort.go#L19)
21 | * [Selection Sort](sort/sort.go#L35)
22 | * [Merge Sort](sort/sort.go#L82)
23 | * [Quick Sort](sort/sort.go#L92)
24 | * [Dijkstra's shortest path](dijkstra/dijkstra.go)
25 |
26 | ## Run Tests
27 |
28 | ```
29 | go test -v ./...
30 | ```
31 |
--------------------------------------------------------------------------------
/node_chain/node_chain_test.go:
--------------------------------------------------------------------------------
1 | package node_chain
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | type nv int // so we can add a String() func
9 |
10 | func (n nv) String() string {
11 | return fmt.Sprintf("%d", n)
12 | }
13 |
14 | func TestNodeChain(t *testing.T) {
15 | tail := Node[nv]{Value: 3}
16 | body := Node[nv]{Value: 2, Next: &tail}
17 | head := Node[nv]{Value: 1, Next: &body}
18 |
19 | want := "1 2 3"
20 | got := head.String()
21 | if want != got {
22 | t.Errorf("got %s, want %s", got, want)
23 | }
24 | }
25 |
26 | func TestMove(t *testing.T) {
27 |
28 | tail := Node[nv]{Value: 4}
29 | second := Node[nv]{Value: 3, Next: &tail}
30 | first := Node[nv]{Value: 2, Next: &second}
31 | head := Node[nv]{Value: 1, Next: &first}
32 |
33 | first.Next = &tail
34 | second.Next = &first
35 | head.Next = &second
36 |
37 | want := "1 3 2 4"
38 | got := head.String()
39 | if want != got {
40 | t.Errorf("got %s, want %s", got, want)
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/queue/queue.go:
--------------------------------------------------------------------------------
1 | package queue
2 |
3 | import (
4 | "fmt"
5 | "fun_with_algorithms_and_data_structures/linked_list"
6 | "strings"
7 | )
8 |
9 | type Queue[T any] struct {
10 | linkedList linked_list.LinkedList[T]
11 | }
12 |
13 | func new[T any]() Queue[T] {
14 | st := Queue[T]{}
15 | st.linkedList = linked_list.LinkedList[T]{}
16 | return st
17 | }
18 |
19 | func (q *Queue[T]) Enqueue(o T) {
20 | node := linked_list.Node[T]{}
21 | node.Value = o
22 | q.linkedList.AddTail(&node)
23 | }
24 |
25 | func (q *Queue[T]) Dequeue() error {
26 | if q.linkedList.Count == 0 {
27 | return fmt.Errorf("error: cannot dequeue from an empty queue")
28 | }
29 | q.linkedList.RemoveHead()
30 |
31 | return nil
32 | }
33 |
34 | func (q *Queue[T]) Peek() (T, error) {
35 | var r T
36 | if q.linkedList.Count == 0 {
37 | return r, fmt.Errorf("error: cannot peek an empty queue")
38 | }
39 |
40 | r = q.linkedList.Head.Value
41 | return r, nil
42 | }
43 |
44 | func (q *Queue[T]) String() string {
45 | var sb strings.Builder
46 | fmt.Fprint(&sb, "START")
47 |
48 | node := q.linkedList.Head
49 | for node != nil {
50 | fmt.Fprintf(&sb, " %v", node.Value)
51 | node = node.Next
52 | }
53 |
54 | fmt.Fprint(&sb, " END")
55 | return sb.String()
56 | }
57 |
--------------------------------------------------------------------------------
/dijkstra/priority_queue.go:
--------------------------------------------------------------------------------
1 | package dijkstra
2 |
3 | import "sort"
4 |
5 | type PriorityQueue struct {
6 | keys []string
7 | nodes map[string]int
8 | }
9 |
10 | func NewQueue() *PriorityQueue {
11 | var q PriorityQueue
12 | q.nodes = make(map[string]int)
13 | return &q
14 | }
15 |
16 | func (q *PriorityQueue) Len() int {
17 | return len(q.keys)
18 | }
19 |
20 | func (q *PriorityQueue) Swap(i, j int) {
21 | q.keys[i], q.keys[j] = q.keys[j], q.keys[i]
22 | }
23 |
24 | func (q *PriorityQueue) Less(i, j int) bool {
25 | a := q.keys[i]
26 | b := q.keys[j]
27 |
28 | return q.nodes[a] < q.nodes[b]
29 | }
30 |
31 | func (q *PriorityQueue) Update(node Node) {
32 | if _, ok := q.nodes[node.Value]; !ok {
33 | q.keys = append(q.keys, node.Value)
34 | }
35 |
36 | q.nodes[node.Value] = node.Distance
37 |
38 | sort.Sort(q)
39 | }
40 |
41 | func (q *PriorityQueue) Next() Node {
42 | val, keys := q.keys[0], q.keys[1:]
43 | q.keys = keys
44 |
45 | dist := q.nodes[val]
46 | delete(q.nodes, val)
47 |
48 | return Node{val, dist}
49 | }
50 |
51 | func (q *PriorityQueue) Empty() bool {
52 | return len(q.keys) == 0
53 | }
54 |
55 | func (q *PriorityQueue) Peek(val string) (priority int, ok bool) {
56 | priority, ok = q.nodes[val]
57 | return
58 | }
59 |
--------------------------------------------------------------------------------
/stack/stack.go:
--------------------------------------------------------------------------------
1 | package stack
2 |
3 | import (
4 | "fmt"
5 | "fun_with_algorithms_and_data_structures/linked_list"
6 | "strings"
7 | )
8 |
9 | type Stack[T any] struct {
10 | linkedList linked_list.LinkedList[T]
11 | }
12 |
13 | func new[T any]() Stack[T] {
14 | st := Stack[T]{}
15 | st.linkedList = linked_list.LinkedList[T]{}
16 | return st
17 | }
18 |
19 | func (s *Stack[T]) Push(o T) {
20 | node := linked_list.Node[T]{}
21 | node.Value = o
22 | s.linkedList.AddHead(&node)
23 | }
24 |
25 | func (s *Stack[T]) Peek() (T, error) {
26 | var r T
27 | if s.linkedList.Count == 0 {
28 | return r, fmt.Errorf("error: cannot peek an empty stack")
29 | }
30 | return s.linkedList.Head.Value, nil
31 | }
32 |
33 | func (s *Stack[T]) Pop() (T, error) {
34 | var r T
35 | if s.linkedList.Count == 0 {
36 | return r, fmt.Errorf("error: cannot pop from empty stack")
37 | }
38 | r, err := s.Peek()
39 | if err != nil {
40 | return r, err
41 | }
42 | s.linkedList.RemoveHead()
43 |
44 | return r, nil
45 | }
46 |
47 | func (s *Stack[T]) String() string {
48 | var sb strings.Builder
49 | fmt.Fprint(&sb, "TOP")
50 |
51 | node := s.linkedList.Head
52 | for node != nil {
53 | fmt.Fprintf(&sb, "\n%v", node.Value)
54 | node = node.Next
55 | }
56 | return sb.String()
57 | }
58 |
--------------------------------------------------------------------------------
/dijkstra/dijkstra.go:
--------------------------------------------------------------------------------
1 | package dijkstra
2 |
3 | type Node struct {
4 | Value string
5 | Distance int
6 | }
7 |
8 | type Edge map[string]int
9 |
10 | type Graph map[string]Edge
11 |
12 | func (g Graph) ShortestPath(from, to string) ([]string, int) {
13 | var path []string
14 | var distance int
15 |
16 | visited := make(map[string]bool)
17 | prev := make(map[string]string)
18 |
19 | q := NewQueue()
20 |
21 | q.Update(Node{from, 0})
22 |
23 | for !q.Empty() {
24 | n := q.Next()
25 |
26 | if n.Value == to {
27 | distance = n.Distance
28 |
29 | nVal := n.Value
30 | for nVal != from {
31 | path = append(path, nVal)
32 | nVal = prev[nVal]
33 | }
34 |
35 | break
36 | }
37 |
38 | visited[n.Value] = true
39 |
40 | for nVal, nDist := range g[n.Value] {
41 | if visited[nVal] {
42 | continue
43 | }
44 |
45 | if _, ok := q.Peek(nVal); !ok {
46 | prev[nVal] = n.Value
47 | q.Update(Node{nVal, n.Distance + nDist})
48 | continue
49 | }
50 |
51 | routeLen, _ := q.Peek(nVal)
52 | nodeLen := n.Distance + nDist
53 |
54 | if nodeLen < routeLen {
55 | prev[nVal] = n.Value
56 | q.Update(Node{nVal, nodeLen})
57 | }
58 | }
59 | }
60 |
61 | path = append(path, from)
62 | flip(path)
63 |
64 | return path, distance
65 | }
66 |
67 | func flip(path []string) {
68 | for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
69 | path[i], path[j] = path[j], path[i]
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/queue/queue_test.go:
--------------------------------------------------------------------------------
1 | package queue
2 |
3 | import "testing"
4 |
5 | func TestEmptyQueue(t *testing.T) {
6 | queue := new[string]()
7 | got := queue.String()
8 | want := "START END"
9 |
10 | if got != want {
11 | t.Errorf("got %s, want %s", got, want)
12 | }
13 | }
14 |
15 | func TestEnqueue(t *testing.T) {
16 | queue := new[string]()
17 | queue.Enqueue("MIDDLE")
18 |
19 | got := queue.String()
20 | want := "START MIDDLE END"
21 |
22 | if got != want {
23 | t.Errorf("got %s, want %s", got, want)
24 | }
25 | }
26 |
27 | func TestDequeue(t *testing.T) {
28 | queue := new[string]()
29 | queue.Enqueue("ONE")
30 | queue.Enqueue("TWO")
31 | queue.Enqueue("THREE")
32 |
33 | queue.Dequeue()
34 |
35 | got := queue.String()
36 | want := "START TWO THREE END"
37 |
38 | if got != want {
39 | t.Errorf("got %s, want %s", got, want)
40 | }
41 | }
42 |
43 | func TestDequeueEmptyQueue(t *testing.T) {
44 | queue := new[string]()
45 |
46 | err := queue.Dequeue()
47 | if err == nil {
48 | t.Error("error: no error dequeuing from empty queue")
49 | }
50 | }
51 |
52 | func TestPeek(t *testing.T) {
53 | queue := new[string]()
54 | want := "ONE"
55 | queue.Enqueue(want)
56 |
57 | got, _ := queue.Peek()
58 | if got != want {
59 | t.Errorf("got %s, want %s", got, want)
60 | }
61 | }
62 |
63 | func TestPeekEmptyQueue(t *testing.T) {
64 | queue := new[string]()
65 |
66 | _, err := queue.Peek()
67 | if err == nil {
68 | t.Error("error: no error peeking empty queue")
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/graph/graph.go:
--------------------------------------------------------------------------------
1 | package graph
2 |
3 | // Node (AKA a Vertex) contains a slice of edges which is all
4 | // of its connections to other nodes.
5 | type Node[T comparable] struct {
6 | Value T
7 | Edges []*Edge[T]
8 | }
9 |
10 | func NewNode[T comparable](val T) Node[T] {
11 | return Node[T]{Value: val}
12 | }
13 |
14 | func (n *Node[T]) AddEdge(to *Node[T], weight int) {
15 | n.Edges = append(n.Edges, &Edge[T]{ToNode: to, Weight: weight})
16 | }
17 |
18 | // Edge represents a link between nodes. This is a directed graph
19 | // so an edge just has a node it is connected to.
20 | type Edge[T comparable] struct {
21 | ToNode *Node[T]
22 | Weight int
23 | visited bool
24 | }
25 |
26 | // unvisited returns all of the edges that haven't been traversed yet
27 | func unvisited[T comparable](edges []*Edge[T]) []*Node[T] {
28 | unv := []*Node[T]{}
29 | for _, edge := range edges {
30 | if !edge.visited {
31 | unv = append(unv, edge.ToNode)
32 | edge.visited = true
33 | }
34 | }
35 | return unv
36 | }
37 |
38 | // trvse recursively walks through the entire graph
39 | func bfs[T comparable](node *Node[T], vals *[]T) {
40 | if node != nil {
41 | *vals = append(*vals, node.Value)
42 | for _, n := range unvisited(node.Edges) {
43 | bfs(n, vals)
44 | }
45 | }
46 | }
47 |
48 | // BreadthFirst traverses through the directed graph visiting nodes
49 | // until it has traveled via all edges.
50 | func BreadthFirst[T comparable](start *Node[T]) []T {
51 | vals := []T{}
52 | bfs(start, &vals)
53 | return vals
54 | }
55 |
--------------------------------------------------------------------------------
/dijkstra/dijkstra_test.go:
--------------------------------------------------------------------------------
1 | package dijkstra
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestShortestPath(t *testing.T) {
8 |
9 | graph := Graph{
10 | "London": {"Birmingham": 202, "Bristol": 190, "Salford": 333},
11 | "Birmingham": {"London": 202, "Bristol": 142},
12 | "Bristol": {"Cardiff": 45, "London": 190, "Birmingham": 142},
13 | "Cardiff": {"Bristol": 45},
14 | "Salford": {"Glasgow": 340, "Birmingham": 151},
15 | "Glasgow": {"Salford": 340},
16 | }
17 |
18 | gotPath, _ := graph.ShortestPath("Cardiff", "Glasgow")
19 | wantPath := []string{"Cardiff", "Bristol", "London", "Salford", "Glasgow"}
20 |
21 | if len(gotPath) != len(wantPath) {
22 | t.Errorf("wanted path %v, got %v", wantPath, gotPath)
23 | }
24 |
25 | for i, v := range gotPath {
26 | if wantPath[i] != gotPath[i] {
27 | t.Errorf("value at %d: want %s, got %s ", i, wantPath[i], v)
28 | }
29 | }
30 | }
31 |
32 | func TestDistance(t *testing.T) {
33 |
34 | graph := Graph{
35 | "London": {"Birmingham": 202, "Bristol": 190, "Salford": 333},
36 | "Birmingham": {"London": 202, "Bristol": 142},
37 | "Bristol": {"Cardiff": 45, "London": 190, "Birmingham": 142},
38 | "Cardiff": {"Bristol": 45},
39 | "Salford": {"Glasgow": 340, "Birmingham": 151},
40 | "Glasgow": {"Salford": 340},
41 | }
42 |
43 | _, gotDistance := graph.ShortestPath("Cardiff", "Glasgow")
44 |
45 | wantDistance := 908
46 | if gotDistance != wantDistance {
47 | t.Errorf("wanted distance %d, got %d", wantDistance, gotDistance)
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/heap/heap.go:
--------------------------------------------------------------------------------
1 | package heap
2 |
3 | type Heap[T any] struct {
4 | Data []T
5 | }
6 |
7 | func NewHeap[T any]() *Heap[T] {
8 | return &Heap[T]{
9 | Data: make([]T, 0),
10 | }
11 | }
12 |
13 | func (h *Heap[T]) Insert(f func(T, T) bool, v T) {
14 | h.Data = append(h.Data, v)
15 | h.siftUp(f, (len(h.Data) - 1))
16 | }
17 |
18 | func (h *Heap[T]) Extract(f func(T, T) bool) (T, bool) {
19 | var val T
20 | if h.Size() == 0 {
21 | return val, false
22 | }
23 | val = h.Data[0]
24 | h.swap(0, h.Size()-1)
25 | h.Data = h.Data[:h.Size()-1]
26 | h.siftDown(f, 0)
27 |
28 | return val, true
29 | }
30 |
31 | func (h *Heap[T]) Size() int {
32 | return len(h.Data)
33 | }
34 |
35 | func (h *Heap[T]) siftUp(f func(T, T) bool, i int) {
36 |
37 | for f(h.Data[parentIndex(i)], h.Data[i]) {
38 | h.swap(i, parentIndex(i))
39 | i = parentIndex(i)
40 | }
41 | }
42 |
43 | func (h *Heap[T]) siftDown(f func(T, T) bool, i int) {
44 | l, r, largest := leftChildIndex(i), rightChildIndex(i), i
45 |
46 | if l < len(h.Data) && f(h.Data[i], h.Data[l]) {
47 | largest = l
48 | }
49 |
50 | if r < len(h.Data) && f(h.Data[largest], h.Data[r]) {
51 | largest = r
52 | }
53 |
54 | if largest != i {
55 | h.swap(i, largest)
56 | h.siftDown(f, largest)
57 | }
58 | }
59 |
60 | func (h *Heap[T]) swap(i, j int) {
61 | h.Data[i], h.Data[j] = h.Data[j], h.Data[i]
62 | }
63 |
64 | func leftChildIndex(i int) int {
65 | return 2*i + 1
66 | }
67 |
68 | func rightChildIndex(i int) int {
69 | return 2*i + 2
70 | }
71 |
72 | func parentIndex(i int) int {
73 | return (i - 1) / 2
74 | }
75 |
--------------------------------------------------------------------------------
/linked_list/linked_list.go:
--------------------------------------------------------------------------------
1 | package linked_list
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | )
7 |
8 | type Node[T any] struct {
9 | Value T
10 | Next *Node[T]
11 | }
12 |
13 | type LinkedList[T any] struct {
14 | Head *Node[T]
15 | Tail *Node[T]
16 | Count int
17 | }
18 |
19 | // AddHead adds a node to the head of the list.
20 | func (l *LinkedList[T]) AddHead(n *Node[T]) {
21 | temp := l.Head
22 | l.Head = n
23 | l.Head.Next = temp
24 | l.Count++
25 | if l.Count == 1 {
26 | l.Tail = l.Head
27 | }
28 | }
29 |
30 | // AddTail adds a node to the tail of the list.
31 | func (l *LinkedList[T]) AddTail(n *Node[T]) {
32 | if l.Count == 0 {
33 | l.Head = n
34 | l.Tail = n
35 | } else {
36 | l.Tail.Next = n
37 | }
38 |
39 | l.Tail = n
40 |
41 | l.Count++
42 | }
43 |
44 | // RemoveHead removes a node from the head of the list.
45 | func (l *LinkedList[T]) RemoveHead() {
46 | if l.Count != 0 {
47 | l.Head = l.Head.Next
48 | l.Count--
49 | if l.Count == 0 {
50 | l.Tail = nil
51 | }
52 | }
53 |
54 | }
55 |
56 | // RemoveTail removes a node from the tail of the list.
57 | // Loops through entire list so decreases in performance by O(n)
58 | func (l *LinkedList[T]) RemoveTail() {
59 | if l.Count != 0 {
60 | if l.Count == 1 {
61 | l.Head = nil
62 | l.Tail = nil
63 | } else {
64 | current := l.Head
65 | for current.Next != l.Tail {
66 | current = current.Next
67 | }
68 | current.Next = nil
69 | l.Tail = current
70 | }
71 | l.Count--
72 | }
73 |
74 | }
75 |
76 | func (l *LinkedList[T]) String() string {
77 | var sb strings.Builder
78 | fmt.Fprint(&sb, "HEAD")
79 |
80 | node := l.Head
81 | for node != nil {
82 | fmt.Fprintf(&sb, "->%v", node.Value)
83 | node = node.Next
84 | }
85 |
86 | fmt.Fprint(&sb, "->TAIL")
87 | return sb.String()
88 | }
89 |
--------------------------------------------------------------------------------
/stack/stack_test.go:
--------------------------------------------------------------------------------
1 | package stack
2 |
3 | import "testing"
4 |
5 | func TestEmptyStack(t *testing.T) {
6 | stack := new[string]()
7 | got := stack.String()
8 | want := "TOP"
9 |
10 | if got != want {
11 | t.Errorf("got %s, want %s", got, want)
12 | }
13 | }
14 |
15 | func TestPush(t *testing.T) {
16 | stack := new[string]()
17 | stack.Push("ONE")
18 | stack.Push("TWO")
19 |
20 | want := "TOP\nTWO\nONE"
21 | got := stack.String()
22 |
23 | if got != want {
24 | t.Errorf("got %s, want %s", got, want)
25 | }
26 |
27 | }
28 |
29 | func TestPeek(t *testing.T) {
30 | stack := new[string]()
31 | stack.Push("ONE")
32 | stack.Push("TWO")
33 |
34 | itemGot, _ := stack.Peek()
35 | itemWant := "TWO"
36 |
37 | if itemGot != itemWant {
38 | t.Errorf("got item %s, want item %s", itemGot, itemWant)
39 | }
40 |
41 | wantStack := "TOP\nTWO\nONE"
42 | gotStack := stack.String()
43 |
44 | if gotStack != wantStack {
45 | t.Errorf("got %s, want %s", gotStack, wantStack)
46 | }
47 | }
48 |
49 | func TestPeekFromEmpty(t *testing.T) {
50 | stack := new[string]()
51 |
52 | _, err := stack.Peek()
53 | if err == nil {
54 | t.Errorf("pop from empty stack should be error")
55 | }
56 | }
57 |
58 | func TestPop(t *testing.T) {
59 | stack := new[string]()
60 | stack.Push("ONE")
61 | stack.Push("TWO")
62 |
63 | itemGot, _ := stack.Pop()
64 | itemWant := "TWO"
65 |
66 | if itemGot != itemWant {
67 | t.Errorf("got item %s, want item %s", itemGot, itemWant)
68 | }
69 |
70 | wantStack := "TOP\nONE"
71 | gotStack := stack.String()
72 |
73 | if gotStack != wantStack {
74 | t.Errorf("got %s, want %s", gotStack, wantStack)
75 | }
76 | }
77 |
78 | func TestPopFromEmpty(t *testing.T) {
79 | stack := new[string]()
80 |
81 | _, err := stack.Pop()
82 | if err == nil {
83 | t.Errorf("pop from empty stack should be error")
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/sort/sort_test.go:
--------------------------------------------------------------------------------
1 | package sort
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestBubbleSort(t *testing.T) {
8 |
9 | items := []int{17, 3, 15, 14, 18, 4, 8, 53, 2, 16, 10, 5, 20, 100, 1, 12, 21, 13, 9, 19, 7, 11, 6}
10 | BubbleSort[int](items)
11 | lower := 0
12 |
13 | for _, item := range items {
14 | if item < lower {
15 | t.Errorf("item %d found before %d", item, lower)
16 | }
17 | lower = item
18 | }
19 | }
20 |
21 | func TestInsertionSort(t *testing.T) {
22 | items := []int{17, 3, 15, 14, 18, 4, 8, 53, 2, 16, 10, 5, 20, 100, 1, 12, 21, 13, 9, 19, 7, 11, 6}
23 | InsertionSort[int](items)
24 | lower := 0
25 |
26 | for _, item := range items {
27 | if item < lower {
28 | t.Errorf("item %d found before %d", item, lower)
29 | }
30 | lower = item
31 | }
32 | }
33 |
34 | func TestSelectionSort(t *testing.T) {
35 | items := []int{17, 3, 15, 14, 18, 4, 8, 53, 2, 16, 10, 5, 20, 100, 1, 12, 21, 13, 9, 19, 7, 11, 6}
36 | SelectionSort[int](items)
37 | lower := 0
38 |
39 | for _, item := range items {
40 | if item < lower {
41 | t.Errorf("item %d found before %d", item, lower)
42 | }
43 | lower = item
44 | }
45 | }
46 |
47 | func TestMergeSort(t *testing.T) {
48 | items := []int{17, 3, 15, 14, 18, 4, 8, 53, 2, 16, 10, 5, 20, 100, 1, 12, 21, 13, 9, 19, 7, 11, 6}
49 | got := MergeSort[int](items)
50 | lower := 0
51 |
52 | for _, item := range got {
53 | if item < lower {
54 | t.Errorf("item %d found before %d", item, lower)
55 | }
56 | lower = item
57 | }
58 | }
59 |
60 | func TestQuickSort(t *testing.T) {
61 | items := []int{17, 3, 15, 14, 18, 4, 8, 53, 2, 16, 10, 5, 20, 100, 1, 12, 21, 13, 9, 19, 7, 11, 6}
62 | QuickSort[int](items)
63 | lower := 0
64 |
65 | for _, item := range items {
66 | if item < lower {
67 | t.Errorf("item %d found before %d", item, lower)
68 | }
69 | lower = item
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/sort/sort.go:
--------------------------------------------------------------------------------
1 | package sort
2 |
3 | import "golang.org/x/exp/constraints"
4 |
5 | func BubbleSort[T constraints.Ordered](items []T) {
6 | if len(items) < 2 {
7 | return
8 | }
9 |
10 | for i := len(items); i > 0; i-- {
11 | for j := 1; j < i; j++ {
12 | if items[j-1] > items[j] {
13 | items[j-1], items[j] = items[j], items[j-1]
14 | }
15 | }
16 | }
17 | }
18 |
19 | func InsertionSort[T constraints.Ordered](items []T) {
20 | if len(items) < 2 {
21 | return
22 | }
23 |
24 | for i := 1; i < len(items); i++ {
25 | j := i
26 | for j > 0 {
27 | if items[j-1] > items[j] {
28 | items[j-1], items[j] = items[j], items[j-1]
29 | }
30 | j--
31 | }
32 | }
33 | }
34 |
35 | func SelectionSort[T constraints.Ordered](items []T) {
36 | if len(items) < 2 {
37 | return
38 | }
39 |
40 | var m int
41 |
42 | for i := 0; i < len(items)-1; i++ {
43 | m = i
44 |
45 | for j := i + 1; j < len(items); j++ {
46 | if items[j] < items[m] {
47 | m = j
48 | }
49 | }
50 | items[m], items[i] = items[i], items[m]
51 | }
52 |
53 | }
54 |
55 | func merge[T constraints.Ordered](left []T, right []T) []T {
56 |
57 | var i, j int
58 | size := len(left) + len(right)
59 | m := make([]T, size)
60 |
61 | for k := 0; k < size; k++ {
62 | if i > len(left)-1 && j <= len(right)-1 {
63 | m[k] = right[j]
64 | j++
65 |
66 | } else if j > len(right)-1 && i <= len(left)-1 {
67 | m[k] = left[i]
68 | i++
69 |
70 | } else if left[i] < right[j] {
71 | m[k] = left[i]
72 |
73 | } else {
74 | m[k] = right[j]
75 | j++
76 | }
77 | }
78 |
79 | return m
80 | }
81 |
82 | func MergeSort[T constraints.Ordered](items []T) []T {
83 | if len(items) < 2 {
84 | return items
85 | }
86 |
87 | mid := (len(items)) / 2
88 |
89 | return merge(MergeSort(items[:mid]), MergeSort(items[mid:]))
90 | }
91 |
92 | func QuickSort[T constraints.Ordered](items []T) {
93 | quickSort(items, 0, len(items)-1)
94 | }
95 |
96 | func quickSort[T constraints.Ordered](items []T, start int, end int) {
97 | if start < end {
98 | pi := partition(items, start, end)
99 | quickSort(items, start, pi-1)
100 | quickSort(items, pi+1, end)
101 | }
102 | }
103 |
104 | func partition[T constraints.Ordered](items []T, start, end int) int {
105 | pivot := items[end]
106 | i := start - 1
107 |
108 | for j := start; j < end; j++ {
109 | if items[j] <= pivot {
110 | i++
111 | items[i], items[j] = items[j], items[i]
112 | }
113 | }
114 |
115 | items[i+1], items[end] = items[end], items[i+1]
116 |
117 | return i + 1
118 | }
119 |
--------------------------------------------------------------------------------
/heap/heap_test.go:
--------------------------------------------------------------------------------
1 | package heap
2 |
3 | import (
4 | "testing"
5 |
6 | "golang.org/x/exp/constraints"
7 | )
8 |
9 | func max[T constraints.Ordered](a, b T) bool {
10 | return a < b
11 | }
12 |
13 | func min[T constraints.Ordered](a, b T) bool {
14 | return a > b
15 | }
16 |
17 | func TestMaxHeapExtract(t *testing.T) {
18 |
19 | heap := NewHeap[int]()
20 | want := 99
21 |
22 | heap.Insert(max[int], 72)
23 | heap.Insert(max[int], 22)
24 | heap.Insert(max[int], want)
25 |
26 | got, ok := heap.Extract(max[int])
27 |
28 | if !ok {
29 | t.Errorf("error extracting item from heap")
30 | } else {
31 | if got != want {
32 | t.Errorf("extract: want %d, got %d", want, got)
33 | }
34 | }
35 | }
36 |
37 | func TestMinHeapExtract(t *testing.T) {
38 |
39 | heap := NewHeap[int]()
40 | want := 22
41 |
42 | heap.Insert(min[int], 72)
43 | heap.Insert(min[int], 99)
44 | heap.Insert(min[int], want)
45 |
46 | got, ok := heap.Extract(max[int])
47 |
48 | if !ok {
49 | t.Errorf("error extracting item from heap")
50 | } else {
51 | if got != want {
52 | t.Errorf("extract: want %d, got %d", want, got)
53 | }
54 | }
55 | }
56 |
57 | func TestMaxHeapPriority(t *testing.T) {
58 |
59 | heap := NewHeap[int]()
60 | items := []int{72, 22, 12, 7, 89, 44}
61 |
62 | for _, n := range items {
63 | heap.Insert(max[int], n)
64 | }
65 |
66 | got := []int{}
67 | for range items { // use size of items
68 | item, ok := heap.Extract(max[int])
69 | if ok {
70 | got = append(got, item)
71 | }
72 | }
73 |
74 | if got == nil {
75 | t.Error("returned nil values")
76 | }
77 |
78 | // highest priority is the highest number for this example
79 | want := []int{89, 72, 44, 22, 12, 7}
80 | for i, v := range got {
81 | if want[i] != got[i] {
82 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
83 | }
84 | }
85 | }
86 |
87 | func TestMinHeapPriority(t *testing.T) {
88 |
89 | heap := NewHeap[int]()
90 | items := []int{72, 22, 12, 7, 89, 44}
91 |
92 | for _, n := range items {
93 | heap.Insert(min[int], n)
94 | }
95 |
96 | got := []int{}
97 | for range items { // use size of items
98 | item, ok := heap.Extract(min[int])
99 | if ok {
100 | got = append(got, item)
101 | }
102 | }
103 |
104 | if got == nil {
105 | t.Error("returned nil values")
106 | }
107 |
108 | // lowest priority is the highest number for this example
109 | want := []int{7, 12, 22, 44, 72, 89}
110 | for i, v := range got {
111 | if want[i] != got[i] {
112 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/linked_list/linked_list_test.go:
--------------------------------------------------------------------------------
1 | package linked_list
2 |
3 | import "testing"
4 |
5 | func TestEmptyLinkedList(t *testing.T) {
6 |
7 | var ll LinkedList[string]
8 |
9 | want := "HEAD->TAIL"
10 | got := ll.String()
11 |
12 | if got != want {
13 | t.Errorf("got %s, want %s", got, want)
14 | }
15 |
16 | }
17 |
18 | func TestAddToHead(t *testing.T) {
19 |
20 | var ll LinkedList[string]
21 |
22 | ll.AddHead(&Node[string]{Value: "ONE"})
23 |
24 | want := "HEAD->ONE->TAIL"
25 | got := ll.String()
26 |
27 | if got != want {
28 | t.Errorf("got %s, want %s", got, want)
29 | }
30 |
31 | }
32 |
33 | func TestAddMultipleToHead(t *testing.T) {
34 |
35 | var ll LinkedList[string]
36 |
37 | ll.AddHead(&Node[string]{Value: "THREE"})
38 | ll.AddHead(&Node[string]{Value: "TWO"})
39 | ll.AddHead(&Node[string]{Value: "ONE"})
40 |
41 | want := "HEAD->ONE->TWO->THREE->TAIL"
42 | got := ll.String()
43 |
44 | if got != want {
45 | t.Errorf("got %s, want %s", got, want)
46 | }
47 |
48 | }
49 |
50 | func TestAddToTail(t *testing.T) {
51 | var ll LinkedList[string]
52 |
53 | ll.AddTail(&Node[string]{Value: "ONE"})
54 |
55 | want := "HEAD->ONE->TAIL"
56 | got := ll.String()
57 |
58 | if got != want {
59 | t.Errorf("got %s, want %s", got, want)
60 | }
61 | }
62 |
63 | func TestMultipleAddToTail(t *testing.T) {
64 | var ll LinkedList[string]
65 |
66 | ll.AddTail(&Node[string]{Value: "ONE"})
67 | ll.AddTail(&Node[string]{Value: "TWO"})
68 | ll.AddTail(&Node[string]{Value: "THREE"})
69 |
70 | want := "HEAD->ONE->TWO->THREE->TAIL"
71 | got := ll.String()
72 |
73 | if got != want {
74 | t.Errorf("got %s, want %s", got, want)
75 | }
76 | }
77 |
78 | func TestRemoveHead(t *testing.T) {
79 | var ll LinkedList[string]
80 |
81 | ll.AddTail(&Node[string]{Value: "ONE"})
82 | ll.AddTail(&Node[string]{Value: "TWO"})
83 | ll.AddTail(&Node[string]{Value: "THREE"})
84 |
85 | ll.RemoveHead()
86 |
87 | want := "HEAD->TWO->THREE->TAIL"
88 | got := ll.String()
89 |
90 | if got != want {
91 | t.Errorf("got %s, want %s", got, want)
92 | }
93 | }
94 |
95 | func TestRemoveTail(t *testing.T) {
96 | var ll LinkedList[string]
97 |
98 | ll.AddTail(&Node[string]{Value: "ONE"})
99 | ll.AddTail(&Node[string]{Value: "TWO"})
100 | ll.AddTail(&Node[string]{Value: "THREE"})
101 |
102 | ll.RemoveTail()
103 |
104 | want := "HEAD->ONE->TWO->TAIL"
105 | got := ll.String()
106 |
107 | if got != want {
108 | t.Errorf("got %s, want %s", got, want)
109 | }
110 | }
111 |
112 | func TestEnumerate(t *testing.T) {
113 | var ll LinkedList[string]
114 |
115 | ll.AddTail(&Node[string]{Value: "1"})
116 | ll.AddTail(&Node[string]{Value: "2"})
117 | ll.AddTail(&Node[string]{Value: "3"})
118 |
119 | got := []string{}
120 |
121 | enum := ll.enumerator()
122 |
123 | node := enum.getNext()
124 | for node != nil {
125 | got = append(got, node.Value)
126 | node = enum.getNext()
127 | }
128 |
129 | if got[0] != "1" || got[1] != "2" || got[2] != "3" {
130 | t.Errorf("got [%s, %s, %s], want [1, 2, 3]", got[0], got[1], got[2])
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/avl_tree/avl_tree.go:
--------------------------------------------------------------------------------
1 | package avl_tree
2 |
3 | import (
4 | "golang.org/x/exp/constraints"
5 | )
6 |
7 | type Node[T constraints.Ordered] struct {
8 | leftChild *Node[T]
9 | rightChild *Node[T]
10 | Data T
11 | height int
12 | }
13 |
14 | func NewNode[T constraints.Ordered](data T) *Node[T] {
15 | return &Node[T]{
16 | height: 1,
17 | Data: data,
18 | }
19 | }
20 |
21 | // AVLTree is an Adelson-Velsky and Landis self-balancing binary search tree.
22 | type AVLTree[T constraints.Ordered] struct {
23 | Root *Node[T]
24 | }
25 |
26 | func NewAVLTree[T constraints.Ordered]() AVLTree[T] {
27 | return AVLTree[T]{}
28 | }
29 |
30 | func max(i, j int) int {
31 | if i > j {
32 | return i
33 | }
34 | return j
35 | }
36 |
37 | func height[T constraints.Ordered](node *Node[T]) int {
38 | if node == nil {
39 | return 0
40 | }
41 |
42 | return node.height
43 | }
44 |
45 | // balanceFactor shows the difference between the left and right
46 | // subtrees of Node n. A difference of more than one would mean
47 | // the balance() function is used to balance the tree
48 | func (n *Node[T]) balanceFactor() int {
49 | if n == nil {
50 | return 0
51 | }
52 |
53 | return height(n.leftChild) - height(n.rightChild)
54 | }
55 |
56 | func rotateRight[T constraints.Ordered](node *Node[T]) *Node[T] {
57 | x := node.leftChild
58 | tmp := x.rightChild
59 |
60 | x.rightChild = node
61 | node.leftChild = tmp
62 |
63 | node.height = max(
64 | height(node.leftChild),
65 | height(node.rightChild),
66 | ) + 1
67 | x.height = max(
68 | height(x.leftChild),
69 | height(x.rightChild),
70 | ) + 1
71 | return x
72 | }
73 |
74 | func rotateLeft[T constraints.Ordered](node *Node[T]) *Node[T] {
75 | y := node.rightChild
76 | tmp := y.leftChild
77 |
78 | y.leftChild = node
79 | node.rightChild = tmp
80 |
81 | node.height = max(
82 | height(node.leftChild),
83 | height(node.rightChild),
84 | ) + 1
85 |
86 | y.height = max(
87 | height(y.leftChild),
88 | height(y.rightChild),
89 | ) + 1
90 |
91 | return y
92 | }
93 |
94 | func insert[T constraints.Ordered](node *Node[T], data T) *Node[T] {
95 | if node == nil {
96 | node = NewNode[T](data)
97 | return node
98 | }
99 |
100 | if data < node.Data {
101 | node.leftChild = insert(node.leftChild, data)
102 | } else if data > node.Data {
103 | node.rightChild = insert(node.rightChild, data)
104 | } else {
105 | return node
106 | }
107 |
108 | node.height = 1 + max(height(node.leftChild), height(node.rightChild))
109 |
110 | bf := node.balanceFactor()
111 |
112 | if bf > 1 && data < node.leftChild.Data {
113 | return rotateRight(node)
114 | }
115 |
116 | if bf < -1 && data > node.rightChild.Data {
117 | return rotateLeft(node)
118 | }
119 |
120 | if bf > 1 && data > node.leftChild.Data {
121 | node.leftChild = rotateLeft(node.leftChild)
122 | return rotateRight(node)
123 | }
124 |
125 | if bf < -1 && data < node.rightChild.Data {
126 | node.rightChild = rotateRight(node.rightChild)
127 | return rotateLeft(node)
128 | }
129 |
130 | return node
131 | }
132 |
133 | // Add an item to the AVL Tree
134 | func (t *AVLTree[T]) Add(data T) {
135 | t.Root = insert(t.Root, data)
136 | }
137 |
138 | func traverseInOrder[T constraints.Ordered](node *Node[T], data *[]T) {
139 | if node != nil {
140 | traverseInOrder(node.leftChild, data)
141 | *data = append(*data, node.Data)
142 | traverseInOrder(node.rightChild, data)
143 | }
144 | }
145 |
146 | // InOrder tree traversal from Root
147 | func (t *AVLTree[T]) InOrder() []T {
148 | data := []T{}
149 | traverseInOrder(t.Root, &data)
150 | return data
151 | }
152 |
--------------------------------------------------------------------------------
/binary_tree/binary_tree.go:
--------------------------------------------------------------------------------
1 | package binary_tree
2 |
3 | import (
4 | "fmt"
5 |
6 | "golang.org/x/exp/constraints"
7 | )
8 |
9 | type Node[T constraints.Ordered] struct {
10 | Value T
11 | Left *Node[T]
12 | Right *Node[T]
13 | }
14 |
15 | func (n *Node[T]) GreaterThan(node *Node[T]) bool {
16 | return n.Value > node.Value
17 | }
18 |
19 | func (n *Node[T]) LessThan(node *Node[T]) bool {
20 | return n.Value < node.Value
21 | }
22 |
23 | type BinaryTree[T constraints.Ordered] struct {
24 | Root *Node[T]
25 | Counter int
26 | }
27 |
28 | func new[T constraints.Ordered]() BinaryTree[T] {
29 | return BinaryTree[T]{}
30 | }
31 |
32 | // addTo inserts the item at the correct position given it's
33 | // either less than or greater than its parent.
34 | func (bt *BinaryTree[T]) addTo(node *Node[T], val T) {
35 | nd := Node[T]{
36 | Value: val,
37 | }
38 |
39 | if nd.LessThan(node) {
40 | if node.Left == nil {
41 | node.Left = &nd
42 | } else {
43 | bt.addTo(node.Left, val)
44 | }
45 | } else {
46 | if node.Right == nil {
47 | node.Right = &nd
48 | } else {
49 | bt.addTo(node.Right, val)
50 | }
51 | }
52 |
53 | }
54 |
55 | // Add an item to the binary tree.
56 | func (bt *BinaryTree[T]) Add(o T) {
57 | if bt.Root == nil {
58 | bt.Root = &Node[T]{
59 | Value: o,
60 | }
61 | } else {
62 | bt.addTo(bt.Root, o)
63 | }
64 | bt.Counter++
65 | }
66 |
67 | func (bt *BinaryTree[T]) Contains(val T) bool {
68 | curr, _ := bt.findFromParent(bt.Root, val)
69 | return curr != nil
70 | }
71 |
72 | func (bt *BinaryTree[T]) Remove(val T) error {
73 | node, parent := bt.findFromParent(bt.Root, val)
74 |
75 | if node == nil {
76 | return fmt.Errorf("%v does not exist in tree", val)
77 | }
78 |
79 | // Case 1: Node has no right child so node's left replaces node
80 | if node.Right == nil {
81 | if parent == nil {
82 | bt.Root = node.Left
83 | } else {
84 | if parent.GreaterThan(node) {
85 | parent.Left = node.Left
86 | } else if parent.LessThan(node) {
87 | parent.Right = node.Left
88 | }
89 | }
90 |
91 | // Case 2: Node's right child has no left child so node's right child replaces node
92 | } else if node.Right.Left == nil {
93 | node.Right.Left = node.Left
94 | if parent == nil {
95 | bt.Root = node.Right
96 | } else {
97 | if parent.GreaterThan(node) {
98 | parent.Left = node.Right
99 | } else if parent.LessThan(node) {
100 | parent.Right = node.Right
101 | }
102 | }
103 |
104 | // Case 3 Node's right child has a left child so node's right child's left most child replaces node
105 | } else {
106 | leftMost := node.Right.Left
107 | leftMostParent := node.Right
108 |
109 | for leftMost.Left != nil {
110 | leftMostParent = leftMost
111 | leftMost = leftMost.Left
112 | }
113 |
114 | leftMostParent.Left = leftMost.Right
115 |
116 | leftMost.Left = node.Left
117 | leftMost.Right = node.Right
118 |
119 | if parent == nil {
120 | bt.Root = leftMost
121 | } else {
122 | if parent.GreaterThan(node) {
123 | parent.Left = leftMost
124 | } else if parent.LessThan(node) {
125 | parent.Right = leftMost
126 | }
127 | }
128 | }
129 |
130 | bt.Counter--
131 |
132 | return nil
133 | }
134 |
135 | func (bt *BinaryTree[T]) findFromParent(node *Node[T], val T) (*Node[T], *Node[T]) {
136 | var parent *Node[T]
137 | find := Node[T]{Value: val}
138 | curr := bt.Root
139 |
140 | for curr != nil {
141 | if find.LessThan(curr) {
142 | parent = curr
143 | curr = curr.Left
144 | } else if find.GreaterThan(curr) {
145 | parent = curr
146 | curr = curr.Right
147 | } else {
148 | break
149 | }
150 | }
151 |
152 | return curr, parent
153 | }
154 |
155 | func (bt *BinaryTree[T]) postOrderTraversal(node *Node[T], vals *[]T) {
156 | var zero *Node[T]
157 |
158 | if node != zero {
159 | bt.postOrderTraversal(node.Left, vals)
160 | bt.postOrderTraversal(node.Right, vals)
161 | *vals = append(*vals, node.Value)
162 | }
163 | }
164 |
165 | // ValuesPostOrder returns the values from the tree after performing an
166 | // postorder traversal:
167 | // 1. Traverse the left subtree
168 | // 2. Traverse the right subtree
169 | // 3. Obtain the value
170 | func (bt *BinaryTree[T]) ValuesPostOrder(node *Node[T]) []T {
171 | values := []T{}
172 | bt.postOrderTraversal(node, &values)
173 | return values
174 | }
175 |
176 | func (bt *BinaryTree[T]) preOrderTraversal(node *Node[T], vals *[]T) {
177 | var zero *Node[T]
178 |
179 | if node != zero {
180 | *vals = append(*vals, node.Value)
181 | bt.preOrderTraversal(node.Left, vals)
182 | bt.preOrderTraversal(node.Right, vals)
183 | }
184 | }
185 |
186 | // ValuesPreOrder returns the values from the tree after performing an
187 | // preorder traversal:
188 | // 1. Obtain the value
189 | // 2. Traverse the left subtree
190 | // 3. Traverse the right subtree
191 | func (bt *BinaryTree[T]) ValuesPreOrder(node *Node[T]) []T {
192 | values := []T{}
193 | bt.preOrderTraversal(node, &values)
194 | return values
195 | }
196 |
197 | func (bt *BinaryTree[T]) inOrderTraversal(node *Node[T], vals *[]T) {
198 | // var zero *Node[T]
199 |
200 | if node != nil {
201 | bt.inOrderTraversal(node.Left, vals)
202 | *vals = append(*vals, node.Value)
203 | bt.inOrderTraversal(node.Right, vals)
204 | }
205 | }
206 |
207 | // ValuesInOrder returns the values from the tree after performing an
208 | // inorder traversal:
209 | // 1. Traverse the left subtree
210 | // 2. Obtain the value
211 | // 3. Traverse the right subtree
212 | func (bt *BinaryTree[T]) ValuesInOrder(node *Node[T]) []T {
213 | values := []T{}
214 | bt.inOrderTraversal(node, &values)
215 | return values
216 | }
217 |
--------------------------------------------------------------------------------
/binary_tree/binary_tree_test.go:
--------------------------------------------------------------------------------
1 | package binary_tree
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestContains(t *testing.T) {
8 | tree := new[int]()
9 |
10 | tree.Add(1)
11 | tree.Add(2)
12 | tree.Add(3)
13 |
14 | want := 3
15 |
16 | if !tree.Contains(want) {
17 | t.Errorf("%d not found in tree", want)
18 | }
19 | }
20 |
21 | func TestRemoveLeftReplacesNodeParentNil(t *testing.T) {
22 | tree := new[int]()
23 |
24 | tree.Add(1)
25 | tree.Add(2)
26 | tree.Add(3)
27 |
28 | want := 1
29 |
30 | if !tree.Contains(want) {
31 | t.Errorf("%d not found in tree", want)
32 | }
33 |
34 | tree.Remove(want)
35 |
36 | if tree.Contains(want) {
37 | t.Errorf("%d not removed from tree", want)
38 | }
39 | }
40 |
41 | func TestRemoveLeftReplacesNode(t *testing.T) {
42 | tree := new[int]()
43 |
44 | tree.Add(1)
45 | tree.Add(2)
46 | tree.Add(3)
47 |
48 | want := 2
49 |
50 | if !tree.Contains(want) {
51 | t.Errorf("%d not found in tree", want)
52 | }
53 |
54 | tree.Remove(want)
55 |
56 | if tree.Contains(want) {
57 | t.Errorf("%d not removed from tree", want)
58 | }
59 | }
60 |
61 | func TestRemoveRightChildReplace(t *testing.T) {
62 | tree := new[int]()
63 |
64 | tree.Add(3)
65 | tree.Add(2)
66 | tree.Add(1)
67 |
68 | want := 2
69 |
70 | if !tree.Contains(want) {
71 | t.Errorf("%d not found in tree", want)
72 | }
73 |
74 | tree.Remove(want)
75 |
76 | if tree.Contains(want) {
77 | t.Errorf("%d not removed from tree", want)
78 | }
79 | }
80 |
81 | func TestRemoveRightChildLeftmostChildReplace(t *testing.T) {
82 | tree := new[int]()
83 |
84 | tree.Add(3)
85 | tree.Add(6)
86 | tree.Add(8)
87 | tree.Add(7)
88 | tree.Add(9)
89 |
90 | want := 6
91 |
92 | if !tree.Contains(want) {
93 | t.Errorf("%d not found in tree", want)
94 | }
95 |
96 | tree.Remove(want)
97 |
98 | if tree.Contains(want) {
99 | t.Errorf("%d not removed from tree", want)
100 | }
101 | }
102 |
103 | func TestUnbalancedValuesPostOrder(t *testing.T) {
104 | tree := new[int]()
105 |
106 | want := []int{9, 8, 7, 6, 5, 4, 3, 2, 1}
107 |
108 | tree.Add(1)
109 | tree.Add(2)
110 | tree.Add(3)
111 | tree.Add(4)
112 | tree.Add(5)
113 | tree.Add(6)
114 | tree.Add(7)
115 | tree.Add(8)
116 | tree.Add(9)
117 |
118 | got := tree.ValuesPostOrder(tree.Root)
119 |
120 | if got == nil {
121 | t.Error("returned nil values")
122 | }
123 |
124 | for i, v := range got {
125 | if want[i] != got[i] {
126 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
127 | }
128 | }
129 | }
130 |
131 | func TestBalancedValuesPostOrder(t *testing.T) {
132 | tree := new[int]()
133 |
134 | want := []int{1, 4, 7, 6, 3, 13, 14, 10, 8}
135 |
136 | tree.Add(8)
137 | tree.Add(3)
138 | tree.Add(10)
139 | tree.Add(1)
140 | tree.Add(6)
141 | tree.Add(14)
142 | tree.Add(4)
143 | tree.Add(7)
144 | tree.Add(13)
145 |
146 | got := tree.ValuesPostOrder(tree.Root)
147 |
148 | if got == nil {
149 | t.Error("returned nil values")
150 | }
151 |
152 | for i, v := range got {
153 | if want[i] != got[i] {
154 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
155 | }
156 | }
157 | }
158 |
159 | func TestUnbalancedValuesPreOrder(t *testing.T) {
160 | tree := new[int]()
161 |
162 | want := []int{1, 9, 8, 7, 6, 5, 4, 3, 2}
163 |
164 | tree.Add(1)
165 | tree.Add(2)
166 | tree.Add(3)
167 | tree.Add(4)
168 | tree.Add(5)
169 | tree.Add(6)
170 | tree.Add(7)
171 | tree.Add(8)
172 | tree.Add(9)
173 |
174 | got := tree.ValuesPreOrder(tree.Root)
175 |
176 | if got == nil {
177 | t.Error("returned nil values")
178 | }
179 |
180 | for i, v := range got {
181 | if want[i] != got[i] {
182 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
183 | }
184 | }
185 | }
186 |
187 | func TestBalancedValuesPreOrder(t *testing.T) {
188 | tree := new[int]()
189 |
190 | want := []int{8, 1, 4, 7, 6, 3, 13, 14, 10}
191 |
192 | tree.Add(8)
193 | tree.Add(3)
194 | tree.Add(10)
195 | tree.Add(1)
196 | tree.Add(6)
197 | tree.Add(14)
198 | tree.Add(4)
199 | tree.Add(7)
200 | tree.Add(13)
201 |
202 | got := tree.ValuesPreOrder(tree.Root)
203 |
204 | if got == nil {
205 | t.Error("returned nil values")
206 | }
207 |
208 | for i, v := range got {
209 | if want[i] != got[i] {
210 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
211 | }
212 | }
213 | }
214 |
215 | func TestUnbalancedValuesInOrder(t *testing.T) {
216 | tree := new[int]()
217 |
218 | want := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
219 |
220 | tree.Add(1)
221 | tree.Add(2)
222 | tree.Add(3)
223 | tree.Add(4)
224 | tree.Add(5)
225 | tree.Add(6)
226 | tree.Add(7)
227 | tree.Add(8)
228 | tree.Add(9)
229 |
230 | got := tree.ValuesInOrder(tree.Root)
231 |
232 | if got == nil {
233 | t.Error("returned nil values")
234 | }
235 |
236 | for i, v := range got {
237 | if want[i] != got[i] {
238 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
239 | }
240 | }
241 | }
242 |
243 | func TestBalancedValuesInOrder(t *testing.T) {
244 | tree := new[int]()
245 |
246 | want := []int{1, 3, 4, 6, 7, 8, 10, 13, 14}
247 |
248 | tree.Add(8)
249 | tree.Add(3)
250 | tree.Add(10)
251 | tree.Add(1)
252 | tree.Add(6)
253 | tree.Add(14)
254 | tree.Add(4)
255 | tree.Add(7)
256 | tree.Add(13)
257 |
258 | got := tree.ValuesInOrder(tree.Root)
259 |
260 | for i, v := range got {
261 | if want[i] != got[i] {
262 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
263 | }
264 | }
265 | }
266 |
267 | func TestRemoveNil(t *testing.T) {
268 | tree := new[int]()
269 | err := tree.Remove(3)
270 |
271 | if err == nil {
272 | t.Error("no error from remove empty item")
273 | }
274 | }
275 |
276 | func TestInOrder(t *testing.T) {
277 | tree := new[int]()
278 |
279 | want := []int{2, 3, 4, 6, 8}
280 |
281 | tree.Add(3)
282 | tree.Add(6)
283 | tree.Add(8)
284 | tree.Add(4)
285 | tree.Add(2)
286 |
287 | got := tree.ValuesInOrder(tree.Root)
288 |
289 | for i, v := range got {
290 | if want[i] != got[i] {
291 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
292 | }
293 | }
294 | }
295 |
296 | func TestPreOrderValues(t *testing.T) {
297 | tree := new[int]()
298 |
299 | want := []int{3, 2, 6, 4, 8}
300 |
301 | tree.Add(3)
302 | tree.Add(6)
303 | tree.Add(8)
304 | tree.Add(4)
305 | tree.Add(2)
306 |
307 | got := tree.ValuesPreOrder(tree.Root)
308 |
309 | for i, v := range got {
310 | if want[i] != got[i] {
311 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
312 | }
313 | }
314 | }
315 |
316 | func TestPostOrderValues(t *testing.T) {
317 | tree := new[int]()
318 |
319 | want := []int{2, 4, 8, 6, 3}
320 |
321 | tree.Add(3)
322 | tree.Add(6)
323 | tree.Add(8)
324 | tree.Add(4)
325 | tree.Add(2)
326 |
327 | got := tree.ValuesPostOrder(tree.Root)
328 |
329 | for i, v := range got {
330 | if want[i] != got[i] {
331 | t.Errorf("value at %d: want %d, got %d ", i, want[i], v)
332 | }
333 | }
334 | }
335 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------