From 153ee2ceba76db27474ebdbd8e81218fa1e89306 Mon Sep 17 00:00:00 2001 From: Tahmeed Tarek Date: Wed, 3 Nov 2021 20:13:45 +0600 Subject: [PATCH 001/202] chore: feat: implement Bellman Ford algorithm (#423) Co-authored-by: Taj --- graph/bellmanford.go | 48 +++++++++++++ graph/bellmanford_test.go | 137 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+) create mode 100644 graph/bellmanford.go create mode 100644 graph/bellmanford_test.go diff --git a/graph/bellmanford.go b/graph/bellmanford.go new file mode 100644 index 000000000..6fe3e42c9 --- /dev/null +++ b/graph/bellmanford.go @@ -0,0 +1,48 @@ +// The Bellman–Ford algorithm is an algorithm that computes shortest paths from a +// single source vertex to all of the other vertices in a weighted durected graph. +// It is slower than Dijkstra but capable of handling negative edge weights. +// https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm +// Implementation is based on the book 'Introduction to Algorithms' (CLRS) +package graph + +import ( + "errors" + "math" +) + +func (g *Graph) BellmanFord(start, end int) (isReachable bool, distance int, err error) { + INF := math.Inf(1) + distances := make([]float64, g.vertices) + + // Set all vertices to unreachable, initialize source + for i := 0; i < g.vertices; i++ { + distances[i] = INF + } + distances[start] = 0 + + // Making iterations equal to #vertices + for n := 0; n < g.vertices; n++ { + + // Looping over all edges + for u, adjacents := range g.edges { + for v, weightUV := range adjacents { + + // If new shorter distance is found, update distance value (relaxation step) + if newDistance := distances[u] + float64(weightUV); distances[v] > newDistance { + distances[v] = newDistance + } + } + } + } + + // Check for negative weight cycle + for u, adjacents := range g.edges { + for v, weightUV := range adjacents { + if newDistance := distances[u] + float64(weightUV); distances[v] > newDistance { + return false, -1, errors.New("negative weight cycle present") + } + } + } + + return distances[end] != INF, int(distances[end]), nil +} diff --git a/graph/bellmanford_test.go b/graph/bellmanford_test.go new file mode 100644 index 000000000..2f9d57ea6 --- /dev/null +++ b/graph/bellmanford_test.go @@ -0,0 +1,137 @@ +package graph + +import ( + "errors" + "fmt" + "math" + "testing" +) + +func TestBellmanford(t *testing.T) { + + var testCases = []struct { + name string + edges [][]int + vertices int + start int + end int + isReachable bool + distance int + err error + }{ + { + "single edge", + [][]int{ + {0, 1, 1}, + }, + 2, 0, 1, true, 1, nil, + }, + { + "negative weights", + [][]int{ + {0, 1, 1}, + {1, 2, -3}, + {2, 1, 4}, + {2, 3, 1}, + }, + 4, 0, 1, true, 1, nil, + }, + { + "negative cycle", + [][]int{ + {0, 1, 1}, + {1, 2, -3}, + {2, 1, 1}, + {2, 3, 1}, + }, + 4, 0, 1, false, -1, errors.New("negative weight cycle present"), + }, + { + "unreachable vertex", + [][]int{ + {0, 6, 771}, + {0, 9, 782}, + {1, 2, 454}, + {2, 8, 48}, + {3, 8, 249}, + {3, 9, 880}, + {3, 5, 280}, + {7, 1, 92}, + {7, 2, 497}, + {8, 1, 102}, + {8, 4, 977}, + }, + 10, 8, 3, false, int(math.Inf(1)), nil, + }, + { + "disconnected graph", + [][]int{ + {0, 1, 10}, + {2, 3, 15}, + {3, 5, 10}, + }, + 6, 0, 3, false, int(math.Inf(1)), nil, + }, + { + "multiple paths", + [][]int{ + {0, 1, 5}, + {1, 2, 10}, + {1, 3, 30}, + {2, 4, 10}, + {4, 5, 15}, + {3, 5, 10}, + }, + 6, 0, 5, true, 40, nil, + }, + { + "random 1", + [][]int{ + {0, 1, 10}, + {1, 2, 10}, + {0, 2, 100}, + {2, 0, -10}, + {1, 2, 1}, + }, + 3, 0, 1, true, 10, nil, + }, + { + "random 2", + [][]int{ + {0, 1, 5498}, + {2, 0, 7679}, + {0, 3, 4999}, + {1, 2, 8629}, + {1, 3, -948}, + {2, 3, 6231}, + }, + 4, 0, 3, true, 4550, nil, + }, + } + + for _, test := range testCases { + t.Run(fmt.Sprint(test.name), func(t *testing.T) { + // Initializing graph, adding edges + graph := New(test.vertices) + graph.Directed = true + for _, edge := range test.edges { + graph.AddWeightedEdge(edge[0], edge[1], edge[2]) + } + + resIsReachable, resDistance, resError := graph.BellmanFord(test.start, test.end) + if resDistance != test.distance { + t.Errorf("Distance, Expected: %d, Computed: %d", test.distance, resDistance) + } + if resIsReachable != test.isReachable { + t.Errorf("Reachable, Expected: %t, Computed: %t", test.isReachable, resIsReachable) + } + if resError != test.err { + if resError == nil || test.err == nil { + t.Errorf("Reachable, Expected: %s, Computed: %s", test.err, resError) + } else if resError.Error() != test.err.Error() { + t.Errorf("Reachable, Expected: %s, Computed: %s", test.err.Error(), resError.Error()) + } + } + }) + } +} From 3a02506b7a663c034125bd7cf98bc97ecf374747 Mon Sep 17 00:00:00 2001 From: Metta Ong Date: Wed, 3 Nov 2021 22:17:32 +0800 Subject: [PATCH 002/202] merge: feat: dijkstra closest distance implementation (#415) * refactor * feat: implement dijkstra * test: adding multi path test cases * fix: varible naming in test * refactor * feat: generalize heap * feat: new implementation * cleanup * codespell * nit * fix conflict * Update graph/dijkstra.go Co-authored-by: Taj * Update graph/dijkstra.go Co-authored-by: Taj * (refactor) Co-authored-by: Taj Co-authored-by: Rak Laptudirm --- graph/dijkstra.go | 62 +++++++++++++++++++++ graph/dijkstra_test.go | 51 +++++++++++++++++ sort/heapsort.go | 124 ++++++++++++++++++++++++++++++++++------- 3 files changed, 217 insertions(+), 20 deletions(-) create mode 100644 graph/dijkstra.go create mode 100644 graph/dijkstra_test.go diff --git a/graph/dijkstra.go b/graph/dijkstra.go new file mode 100644 index 000000000..26b2becbc --- /dev/null +++ b/graph/dijkstra.go @@ -0,0 +1,62 @@ +package graph + +import "github.com/TheAlgorithms/Go/sort" + +type Item struct { + node int + dist int +} + +func (a Item) More(b interface{}) bool { + // reverse direction for minheap + return a.dist < b.(Item).dist +} +func (a Item) Idx() int { + return a.node +} + +func (g *Graph) Dijkstra(start, end int) (int, bool) { + visited := make(map[int]bool) + nodes := make(map[int]*Item) + + nodes[start] = &Item{ + dist: 0, + node: start, + } + pq := sort.MaxHeap{} + pq.Init(nil) + pq.Push(*nodes[start]) + + visit := func(curr Item) { + visited[curr.node] = true + for n, d := range g.edges[curr.node] { + if visited[n] { + continue + } + + item := nodes[n] + dist2 := curr.dist + d + if item == nil { + nodes[n] = &Item{node: n, dist: dist2} + pq.Push(*nodes[n]) + } else if item.dist > dist2 { + item.dist = dist2 + pq.Update(*item) + } + } + } + + for pq.Size() > 0 { + curr := pq.Pop().(Item) + if curr.node == end { + break + } + visit(curr) + } + + item := nodes[end] + if item == nil { + return -1, false + } + return item.dist, true +} diff --git a/graph/dijkstra_test.go b/graph/dijkstra_test.go new file mode 100644 index 000000000..168c7da69 --- /dev/null +++ b/graph/dijkstra_test.go @@ -0,0 +1,51 @@ +package graph + +import ( + "testing" +) + +var tc_dijkstra = []struct { + name string + edges [][]int + node0 int + node1 int + expected int +}{ + { + "straight line graph", + [][]int{{0, 1, 5}, {1, 2, 2}}, + 0, 2, 7, + }, + { + "unconnected node", + [][]int{{0, 1, 5}}, + 0, 2, -1, + }, + { + "double paths", + [][]int{{0, 1, 5}, {1, 3, 5}, {0, 2, 5}, {2, 3, 4}}, + 0, 3, 9, + }, + { + "double paths extended", + [][]int{{0, 1, 5}, {1, 3, 5}, {0, 2, 5}, {2, 3, 4}, {3, 4, 1}}, + 0, 4, 10, + }, +} + +func TestDijkstra(t *testing.T) { + for _, tc := range tc_dijkstra { + t.Run(tc.name, func(t *testing.T) { + var graph Graph + for _, edge := range tc.edges { + graph.AddWeightedEdge(edge[0], edge[1], edge[2]) + } + + actual, _ := graph.Dijkstra(tc.node0, tc.node1) + if actual != tc.expected { + t.Errorf("expected %d, got %d, from node %d to %d, with %v", + tc.expected, actual, tc.node0, tc.node1, tc.edges) + } + }) + } +} diff --git a/sort/heapsort.go b/sort/heapsort.go index 698c7610f..0c44eb515 100644 --- a/sort/heapsort.go +++ b/sort/heapsort.go @@ -1,50 +1,134 @@ package sort -type maxHeap struct { - slice []int +type MaxHeap struct { + slice []Comparable heapSize int + indices map[int]int } -func buildMaxHeap(slice []int) maxHeap { - h := maxHeap{slice: slice, heapSize: len(slice)} - for i := len(slice) / 2; i >= 0; i-- { - h.MaxHeapify(i) +func buildMaxHeap(slice0 []int) MaxHeap { + var slice []Comparable + for _, i := range slice0 { + slice = append(slice, Int(i)) } + h := MaxHeap{} + h.Init(slice) return h } -func (h maxHeap) MaxHeapify(i int) { +func (h *MaxHeap) Init(slice []Comparable) { + if slice == nil { + slice = make([]Comparable, 0) + } + + h.slice = slice + h.heapSize = len(slice) + h.indices = make(map[int]int) + h.Heapify() +} + +func (h MaxHeap) Heapify() { + for i, v := range h.slice { + h.indices[v.Idx()] = i + } + for i := h.heapSize / 2; i >= 0; i-- { + h.heapifyDown(i) + } +} + +func (h *MaxHeap) Pop() Comparable { + if h.heapSize == 0 { + return nil + } + + i := h.slice[0] + h.heapSize-- + + h.slice[0] = h.slice[h.heapSize] + h.updateidx(0) + h.heapifyDown(0) + + h.slice = h.slice[0:h.heapSize] + return i +} + +func (h *MaxHeap) Push(i Comparable) { + h.slice = append(h.slice, i) + h.updateidx(h.heapSize) + h.heapifyUp(h.heapSize) + h.heapSize++ +} + +func (h MaxHeap) Size() int { + return h.heapSize +} + +func (h MaxHeap) Update(i Comparable) { + h.slice[h.indices[i.Idx()]] = i + h.heapifyUp(h.indices[i.Idx()]) + h.heapifyDown(h.indices[i.Idx()]) +} + +func (h MaxHeap) updateidx(i int) { + h.indices[h.slice[i].Idx()] = i +} + +func (h MaxHeap) heapifyUp(i int) { + if i == 0 { + return + } + p := i / 2 + + if h.slice[i].More(h.slice[p]) { + h.slice[i], h.slice[p] = h.slice[p], h.slice[i] + h.updateidx(i) + h.updateidx(p) + h.heapifyUp(p) + } +} + +func (h MaxHeap) heapifyDown(i int) { l, r := 2*i+1, 2*i+2 max := i - if l < h.size() && h.slice[l] > h.slice[max] { + if l < h.heapSize && h.slice[l].More(h.slice[max]) { max = l } - if r < h.size() && h.slice[r] > h.slice[max] { + if r < h.heapSize && h.slice[r].More(h.slice[max]) { max = r } - //log.Printf("MaxHeapify(%v): l,r=%v,%v; max=%v\t%v\n", i, l, r, max, h.slice) if max != i { h.slice[i], h.slice[max] = h.slice[max], h.slice[i] - h.MaxHeapify(max) + h.updateidx(i) + h.updateidx(max) + h.heapifyDown(max) } } -func (h maxHeap) size() int { return h.heapSize } // ??? +type Comparable interface { + Idx() int + More(interface{}) bool +} +type Int int + +func (a Int) More(b interface{}) bool { + return a > b.(Int) +} +func (a Int) Idx() int { + return int(a) +} func HeapSort(slice []int) []int { h := buildMaxHeap(slice) - //log.Println(slice) for i := len(h.slice) - 1; i >= 1; i-- { h.slice[0], h.slice[i] = h.slice[i], h.slice[0] h.heapSize-- - h.MaxHeapify(0) - /*if i == len(h.slice)-1 || i == len(h.slice)-3 || i == len(h.slice)-5 { - element := (i - len(h.slice)) * -1 - fmt.Println("Heap after removing ", element, " elements") - fmt.Println(h.slice) + h.heapifyDown(0) + } - }*/ + res := []int{} + for _, i := range h.slice { + res = append(res, int(i.(Int))) } - return h.slice + return res } From 7ccc45ec7cb4fc03bb431fe72a711cbad455147d Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Mon, 8 Nov 2021 12:27:25 +0300 Subject: [PATCH 003/202] merge: feat: bitwise min (#427) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition Co-authored-by: Rak Laptudirm --- math/min/bitwisemin.go | 16 +++++++ math/min/min_test.go | 103 +++++++++++++++++------------------------ 2 files changed, 58 insertions(+), 61 deletions(-) create mode 100644 math/min/bitwisemin.go diff --git a/math/min/bitwisemin.go b/math/min/bitwisemin.go new file mode 100644 index 000000000..9710910aa --- /dev/null +++ b/math/min/bitwisemin.go @@ -0,0 +1,16 @@ +// bitwisemin.go +// description: Gives min of two integers +// details: +// implementation of finding the minimum of two numbers using only binary operations without using conditions +// author(s) [red_byte](https://github.com/i-redbyte) +// see bitwisemin_test.go + +package min + +func Bitwise(base int, value int, values ...int) int { + min := value + for _, val := range values { + min = min&((min-val)>>base) | val&(^(min-val)>>base) + } + return min +} diff --git a/math/min/min_test.go b/math/min/min_test.go index 663f5b734..ec63ed0b8 100644 --- a/math/min/min_test.go +++ b/math/min/min_test.go @@ -1,81 +1,62 @@ -package min_test +package min import ( "testing" - - "github.com/TheAlgorithms/Go/math/min" ) -func TestMin(t *testing.T) { - testCases := []struct { - name string - left int - right int - min int +func getTestCases() []struct { + name string + base int + numbers []int + min int +} { + var tests = []struct { + name string + base int + numbers []int + min int }{ - { - name: "left is min", - left: 1, - right: 10, - min: 1, - }, - { - name: "right is min", - left: 10, - right: 9, - min: 9, - }, + {"Minimum of [128, 127], min = 117", 8, []int{128, 127}, 127}, + {"Minimum of [5], min = 5", 32, []int{5}, 5}, + {"Minimum of [-8, 32, 64, -1, 0], min = -8", 64, []int{-8, 32, 64, -1, 0}, -8}, + {"Minimum of [1, 2, 3, 4, 5], min = 1", 32, []int{1, 2, 3, 4, 5}, 1}, + {"Minimum of [1024, 512, 256, 333, 777], min = 256", 64, []int{1024, 512, 256, 333, 777}, 256}, + {"Minimum of [-9223372036854770001, -9223372036854770000, 256, 333, 777], min = 256", 64, []int{-9223372036854770001, -9223372036854770000, 256, 333, 777}, -9223372036854770001}, } + return tests +} - for _, test := range testCases { +func TestBitwiseMin(t *testing.T) { + tests := getTestCases() + for _, test := range tests { t.Run(test.name, func(t *testing.T) { - actualMin := min.Int(test.left, test.right) - if actualMin != test.min { - t.Errorf("Failed test %s\n\tleft: %v, right: %v, min: %v but received: %v", - test.name, test.left, test.right, test.min, actualMin) + result := Bitwise(test.base, 999, test.numbers...) + if result != test.min { + t.Errorf("Wrong result! Expected:%v, returned:%v ", test.min, result) } }) } } -func TestMinOfThree(t *testing.T) { - testCases := []struct { - name string - left int - middle int - right int - min int - }{ - { - name: "left is min", - left: 1, - middle: 5, - right: 10, - min: 1, - }, - { - name: "middle is min", - left: 10, - middle: 5, - right: 9, - min: 5, - }, - { - name: "right is min", - left: 10, - middle: 8, - right: 6, - min: 6, - }, - } - - for _, test := range testCases { +func TestMin(t *testing.T) { + for _, test := range getTestCases() { t.Run(test.name, func(t *testing.T) { - actualMin := min.Int(test.left, test.middle, test.right) + actualMin := Int(test.numbers...) if actualMin != test.min { - t.Errorf("Failed test %s\n\tleft: %v, middle: %v, right: %v, min: %v but received: %v", - test.name, test.left, test.middle, test.right, test.min, actualMin) + t.Errorf("Wrong result! Expected:%v, returned:%v ", test.min, actualMin) } }) } } + +func BenchmarkTestMinInt(b *testing.B) { + for i := 0; i < b.N; i++ { + Int(0, 10, 9, 7, 2, 1, 4, 3, 5, 6) + } +} + +func BenchmarkTestBitwiseMin(b *testing.B) { + for i := 0; i < b.N; i++ { + Bitwise(32, 10, 9, 7, 2, 1, 4, 3, 5, 6) + } +} From ec28323411dc5381c897fc49703f8ba1974c5536 Mon Sep 17 00:00:00 2001 From: Taj Date: Tue, 9 Nov 2021 19:12:47 +0000 Subject: [PATCH 004/202] feat: Godocmd action added for updating readme automatically. (#429) * workflow * fix: workflow * feat: workflow * Updated README.md * Update README.md * Updated README.md * Update generate_readme.yml * Update generate_readme.yml * Updated Documentation in README.md * Update generate_readme.yml * Updated Documentation in README.md * Update README.md * Updated Documentation in README.md * Update generate_readme.yml * Updated Documentation in README.md * Update README.md * Updated Documentation in README.md * fix: package level documentation * Updated Documentation in README.md * fix: incorrect package level documentation * Updated Documentation in README.md * Update README.md * Updated Documentation in README.md * Update decimaltobinary.go * Updated Documentation in README.md * fix: incorrect documentation format * Updated Documentation in README.md * fix: documentation format * Updated Documentation in README.md * fix: documentation format * Updated Documentation in README.md * fix: documentation * Updated Documentation in README.md * fix: documentation * Updated Documentation in README.md * Update generate_readme.yml * Update golang_lint_and_test.yml * Update generate_readme.yml * Update generate_readme.yml * fix: documentation * fix: godocmd badge * Update README.md * Update godocmd.yml * Updated Documentation in README.md Co-authored-by: godocmd-action <${GITHUB_ACTOR}@users.noreply.github.com> --- .github/workflows/godocmd.yml | 28 + .github/workflows/golang_lint_and_test.yml | 13 +- README.md | 934 ++++++++++++++++++--- conversion/binarytodecimal.go | 1 - conversion/decimaltobinary.go | 1 - graph/bellmanford.go | 1 + math/binary/xorsearch_test.go | 1 + sort/countingsort.go | 1 - structure/set/set.go | 3 + structure/set/set_test.go | 3 - structure/set/setexample_test.go | 4 - 11 files changed, 870 insertions(+), 120 deletions(-) create mode 100644 .github/workflows/godocmd.yml diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml new file mode 100644 index 000000000..86abaa4cc --- /dev/null +++ b/.github/workflows/godocmd.yml @@ -0,0 +1,28 @@ +name: godocmd +on: [push, pull_request] +jobs: + generate_readme: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: '^1.17' + - name: Install GoDocMD + run: | + go install github.com/tjgurwara99/godocmd@v0.1.2 + - name: Configure Github Action + run: | + git config --global user.name github-action + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + - name: Update README.md file + run: | + godocmd -r -module ./ -w + - name: Commit changes if README.md is different + run: | + if [[ `git status --porcelain` ]]; then + git commit -am "Updated Documentation in README.md" + git push + else + echo "NO CHANGES DETECTED" + fi diff --git a/.github/workflows/golang_lint_and_test.yml b/.github/workflows/golang_lint_and_test.yml index f065817f4..4cb59f712 100644 --- a/.github/workflows/golang_lint_and_test.yml +++ b/.github/workflows/golang_lint_and_test.yml @@ -8,14 +8,17 @@ jobs: fail-fast: false steps: - uses: actions/checkout@v2 - - uses: codespell-project/actions-codespell@master + - name: Codespell + uses: codespell-project/actions-codespell@master with: ignore_words_list: "actualy,nwe" skip: "go.mod,go.sum" - - uses: actions/setup-go@v2 - - run: go version - - uses: golangci/golangci-lint-action@v2 + - name: Setup Go + uses: actions/setup-go@v2 + - name: Run Golang CI Lint + uses: golangci/golangci-lint-action@v2 with: version: latest args: -E gofmt - - run: go test ./... + - name: Run tests + run: go test ./... diff --git a/README.md b/README.md index 81696afd9..9d6dc902a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # The Algorithms - Go [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Go)  ![golangci-lint](https://github.com/TheAlgorithms/Go/workflows/golangci-lint/badge.svg) +![godocmd](https://github.com/tjgurwara99/Go/workflows/godocmd/badge.svg) ![](https://img.shields.io/github/repo-size/TheAlgorithms/Go.svg?label=Repo%20size&style=flat-square)  ![update_directory_md](https://github.com/TheAlgorithms/Go/workflows/update_directory_md/badge.svg) [![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6)  @@ -12,109 +13,832 @@ The repository is a collection of open-source implementation of a variety of alg Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ## List of Algorithms + +# Packages: -### Ciphers -* [Caesar](./cipher/caesar/caesar.go) -* [Diffie Hellman Key Exchange](./cipher/diffiehellman/diffiehellmankeyexchange.go) -* [Polybius](./cipher/polybius/polybius.go) -* [Rot13](./cipher/rot13/rot13.go) -* [Rsa](./cipher/rsa/rsa.go) -* [Xor](./cipher/xor/xor.go) - -### Conversions -* [Roman Numeral To Integer](./conversion/romantointeger.go) -* [Integer To Roman Numeral](./conversion/integertoroman.go) -* [Decimal To Binary](./conversion/decimaltobinary.go) -* [Binary To Decimal](./conversion/binarytodecimal.go) - -### Data Structures -* [AVL Tree](./structure/avl/avl.go) -* [Binary Tree](./structure/binarysearchtree/bstree.go) -* [Dynamic Array](./structure/dynamicarray/dynamicarray.go) -* [Hashmap](./structure/hashmap/hashmap.go) -* Linked-List - * [Doubly Linked List](./structure/linkedlist/doubly.go) - * [Singly Linked List](./structure/linkedlist/singlylinkedlist.go) - * [Cyclic Linked List AKA Looped Linked List](./structure/linkedlist/cyclic.go) -* [Queue](./structure/queue) - * [Array Based](./structure/queue/queuearray.go) - * [Custom Linked List Based](./structure/queue/queuelinkedlist.go) - * [Standard Library Container/List Based](./structure/queue/queuelinkedlist.go) -* [Set](./structure/set/set.go) -* [Stack](./structure/stack) - * [Array Based](./structure/stack/stackarray.go) - * [Custom Linked List](./structure/stack/stacklinkedlist.go) - * [Standard Library Container/List Based](structure/stack/stacklinkedlistwithlist.go) -* [Trie](./structure/trie/trie.go) - -### Dynamic Programming -* [Binomial Coefficient](./dynamic/binomialcoefficient.go) -* [Fibonacci](./dynamic/fibonacci.go) -* [Knapsack](./dynamic/knapsack.go) -* [Longest Common Subsequence](./dynamic/longestcommonsubsequence.go) -* [Longest Palindromic Subsequence](./dynamic/longestpalindromicsubsequence.go) -* [Matrix Multiplication](./dynamic/matrixmultiplication.go) -* [Cutting a Rod](./dynamic/rodcutting.go) - -### Graphs -* [Breadth First Search](./graph/breadthfirstsearch.go) -* [Depth First Search](./graph/depthfirstsearch.go) -* [Floyd Warshall](./graph/floydwarshall.go) -* [Coloring Algorithms](./graph/coloring) - * [Using BFS](./graph/coloring/bfs.go) - * [Using Backtracking](./graph/coloring/backtracking.go) - * [Using Greedy Approach](./graph/coloring/greedy.go) - -### Math -* [Gcd](./math/gcd) - * [Extended](./math/gcd/extended.go) - * [Recursive](./math/gcd/gcd.go) - * [Iterative](./math/gcd/gcditerative.go) -* [Lcm](./math/lcm/lcm.go) -* [Max](./math/max/max.go) -* [Modular](./math/modular) - * [Exponentiation](./math/modular/exponentiation.go) - * [Inverse](./math/modular/inverse.go) -* [Moser-de Bruijn sequence](./math/moserdebruijnsequence/sequence.go) -* [Permutation](./math/permutation/heaps.go) -* [Power](./math/power/fastexponent.go) -* [Prime](./math/prime) - * [Miller Rabin Primality Test](./math/prime/millerrabinprimalitytest.go) - * [Naive and Pair Approach](./math/prime/primecheck.go) - * [Sieve](./math/prime/sieve.go) -* [Pythagoras](./math/pythagoras/pythagoras.go) -* [Sieve](./math/prime/sieve.go) -* [Straight Lines](./math/geometry/straightlines.go) - -### Other -* [Max Subarray Sum](./other/maxsubarraysum/maxsubarraysum.go) -* [Nested Brackets](./other/nested/nestedbrackets.go) -* [Password Generator](./other/password/generator.go) - -### Searches -* [Binary Search](./search/binary.go) -* [Linear Search](./search/linear.go) -* [Interpolation Search](./search/interpolation.go) - -### Sorts -* [Bubble Sort](./sort/bubblesort.go) -* [Heap Sort](./sort/heapsort.go) -* [Insertion Sort](./sort/insertionsort.go) -* [Merge Sort](./sort/mergesort.go) -* [Quick Sort](./sort/quicksort.go) -* [Radix Sort](./sort/radixsort.go) -* [Selection Sort](./sort/selectionsort.go) -* [Shell Sort](./sort/shellsort.go) - - -* [Sorts Test](./sort/sorts_test.go) - -### Strings -* [Levenshtein Distance](./strings/levenshtein/levenshteindistance.go) -* Multiple String Matching - * [Advanced Aho Corasick](./strings/ahocorasick/advancedahocorasick.go) - * [Aho Corasick](./strings/ahocorasick/ahocorasick.go) -* Single String Matching - * [Bom](./strings/bom/bom.go) - * [Horspool](./strings/horspool/horspool.go) - * [Kmp](./strings/kmp/kmp.go) +
+ ahocorasick + +--- + +##### Functions: + +1. [`Advanced`](./strings/ahocorasick/advancedahocorasick.go#L10): Advanced Function performing the Advanced Aho-Corasick algorithm. Finds and prints occurrences of each pattern. +2. [`AhoCorasick`](./strings/ahocorasick/ahocorasick.go#L15): AhoCorasick Function performing the Basic Aho-Corasick algorithm. Finds and prints occurrences of each pattern. +3. [`ArrayUnion`](./strings/ahocorasick/shared.go#L86): ArrayUnion Concats two arrays of int's into one. +4. [`BoolArrayCapUp`](./strings/ahocorasick/shared.go#L78): BoolArrayCapUp Dynamically increases an array size of bool's by 1. +5. [`BuildAc`](./strings/ahocorasick/ahocorasick.go#L54): Functions that builds Aho Corasick automaton. +6. [`BuildExtendedAc`](./strings/ahocorasick/advancedahocorasick.go#L46): BuildExtendedAc Functions that builds extended Aho Corasick automaton. +7. [`ComputeAlphabet`](./strings/ahocorasick/shared.go#L61): ComputeAlphabet Function that returns string of all the possible characters in given patterns. +8. [`ConstructTrie`](./strings/ahocorasick/shared.go#L4): ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings. +9. [`Contains`](./strings/ahocorasick/shared.go#L39): Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise. +10. [`CreateNewState`](./strings/ahocorasick/shared.go#L111): CreateNewState Automaton function for creating a new state 'state'. +11. [`CreateTransition`](./strings/ahocorasick/shared.go#L116): CreateTransition Creates a transition for function σ(state,letter) = end. +12. [`GetParent`](./strings/ahocorasick/shared.go#L99): GetParent Function that finds the first previous state of a state and returns it. Used for trie where there is only one parent. +13. [`GetTransition`](./strings/ahocorasick/shared.go#L121): GetTransition Returns ending state for transition σ(fromState,overChar), '-1' if there is none. +14. [`GetWord`](./strings/ahocorasick/shared.go#L49): GetWord Function that returns word found in text 't' at position range 'begin' to 'end'. +15. [`IntArrayCapUp`](./strings/ahocorasick/shared.go#L70): IntArrayCapUp Dynamically increases an array size of int's by 1. +16. [`StateExists`](./strings/ahocorasick/shared.go#L133): StateExists Checks if state 'state' exists. Returns 'true' if it does, 'false' otherwise. + +--- +##### Types + +1. [`Result`](./strings/ahocorasick/ahocorasick.go#L9): No description provided. + + +--- +
+ avl + +--- + +##### Package avl is a Adelson-Velskii and Landis tree implemnation avl is self-balancing tree, i.e for all node in a tree, height difference between its left and right child will not exceed 1 more information : https://en.wikipedia.org/wiki/AVL_tree + +--- +##### Functions: + +1. [`Delete`](./structure/avl/avl.go#L72): Delete : remove given key from the tree +2. [`Get`](./structure/avl/avl.go#L20): Get : return node with given key +3. [`Insert`](./structure/avl/avl.go#L35): Insert a new item +4. [`NewTree`](./structure/avl/avl.go#L15): NewTree create a new AVL tree + +--- +##### Types + +1. [`Node`](./structure/avl/avl.go#L8): No description provided. + + +--- +
+ binary + +--- + +##### Package binary describes algorithms that use binary operations for different calculations. + +--- +##### Functions: + +1. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. +2. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 +3. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L11): No description provided. +4. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L15): No description provided. +5. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. +6. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L10): No description provided. + +--- +
+ binarytree + +--- + +##### Functions: + +1. [`AccessNodesByLayer`](./structure/binarysearchtree/bstree.go#L145): AccessNodesByLayer Function that access nodes layer by layer instead of printing the results as one line. +2. [`BstDelete`](./structure/binarysearchtree/bstree.go#L44): BstDelete removes the node +3. [`InOrder`](./structure/binarysearchtree/bstree.go#L79): Travers the tree in the following order left --> root --> right +4. [`InOrderSuccessor`](./structure/binarysearchtree/bstree.go#L35): InOrderSuccessor Goes to the left +5. [`Insert`](./structure/binarysearchtree/bstree.go#L17): Insert a value in the BSTree +6. [`LevelOrder`](./structure/binarysearchtree/bstree.go#L138): No description provided. +7. [`Max`](./structure/binarysearchtree/bstree.go#L174): Max Function that returns max of two numbers - possibly already declared. +8. [`NewNode`](./structure/binarysearchtree/node.go#L11): NewNode Returns a new pointer to an empty Node +9. [`PostOrder`](./structure/binarysearchtree/bstree.go#L113): Travers the tree in the following order left --> right --> root +10. [`PreOrder`](./structure/binarysearchtree/bstree.go#L96): Travers the tree in the following order root --> left --> right + +--- +##### Types + +1. [`BSTree`](./structure/binarysearchtree/bstree.go#L4): No description provided. + +2. [`Node`](./structure/binarysearchtree/node.go#L4): No description provided. + + +--- +
+ caesar + +--- + +##### Package caesar is the shift cipher ref: https://en.wikipedia.org/wiki/Caesar_cipher + +--- +##### Functions: + +1. [`Decrypt`](./cipher/caesar/caesar.go#L27): Decrypt decrypts by left shift of "key" each character of "input" +2. [`Encrypt`](./cipher/caesar/caesar.go#L6): Encrypt encrypts by right shift of "key" each character of "input" + +--- +
+ coloring + +--- + +##### Package coloring provides implementation of different graph coloring algorithms, e.g. coloring using BFS, using Backtracking, using greedy approach. Author(s): [Shivam](https://github.com/Shivam010) + +--- +##### Functions: + +1. [`BipartiteCheck`](./graph/coloring/bipartite.go#L40): basically tries to color the graph in two colors if each edge connects 2 differently colored nodes the graph can be considered bipartite + +--- +##### Types + +1. [`Graph`](./graph/coloring/graph.go#L14): No description provided. + + +--- +
+ combination + +--- + +##### Package combination ... + +--- +##### Functions: + +1. [`Start`](./strings/combination/combination.go#L13): Start ... + +--- +##### Types + +1. [`Combinations`](./strings/combination/combination.go#L7): No description provided. + + +--- +
+ conversion + +--- + +##### Package conversion is a package of implementations which converts one data structure to another. + +--- +##### Functions: + +1. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return it's Decimal equivalent as integer. +2. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. +3. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue +4. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. +5. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex +6. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. +7. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. + +--- +
+ diffiehellman + +--- + +##### Package diffiehellman implements Deffie Hellman Key Exchange Algorithm for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI + +--- +##### Functions: + +1. [`GenerateMutualKey`](./cipher/diffiehellman/diffiehellmankeyexchange.go#L19): GenerateMutualKey : generates a mutual key that can be used by only alice and bob mutualKey = (shareKey^prvKey)%primeNumber +2. [`GenerateShareKey`](./cipher/diffiehellman/diffiehellmankeyexchange.go#L13): GenerateShareKey : generates a key using client private key , generator and primeNumber this key can be made public shareKey = (g^key)%primeNumber + +--- +
+ dynamic + +--- + +##### Package dynamic is a package of certain implementations of dynamically run algorithms. + +--- +##### Functions: + +1. [`Bin2`](./dynamic/binomialcoefficient.go#L21): Bin2 function +2. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming +3. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach +4. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively. +5. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. +6. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. +7. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit +8. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function +9. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order +10. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function +11. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function +12. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function +13. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function +14. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate +15. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) +16. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number + +--- +
+ dynamicarray + +--- + +##### Package dynamicarray A dynamic array is quite similar to a regular array, but its Size is modifiable during program runtime, very similar to how a slice in Go works. The implementation is for educational purposes and explains how one might go about implementing their own version of slices. For more details check out those links below here: GeeksForGeeks article : https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/ Go blog: https://blog.golang.org/slices-intro Go blog: https://blog.golang.org/slices authors [Wesllhey Holanda](https://github.com/wesllhey), [Milad](https://github.com/miraddo) see dynamicarray.go, dynamicarray_test.go + +--- +##### Types + +1. [`DynamicArray`](./structure/dynamicarray/dynamicarray.go#L21): No description provided. + + +--- +
+ factorial + +--- + +##### Package factorial describes algorithms Factorials calculations. + +--- +##### Functions: + +1. [`BruteForceFactorial`](./math/factorial/factorial.go#L11): No description provided. +2. [`CalculateFactorialUseTree`](./math/factorial/factorial.go#L27): No description provided. +3. [`RecursiveFactorial`](./math/factorial/factorial.go#L19): No description provided. + +--- +
+ gcd + +--- + +##### Functions: + +1. [`Extended`](./math/gcd/extended.go#L12): Extended simple extended gcd +2. [`ExtendedIterative`](./math/gcd/extendedgcditerative.go#L4): ExtendedIterative finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b). +3. [`ExtendedRecursive`](./math/gcd/extendedgcd.go#L4): ExtendedRecursive finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b). +4. [`Iterative`](./math/gcd/gcditerative.go#L4): Iterative Faster iterative version of GcdRecursive without holding up too much of the stack +5. [`Recursive`](./math/gcd/gcd.go#L4): Recursive finds and returns the greatest common divisor of a given integer. +6. [`TemplateBenchmarkExtendedGCD`](./math/gcd/extendedgcd_test.go#L44): No description provided. +7. [`TemplateBenchmarkGCD`](./math/gcd/gcd_test.go#L37): No description provided. +8. [`TemplateTestExtendedGCD`](./math/gcd/extendedgcd_test.go#L7): No description provided. +9. [`TemplateTestGCD`](./math/gcd/gcd_test.go#L18): No description provided. + +--- +
+ generateparentheses + +--- + +##### Functions: + +1. [`GenerateParenthesis`](./strings/generateparentheses/generateparentheses.go#L12): No description provided. + +--- +
+ genetic + +--- + +##### Package genetic provides functions to work with strings using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia + +--- +##### Functions: + +1. [`GeneticString`](./strings/genetic/genetic.go#L71): GeneticString generates PopultaionItem based on the imputed target string, and a set of possible runes to build a string with. In order to optimise string generation additional configurations can be provided with Conf instance. Empty instance of Conf (&Conf{}) can be provided, then default values would be set. Link to the same algorithm implemented in python: https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py + +--- +##### Types + +1. [`Conf`](./strings/genetic/genetic.go#L32): No description provided. + +2. [`PopulationItem`](./strings/genetic/genetic.go#L26): No description provided. + +3. [`Result`](./strings/genetic/genetic.go#L52): No description provided. + + +--- +
+ geometry + +--- + +##### Functions: + +1. [`Distance`](./math/geometry/straightlines.go#L17): Calculates the shortest distance between two points. +2. [`Intercept`](./math/geometry/straightlines.go#L36): Calculates the Y-Intercept of a line from a specific Point. +3. [`IsParallel`](./math/geometry/straightlines.go#L41): Checks if two lines are parallel or not. +4. [`IsPerpendicular`](./math/geometry/straightlines.go#L46): Checks if two lines are perpendicular or not. +5. [`PointDistance`](./math/geometry/straightlines.go#L52): Calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. +6. [`Section`](./math/geometry/straightlines.go#L23): Calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. +7. [`Slope`](./math/geometry/straightlines.go#L31): Calculates the slope (gradient) of a line. + +--- +##### Types + +1. [`Line`](./math/geometry/straightlines.go#L12): No description provided. + +2. [`Point`](./math/geometry/straightlines.go#L8): No description provided. + + +--- +
+ graph + +--- + +##### Package graph demonstrates Graph search algorithms reference: https://en.wikipedia.org/wiki/Tree_traversal + +--- +##### Functions: + +1. [`BreadthFirstSearch`](./graph/breadthfirstsearch.go#L9): BreadthFirstSearch is an algorithm for traversing and searching graph data structures. It starts at an arbitrary node of a graph, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) reference: https://en.wikipedia.org/wiki/Breadth-first_search +2. [`DepthFirstSearch`](./graph/depthfirstsearch.go#L53): No description provided. +3. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided. +4. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm +5. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. +6. [`KruskalMST`](./graph/kruskal.go#L87): KruskalMST will return a minimum spanning tree along with its total cost to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is the number of edges in the graph and n is number of nodes in it. +7. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) +8. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made +9. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. +10. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b + +--- +##### Types + +1. [`DisjointSetUnion`](./graph/kruskal.go#L29): No description provided. + +2. [`DisjointSetUnionElement`](./graph/kruskal.go#L21): No description provided. + +3. [`Edge`](./graph/kruskal.go#L14): No description provided. + +4. [`Graph`](./graph/graph.go#L9): No description provided. + +5. [`Item`](./graph/dijkstra.go#L5): No description provided. + +6. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. + + +--- +
+ hashmap + +--- + +##### Functions: + +1. [`New`](./structure/hashmap/hashmap.go#L24): New return new HashMap instance + +--- +##### Types + +1. [`HashMap`](./structure/hashmap/hashmap.go#L17): No description provided. + + +--- +
+ kmp + +--- + +##### Functions: + +1. [`Kmp`](./strings/kmp/kmp.go#L70): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. Prints whether the word/pattern was found and on what position in the text or not. m - current match in text, i - current character in w, c - amount of comparisons. + +--- +##### Types + +1. [`Result`](./strings/kmp/kmp.go#L15): No description provided. + + +--- +
+ lcm + +--- + +##### Functions: + +1. [`Lcm`](./math/lcm/lcm.go#L10): Lcm returns the lcm of two numbers using the fact that lcm(a,b) * gcd(a,b) = | a * b | + +--- +
+ levenshtein + +--- + +##### Functions: + +1. [`Distance`](./strings/levenshtein/levenshteindistance.go#L10): Distance Function that gives Levenshtein Distance + +--- +
+ linkedlist + +--- + +##### Package linkedlist demonstates different implementations on linkedlists. + +--- +##### Functions: + +1. [`JosephusProblem`](./structure/linkedlist/cyclic.go#L120): https://en.wikipedia.org/wiki/Josephus_problem This is a struct-based solution for Josephus problem. +2. [`NewCyclic`](./structure/linkedlist/cyclic.go#L12): Create new list. +3. [`NewDoubly`](./structure/linkedlist/doubly.go#L22): No description provided. +4. [`NewNode`](./structure/linkedlist/shared.go#L12): Create new node. +5. [`NewSingly`](./structure/linkedlist/singlylinkedlist.go#L19): NewSingly returns a new instance of a linked list + +--- +##### Types + +1. [`Cyclic`](./structure/linkedlist/cyclic.go#L6): No description provided. + +2. [`Doubly`](./structure/linkedlist/doubly.go#L18): No description provided. + +3. [`Node`](./structure/linkedlist/shared.go#L5): No description provided. + +4. [`Singly`](./structure/linkedlist/singlylinkedlist.go#L10): No description provided. + +5. [`testCase`](./structure/linkedlist/cyclic_test.go#L105): No description provided. + + +--- +
+ manacher + +--- + +##### Functions: + +1. [`LongestPalindrome`](./strings/manacher/longestpalindrome.go#L37): No description provided. + +--- +
+ math + +--- + +##### Package math is a package that contains mathematical algorithms and its different implementations. + +--- +##### Functions: + +1. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +2. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. + +--- +
+ max + +--- + +##### Functions: + +1. [`BitwiseMax`](./math/max/bitwisemax.go#L10): No description provided. +2. [`Int`](./math/max/max.go#L4): Int is a function which returns the maximum of all the integers provided as arguments. + +--- +
+ maxsubarraysum + +--- + +##### Package maxsubarraysum is a package containing a solution to a common problem of finding max contiguous sum within a array of ints. + +--- +##### Functions: + +1. [`MaxSubarraySum`](./other/maxsubarraysum/maxsubarraysum.go#L13): MaxSubarraySum returns the maximum subarray sum + +--- +
+ min + +--- + +##### Functions: + +1. [`Bitwise`](./math/min/bitwisemin.go#L10): No description provided. +2. [`Int`](./math/min/min.go#L4): Int is a function which returns the minimum of all the integers provided as arguments. + +--- +
+ modular + +--- + +##### Functions: + +1. [`Exponentiation`](./math/modular/exponentiation.go#L22): Exponentiation returns base^exponent % mod +2. [`Inverse`](./math/modular/inverse.go#L20): Inverse Modular function +3. [`Multiply64BitInt`](./math/modular/exponentiation.go#L51): Multiply64BitInt Checking if the integer multiplication overflows + +--- +
+ moserdebruijnsequence + +--- + +##### Functions: + +1. [`MoserDeBruijnSequence`](./math/moserdebruijnsequence/sequence.go#L7): No description provided. + +--- +
+ nested + +--- + +##### Package nested provides functions for testing strings proper brackets nesting. + +--- +##### Functions: + +1. [`IsBalanced`](./other/nested/nestedbrackets.go#L20): IsBalanced returns true if provided input string is properly nested. Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. A sequence of brackets `s` is considered properly nested if any of the following conditions are true: - `s` is empty; - `s` has the form (U) or [U] or {U} where U is a properly nested string; - `s` has the form VW where V and W are properly nested strings. For example, the string "()()[()]" is properly nested but "[(()]" is not. **Note** Providing characters other then brackets would return false, despite brackets sequence in the string. Make sure to filter input before usage. + +--- +
+ palindrome + +--- + +##### Functions: + +1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided. + +--- +
+ password + +--- + +##### Package password contains functions to help generate random passwords + +--- +##### Functions: + +1. [`Generate`](./other/password/generator.go#L15): Generate returns a newly generated password + +--- +
+ permutation + +--- + +##### Functions: + +1. [`GenerateElementSet`](./math/permutation/heaps.go#L37): No description provided. +2. [`Heaps`](./math/permutation/heaps.go#L8): Heap's Algorithm for generating all permutations of n objects + +--- +
+ pi + +--- + +##### spigotpi_test.go description: Test for Spigot Algorithm for the Digits of Pi author(s) [red_byte](https://github.com/i-redbyte) see spigotpi.go + +--- +##### Functions: + +1. [`MonteCarloPi`](./math/pi/montecarlopi.go#L15): No description provided. +2. [`Spigot`](./math/pi/spigotpi.go#L12): No description provided. + +--- +
+ polybius + +--- + +##### Package polybius is encrypting method with polybius square ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher + +--- +##### Functions: + +1. [`NewPolybius`](./cipher/polybius/polybius.go#L21): NewPolybius returns a pointer to object of Polybius. If the size of "chars" is longer than "size", "chars" are truncated to "size". + +--- +##### Types + +1. [`Polybius`](./cipher/polybius/polybius.go#L12): No description provided. + + +--- +
+ power + +--- + +##### Functions: + +1. [`IterativePower`](./math/power/fastexponent.go#L4): IterativePower is iterative O(logn) function for pow(x, y) +2. [`RecursivePower`](./math/power/fastexponent.go#L18): RecursivePower is recursive O(logn) function for pow(x, y) +3. [`RecursivePower1`](./math/power/fastexponent.go#L30): RecursivePower1 is recursive O(n) function for pow(x, y) +4. [`UsingLog`](./math/power/powvialogarithm.go#L14): No description provided. + +--- +
+ prime + +--- + +##### Functions: + +1. [`Factorize`](./math/prime/primefactorization.go#L5): Factorize is a function that computes the exponents of each prime in the prime factorization of n +2. [`Generate`](./math/prime/sieve.go#L26): Generate returns a int slice of prime numbers up to the limit +3. [`GenerateChannel`](./math/prime/sieve.go#L9): Generate generates the sequence of integers starting at 2 and sends it to the channel `ch` +4. [`MillerRabinTest`](./math/prime/millerrabinprimalitytest.go#L59): MillerRabinTest Probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. +5. [`MillerTest`](./math/prime/millerrabinprimalitytest.go#L32): MillerTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result. +6. [`NaiveApproach`](./math/prime/primecheck.go#L8): NaiveApproach checks if an integer is prime or not. Returns a bool. +7. [`PairApproach`](./math/prime/primecheck.go#L22): PairApproach checks primality of an integer and returns a bool. More efficient than the naive approach as number of iterations are less. +8. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels + +--- +
+ pythagoras + +--- + +##### Functions: + +1. [`Distance`](./math/pythagoras/pythagoras.go#L15): Distance calculates the distance between to vectors with the Pythagoras theorem + +--- +##### Types + +1. [`Vector`](./math/pythagoras/pythagoras.go#L8): No description provided. + + +--- +
+ queue + +--- + +##### Functions: + +1. [`BackQueue`](./structure/queue/queuearray.go#L32): BackQueue return the Back value +2. [`DeQueue`](./structure/queue/queuearray.go#L20): DeQueue it will be removed the first value that added into the list +3. [`EnQueue`](./structure/queue/queuearray.go#L15): EnQueue it will be added new value into our list +4. [`FrontQueue`](./structure/queue/queuearray.go#L27): FrontQueue return the Front value +5. [`IsEmptyQueue`](./structure/queue/queuearray.go#L42): IsEmptyQueue check our list is empty or not +6. [`LenQueue`](./structure/queue/queuearray.go#L37): LenQueue will return the length of the queue list + +--- +##### Types + +1. [`LQueue`](./structure/queue/queuelinklistwithlist.go#L20): No description provided. + +2. [`Node`](./structure/queue/queuelinkedlist.go#L13): No description provided. + +3. [`Queue`](./structure/queue/queuelinkedlist.go#L19): No description provided. + + +--- +
+ rsa + +--- + +##### Package rsa shows a simple implementation of RSA algorithm + +--- +##### Functions: + +1. [`Decrypt`](./cipher/rsa/rsa.go#L43): Decrypt decrypts encrypted rune slice based on the RSA algorithm +2. [`Encrypt`](./cipher/rsa/rsa.go#L28): Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory + +--- +
+ search + +--- + +##### Functions: + +1. [`BoyerMoore`](./strings/search/boyermoore.go#L5): Implementation of boyer moore string search O(l) where l=len(text) +2. [`Naive`](./strings/search/naive.go#L5): Implementation of naive string search O(n*m) where n=len(txt) and m=len(pattern) + +--- +
+ segmenttree + +--- + +##### Functions: + +1. [`NewSegmentTree`](./structure/segmenttree/segmenttree.go#L114): No description provided. + +--- +##### Types + +1. [`SegmentTree`](./structure/segmenttree/segmenttree.go#L17): No description provided. + + +--- +
+ set + +--- + +##### package set implements a Set using a golang map. This implies that only the types that are accepted as valid map keys can be used as set elements. For instance, do not try to Add a slice, or the program will panic. + +--- +##### Functions: + +1. [`New`](./structure/set/set.go#L7): New gives new set. + +--- +
+ sort + +--- + +##### Package sort a package for demonstrating sorting algorithms in Go + +--- +##### Functions: + +1. [`Count`](./sort/countingsort.go#L9): No description provided. +2. [`Exchange`](./sort/exchangesort.go#L6): No description provided. +3. [`HeapSort`](./sort/heapsort.go#L121): No description provided. +4. [`ImprovedSimpleSort`](./sort/simplesort.go#L25): ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +5. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. +6. [`Mergesort`](./sort/mergesort.go#L35): Mergesort Perform mergesort on a slice of ints +7. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +8. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array +9. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array +10. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +11. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. +12. [`ShellSort`](./sort/shellsort.go#L3): No description provided. +13. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. + +--- +##### Types + +1. [`Int`](#L0): + + Methods: + 1. [`More`](./sort/heapsort.go#L114): No description provided. +2. [`MaxHeap`](./sort/heapsort.go#L3): No description provided. + + +--- +
+ stack + +--- + +##### Types + +1. [`Node`](./structure/stack/stacklinkedlist.go#L13): No description provided. + +2. [`SList`](./structure/stack/stacklinkedlistwithlist.go#L18): No description provided. + +3. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided. + + +--- +
+ transposition + +--- + +##### Functions: + +1. [`Decrypt`](./cipher/transposition/transposition.go#L82): No description provided. +2. [`Encrypt`](./cipher/transposition/transposition.go#L54): No description provided. + +--- +##### Types + +1. [`KeyMissingError`](./cipher/transposition/transposition.go#L16): No description provided. + +2. [`NoTextToEncryptError`](./cipher/transposition/transposition.go#L15): No description provided. + + +--- +
+ trie + +--- + +##### Package trie provides Trie data structures in golang. Wikipedia: https://en.wikipedia.org/wiki/Trie + +--- +##### Functions: + +1. [`NewNode`](./structure/trie/trie.go#L14): NewNode creates a new Trie node with initialized children map. + +--- +##### Types + +1. [`Node`](./structure/trie/trie.go#L7): No description provided. + + +--- +
+ xor + +--- + +##### Package xor is an encryption algorithm that operates the exclusive disjunction(XOR) ref: https://en.wikipedia.org/wiki/XOR_cipher + +--- +##### Functions: + +1. [`Decrypt`](./cipher/xor/xor.go#L19): Decrypt decrypts with Xor encryption +2. [`Encrypt`](./cipher/xor/xor.go#L10): Encrypt encrypts with Xor encryption after converting each character to byte The returned value might not be readable because there is no guarantee which is within the ASCII range If using other type such as string, []int, or some other types, add the statements for converting the type to []byte. + +--- +
+ diff --git a/conversion/binarytodecimal.go b/conversion/binarytodecimal.go index 54ac7993a..bc67745fd 100644 --- a/conversion/binarytodecimal.go +++ b/conversion/binarytodecimal.go @@ -10,7 +10,6 @@ Date: 19-Oct-2021 // Function receives a Binary Number as string and returns the Decimal number as integer. // Supported Binary number range is 0 to 2^(31-1). -// Package name. package conversion // Importing necessary package. diff --git a/conversion/decimaltobinary.go b/conversion/decimaltobinary.go index f5cc9bbbe..63ef8b1c0 100644 --- a/conversion/decimaltobinary.go +++ b/conversion/decimaltobinary.go @@ -9,7 +9,6 @@ Date: 14-Oct-2021 // Function receives a integer as a Decimal number and returns the Binary number. // Supported integer value range is 0 to 2^(31 -1). -// Package name. package conversion // Importing necessary package. diff --git a/graph/bellmanford.go b/graph/bellmanford.go index 6fe3e42c9..c9e791f6d 100644 --- a/graph/bellmanford.go +++ b/graph/bellmanford.go @@ -3,6 +3,7 @@ // It is slower than Dijkstra but capable of handling negative edge weights. // https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm // Implementation is based on the book 'Introduction to Algorithms' (CLRS) + package graph import ( diff --git a/math/binary/xorsearch_test.go b/math/binary/xorsearch_test.go index 40bc8a8ef..2168a49f6 100644 --- a/math/binary/xorsearch_test.go +++ b/math/binary/xorsearch_test.go @@ -2,6 +2,7 @@ // description: Test for Find a missing number in a sequence // author(s) [red_byte](https://github.com/i-redbyte) // see xorsearch.go + package binary import ( diff --git a/sort/countingsort.go b/sort/countingsort.go index 9ac7fbdfc..3dae5934a 100644 --- a/sort/countingsort.go +++ b/sort/countingsort.go @@ -4,7 +4,6 @@ // author [Phil](https://github.com/pschik) // see sort_test.go for a test implementation, test function TestQuickSort -// package sort provides primitives for sorting slices and user-defined collections package sort func Count(data []int) []int { diff --git a/structure/set/set.go b/structure/set/set.go index 32624b63a..00ffd0629 100644 --- a/structure/set/set.go +++ b/structure/set/set.go @@ -1,3 +1,6 @@ +// package set implements a Set using a golang map. +// This implies that only the types that are accepted as valid map keys can be used as set elements. +// For instance, do not try to Add a slice, or the program will panic. package set // New gives new set. diff --git a/structure/set/set_test.go b/structure/set/set_test.go index 35ccaa5d7..b07fe89a2 100644 --- a/structure/set/set_test.go +++ b/structure/set/set_test.go @@ -1,6 +1,3 @@ -// package set implements a Set using a golang map. -// This implies that only the types that are accepted as valid map keys can be used as set elements. -// For instance, do not try to Add a slice, or the program will panic. package set import ( diff --git a/structure/set/setexample_test.go b/structure/set/setexample_test.go index 801298217..7cd929462 100644 --- a/structure/set/setexample_test.go +++ b/structure/set/setexample_test.go @@ -1,7 +1,3 @@ -// package set implements a Set using a golang map. -// This implies that only the types that are accepted as valid map keys can be used as set elements. -// For instance, do not try to Add a slice, or the program will panic. -// package set import ( From a671c904d9153474c9ca85d0bdf27b132afc25c7 Mon Sep 17 00:00:00 2001 From: Taj Date: Wed, 10 Nov 2021 04:30:08 +0000 Subject: [PATCH 005/202] fix: godocmd (#432) --- .github/workflows/godocmd.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index 86abaa4cc..6494d6bd7 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -5,6 +5,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 + with: + fetch-depth: 0 - uses: actions/setup-go@v2 with: go-version: '^1.17' From 9f8a45b39b9cb645d6d6f6b13ffa3d1cc3830730 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Wed, 10 Nov 2021 08:00:24 +0300 Subject: [PATCH 006/202] merge: Feat/catalan number (#430) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: Catalan number * fix: add details * fix: change test struct * Updated Documentation in README.md Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 10 ++++++++ math/catalan/catalannumber.go | 17 ++++++++++++++ math/catalan/catalannumber_test.go | 37 ++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 math/catalan/catalannumber.go create mode 100644 math/catalan/catalannumber_test.go diff --git a/README.md b/README.md index 9d6dc902a..a6d6afd99 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Decrypt`](./cipher/caesar/caesar.go#L27): Decrypt decrypts by left shift of "key" each character of "input" 2. [`Encrypt`](./cipher/caesar/caesar.go#L6): Encrypt encrypts by right shift of "key" each character of "input" +--- +
+ catalan + +--- + +##### Functions: + +1. [`CatalanNumber`](./math/catalan/catalannumber.go#L15): No description provided. + ---
coloring diff --git a/math/catalan/catalannumber.go b/math/catalan/catalannumber.go new file mode 100644 index 000000000..b899d2569 --- /dev/null +++ b/math/catalan/catalannumber.go @@ -0,0 +1,17 @@ +// catalannumber.go +// description: Returns the Catalan number +// details: +// In combinatorial mathematics, the Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. - [Catalan number](https://en.wikipedia.org/wiki/Catalan_number) +// The input is the number of the Catalan number n, at the output we get the value of the number +// author(s) [red_byte](https://github.com/i-redbyte) +// see catalannumber_test.go + +package catalan + +import ( + f "github.com/TheAlgorithms/Go/math/factorial" +) + +func CatalanNumber(n int) int { + return f.BruteForceFactorial(n*2) / (f.BruteForceFactorial(n) * f.BruteForceFactorial(n+1)) +} diff --git a/math/catalan/catalannumber_test.go b/math/catalan/catalannumber_test.go new file mode 100644 index 000000000..6d7896d35 --- /dev/null +++ b/math/catalan/catalannumber_test.go @@ -0,0 +1,37 @@ +// catalannumber_test.go +// description: Test for returns the Catalan number +// author(s) [red_byte](https://github.com/i-redbyte) +// see catalannumber.go + +package catalan + +import "testing" + +func TestCatalanNumber(t *testing.T) { + tests := []struct { + name string + n int + want int + }{ + {"zero Catalan number ", 0, 1}, + {"second Catalan number ", 2, 2}, + {"third Catalan number ", 3, 5}, + {"fourth Catalan number ", 4, 14}, + {"fifth Catalan number ", 5, 42}, + {"sixth Catalan number ", 6, 132}, + {"tenth Catalan number ", 10, 16796}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := CatalanNumber(test.n); got != test.want { + t.Errorf("CatalanNumber() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkCatalanNumber(b *testing.B) { + for i := 0; i < b.N; i++ { + CatalanNumber(10) + } +} From 37cb38e9d91f675ef3b2f53663d8fb5a6fce6159 Mon Sep 17 00:00:00 2001 From: kavithajm <91771245+kavithajm@users.noreply.github.com> Date: Fri, 12 Nov 2021 00:22:11 +0530 Subject: [PATCH 007/202] Comb Sort algorithm implementation (#407) * Adding comb sort * Update sort/combSort.go Co-authored-by: Taj * Updating test for comb sort * Updated Documentation in README.md Co-authored-by: Taj Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 27 ++++++++++++++------------- sort/combSort.go | 30 ++++++++++++++++++++++++++++++ sort/sorts_test.go | 8 ++++++++ 3 files changed, 52 insertions(+), 13 deletions(-) create mode 100644 sort/combSort.go diff --git a/README.md b/README.md index a6d6afd99..a5c904b18 100644 --- a/README.md +++ b/README.md @@ -758,19 +758,20 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`Count`](./sort/countingsort.go#L9): No description provided. -2. [`Exchange`](./sort/exchangesort.go#L6): No description provided. -3. [`HeapSort`](./sort/heapsort.go#L121): No description provided. -4. [`ImprovedSimpleSort`](./sort/simplesort.go#L25): ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort -5. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. -6. [`Mergesort`](./sort/mergesort.go#L35): Mergesort Perform mergesort on a slice of ints -7. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -8. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array -9. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array -10. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -11. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. -12. [`ShellSort`](./sort/shellsort.go#L3): No description provided. -13. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. +1. [`Comb`](./sort/combSort.go#L14): No description provided. +2. [`Count`](./sort/countingsort.go#L9): No description provided. +3. [`Exchange`](./sort/exchangesort.go#L6): No description provided. +4. [`HeapSort`](./sort/heapsort.go#L121): No description provided. +5. [`ImprovedSimpleSort`](./sort/simplesort.go#L25): ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +6. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. +7. [`Mergesort`](./sort/mergesort.go#L35): Mergesort Perform mergesort on a slice of ints +8. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +9. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array +10. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array +11. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +12. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. +13. [`ShellSort`](./sort/shellsort.go#L3): No description provided. +14. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. --- ##### Types diff --git a/sort/combSort.go b/sort/combSort.go new file mode 100644 index 000000000..fa7b173d9 --- /dev/null +++ b/sort/combSort.go @@ -0,0 +1,30 @@ +// Implementation of comb sort algorithm, an improvement of bubble sort +// Reference: https://www.geeksforgeeks.org/comb-sort/ + +package sort + +func getNextGap(gap int) int { + gap = (gap * 10) / 13 + if gap < 1 { + return 1 + } + return gap +} + +func Comb(data []int) []int { + n := len(data) + gap := n + swapped := true + + for gap != 1 || swapped { + gap = getNextGap(gap) + swapped = false + for i := 0; i < n-gap; i++ { + if data[i] > data[i+gap] { + data[i], data[i+gap] = data[i+gap], data[i] + swapped = true + } + } + } + return data +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 5342121cc..be239205e 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -122,6 +122,10 @@ func TestSelection(t *testing.T) { testFramework(t, SelectionSort) } +func TestComb(t *testing.T) { + testFramework(t, Comb) +} + func TestPigeonhole(t *testing.T) { testFramework(t, Pigeonhole) } @@ -216,6 +220,10 @@ func BenchmarkSelection(b *testing.B) { benchmarkFramework(b, SelectionSort) } +func BenchmarkComb(b *testing.B) { + benchmarkFramework(b, Comb) +} + func BenchmarkPigeonhole(b *testing.B) { benchmarkFramework(b, Pigeonhole) } From eb39cb7b8f1d2aedc32a80856e15d2c6da672324 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Fri, 12 Nov 2021 09:57:55 +0300 Subject: [PATCH 008/202] Feat/pascal (#433) Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 10 ++++++++ math/pascal/pascaltriangle.go | 34 +++++++++++++++++++++++++++ math/pascal/pascaltriangle_test.go | 37 ++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 math/pascal/pascaltriangle.go create mode 100644 math/pascal/pascaltriangle_test.go diff --git a/README.md b/README.md index a5c904b18..706c86e9a 100644 --- a/README.md +++ b/README.md @@ -565,6 +565,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided. +--- +
+ pascal + +--- + +##### Functions: + +1. [`GenerateTriangle`](./math/pascal/pascaltriangle.go#L24): GenerateTriangle This function generates a Pascal's triangle of n lines + ---
password diff --git a/math/pascal/pascaltriangle.go b/math/pascal/pascaltriangle.go new file mode 100644 index 000000000..12f227fd0 --- /dev/null +++ b/math/pascal/pascaltriangle.go @@ -0,0 +1,34 @@ +// pascaltriangle.go +// description: Pascal's triangle +// details: +// Pascal's triangle is a triangular array of the binomial coefficients that arises in probability theory, combinatorics, and algebra. - [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) +// example: +//1 +//1 1 +//1 2 1 +//1 3 3 1 +//1 4 6 4 1 +//1 5 10 10 5 1 +//1 6 15 20 15 6 1 +//1 7 21 35 35 21 7 1 +//1 8 28 56 70 56 28 8 1 +//1 9 36 84 126 126 84 36 9 1 +//1 10 45 120 210 252 210 120 45 10 1 +//... +// author(s) [red_byte](https://github.com/i-redbyte) +// see pascaltriangle_test.go + +package pascal + +// GenerateTriangle This function generates a Pascal's triangle of n lines +func GenerateTriangle(n int) [][]int { + var triangle = make([][]int, n) + for i := 0; i < n; i++ { + triangle[i] = make([]int, i+1) + triangle[i][0], triangle[i][i] = 1, 1 + for j := 1; j < i; j++ { + triangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1] + } + } + return triangle +} diff --git a/math/pascal/pascaltriangle_test.go b/math/pascal/pascaltriangle_test.go new file mode 100644 index 000000000..33fe53e2c --- /dev/null +++ b/math/pascal/pascaltriangle_test.go @@ -0,0 +1,37 @@ +// pascaltriangle_test.go +// description: Test for Pascal's triangle +// author(s) [red_byte](https://github.com/i-redbyte) +// see pascaltriangle.go + +package pascal + +import ( + "reflect" + "testing" +) + +func TestGenerateTriangle(t *testing.T) { + tests := []struct { + name string + n int + want [][]int + }{ + {name: "Pascal's three-line triangle", n: 3, want: [][]int{{1}, {1, 1}, {1, 2, 1}}}, + {name: "Pascal's 0-line triangle", n: 0, want: [][]int{}}, + {name: "Pascal's one-line triangle", n: 1, want: [][]int{{1}}}, + {name: "Pascal's 7-line triangle", n: 7, want: [][]int{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := GenerateTriangle(test.n); !reflect.DeepEqual(got, test.want) { + t.Errorf("GenerateTriangle() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkGenerateTriangle(b *testing.B) { + for i := 0; i < b.N; i++ { + GenerateTriangle(10) + } +} From 28b4df5eab31f96a71ea3e4d7b69df033b8d2e52 Mon Sep 17 00:00:00 2001 From: Michele Caci Date: Fri, 12 Nov 2021 23:39:59 +0100 Subject: [PATCH 009/202] test: improve coverage on hashmap package (#435) * test: improve coverage on hashmap package * Updated Documentation in README.md Co-authored-by: Michele Caci Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 3 ++- structure/hashmap/hashmap.go | 9 +++++++++ structure/hashmap/hashmap_test.go | 30 ++++++++++++++++++++++++++---- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 706c86e9a..cc96f6fe3 100644 --- a/README.md +++ b/README.md @@ -386,7 +386,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`New`](./structure/hashmap/hashmap.go#L24): New return new HashMap instance +1. [`Make`](./structure/hashmap/hashmap.go#L32): Make creates a new HashMap instance with input size and capacity +2. [`New`](./structure/hashmap/hashmap.go#L24): New return new HashMap instance --- ##### Types diff --git a/structure/hashmap/hashmap.go b/structure/hashmap/hashmap.go index bd03e641f..1665a50c7 100644 --- a/structure/hashmap/hashmap.go +++ b/structure/hashmap/hashmap.go @@ -28,6 +28,15 @@ func New() *HashMap { } } +// Make creates a new HashMap instance with input size and capacity +func Make(size, capacity uint64) HashMap { + return HashMap{ + size: size, + capacity: capacity, + table: make([]*node, capacity), + } +} + // Get returns value associated with given key func (hm *HashMap) Get(key interface{}) interface{} { node := hm.getNodeByHash(hm.hash(key)) diff --git a/structure/hashmap/hashmap_test.go b/structure/hashmap/hashmap_test.go index 64a276d46..2b0030b7e 100644 --- a/structure/hashmap/hashmap_test.go +++ b/structure/hashmap/hashmap_test.go @@ -1,12 +1,14 @@ -package hashmap +package hashmap_test import ( "testing" + + "github.com/TheAlgorithms/Go/structure/hashmap" ) func TestHashMap(t *testing.T) { - mp := New() + mp := hashmap.New() t.Run("Test 1: Put(10) and checking if Get() is correct", func(t *testing.T) { mp.Put("test", 10) @@ -48,12 +50,32 @@ func TestHashMap(t *testing.T) { } }) - t.Run("Test 6: Checking if the key that doesn't exists returns false", func(t *testing.T) { + t.Run("Test 6: Checking if the key that does not exist returns false", func(t *testing.T) { want := false got := mp.Contains(2) if got != want { - t.Errorf("Key '2' doesn't exists in the map but it says otherwise") + t.Errorf("Key '2' does not exist in the map but it says otherwise") + } + }) + + t.Run("Test 7: Checking if the key does not exist Get func returns nil", func(t *testing.T) { + want := interface{}(nil) + got := mp.Get(2) + if got != want { + t.Errorf("Key '2' does not exists in the map but it says otherwise") } }) + t.Run("Test 8: Resizing a map", func(t *testing.T) { + mp := hashmap.Make(4, 4) + + for i := 0; i < 20; i++ { + mp.Put(i, 40) + } + + got := mp.Get(5) + if got != 40 { + t.Errorf("Put: %v, Got: %v", got, 40) + } + }) } From e9ba9c447d7084caa6bf68b944ee881a41a68ca3 Mon Sep 17 00:00:00 2001 From: kavithajm <91771245+kavithajm@users.noreply.github.com> Date: Wed, 17 Nov 2021 14:17:12 +0530 Subject: [PATCH 010/202] merge: Add Pangram program (#441) * Add Pangram program * Updated Documentation in README.md Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 10 ++++++ strings/pangram/ispangram.go | 31 ++++++++++++++++++ strings/pangram/ispangram_test.go | 53 +++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 strings/pangram/ispangram.go create mode 100644 strings/pangram/ispangram_test.go diff --git a/README.md b/README.md index cc96f6fe3..aad7edd56 100644 --- a/README.md +++ b/README.md @@ -566,6 +566,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided. +--- +
+ pangram + +--- + +##### Functions: + +1. [`IsPangram`](./strings/pangram/ispangram.go#L21): No description provided. + ---
pascal diff --git a/strings/pangram/ispangram.go b/strings/pangram/ispangram.go new file mode 100644 index 000000000..18d9f90b4 --- /dev/null +++ b/strings/pangram/ispangram.go @@ -0,0 +1,31 @@ +// ispangram.go +// description: Checks if a given string is pangram or not +// details: A pangram is a sentence or expression that uses all the letters of the alphabet. +// Reference: https://www.geeksforgeeks.org/pangram-checking/ +// Author : Kavitha J + +package pangram + +import ( + "regexp" + "strings" +) + +func cleanString(text string) string { + cleanText := strings.ToLower(text) // Convert to lowercase + cleanText = strings.Join(strings.Fields(cleanText), "") // Remove spaces + regex, _ := regexp.Compile(`[^\p{L}\p{N} ]+`) // Regular expression for alphanumeric only characters + return regex.ReplaceAllString(cleanText, "") +} + +func IsPangram(text string) bool { + cleanText := cleanString(text) + if len(cleanText) < 26 { + return false + } + var data = make(map[rune]bool) + for _, i := range cleanText { + data[i] = true + } + return len(data) == 26 +} diff --git a/strings/pangram/ispangram_test.go b/strings/pangram/ispangram_test.go new file mode 100644 index 000000000..29e48de21 --- /dev/null +++ b/strings/pangram/ispangram_test.go @@ -0,0 +1,53 @@ +package pangram + +import ( + "testing" +) + +var testCases = []struct { + name string // test description + input string // user input + expected bool // expected return +}{ + { + "empty string", + "", + false, + }, + { + "non pangram string without spaces", + "abc", + false, + }, + { + "non pangram string with spaces", + "Hello World", + false, + }, + { + "Pangram string 1", + " Abcdefghijklmnopqrstuvwxyz", + true, + }, + { + "pangram string 2", + "cdefghijklmnopqrstuvwxABC zyb", + true, + }, + { + "pangram string 3", + "The Quick Brown Fox Jumps Over the Lazy Dog", + true, + }, +} + +func TestIsPangram(t *testing.T) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + func_result := IsPangram(test.input) + if test.expected != func_result { + t.Errorf("Expected answer '%t' for string '%s' but answer given was %t", test.expected, test.input, func_result) + } + }) + } +} From 9fec515fa43429012d1eba1b4924d8db953d36a4 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Wed, 17 Nov 2021 11:55:08 +0300 Subject: [PATCH 011/202] merge: Feat: bits counter (#439) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: bits counter * Updated Documentation in README.md * fix: change test cases name Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 13 +++++++------ math/binary/bitcounter.go | 20 ++++++++++++++++++++ math/binary/bitcounter_test.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 math/binary/bitcounter.go create mode 100644 math/binary/bitcounter_test.go diff --git a/README.md b/README.md index aad7edd56..d8a2b8894 100644 --- a/README.md +++ b/README.md @@ -79,12 +79,13 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. -2. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 -3. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L11): No description provided. -4. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L15): No description provided. -5. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -6. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L10): No description provided. +1. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number +2. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. +3. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 +4. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L11): No description provided. +5. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L15): No description provided. +6. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. +7. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L10): No description provided. ---
diff --git a/math/binary/bitcounter.go b/math/binary/bitcounter.go new file mode 100644 index 000000000..33e24256d --- /dev/null +++ b/math/binary/bitcounter.go @@ -0,0 +1,20 @@ +// bitcounter.go +// description: Counts the number of set bits in a number +// details: +// For unsigned integer number N, return the number of bits set to 1 - [Bit numbering](https://en.wikipedia.org/wiki/Bit_numbering) +// author(s) [red_byte](https://github.com/i-redbyte) +// see bitcounter_test.go + +package binary + +// BitCounter - The function returns the number of set bits for an unsigned integer number +func BitCounter(n uint) int { + counter := 0 + for n != 0 { + if n&1 == 1 { + counter++ + } + n >>= 1 + } + return counter +} diff --git a/math/binary/bitcounter_test.go b/math/binary/bitcounter_test.go new file mode 100644 index 000000000..f5d61ec3f --- /dev/null +++ b/math/binary/bitcounter_test.go @@ -0,0 +1,33 @@ +// bitcounter_test.go +// description: Test for counts the number of set bits in a number +// author(s) [red_byte](https://github.com/i-redbyte) +// see bitcounter.go + +package binary + +import "testing" + +func TestBitCounter(t *testing.T) { + tests := []struct { + name string + number uint + want int + }{ + {"Number of bits in a number 0", 0, 0}, + {"Number of bits in a number 1", 1, 1}, + {"Number of bits in a number 255", 255, 8}, + {"Number of bits in a number 7", 7, 3}, + {"Number of bits in a number 8", 8, 1}, + {"Number of bits in a number 9223372036854775807", 9223372036854775807, 63}, + {"Number of bits in a number 2147483647", 2147483647, 31}, + {"Number of bits in a number 15", 15, 4}, + {"Number of bits in a number 16", 16, 1}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := BitCounter(test.number); got != test.want { + t.Errorf("BitCounter() = %v, want %v", got, test.want) + } + }) + } +} From 57a20cf48ea0d2dcdb63bf50da65977e358189ff Mon Sep 17 00:00:00 2001 From: kavithajm <91771245+kavithajm@users.noreply.github.com> Date: Fri, 19 Nov 2021 22:41:09 +0530 Subject: [PATCH 012/202] Adding program to check if the number is an Armstrong number (#442) * Adding program to check if the number is an armstrong number * Updated Documentation in README.md * Update loop in isarmstrong Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 10 ++++++ math/armstrong/isarmstrong.go | 32 ++++++++++++++++++ math/armstrong/isarmstrong_test.go | 53 ++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 math/armstrong/isarmstrong.go create mode 100644 math/armstrong/isarmstrong_test.go diff --git a/README.md b/README.md index d8a2b8894..f88a49ea1 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Result`](./strings/ahocorasick/ahocorasick.go#L9): No description provided. +--- +
+ armstrong + +--- + +##### Functions: + +1. [`IsArmstrong`](./math/armstrong/isarmstrong.go#L14): No description provided. + ---
avl diff --git a/math/armstrong/isarmstrong.go b/math/armstrong/isarmstrong.go new file mode 100644 index 000000000..68055dee8 --- /dev/null +++ b/math/armstrong/isarmstrong.go @@ -0,0 +1,32 @@ +// isarmstrong.go +// description: Checks if the given number is armstrong number or not +// details: An Armstrong number is a n-digit number that is equal to the sum of each of its digits taken to the nth power. +// ref: https://mathlair.allfunandgames.ca/armstrong.php +// author: Kavitha J + +package armstrong + +import ( + "math" + "strconv" +) + +func IsArmstrong(number int) bool { + var rightMost int + var sum int = 0 + var tempNum int = number + + // to get the number of digits in the number + length := float64(len(strconv.Itoa(number))) + + // get the right most digit and break the loop once all digits are iterated + for tempNum > 0 { + rightMost = tempNum % 10 + sum += int(math.Pow(float64(rightMost), length)) + + // update the input digit minus the processed rightMost + tempNum /= 10 + } + + return number == sum +} diff --git a/math/armstrong/isarmstrong_test.go b/math/armstrong/isarmstrong_test.go new file mode 100644 index 000000000..bab9601c8 --- /dev/null +++ b/math/armstrong/isarmstrong_test.go @@ -0,0 +1,53 @@ +// isarmstrong_test.go + +package armstrong + +import "testing" + +var testCases = []struct { + name string // test description + input int // user input + expected bool // expected return +}{ + { + "negative number: Not an armstrong number", + -140, + false, + }, + { + "positive number: Not an armstrong number", + 23, + false, + }, + { + "smallest armstrong number", + 0, + true, + }, + { + "smallest armstrong number with more than one digit", + 153, + true, + }, + { + "random armstrong number", + 407, + true, + }, + { + "random armstrong number", + 9474, + true, + }, +} + +func TestIsArmstrong(t *testing.T) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + funcResult := IsArmstrong(test.input) + if test.expected != funcResult { + t.Errorf("Expected answer '%t' for the number '%d' but answer given was %t", test.expected, test.input, funcResult) + } + }) + } +} From 6fd8a07848d9ac72601205777714f7b86474bf06 Mon Sep 17 00:00:00 2001 From: Paul Leydier <75126792+paul-leydier@users.noreply.github.com> Date: Fri, 19 Nov 2021 19:44:12 +0100 Subject: [PATCH 013/202] feat: add Conversion/base64 algorithm (#437) * feat: base64 encoding * test: base64 encoding * docs: Added base64 declaration to README.md * feat: use string builder to drastically improve efficiency of Encode * docs: formatting * feat: base64 decoding * test: base64 decoding * docs: added base64 Decode function to README.md * test: test base64 Encode and Decode inverse functions * docs: base64 Decode docstring * docs: improve package documentation Co-authored-by: Taj * feat: remove usage of predefined return values * feat: base64 move to conversion package * fix: remove deleted line in README.md * Update conversion/base64.go * Update conversion/base64.go Co-authored-by: Taj Co-authored-by: Rak Laptudirm Co-authored-by: Andrii Siriak --- conversion/base64.go | 81 ++++++++++++++++++++++++++++ conversion/base64_test.go | 111 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+) create mode 100644 conversion/base64.go create mode 100644 conversion/base64_test.go diff --git a/conversion/base64.go b/conversion/base64.go new file mode 100644 index 000000000..8828f6a7a --- /dev/null +++ b/conversion/base64.go @@ -0,0 +1,81 @@ +// base64.go +// description: The base64 encoding algorithm as defined in the RFC4648 standard. +// author: [Paul Leydier] (https://github.com/paul-leydier) +// ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4 +// ref: https://en.wikipedia.org/wiki/Base64 +// see base64_test.go + +package conversion + +import ( + "strings" // Used for efficient string builder (more efficient than simply appending strings) +) + +const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + +// Base64Encode encodes the received input bytes slice into a base64 string. +// The implementation follows the RFC4648 standard, which is documented +// at https://datatracker.ietf.org/doc/html/rfc4648#section-4 +func Base64Encode(input []byte) string { + var sb strings.Builder + // If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output + var padding string + for i := len(input) % 3; i > 0 && i < 3; i++ { + var zeroByte byte + input = append(input, zeroByte) + padding += "=" + } + + // encode 24 bits per 24 bits (3 bytes per 3 bytes) + for i := 0; i < len(input); i += 3 { + // select 3 8-bit input groups, and re-arrange them into 4 6-bit groups + // the literal 0x3F corresponds to the byte "0011 1111" + // the operation "byte & 0x3F" masks the two left-most bits + group := [4]byte{ + input[i] >> 2, + (input[i]<<4)&0x3F + input[i+1]>>4, + (input[i+1]<<2)&0x3F + input[i+2]>>6, + input[i+2] & 0x3F, + } + + // translate each group into a char using the static map + for _, b := range group { + sb.WriteString(string(Alphabet[int(b)])) + } + } + encoded := sb.String() + + // Apply the output padding + encoded = encoded[:len(encoded)-len(padding)] + padding[:] + + return encoded +} + +// Base64Decode decodes the received input base64 string into a byte slice. +// The implementation follows the RFC4648 standard, which is documented +// at https://datatracker.ietf.org/doc/html/rfc4648#section-4 +func Base64Decode(input string) []byte { + padding := strings.Count(input, "=") // Number of bytes which will be ignored + var decoded []byte + + // select 4 6-bit input groups, and re-arrange them into 3 8-bit groups + for i := 0; i < len(input); i += 4 { + // translate each group into a byte using the static map + byteInput := [4]byte{ + byte(strings.IndexByte(Alphabet, input[i])), + byte(strings.IndexByte(Alphabet, input[i+1])), + byte(strings.IndexByte(Alphabet, input[i+2])), + byte(strings.IndexByte(Alphabet, input[i+3])), + } + + group := [3]byte{ + byteInput[0]<<2 + byteInput[1]>>4, + byteInput[1]<<4 + byteInput[2]>>2, + byteInput[2]<<6 + byteInput[3], + } + + decoded = append(decoded, group[:]...) + } + + return decoded[:len(decoded)-padding] +} diff --git a/conversion/base64_test.go b/conversion/base64_test.go new file mode 100644 index 000000000..ed882634c --- /dev/null +++ b/conversion/base64_test.go @@ -0,0 +1,111 @@ +package conversion + +import "testing" + +func TestBase64Encode(t *testing.T) { + testCases := []struct { + in string + expected string + }{ + {"Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits) + {"Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1 + {"Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2 + {"", ""}, // empty byte slice + {"6", "Ng=="}, // short text + {"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text + } + + for _, tc := range testCases { + result := Base64Encode([]byte(tc.in)) + if result != tc.expected { + t.Fatalf("Base64Encode(%s) = %s, want %s", tc.in, result, tc.expected) + } + } +} + +func BenchmarkBase64Encode(b *testing.B) { + benchmarks := []struct { + name string + in string + expected string + }{ + {"Hello World!", "Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits) + {"Hello World!a", "Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1 + {"Hello World!ab", "Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2 + {"Empty", "", ""}, // empty byte slice + {"6", "6", "Ng=="}, // short text + {"Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text + } + + for _, bm := range benchmarks { + b.Run(bm.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + Base64Encode([]byte(bm.in)) + } + }) + } +} + +func TestBase64Decode(t *testing.T) { + testCases := []struct { + expected string + in string + }{ + {"Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits) + {"Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1 + {"Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2 + {"", ""}, // empty byte slice + {"6", "Ng=="}, // short text + {"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text + } + + for _, tc := range testCases { + result := string(Base64Decode(tc.in)) + if result != tc.expected { + t.Fatalf("Base64Decode(%s) = %s, want %s", tc.in, result, tc.expected) + } + } +} + +func BenchmarkBase64Decode(b *testing.B) { + benchmarks := []struct { + name string + expected string + in string + }{ + {"Hello World!", "Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits) + {"Hello World!a", "Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1 + {"Hello World!ab", "Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2 + {"Empty", "", ""}, // empty byte slice + {"6", "6", "Ng=="}, // short text + {"Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text + } + + for _, bm := range benchmarks { + b.Run(bm.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + Base64Decode(bm.in) + } + }) + } +} + +func TestBase64EncodeDecodeInverse(t *testing.T) { + testCases := []struct { + in string + }{ + {"Hello World!"}, // multiple of 3 byte length (multiple of 24-bits) + {"Hello World!a"}, // multiple of 3 byte length + 1 + {"Hello World!ab"}, // multiple of 3 byte length + 2 + {""}, // empty byte slice + {"6"}, // short text + {"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}, // Long text + } + + for _, tc := range testCases { + result := string(Base64Decode(Base64Encode([]byte(tc.in)))) + if result != tc.in { + t.Fatalf("Base64Decode(Base64Encode(%s)) = %s, want %s", tc.in, result, tc.in) + } + } +} From 385fe843dfe8de60dc9fb4288d2c7d7ed4d843f6 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Mon, 22 Nov 2021 16:38:14 +0300 Subject: [PATCH 014/202] fix: docs (#445) Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 34 ++++++++++++++-------------- math/binary/arithmeticmean.go | 2 ++ math/binary/xorsearch.go | 1 + math/catalan/catalannumber.go | 3 ++- math/factorial/factorial.go | 11 +++++---- math/factorial/factorial_test.go | 12 +++++----- math/max/bitwisemax.go | 3 ++- math/max/bitwisemax_test.go | 38 ++++++++++++++++---------------- math/min/bitwisemin.go | 1 + 9 files changed, 58 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index f88a49ea1..1fca7fa00 100644 --- a/README.md +++ b/README.md @@ -92,10 +92,10 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number 2. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. 3. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 -4. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L11): No description provided. -5. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L15): No description provided. +4. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations +5. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift 6. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -7. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L10): No description provided. +7. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
@@ -146,7 +146,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`CatalanNumber`](./math/catalan/catalannumber.go#L15): No description provided. +1. [`CatalanNumber`](./math/catalan/catalannumber.go#L16): CatalanNumber This function returns the `nth` Catalan number ---
@@ -197,13 +197,15 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return it's Decimal equivalent as integer. -2. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. -3. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue -4. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. -5. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex -6. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. -7. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. +1. [`Base64Decode`](./conversion/base64.go#L57): Base64Decode decodes the received input base64 string into a byte slice. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4 +2. [`Base64Encode`](./conversion/base64.go#L19): Base64Encode encodes the received input bytes slice into a base64 string. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4 +3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return it's Decimal equivalent as integer. +4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. +5. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue +6. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. +7. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex +8. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. +9. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. ---
@@ -272,9 +274,9 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`BruteForceFactorial`](./math/factorial/factorial.go#L11): No description provided. -2. [`CalculateFactorialUseTree`](./math/factorial/factorial.go#L27): No description provided. -3. [`RecursiveFactorial`](./math/factorial/factorial.go#L19): No description provided. +1. [`Iterative`](./math/factorial/factorial.go#L12): Iterative returns the iteratively brute forced factorial of n +2. [`Recursive`](./math/factorial/factorial.go#L21): Recursive This function recursively computes the factorial of a number +3. [`UsingTree`](./math/factorial/factorial.go#L30): UsingTree This function finds the factorial of a number using a binary tree ---
@@ -505,7 +507,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`BitwiseMax`](./math/max/bitwisemax.go#L10): No description provided. +1. [`Bitwise`](./math/max/bitwisemax.go#L11): Bitwise computes using bitwise operator the maximum of all the integer input and returns it 2. [`Int`](./math/max/max.go#L4): Int is a function which returns the maximum of all the integers provided as arguments. --- @@ -529,7 +531,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Bitwise`](./math/min/bitwisemin.go#L10): No description provided. +1. [`Bitwise`](./math/min/bitwisemin.go#L11): Bitwise This function returns the minimum integer using bit operations 2. [`Int`](./math/min/min.go#L4): Int is a function which returns the minimum of all the integers provided as arguments. --- diff --git a/math/binary/arithmeticmean.go b/math/binary/arithmeticmean.go index 3fbce0631..9fa56560e 100644 --- a/math/binary/arithmeticmean.go +++ b/math/binary/arithmeticmean.go @@ -8,10 +8,12 @@ // Package binary describes algorithms that use binary operations for different calculations. package binary +// MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations func MeanUsingAndXor(a int, b int) int { return ((a ^ b) >> 1) + (a & b) } +// MeanUsingRightShift This function finds arithmetic mean using right shift func MeanUsingRightShift(a int, b int) int { return (a + b) >> 1 } diff --git a/math/binary/xorsearch.go b/math/binary/xorsearch.go index cdd4e09c8..b16b7846b 100644 --- a/math/binary/xorsearch.go +++ b/math/binary/xorsearch.go @@ -7,6 +7,7 @@ package binary +// XorSearchMissingNumber This function finds a missing number in a sequence func XorSearchMissingNumber(a []int) int { n := len(a) result := len(a) diff --git a/math/catalan/catalannumber.go b/math/catalan/catalannumber.go index b899d2569..31a424347 100644 --- a/math/catalan/catalannumber.go +++ b/math/catalan/catalannumber.go @@ -12,6 +12,7 @@ import ( f "github.com/TheAlgorithms/Go/math/factorial" ) +// CatalanNumber This function returns the `nth` Catalan number func CatalanNumber(n int) int { - return f.BruteForceFactorial(n*2) / (f.BruteForceFactorial(n) * f.BruteForceFactorial(n+1)) + return f.Iterative(n*2) / (f.Iterative(n) * f.Iterative(n+1)) } diff --git a/math/factorial/factorial.go b/math/factorial/factorial.go index 2d376a87b..6b7f5f516 100644 --- a/math/factorial/factorial.go +++ b/math/factorial/factorial.go @@ -8,7 +8,8 @@ // Package factorial describes algorithms Factorials calculations. package factorial -func BruteForceFactorial(n int) int { +// Iterative returns the iteratively brute forced factorial of n +func Iterative(n int) int { result := 1 for i := 2; i <= n; i++ { result *= i @@ -16,15 +17,17 @@ func BruteForceFactorial(n int) int { return result } -func RecursiveFactorial(n int) int { +// Recursive This function recursively computes the factorial of a number +func Recursive(n int) int { if n == 1 { return 1 } else { - return n * RecursiveFactorial(n-1) + return n * Recursive(n-1) } } -func CalculateFactorialUseTree(n int) int { +// UsingTree This function finds the factorial of a number using a binary tree +func UsingTree(n int) int { if n < 0 { return 0 } diff --git a/math/factorial/factorial_test.go b/math/factorial/factorial_test.go index 9a083441d..04eceb973 100644 --- a/math/factorial/factorial_test.go +++ b/math/factorial/factorial_test.go @@ -30,7 +30,7 @@ func TestBruteForceFactorial(t *testing.T) { tests := getTests() for _, tv := range tests { t.Run(tv.name, func(t *testing.T) { - result := BruteForceFactorial(tv.n) + result := Iterative(tv.n) if result != tv.result { t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) } @@ -42,7 +42,7 @@ func TestRecursiveFactorial(t *testing.T) { tests := getTests() for _, tv := range tests { t.Run(tv.name, func(t *testing.T) { - result := RecursiveFactorial(tv.n) + result := Recursive(tv.n) if result != tv.result { t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) } @@ -54,7 +54,7 @@ func TestCalculateFactorialUseTree(t *testing.T) { tests := getTests() for _, tv := range tests { t.Run(tv.name, func(t *testing.T) { - result := CalculateFactorialUseTree(tv.n) + result := UsingTree(tv.n) if result != tv.result { t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) } @@ -64,18 +64,18 @@ func TestCalculateFactorialUseTree(t *testing.T) { func BenchmarkBruteForceFactorial(b *testing.B) { for i := 0; i < b.N; i++ { - BruteForceFactorial(10) + Iterative(10) } } func BenchmarkRecursiveFactorial(b *testing.B) { for i := 0; i < b.N; i++ { - RecursiveFactorial(10) + Recursive(10) } } func BenchmarkCalculateFactorialUseTree(b *testing.B) { for i := 0; i < b.N; i++ { - RecursiveFactorial(10) + Recursive(10) } } diff --git a/math/max/bitwisemax.go b/math/max/bitwisemax.go index ece9c4dbe..b6c3a4623 100644 --- a/math/max/bitwisemax.go +++ b/math/max/bitwisemax.go @@ -7,7 +7,8 @@ package max -func BitwiseMax(a int, b int, base int) int { +// Bitwise computes using bitwise operator the maximum of all the integer input and returns it +func Bitwise(a int, b int, base int) int { z := a - b i := (z >> base) & 1 return a - (i * z) diff --git a/math/max/bitwisemax_test.go b/math/max/bitwisemax_test.go index addf45733..c28bb1cf6 100644 --- a/math/max/bitwisemax_test.go +++ b/math/max/bitwisemax_test.go @@ -1,5 +1,5 @@ // bitwiseMax_test.go -// description: Test for BitwiseMax +// description: Test for Bitwise // author(s) [red_byte](https://github.com/i-redbyte) // see bitwiseMax.go @@ -11,67 +11,67 @@ func TestBitwiseMax(t *testing.T) { base32 := 31 t.Run("Testing(32bit) a = 32 and m = 64: ", func(t *testing.T) { - max := BitwiseMax(32, 64, base32) + max := Bitwise(32, 64, base32) if max != 64 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(32bit) a = 1024 and m = -9: ", func(t *testing.T) { - max := BitwiseMax(1024, -9, base32) + max := Bitwise(1024, -9, base32) if max != 1024 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(32bit) a = -6 and m = -6: ", func(t *testing.T) { - max := BitwiseMax(-6, -6, base32) + max := Bitwise(-6, -6, base32) if max != -6 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(32bit) a = -72 and m = -73: ", func(t *testing.T) { - max := BitwiseMax(-72, -73, base32) + max := Bitwise(-72, -73, base32) if max != -72 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) base64 := 63 t.Run("Testing(64bit) a = 32 and m = 9223372036854775807: ", func(t *testing.T) { - max := BitwiseMax(32, 9223372036854775807, base64) + max := Bitwise(32, 9223372036854775807, base64) if max != 9223372036854775807 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(64bit) a = 1024 and m = -9223372036854770001: ", func(t *testing.T) { - max := BitwiseMax(1024, -9223372036854770001, base64) + max := Bitwise(1024, -9223372036854770001, base64) if max != 1024 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(64bit) a = -6 and m = -6: ", func(t *testing.T) { - max := BitwiseMax(-6, -6, base64) + max := Bitwise(-6, -6, base64) if max != -6 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) t.Run("Testing(64bit) a = -4223372036854775809 and m = -4223372036854775808: ", func(t *testing.T) { - max := BitwiseMax(-4223372036854775809, -4223372036854775808, base64) + max := Bitwise(-4223372036854775809, -4223372036854775808, base64) if max != -4223372036854775808 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) base8 := 7 t.Run("Testing(8bit) a = 257 and m = 256: ", func(t *testing.T) { - max := BitwiseMax(8, 16, base8) + max := Bitwise(8, 16, base8) if max != 16 { - t.Fatalf("Error: BitwiseMax returned bad value") + t.Fatalf("Error: Bitwise returned bad value") } }) } diff --git a/math/min/bitwisemin.go b/math/min/bitwisemin.go index 9710910aa..679d95840 100644 --- a/math/min/bitwisemin.go +++ b/math/min/bitwisemin.go @@ -7,6 +7,7 @@ package min +// Bitwise This function returns the minimum integer using bit operations func Bitwise(base int, value int, values ...int) int { min := value for _, val := range values { From 068ea4bc63c66cd57a00399966b8fea731b65859 Mon Sep 17 00:00:00 2001 From: Paul Leydier <75126792+paul-leydier@users.noreply.github.com> Date: Tue, 23 Nov 2021 17:58:32 +0100 Subject: [PATCH 015/202] feat: add hashing/sha256 implementation (#447) * feat: new hashing package * feat: sha256 hashing function * test: sha256 hashing test cases and benchmarks * doc: improve sha256 docs --- hashing/doc.go | 2 + hashing/hashing_test.go | 3 + hashing/sha256/sha256.go | 112 ++++++++++++++++++++++++++++++++++ hashing/sha256/sha256_test.go | 48 +++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 hashing/doc.go create mode 100644 hashing/hashing_test.go create mode 100644 hashing/sha256/sha256.go create mode 100644 hashing/sha256/sha256_test.go diff --git a/hashing/doc.go b/hashing/doc.go new file mode 100644 index 000000000..1e4425334 --- /dev/null +++ b/hashing/doc.go @@ -0,0 +1,2 @@ +// Package hashing containing different implementation of certain hashing +package hashing diff --git a/hashing/hashing_test.go b/hashing/hashing_test.go new file mode 100644 index 000000000..9067f8411 --- /dev/null +++ b/hashing/hashing_test.go @@ -0,0 +1,3 @@ +// Empty test file to keep track of all the tests for the algorithms. + +package hashing diff --git a/hashing/sha256/sha256.go b/hashing/sha256/sha256.go new file mode 100644 index 000000000..9061f3801 --- /dev/null +++ b/hashing/sha256/sha256.go @@ -0,0 +1,112 @@ +// sha256.go +// description: The sha256 cryptographic hash function as defined in the RFC6234 standard. +// author: [Paul Leydier] (https://github.com/paul-leydier) +// ref: https://datatracker.ietf.org/doc/html/rfc6234 +// ref: https://en.wikipedia.org/wiki/SHA-2 +// see sha256_test.go + +package sha256 + +import ( + "encoding/binary" // Used for interacting with uint at the byte level + "math/bits" // Used for bits rotation operations +) + +var K = [64]uint32{ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +} + +const chunkSize = 64 + +// pad returns a padded version of the input message, such as the padded message's length is a multiple +// of 512 bits. +// The padding methodology is as follows: +// A "1" bit is appended at the end of the input message, followed by m "0" bits such as the length is +// 64 bits short of a 512 bits multiple. The remaining 64 bits are filled with the initial length of the +// message, represented as a 64-bits unsigned integer. +// For more details, see: https://datatracker.ietf.org/doc/html/rfc6234#section-4.1 +func pad(message []byte) []byte { + L := make([]byte, 8) + binary.BigEndian.PutUint64(L, uint64(len(message)*8)) + message = append(message, 0x80) // "1" bit followed by 7 "0" bits + for (len(message)+8)%64 != 0 { + message = append(message, 0x00) // 8 "0" bits + } + message = append(message, L...) + + return message +} + +// Hash hashes the input message using the sha256 hashing function, and return a 32 byte array. +// The implementation follows the RGC6234 standard, which is documented +// at https://datatracker.ietf.org/doc/html/rfc6234 +func Hash(message []byte) [32]byte { + message = pad(message) + + // Initialize round constants + h0, h1, h2, h3, h4, h5, h6, h7 := uint32(0x6a09e667), uint32(0xbb67ae85), uint32(0x3c6ef372), uint32(0xa54ff53a), + uint32(0x510e527f), uint32(0x9b05688c), uint32(0x1f83d9ab), uint32(0x5be0cd19) + + // Iterate through 512-bit chunks + for chunkStart := 0; chunkStart < len(message); chunkStart += chunkSize { + // Message schedule + var w [64]uint32 + for i := 0; i*4 < chunkSize; i++ { + w[i] = binary.BigEndian.Uint32(message[chunkStart+i*4 : chunkStart+(i+1)*4]) + } + + // Extend the 16 bytes chunk to the whole 64 bytes message schedule + for i := 16; i < 64; i++ { + s0 := bits.RotateLeft32(w[i-15], -7) ^ bits.RotateLeft32(w[i-15], -18) ^ (w[i-15] >> 3) + s1 := bits.RotateLeft32(w[i-2], -17) ^ bits.RotateLeft32(w[i-2], -19) ^ (w[i-2] >> 10) + w[i] = w[i-16] + s0 + w[i-7] + s1 + } + + // Actual hashing loop + a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7 + for i := 0; i < 64; i++ { + S1 := bits.RotateLeft32(e, -6) ^ bits.RotateLeft32(e, -11) ^ bits.RotateLeft32(e, -25) + ch := (e & f) ^ ((^e) & g) + tmp1 := h + S1 + ch + K[i] + w[i] + S0 := bits.RotateLeft32(a, -2) ^ bits.RotateLeft32(a, -13) ^ bits.RotateLeft32(a, -22) + maj := (a & b) ^ (a & c) ^ (b & c) + tmp2 := S0 + maj + h = g + g = f + f = e + e = d + tmp1 + d = c + c = b + b = a + a = tmp1 + tmp2 + } + h0 += a + h1 += b + h2 += c + h3 += d + h4 += e + h5 += f + h6 += g + h7 += h + } + + // Export digest + digest := [32]byte{} + binary.BigEndian.PutUint32(digest[:4], h0) + binary.BigEndian.PutUint32(digest[4:8], h1) + binary.BigEndian.PutUint32(digest[8:12], h2) + binary.BigEndian.PutUint32(digest[12:16], h3) + binary.BigEndian.PutUint32(digest[16:20], h4) + binary.BigEndian.PutUint32(digest[20:24], h5) + binary.BigEndian.PutUint32(digest[24:28], h6) + binary.BigEndian.PutUint32(digest[28:], h7) + + return digest +} diff --git a/hashing/sha256/sha256_test.go b/hashing/sha256/sha256_test.go new file mode 100644 index 000000000..7e87a71ef --- /dev/null +++ b/hashing/sha256/sha256_test.go @@ -0,0 +1,48 @@ +package sha256 + +import ( + "encoding/hex" + "testing" +) + +func TestHash(t *testing.T) { + testCases := []struct { + in string + expected string + }{ + {"hello world", "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"}, + {"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + {"a", "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"}, + {"The quick brown fox jumps over the lazy dog", "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"}, + {"The quick brown fox jumps over the lazy dog.", "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"}, + {"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "2d8c2f6d978ca21712b5f6de36c9d31fa8e96a4fa5d8ff8b0188dfb9e7c171bb"}, + } + for _, tc := range testCases { + res := Hash([]byte(tc.in)) + result := hex.EncodeToString(res[:]) + if result != tc.expected { + t.Fatalf("Hash(%s) = %s, expected %s", tc.in, result, tc.expected) + } + } +} + +func BenchmarkHash(b *testing.B) { + testCases := []struct { + name string + in string + }{ + {"hello world", "hello world"}, + {"empty", ""}, + {"a", "a"}, + {"The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy dog"}, + {"The quick brown fox jumps over the lazy dog.", "The quick brown fox jumps over the lazy dog."}, + {"Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}, + } + for _, testCase := range testCases { + b.Run(testCase.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + Hash([]byte(testCase.in)) + } + }) + } +} From 8594e1119945653e7db3d78fa2080f27fb21a484 Mon Sep 17 00:00:00 2001 From: Taj Date: Thu, 25 Nov 2021 18:24:26 +0000 Subject: [PATCH 016/202] fix: pull request check hanging (#444) Co-authored-by: Andrii Siriak --- .github/workflows/godocmd.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index 6494d6bd7..3b4f0ef4c 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -1,5 +1,5 @@ name: godocmd -on: [push, pull_request] +on: [push] jobs: generate_readme: runs-on: ubuntu-latest From 83832b6be79d0223424226d06d91460fed04883a Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 25 Nov 2021 21:26:54 +0300 Subject: [PATCH 017/202] feat: fibonacci with matrix (#446) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * feat: n-th fibonacci number use matrix method * Updated Documentation in README.md * fix: ineffectual assignment to ta (ineffassign) * fix: ineffectual assignment to tb (ineffassign) * Updated Documentation in README.md Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Andrii Siriak --- README.md | 20 ++++++++++ math/fibonacci/fibonacci.go | 34 ++++++++++++++++ math/fibonacci/fibonacci_test.go | 66 ++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 math/fibonacci/fibonacci.go create mode 100644 math/fibonacci/fibonacci_test.go diff --git a/README.md b/README.md index 1fca7fa00..20aade7f6 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`Recursive`](./math/factorial/factorial.go#L21): Recursive This function recursively computes the factorial of a number 3. [`UsingTree`](./math/factorial/factorial.go#L30): UsingTree This function finds the factorial of a number using a binary tree +--- +
+ fibonacci + +--- + +##### Functions: + +1. [`Matrix`](./math/fibonacci/fibonacci.go#L11): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) + ---
gcd @@ -781,6 +791,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`New`](./structure/set/set.go#L7): New gives new set. +--- +
+ sha256 + +--- + +##### Functions: + +1. [`Hash`](./hashing/sha256/sha256.go#L50): Hash hashes the input message using the sha256 hashing function, and return a 32 byte array. The implementation follows the RGC6234 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc6234 + ---
sort diff --git a/math/fibonacci/fibonacci.go b/math/fibonacci/fibonacci.go new file mode 100644 index 000000000..06d8830e3 --- /dev/null +++ b/math/fibonacci/fibonacci.go @@ -0,0 +1,34 @@ +// fibonacci.go +// description: Get the nth Fibonacci Number +// details: +// In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number) +// author(s) [red_byte](https://github.com/i-redbyte) +// see fibonacci_test.go + +package fibonacci + +// Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) +func Matrix(n uint) uint { + a, b := 1, 1 + c, rc, tc := 1, 0, 0 + d, rd := 0, 1 + + for n != 0 { + if n&1 == 1 { + tc = rc + rc = rc*a + rd*c + rd = tc*b + rd*d + } + + ta := a + tb := b + tc = c + a = a*a + b*c + b = ta*b + b*d + c = c*ta + d*c + d = tc*tb + d*d + + n >>= 1 + } + return uint(rc) +} diff --git a/math/fibonacci/fibonacci_test.go b/math/fibonacci/fibonacci_test.go new file mode 100644 index 000000000..32fa7da6e --- /dev/null +++ b/math/fibonacci/fibonacci_test.go @@ -0,0 +1,66 @@ +package fibonacci + +import ( + "github.com/TheAlgorithms/Go/dynamic" + "testing" +) + +func getTests() []struct { + name string + n uint + want uint +} { + tests := []struct { + name string + n uint + want uint + }{ + {"Fibonacci 0-th number == 0", 0, 0}, + {"Fibonacci 1-th number == 1", 1, 1}, + {"Fibonacci 2-th number == 1", 2, 1}, + {"Fibonacci 3-th number == 2", 3, 2}, + {"Fibonacci 4-th number == 3", 4, 3}, + {"Fibonacci 5-th number == 5", 5, 5}, + {"Fibonacci 6-th number == 8", 6, 8}, + {"Fibonacci 7-th number == 13", 7, 13}, + {"Fibonacci 8-th number == 21", 8, 21}, + {"Fibonacci 9-th number == 34", 9, 34}, + {"Fibonacci 10-th number == 55", 10, 55}, + {"Fibonacci 90-th number == 2880067194370816120", 90, 2880067194370816120}, + } + return tests +} + +func TestMatrix(t *testing.T) { + tests := getTests() + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := Matrix(test.n); got != test.want { + t.Errorf("Return value = %v, want %v", got, test.want) + } + }) + } +} + +func TestNthFibonacci(t *testing.T) { + tests := getTests() + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := dynamic.NthFibonacci(test.n); got != test.want { + t.Errorf("Return value = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkNthFibonacci(b *testing.B) { + for i := 0; i < b.N; i++ { + dynamic.NthFibonacci(90) + } +} + +func BenchmarkMatrix(b *testing.B) { + for i := 0; i < b.N; i++ { + Matrix(90) + } +} From c85f9314b5c8b2c0ae4fad3c39de326dbf322d97 Mon Sep 17 00:00:00 2001 From: Paul Leydier <75126792+paul-leydier@users.noreply.github.com> Date: Sat, 27 Nov 2021 23:01:25 +0100 Subject: [PATCH 018/202] feat: add math/MontecarloPi2 implementation (#448) * feat: Parallel MonteCarloPi using channels * test: Parallel MonteCarloPi using channels * doc: MonteCarloPi2 documentation * doc: fix typo * feat: rename MonteCarloPi2 to MonteCarloPiConcurrent Co-authored-by: Taj --- math/pi/montecarlopi.go | 74 ++++++++++++++++++++++++++++++++++-- math/pi/montecarlopi_test.go | 56 +++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 4 deletions(-) diff --git a/math/pi/montecarlopi.go b/math/pi/montecarlopi.go index d31b20a45..7bbadf01c 100644 --- a/math/pi/montecarlopi.go +++ b/math/pi/montecarlopi.go @@ -1,15 +1,17 @@ // montecarlopi.go // description: Calculating pi by the Monte Carlo method // details: -// implementation of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method) -// author(s) [red_byte](https://github.com/i-redbyte) +// implementations of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method) +// author(s): [red_byte](https://github.com/i-redbyte), [Paul Leydier] (https://github.com/paul-leydier) // see montecarlopi_test.go package pi import ( - "math/rand" - "time" + "fmt" // Used for error formatting + "math/rand" // Used for random number generation in Monte Carlo method + "runtime" // Used to get information on available CPUs + "time" // Used for seeding the random number generation ) func MonteCarloPi(randomPoints int) float64 { @@ -25,3 +27,67 @@ func MonteCarloPi(randomPoints int) float64 { pi := float64(inside) / float64(randomPoints) * 4 return pi } + +// MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method. +// Unlike the MonteCarloPi function (first version), this implementation uses +// goroutines and channels to parallelize the computation. +// More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method. +// More details on goroutines parallelization available at https://go.dev/doc/effective_go#parallel. +func MonteCarloPiConcurrent(n int) (float64, error) { + numCPU := runtime.GOMAXPROCS(0) + c := make(chan int, numCPU) + pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes + if err != nil { + return 0, err + } + + // launch numCPU parallel tasks + for _, p := range pointsToDraw { + go drawPoints(p, c) + } + + // collect the tasks results + inside := 0 + for i := 0; i < numCPU; i++ { + inside += <-c + } + return float64(inside) / float64(n) * 4, nil +} + +// drawPoints draws n random two-dimensional points in the interval [0, 1), [0, 1) and sends through c +// the number of points which where within the circle of center 0 and radius 1 (unit circle) +func drawPoints(n int, c chan<- int) { + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) + inside := 0 + for i := 0; i < n; i++ { + x, y := rnd.Float64(), rnd.Float64() + if x*x+y*y <= 1 { + inside++ + } + } + c <- inside +} + +// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform +// way possible. +// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil +func splitInt(x int, n int) ([]int, error) { + if x < n { + return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n) + } + split := make([]int, n) + if x%n == 0 { + for i := 0; i < n; i++ { + split[i] = x / n + } + } else { + limit := x % n + for i := 0; i < limit; i++ { + split[i] = x/n + 1 + } + for i := limit; i < n; i++ { + split[i] = x / n + } + } + return split, nil +} diff --git a/math/pi/montecarlopi_test.go b/math/pi/montecarlopi_test.go index 4c650899e..acf862453 100644 --- a/math/pi/montecarlopi_test.go +++ b/math/pi/montecarlopi_test.go @@ -25,3 +25,59 @@ func BenchmarkMonteCarloPi(b *testing.B) { MonteCarloPi(100000000) } } + +func TestSplitInt(t *testing.T) { + testCases := []struct { + name string + x int + n int + expectedResult []int + expectedError bool + }{ + {"multiple", 10, 5, []int{2, 2, 2, 2, 2}, false}, + {"n=1", 10, 1, []int{10}, false}, + {"x=10, n=3", 10, 3, []int{4, 3, 3}, false}, + {"x=10, n=7", 10, 7, []int{2, 2, 2, 1, 1, 1, 1}, false}, + {"n>x", 10, 11, nil, true}, + } + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + res, err := splitInt(testCase.x, testCase.n) + for i := 0; i < len(testCase.expectedResult); i++ { + if res[i] != testCase.expectedResult[i] { + t.Fatalf("unexpected result at index %d: %d - expected %d", i, res[i], testCase.expectedResult[i]) + } + } + if testCase.expectedError { + if err == nil { + t.Fatal("expected an error, got nil") + } + } else { + if err != nil { + t.Fatalf("unexpected error - %s", err) + } + } + }) + } +} + +func TestMonteCarloPi2(t *testing.T) { + res, err := MonteCarloPiConcurrent(100000000) + if err != nil { + t.Errorf("unexpected error %s", err) + } + result := fmt.Sprintf("%.2f", res) + t.Log(result) + if result != "3.14" { + t.Errorf("Wrong result! Expected:%f, returned:%s ", 3.1415, result) + } +} + +func BenchmarkMonteCarloPi2(b *testing.B) { + for i := 0; i < b.N; i++ { + _, err := MonteCarloPiConcurrent(100000000) + if err != nil { + b.Fatalf("unexpected error - %s", err) + } + } +} From e6cf58267ccff495fe3262093de2258f3541107e Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Wed, 1 Dec 2021 20:49:34 +0300 Subject: [PATCH 019/202] Feat: reflected binary code (#449) --- README.md | 8 +++++--- math/binary/rbc.go | 18 ++++++++++++++++++ math/binary/rbc_test.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 math/binary/rbc.go create mode 100644 math/binary/rbc_test.go diff --git a/README.md b/README.md index 20aade7f6..f11140a6f 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations 5. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift 6. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -7. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +7. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n +8. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
@@ -644,8 +645,9 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`MonteCarloPi`](./math/pi/montecarlopi.go#L15): No description provided. -2. [`Spigot`](./math/pi/spigotpi.go#L12): No description provided. +1. [`MonteCarloPi`](./math/pi/montecarlopi.go#L17): No description provided. +2. [`MonteCarloPiConcurrent`](./math/pi/montecarlopi.go#L36): MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method. Unlike the MonteCarloPi function (first version), this implementation uses goroutines and channels to parallelize the computation. More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method. More details on goroutines parallelization available at https://go.dev/doc/effective_go#parallel. +3. [`Spigot`](./math/pi/spigotpi.go#L12): No description provided. ---
diff --git a/math/binary/rbc.go b/math/binary/rbc.go new file mode 100644 index 000000000..c0a6e78f1 --- /dev/null +++ b/math/binary/rbc.go @@ -0,0 +1,18 @@ +// rbc.go +// description: Reflected binary code (RBC) +// details: +// The reflected binary code (RBC), also known just as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). - [RBC](https://en.wikipedia.org/wiki/Gray_code) +// author(s) [red_byte](https://github.com/i-redbyte) +// see rbc_test.go + +package binary + +// SequenceGrayCode The function generates an "Gray code" sequence of length n +func SequenceGrayCode(n uint) []uint { + result := make([]uint, 0) + var i uint + for i = 0; i < 1<>1)) + } + return result +} diff --git a/math/binary/rbc_test.go b/math/binary/rbc_test.go new file mode 100644 index 000000000..60b6ff448 --- /dev/null +++ b/math/binary/rbc_test.go @@ -0,0 +1,37 @@ +// rbc_test.go +// description: Test for Reflected binary code +// author(s) [red_byte](https://github.com/i-redbyte) +// see rbc.go + +package binary + +import ( + "reflect" + "testing" +) + +func TestSequenceGrayCode(t *testing.T) { + tests := []struct { + name string + n uint + want []uint + }{ + {"Sequence of values for 1", 1, []uint{0, 1}}, + {"Sequence of values for 2", 2, []uint{0, 1, 3, 2}}, + {"Sequence of values for 6", 6, []uint{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, 24, 25, 27, 26, 30, 31, 29, 28, 20, 21, 23, 22, 18, 19, 17, 16, 48, 49, 51, 50, 54, 55, 53, 52, 60, 61, 63, 62, 58, 59, 57, 56, 40, 41, 43, 42, 46, 47, 45, 44, 36, 37, 39, 38, 34, 35, 33, 32}}, + {"Sequence of values for 8", 8, []uint{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, 24, 25, 27, 26, 30, 31, 29, 28, 20, 21, 23, 22, 18, 19, 17, 16, 48, 49, 51, 50, 54, 55, 53, 52, 60, 61, 63, 62, 58, 59, 57, 56, 40, 41, 43, 42, 46, 47, 45, 44, 36, 37, 39, 38, 34, 35, 33, 32, 96, 97, 99, 98, 102, 103, 101, 100, 108, 109, 111, 110, 106, 107, 105, 104, 120, 121, 123, 122, 126, 127, 125, 124, 116, 117, 119, 118, 114, 115, 113, 112, 80, 81, 83, 82, 86, 87, 85, 84, 92, 93, 95, 94, 90, 91, 89, 88, 72, 73, 75, 74, 78, 79, 77, 76, 68, 69, 71, 70, 66, 67, 65, 64, 192, 193, 195, 194, 198, 199, 197, 196, 204, 205, 207, 206, 202, 203, 201, 200, 216, 217, 219, 218, 222, 223, 221, 220, 212, 213, 215, 214, 210, 211, 209, 208, 240, 241, 243, 242, 246, 247, 245, 244, 252, 253, 255, 254, 250, 251, 249, 248, 232, 233, 235, 234, 238, 239, 237, 236, 228, 229, 231, 230, 226, 227, 225, 224, 160, 161, 163, 162, 166, 167, 165, 164, 172, 173, 175, 174, 170, 171, 169, 168, 184, 185, 187, 186, 190, 191, 189, 188, 180, 181, 183, 182, 178, 179, 177, 176, 144, 145, 147, 146, 150, 151, 149, 148, 156, 157, 159, 158, 154, 155, 153, 152, 136, 137, 139, 138, 142, 143, 141, 140, 132, 133, 135, 134, 130, 131, 129, 128}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := SequenceGrayCode(test.n); !reflect.DeepEqual(got, test.want) { + t.Errorf("SequenceGrayCode() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkSequenceGrayCode(b *testing.B) { + for i := 0; i < b.N; i++ { + SequenceGrayCode(6) + } +} From 37664206f73d5618b5b8f2f6db4b76c7054fd538 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Sun, 5 Dec 2021 17:22:40 +0300 Subject: [PATCH 020/202] feat: nth Fibonacci number using formula (#450) Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 3 ++- math/fibonacci/fibonacci.go | 13 +++++++++++++ math/fibonacci/fibonacci_test.go | 17 +++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f11140a6f..0cd05d43e 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Matrix`](./math/fibonacci/fibonacci.go#L11): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) +1. [`Formula`](./math/fibonacci/fibonacci.go#L42): Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers +2. [`Matrix`](./math/fibonacci/fibonacci.go#L15): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) ---
diff --git a/math/fibonacci/fibonacci.go b/math/fibonacci/fibonacci.go index 06d8830e3..9718acbbc 100644 --- a/math/fibonacci/fibonacci.go +++ b/math/fibonacci/fibonacci.go @@ -7,6 +7,10 @@ package fibonacci +import ( + "math" +) + // Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) func Matrix(n uint) uint { a, b := 1, 1 @@ -32,3 +36,12 @@ func Matrix(n uint) uint { } return uint(rc) } + +// Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) +// Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers +func Formula(n uint) uint { + sqrt5 := math.Sqrt(5) + phi := (sqrt5 + 1) / 2 + powPhi := math.Pow(phi, float64(n)) + return uint(powPhi/sqrt5 + 0.5) +} diff --git a/math/fibonacci/fibonacci_test.go b/math/fibonacci/fibonacci_test.go index 32fa7da6e..990930251 100644 --- a/math/fibonacci/fibonacci_test.go +++ b/math/fibonacci/fibonacci_test.go @@ -53,6 +53,17 @@ func TestNthFibonacci(t *testing.T) { } } +func TestFormula(t *testing.T) { + tests := getTests() + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := Formula(test.n); test.n <= 10 && got != test.want { + t.Errorf("Return value = %v, want %v", got, test.want) + } + }) + } +} + func BenchmarkNthFibonacci(b *testing.B) { for i := 0; i < b.N; i++ { dynamic.NthFibonacci(90) @@ -64,3 +75,9 @@ func BenchmarkMatrix(b *testing.B) { Matrix(90) } } + +func BenchmarkFormula(b *testing.B) { + for i := 0; i < b.N; i++ { + Formula(90) + } +} From 7fcbe26e5cf455b4ba27e75d15a65534f424a967 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Fri, 10 Dec 2021 23:02:47 +0300 Subject: [PATCH 021/202] Feat: Luhn algorithm (#451) Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 13 +++++++++++++ checksum/luhn.go | 28 ++++++++++++++++++++++++++++ checksum/luhn_test.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 checksum/luhn.go create mode 100644 checksum/luhn_test.go diff --git a/README.md b/README.md index 0cd05d43e..a3956cf92 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,19 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`CatalanNumber`](./math/catalan/catalannumber.go#L16): CatalanNumber This function returns the `nth` Catalan number +--- +
+ checksum + +--- + +##### Package checksum describes algorithms for finding various checksums + +--- +##### Functions: + +1. [`LuhnAlgorithm`](./checksum/luhn.go#L11): LuhnAlgorithm This function calculates the checksum using the Luna algorithm + ---
coloring diff --git a/checksum/luhn.go b/checksum/luhn.go new file mode 100644 index 000000000..f3e230ead --- /dev/null +++ b/checksum/luhn.go @@ -0,0 +1,28 @@ +// lunh.go +// description: Luhn algorithm +// details: is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, etc [Lunh](https://en.wikipedia.org/wiki/Luhn_algorithm) +// author(s) [red_byte](https://github.com/i-redbyte) +// see lunh_test.go + +// Package checksum describes algorithms for finding various checksums +package checksum + +// LuhnAlgorithm This function calculates the checksum using the Luna algorithm +func LuhnAlgorithm(s []rune) bool { + n := len(s) + number := 0 + result := 0 + for i := 0; i < n; i++ { + number = int(s[i]) - '0' + if i%2 != 0 { + result += number + continue + } + number *= 2 + if number > 9 { + number -= 9 + } + result += number + } + return result%10 == 0 +} diff --git a/checksum/luhn_test.go b/checksum/luhn_test.go new file mode 100644 index 000000000..e928e51b6 --- /dev/null +++ b/checksum/luhn_test.go @@ -0,0 +1,37 @@ +// luhn_test.go +// description: Test for Luhn algorithm +// author(s) [red_byte](https://github.com/i-redbyte) +// see luhn.go + +package checksum + +import "testing" + +func TestLuhnAlgorithm(t *testing.T) { + tests := []struct { + name string + s []rune + want bool + }{ + {"check 4242424242424242", []rune("4242424242424242"), true}, + {"check 6200000000000005", []rune("6200000000000005"), true}, + {"check 5534200028533164", []rune("5534200028533164"), true}, + {"check 36227206271667", []rune("36227206271667"), true}, + {"check 471629309440", []rune("471629309440"), false}, + {"check 1111", []rune("1111"), false}, + {"check 12345674", []rune("12345674"), true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := LuhnAlgorithm(test.s); got != test.want { + t.Errorf("LuhnAlgorithm() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkBruteForceFactorial(b *testing.B) { + for i := 0; i < b.N; i++ { + LuhnAlgorithm([]rune("4242424242424242")) + } +} From 75b615cc38ffc111ddcd4f0dfadc5fdf2d417201 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 23 Dec 2021 20:09:34 +0300 Subject: [PATCH 022/202] Abs algo (#453) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 22 ++++++++------- math/abs.go | 16 +++++++++++ math/abs_test.go | 61 +++++++++++++++++++++++++++++++++++++++++ math/binary/abs.go | 13 +++++++++ math/binary/abs_test.go | 37 +++++++++++++++++++++++++ 5 files changed, 139 insertions(+), 10 deletions(-) create mode 100644 math/abs.go create mode 100644 math/abs_test.go create mode 100644 math/binary/abs.go create mode 100644 math/binary/abs_test.go diff --git a/README.md b/README.md index a3956cf92..03f8529c5 100644 --- a/README.md +++ b/README.md @@ -89,14 +89,15 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number -2. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. -3. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 -4. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations -5. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift -6. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -7. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n -8. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +1. [`Abs`](./math/binary/abs.go#L10): Abs returns absolute value using binary operation Principle of operation: 1) Get the mask by right shift by the base 2) Base is the size of an integer variable in bits, for example, for int32 it will be 32, for int64 it will be 64 3) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. 4) Add the mask to the given number. 5) XOR of mask + n and mask gives the absolute value. +2. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number +3. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. +4. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 +5. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations +6. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift +7. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. +8. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n +9. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
@@ -521,8 +522,9 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -2. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +1. [`Abs`](./math/abs.go#L11): Abs returns absolute value +2. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +3. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. ---
diff --git a/math/abs.go b/math/abs.go new file mode 100644 index 000000000..7d0b3e6ac --- /dev/null +++ b/math/abs.go @@ -0,0 +1,16 @@ +// abs.go +// description: Absolute value +// details: +// In mathematics, the absolute value or modulus of a real number x, denoted |x|, is the non-negative value of x without regard to its sign. [Absolute value](https://en.wikipedia.org/wiki/Average#Arithmetic_mean) +// author(s) [red_byte](https://github.com/i-redbyte) +// see abs_test.go + +package math + +// Abs returns absolute value +func Abs(n int) int { + if n < 0 { + return -n + } + return n +} diff --git a/math/abs_test.go b/math/abs_test.go new file mode 100644 index 000000000..cd166f91d --- /dev/null +++ b/math/abs_test.go @@ -0,0 +1,61 @@ +package math + +import ( + "github.com/TheAlgorithms/Go/math/binary" + "math" + "testing" +) + +func TestAbs(t *testing.T) { + tests := getTests() + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := Abs(test.n); got != test.want { + t.Errorf("Abs() = %v, want %v", got, test.want) + } + }) + } +} + +func getTests() []struct { + name string + n int + want int +} { + tests := []struct { + name string + n int + want int + }{ + {"-1 = |1| ", -1, 1}, + {"-255 = |255| ", -255, 255}, + {"0 = |0| ", 0, 0}, + {"5 = |5| ", 5, 5}, + {"-5 = |5| ", -5, 5}, + {"-98368972 = |98368972| ", -98368972, 98368972}, + } + return tests +} + +func BenchmarkSimpleAbs(b *testing.B) { + for i := 0; i < b.N; i++ { + Abs(-1024) + } +} +func BenchmarkBinaryAbs32(b *testing.B) { + for i := 0; i < b.N; i++ { + binary.Abs(32, -1024) + } +} + +func BenchmarkBinaryAbs64(b *testing.B) { + for i := 0; i < b.N; i++ { + binary.Abs(64, -1024) + } +} + +func BenchmarkStdLibAbs(b *testing.B) { + for i := 0; i < b.N; i++ { + math.Abs(-1024) + } +} diff --git a/math/binary/abs.go b/math/binary/abs.go new file mode 100644 index 000000000..9762c7c8a --- /dev/null +++ b/math/binary/abs.go @@ -0,0 +1,13 @@ +package binary + +// Abs returns absolute value using binary operation +// Principle of operation: +// 1) Get the mask by right shift by the base +// 2) Base is the size of an integer variable in bits, for example, for int32 it will be 32, for int64 it will be 64 +// 3) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. +// 4) Add the mask to the given number. +// 5) XOR of mask + n and mask gives the absolute value. +func Abs(base, n int) int { + m := n >> (base - 1) + return (n + m) ^ m +} diff --git a/math/binary/abs_test.go b/math/binary/abs_test.go new file mode 100644 index 000000000..20500ec5a --- /dev/null +++ b/math/binary/abs_test.go @@ -0,0 +1,37 @@ +package binary + +import "testing" + +func TestAbs(t *testing.T) { + tests := getAbsTests() + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := Abs(test.base, test.n); got != test.want { + t.Errorf("Abs() = %v, want %v", got, test.want) + } + }) + } +} + +func getAbsTests() []struct { + name string + base int + n int + want int +} { + tests := []struct { + name string + base int + n int + want int + }{ + {"-1 = |1| ", 32, -1, 1}, + {"-255 = |255| ", 32, -255, 255}, + {"0 = |0| ", 64, 0, 0}, + {"5 = |5| ", 16, 5, 5}, + {"-5 = |5| ", 32, -5, 5}, + {"-98368972 = |98368972| ", 64, -98368972, 98368972}, + {"-110298368972 = |110298368972| ", 64, -98368972, 98368972}, + } + return tests +} From b46d6dafde58817feafefa5788f6fa052bcd2903 Mon Sep 17 00:00:00 2001 From: Nischal Patel Date: Wed, 29 Dec 2021 01:26:27 +0530 Subject: [PATCH 023/202] Add recursive method for palindrome (#455) --- strings/palindrome/ispalindrome.go | 18 ++++++++++++++++++ strings/palindrome/ispalindrome_test.go | 11 +++++++++++ 2 files changed, 29 insertions(+) diff --git a/strings/palindrome/ispalindrome.go b/strings/palindrome/ispalindrome.go index 65d525dd3..eb3ab289e 100644 --- a/strings/palindrome/ispalindrome.go +++ b/strings/palindrome/ispalindrome.go @@ -35,3 +35,21 @@ func IsPalindrome(text string) bool { } return true } + +func IsPalindromeRecursive(text string) bool { + clean_text := cleanString(text) + runes := []rune(clean_text) + return isPalindromeRecursiveHelper(runes, 0, int64(len(runes))) +} + +func isPalindromeRecursiveHelper(runes []rune, start int64, end int64) bool { + if start >= end { + return true + } + if runes[start] != runes[end-1] { + return false + } + start = start + 1 + end = end - 1 + return isPalindromeRecursiveHelper(runes, start, end) +} diff --git a/strings/palindrome/ispalindrome_test.go b/strings/palindrome/ispalindrome_test.go index 409e6bb8f..7b973b1d5 100644 --- a/strings/palindrome/ispalindrome_test.go +++ b/strings/palindrome/ispalindrome_test.go @@ -51,3 +51,14 @@ func TestIsPalindrome(t *testing.T) { }) } } + +func TestIsPalindromeRecursive(t *testing.T) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + func_result := IsPalindromeRecursive(test.input) + if test.expected != func_result { + t.Errorf("Expected answer '%t' for string '%s' but answer given was %t", test.expected, test.input, func_result) + } + }) + } +} From ef59b691c1ade0c8576aae85d80367471324be55 Mon Sep 17 00:00:00 2001 From: 1327253585 <1327253585@qq.com> Date: Tue, 4 Jan 2022 00:49:27 +0800 Subject: [PATCH 024/202] merge: feat: add a clear implemention of jump search (#458) --- search/jump2.go | 24 ++++++++++++++++++++++++ search/jump2_test.go | 23 +++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 search/jump2.go create mode 100644 search/jump2_test.go diff --git a/search/jump2.go b/search/jump2.go new file mode 100644 index 000000000..ca16a94fb --- /dev/null +++ b/search/jump2.go @@ -0,0 +1,24 @@ +package search + +import "math" + +func Jump2(arr []int, target int) (int, error) { + step := int(math.Round(math.Sqrt(float64(len(arr))))) + rbound := len(arr) + for i := step; i < len(arr); i += step { + if arr[i] > target { + rbound = i + break + } + } + + for i := rbound - step; i < rbound; i++ { + if arr[i] == target { + return i, nil + } + if arr[i] > target { + break + } + } + return -1, ErrNotFound +} diff --git a/search/jump2_test.go b/search/jump2_test.go new file mode 100644 index 000000000..fc2cdb4af --- /dev/null +++ b/search/jump2_test.go @@ -0,0 +1,23 @@ +package search + +import "testing" + +func TestJump2(t *testing.T) { + for _, test := range searchTests { + actualValue, actualError := Jump2(test.data, test.key) + if actualValue != test.expected { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) + } + if actualError != test.expectedError { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) + } + } +} + +func BenchmarkJump2(b *testing.B) { + testCase := generateBenchmarkTestCase() + b.ResetTimer() // exclude time taken to generate test case + for i := 0; i < b.N; i++ { + _, _ = Jump2(testCase, i) + } +} From a918456a93209ce3a13e4347d69247febfa42723 Mon Sep 17 00:00:00 2001 From: 1327253585 <1327253585@qq.com> Date: Tue, 4 Jan 2022 00:53:25 +0800 Subject: [PATCH 025/202] merge: feat: add qucik select algorithm (#457) Co-authored-by: Rak Laptudirm --- search/selectk.go | 32 ++++++++++++++++++++++++++++++++ search/selectk_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 search/selectk.go create mode 100644 search/selectk_test.go diff --git a/search/selectk.go b/search/selectk.go new file mode 100644 index 000000000..bb81937b4 --- /dev/null +++ b/search/selectk.go @@ -0,0 +1,32 @@ +package search + +func SelectK(array []int, k int) (int, error) { + if k > len(array) { + return -1, ErrNotFound + } + return selectK(array, 0, len(array), len(array)-k), nil +} + +// search the element which index is idx +func selectK(array []int, l, r, idx int) int { + index := partition(array, l, r) + if index == idx { + return array[index] + } + if index < idx { + return selectK(array, index+1, r, idx) + } + return selectK(array, l, index, idx) +} + +func partition(array []int, l, r int) int { + elem, j := array[l], l+1 + for i := l + 1; i < r; i++ { + if array[i] <= elem { + array[i], array[j] = array[j], array[i] + j++ + } + } + array[l], array[j-1] = array[j-1], array[l] + return j - 1 +} diff --git a/search/selectk_test.go b/search/selectk_test.go new file mode 100644 index 000000000..bf81fb9d1 --- /dev/null +++ b/search/selectk_test.go @@ -0,0 +1,41 @@ +package search + +import ( + "testing" +) + +func TestSelectK(t *testing.T) { + tests := []struct { + data []int + k int + expected int + err error + name string + }{ + {[]int{1, 2, 3, 4, 5}, 1, 5, nil, "sorted data"}, + {[]int{5, 4, 3, 2, 1}, 2, 4, nil, "reversed data"}, + {[]int{3, 1, 2, 5, 4}, 3, 3, nil, "random data"}, + {[]int{3, 2, 1, 5, 4}, 10, -1, ErrNotFound, " absent data"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + elem, err := SelectK(tc.data, tc.k) + if err != tc.err { + t.Errorf("name:%v SelectK() = _, %v, want err: %v", tc.name, err, tc.err) + } + if elem != tc.expected { + t.Errorf("name:%v SelectK() = %v,_ , want: %v", tc.name, elem, tc.expected) + } + }) + } +} + +func BenchmarkSelectK(b *testing.B) { + testCase := generateBenchmarkTestCase() + testCase = append(testCase, 1) // make sure len(testCase)/2+1 is valid + b.ResetTimer() + + for i := 0; i < b.N; i++ { + _, _ = SelectK(testCase, len(testCase)/2) + } +} From 6134d6e383f0e2f42d9123c50d22d6e7333c1a3f Mon Sep 17 00:00:00 2001 From: 1327253585 <1327253585@qq.com> Date: Tue, 4 Jan 2022 17:29:55 +0800 Subject: [PATCH 026/202] merge: add merge sort (#456) * add merge sort * change code style * move iterative implementation to mergesort.go * fix: rename MegrgeSortIter to MergeIter Co-authored-by: zhaodeliang Co-authored-by: Rak Laptudirm --- sort/mergesort.go | 12 ++++++++++++ sort/sorts_test.go | 8 ++++++++ 2 files changed, 20 insertions(+) diff --git a/sort/mergesort.go b/sort/mergesort.go index a5b4e2a36..45c17ab04 100644 --- a/sort/mergesort.go +++ b/sort/mergesort.go @@ -1,5 +1,7 @@ package sort +import "github.com/TheAlgorithms/Go/math/min" + func merge(a []int, b []int) []int { var r = make([]int, len(a)+len(b)) @@ -45,3 +47,13 @@ func Mergesort(items []int) []int { return merge(a, b) } + +func MergeIter(items []int) []int { + for step := 1; step < len(items); step += step { + for i := 0; i+step < len(items); i += 2 * step { + tmp := merge(items[i:i+step], items[i+step:min.Int(i+2*step, len(items))]) + copy(items[i:], tmp) + } + } + return items +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index be239205e..828b907cb 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -90,6 +90,10 @@ func TestMerge(t *testing.T) { testFramework(t, Mergesort) } +func TestMergeIter(t *testing.T) { + testFramework(t, MergeIter) +} + func TestHeap(t *testing.T) { testFramework(t, HeapSort) } @@ -187,6 +191,10 @@ func BenchmarkMerge(b *testing.B) { benchmarkFramework(b, Mergesort) } +func BenchmarkMergeIter(b *testing.B) { + benchmarkFramework(b, MergeIter) +} + func BenchmarkHeap(b *testing.B) { benchmarkFramework(b, HeapSort) } From 1378d8ce359f7b488da0af65a142350be205bde7 Mon Sep 17 00:00:00 2001 From: Aniruddha Bhattacharjee Date: Tue, 11 Jan 2022 17:05:30 +0530 Subject: [PATCH 027/202] Graphs articulation points (#452) * Articualtion point initial commit * Refactor the function definitions * Add introduction comments and helpful links * Add test for articulation point algorithm * Inital commit for articulation point test * Correct test cases * Rename files to conform to the naming conventions * Add comments * Updated Documentation in README.md * Remove earlier files * Updated Documentation in README.md * Rename dfs to ArticulationPointHelper to avoid confusion * Updated Documentation in README.md * Make the helper function unexported * Updated Documentation in README.md * Refactor the code to avoid global variables * Updated Documentation in README.md * Refactor to use structs instead function parameters * Updated Documentation in README.md * Restructure comments to compile with project conventions * Updated Documentation in README.md * Linting changes * Reduce comment length and accommodate review comments * Updated Documentation in README.md * Updated Documentation in README.md * Modify function definition to pass graph parameter as a pointer Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj Co-authored-by: Rak Laptudirm --- README.md | 39 ++++++------ graph/articulationpoints.go | 100 +++++++++++++++++++++++++++++++ graph/articulationpoints_test.go | 82 +++++++++++++++++++++++++ 3 files changed, 203 insertions(+), 18 deletions(-) create mode 100644 graph/articulationpoints.go create mode 100644 graph/articulationpoints_test.go diff --git a/README.md b/README.md index 03f8529c5..0743c1981 100644 --- a/README.md +++ b/README.md @@ -390,16 +390,17 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`BreadthFirstSearch`](./graph/breadthfirstsearch.go#L9): BreadthFirstSearch is an algorithm for traversing and searching graph data structures. It starts at an arbitrary node of a graph, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) reference: https://en.wikipedia.org/wiki/Breadth-first_search -2. [`DepthFirstSearch`](./graph/depthfirstsearch.go#L53): No description provided. -3. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided. -4. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm -5. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. -6. [`KruskalMST`](./graph/kruskal.go#L87): KruskalMST will return a minimum spanning tree along with its total cost to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is the number of edges in the graph and n is number of nodes in it. -7. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) -8. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made -9. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. -10. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b +1. [`ArticulationPoint`](./graph/articulationpoints.go#L19): ArticulationPoint is a function to identify articulation points in a graph. The function takes the graph as an argument and returns a boolean slice which indicates whether a vertex is an articulation point or not. Worst Case Time Complexity: O(|V| + |E|) Auxiliary Space: O(|V|) reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point +2. [`BreadthFirstSearch`](./graph/breadthfirstsearch.go#L9): BreadthFirstSearch is an algorithm for traversing and searching graph data structures. It starts at an arbitrary node of a graph, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) reference: https://en.wikipedia.org/wiki/Breadth-first_search +3. [`DepthFirstSearch`](./graph/depthfirstsearch.go#L53): No description provided. +4. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided. +5. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm +6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. +7. [`KruskalMST`](./graph/kruskal.go#L87): KruskalMST will return a minimum spanning tree along with its total cost to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is the number of edges in the graph and n is number of nodes in it. +8. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) +9. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made +10. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. +11. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b --- ##### Types @@ -605,6 +606,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided. +2. [`IsPalindromeRecursive`](./strings/palindrome/ispalindrome.go#L39): No description provided. ---
@@ -836,14 +838,15 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`HeapSort`](./sort/heapsort.go#L121): No description provided. 5. [`ImprovedSimpleSort`](./sort/simplesort.go#L25): ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort 6. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. -7. [`Mergesort`](./sort/mergesort.go#L35): Mergesort Perform mergesort on a slice of ints -8. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -9. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array -10. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array -11. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -12. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. -13. [`ShellSort`](./sort/shellsort.go#L3): No description provided. -14. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. +7. [`MergeIter`](./sort/mergesort.go#L51): No description provided. +8. [`Mergesort`](./sort/mergesort.go#L37): Mergesort Perform mergesort on a slice of ints +9. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +10. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array +11. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array +12. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +13. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. +14. [`ShellSort`](./sort/shellsort.go#L3): No description provided. +15. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. --- ##### Types diff --git a/graph/articulationpoints.go b/graph/articulationpoints.go new file mode 100644 index 000000000..8c295d639 --- /dev/null +++ b/graph/articulationpoints.go @@ -0,0 +1,100 @@ +package graph + +import "github.com/TheAlgorithms/Go/math/min" + +type apHelper struct { + is_ap []bool + visited []bool + child_cnt []int + discovery_time []int + earliest_discovery []int +} + +// ArticulationPoint is a function to identify articulation points in a graph. +// The function takes the graph as an argument and returns a boolean slice +// which indicates whether a vertex is an articulation point or not. +// Worst Case Time Complexity: O(|V| + |E|) +// Auxiliary Space: O(|V|) +// reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point +func ArticulationPoint(graph *Graph) []bool { + // time variable to keep track of the time of discovery_time of a vertex + time := 0 + + //initialize all the variables + apHelperInstance := &apHelper{ + is_ap: make([]bool, graph.vertices), + visited: make([]bool, graph.vertices), + child_cnt: make([]int, graph.vertices), + // integer slice to store the discovery time of a vertex as we traverse + // the graph in a depth first manner + discovery_time: make([]int, graph.vertices), + // integer slice to store the earliest discovered vertex reachable from a vertex + earliest_discovery: make([]int, graph.vertices), + } + articulationPointHelper( + apHelperInstance, + 0, + -1, + &time, + graph, + ) + + if apHelperInstance.child_cnt[0] == 1 { + // if the root has only one child, it is not an articulation point + apHelperInstance.is_ap[0] = false + } + + return apHelperInstance.is_ap +} + +// articulationPointHelper is a recursive function to traverse the graph +// and mark articulation points. Based on the depth first search transversal +// of the graph, however modified to keep track and update the +// `child_cnt`, `discovery_time`` and `earliest_discovery` slices defined above +func articulationPointHelper( + apHelperInstance *apHelper, + vertex int, + parent int, + time *int, + graph *Graph, +) { + apHelperInstance.visited[vertex] = true + + // Mark the time of discovery of a vertex + // set the earliest discovery time to the discovered time + // increment the time + apHelperInstance.discovery_time[vertex] = *time + apHelperInstance.earliest_discovery[vertex] = apHelperInstance.discovery_time[vertex] + *time++ + + for next_vertex := range graph.edges[vertex] { + if next_vertex == parent { + continue + } + + if apHelperInstance.visited[next_vertex] { + apHelperInstance.earliest_discovery[vertex] = min.Int( + apHelperInstance.earliest_discovery[vertex], + apHelperInstance.discovery_time[next_vertex], + ) + continue + } + + apHelperInstance.child_cnt[vertex]++ + articulationPointHelper( + apHelperInstance, + next_vertex, + vertex, + time, + graph, + ) + apHelperInstance.earliest_discovery[vertex] = min.Int( + apHelperInstance.earliest_discovery[vertex], + apHelperInstance.earliest_discovery[next_vertex], + ) + if apHelperInstance.earliest_discovery[next_vertex] >= apHelperInstance.discovery_time[vertex] { + apHelperInstance.is_ap[vertex] = true + } + + } +} diff --git a/graph/articulationpoints_test.go b/graph/articulationpoints_test.go new file mode 100644 index 000000000..a9dca3e6d --- /dev/null +++ b/graph/articulationpoints_test.go @@ -0,0 +1,82 @@ +package graph + +import ( + "reflect" + "testing" +) + +func TestArticulationPoints(t *testing.T) { + var testCases = []struct { + description string + graph Graph + expected []bool + }{ + { + "Linear tree structure", + Graph{ + vertices: 5, + edges: map[int]map[int]int{ + 0: { + 1: 0, + }, + + 1: { + 0: 0, + 2: 0, + }, + + 2: { + 1: 0, + 3: 0, + }, + + 3: { + 2: 0, + 4: 0, + }, + }, + }, + []bool{false, true, true, true, false}, + }, { + "A complete graph", + Graph{ + vertices: 4, + edges: map[int]map[int]int{ + 0: { + 1: 0, + 2: 0, + 3: 0, + }, + + 1: { + 0: 0, + 2: 0, + 3: 0, + }, + + 2: { + 0: 0, + 1: 0, + 3: 0, + }, + + 3: { + 0: 0, + 1: 0, + 2: 0, + }, + }, + }, + []bool{false, false, false, false}, + }, + } + + for _, test := range testCases { + t.Run(test.description, func(t *testing.T) { + is_ap := ArticulationPoint(&test.graph) + if !reflect.DeepEqual(is_ap, test.expected) { + t.Logf("FAIL: %s", test.description) + } + }) + } +} From 63bca76880283598d5a98764f501a0aa906d62d4 Mon Sep 17 00:00:00 2001 From: qzQi <62093728+qzQi@users.noreply.github.com> Date: Mon, 24 Jan 2022 17:07:00 +0800 Subject: [PATCH 028/202] merge: Update singlylinkedlist.go (#463) fix int -->interface{} --- structure/linkedlist/singlylinkedlist.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/structure/linkedlist/singlylinkedlist.go b/structure/linkedlist/singlylinkedlist.go index 5dd92e335..5b9d71787 100644 --- a/structure/linkedlist/singlylinkedlist.go +++ b/structure/linkedlist/singlylinkedlist.go @@ -29,7 +29,7 @@ func (ll *Singly) AddAtBeg(val interface{}) { } // AddAtEnd adds a new snode with given value at the end of the list. -func (ll *Singly) AddAtEnd(val int) { +func (ll *Singly) AddAtEnd(val interface{}) { n := NewNode(val) if ll.Head == nil { From 331446cfd3fccf460ee7b27f972069f644127c3b Mon Sep 17 00:00:00 2001 From: Simon Berndtsson Date: Sat, 5 Feb 2022 20:48:57 +0100 Subject: [PATCH 029/202] Simplify BreadthFirstSearch.go (#465) Remove redundant if clause which condition is always met at line of execution --- graph/breadthfirstsearch.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/graph/breadthfirstsearch.go b/graph/breadthfirstsearch.go index 93d29f9e4..7325c06a3 100644 --- a/graph/breadthfirstsearch.go +++ b/graph/breadthfirstsearch.go @@ -13,9 +13,7 @@ func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, queue = append(queue, start) for len(queue) > 0 { v := queue[0] - if len(queue) > 0 { - queue = queue[1:] - } + queue = queue[1:] for i := 0; i < len(edges[v]); i++ { if discovered[i] == 0 && edges[v][i] > 0 { if i == end { From 30292322c165952c32f0e2d981540363f6cfe848 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 10 Feb 2022 16:01:27 +0300 Subject: [PATCH 030/202] merge: CRC8 algo (#469) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * feat: crc8 algorithm * Updated Documentation in README.md * fix test * fix after review * Updated Documentation in README.md * fix after review Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 19 +++++++++++ checksum/crc/crc8.go | 66 +++++++++++++++++++++++++++++++++++++++ checksum/crc/crc8_test.go | 59 ++++++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 checksum/crc/crc8.go create mode 100644 checksum/crc/crc8_test.go diff --git a/README.md b/README.md index 0743c1981..fbb464a0a 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,25 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 8. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. 9. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. +--- +
+ crc + +--- + +##### Package crc describes algorithms for finding various CRC checksums + +--- +##### Functions: + +1. [`CalculateCRC8`](./checksum/crc/crc8.go#L26): CalculateCRC8 This function calculate CRC8 checksum. + +--- +##### Types + +1. [`CRCModel`](./checksum/crc/crc8.go#L16): No description provided. + + ---
diffiehellman diff --git a/checksum/crc/crc8.go b/checksum/crc/crc8.go new file mode 100644 index 000000000..3c69aeec2 --- /dev/null +++ b/checksum/crc/crc8.go @@ -0,0 +1,66 @@ +// crc8.go +// description: Calculate CRC8 +// details: +// A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks +// and storage devices to detect accidental changes to raw data. +// See more [CRC](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) +// author(s) [red_byte](https://github.com/i-redbyte) +// see crc8_test.go + +// Package crc describes algorithms for finding various CRC checksums +package crc + +import "math/bits" + +// CRCModel contains the necessary parameters for calculating the DRC algorithm +type CRCModel struct { + Poly uint8 + Init uint8 + RefIn bool + RefOut bool + XorOut uint8 + Name string +} + +// CalculateCRC8 This function calculate CRC8 checksum. +func CalculateCRC8(data []byte, model CRCModel) uint8 { + table := getTable(model) + crcResult := model.Init + crcResult = addBytes(data, model, crcResult, table) + if model.RefOut { + crcResult = bits.Reverse8(crcResult) + } + return crcResult ^ model.XorOut +} + +// This function get the result of adding the bytes in data to the crc +func addBytes(data []byte, model CRCModel, crcResult uint8, table []uint8) uint8 { + if model.RefIn { + for _, d := range data { + d = bits.Reverse8(d) + crcResult = table[crcResult^d] + } + return crcResult + } + for _, d := range data { + crcResult = table[crcResult^d] + } + return crcResult +} + +// This function get 256-byte (256x8) table for efficient processing. +func getTable(model CRCModel) []uint8 { + table := make([]uint8, 256) + for i := 0; i < 256; i++ { + crc := uint8(i) + for j := 0; j < 8; j++ { + isSetBit := (crc & 0x80) != 0 + crc <<= 1 + if isSetBit { + crc ^= model.Poly + } + } + table[i] = crc + } + return table +} diff --git a/checksum/crc/crc8_test.go b/checksum/crc/crc8_test.go new file mode 100644 index 000000000..ee6ac2188 --- /dev/null +++ b/checksum/crc/crc8_test.go @@ -0,0 +1,59 @@ +// crc8_test.go +// description: Test for calculate crc8 +// author(s) [red_byte](https://github.com/i-redbyte) +// see crc8.go + +package crc + +import ( + "fmt" + "testing" +) + +var ( + CRC8 = CRCModel{0x07, 0x00, false, false, 0x00, "CRC-8"} + CRC8CDMA2000 = CRCModel{0x9B, 0xFF, false, false, 0x00, "CRC-8/CDMA2000"} + CRC8DARC = CRCModel{0x39, 0x00, true, true, 0x00, "CRC-8/DARC"} + CRC8DVBS2 = CRCModel{0xD5, 0x00, false, false, 0x00, "CRC-8/DVB-S2"} + CRC8EBU = CRCModel{0x1D, 0xFF, true, true, 0x00, "CRC-8/EBU"} + CRC8ICODE = CRCModel{0x1D, 0xFD, false, false, 0x00, "CRC-8/I-CODE"} + CRC8ITU = CRCModel{0x07, 0x00, false, false, 0x55, "CRC-8/ITU"} + CRC8MAXIM = CRCModel{0x31, 0x00, true, true, 0x00, "CRC-8/MAXIM"} + CRC8ROHC = CRCModel{0x07, 0xFF, true, true, 0x00, "CRC-8/ROHC"} + CRC8WCDMA = CRCModel{0x9B, 0x00, true, true, 0x00, "CRC-8/WCDMA"} +) + +func TestCalculateCRC8(t *testing.T) { + data := []byte("123456789") + tests := []struct { + name string + data []byte + model CRCModel + want uint8 + }{ + {CRC8.Name, data, CRC8, 0xF4}, + {CRC8CDMA2000.Name, data, CRC8CDMA2000, 0xDA}, + {CRC8DARC.Name, data, CRC8DARC, 0x15}, + {CRC8DVBS2.Name, data, CRC8DVBS2, 0xBC}, + {CRC8EBU.Name, data, CRC8EBU, 0x97}, + {CRC8ICODE.Name, data, CRC8ICODE, 0x7E}, + {CRC8ITU.Name, data, CRC8ITU, 0xA1}, + {CRC8MAXIM.Name, data, CRC8MAXIM, 0xA1}, + {CRC8ROHC.Name, data, CRC8ROHC, 0xD0}, + {CRC8WCDMA.Name, data, CRC8WCDMA, 0x25}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + fmt.Println(CalculateCRC8(test.data, test.model)) + if got := CalculateCRC8(test.data, test.model); got != test.want { + t.Errorf("CalculateCRC8() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkCalculateCRC8(b *testing.B) { + for i := 0; i < b.N; i++ { + CalculateCRC8([]byte("123456789"), CRC8) + } +} From 2cc5f5a27da9e56a7303f3a0e0010fc15dc2047e Mon Sep 17 00:00:00 2001 From: Aniruddha Bhattacharjee Date: Fri, 11 Feb 2022 13:55:20 +0530 Subject: [PATCH 031/202] merge: Longest increasing subsequence greedy (#466) * Initial commit for the greedy implementation of the longest increasing subsequence question * Updated Documentation in README.md * Minor naming changes * Add test for longest increasing subsequence function * Change the lowerBound function * Remove extraneous blank lines * Updated Documentation in README.md * Reorganize files and use existing tests for longest increasing subsequence * Updated Documentation in README.md * Edit description * Updated Documentation in README.md * Refactor test for longest increasing subsequence * Updated Documentation in README.md * Unexport utility test function * Updated Documentation in README.md Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Rak Laptudirm --- README.md | 15 ++++--- dynamic/longestincreasingsubsequence_test.go | 12 +++++- dynamic/longestincreasingsubsequencegreedy.go | 43 +++++++++++++++++++ 3 files changed, 61 insertions(+), 9 deletions(-) create mode 100644 dynamic/longestincreasingsubsequencegreedy.go diff --git a/README.md b/README.md index fbb464a0a..a608159be 100644 --- a/README.md +++ b/README.md @@ -275,13 +275,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 7. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit 8. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function 9. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order -10. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function -11. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function -12. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function -13. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function -14. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate -15. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) -16. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number +10. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ +11. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function +12. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function +13. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function +14. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function +15. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate +16. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) +17. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number ---
diff --git a/dynamic/longestincreasingsubsequence_test.go b/dynamic/longestincreasingsubsequence_test.go index ed021db1e..81ea2fcde 100644 --- a/dynamic/longestincreasingsubsequence_test.go +++ b/dynamic/longestincreasingsubsequence_test.go @@ -7,7 +7,7 @@ import ( "github.com/TheAlgorithms/Go/dynamic" ) -func TestLongestIncreasingSubsequence(t *testing.T) { +func longestIncreasingSubsequenceTest(t *testing.T, algorithm func(nums []int) int) { td := []struct { elements []int expectedLen int @@ -21,10 +21,18 @@ func TestLongestIncreasingSubsequence(t *testing.T) { } for _, tc := range td { t.Run(fmt.Sprint("test with", tc.elements), func(t *testing.T) { - actualLen := dynamic.LongestIncreasingSubsequence(tc.elements) + actualLen := algorithm(tc.elements) if tc.expectedLen != actualLen { t.Fatalf("expecting a sequence of len %d to be found but the actual len was %d; input: %v", tc.expectedLen, actualLen, tc.elements) } }) } } + +func TestLongestIncreasingSubsequence(t *testing.T) { + longestIncreasingSubsequenceTest(t, dynamic.LongestIncreasingSubsequence) +} + +func TestLongestIncreasingSubsequenceGreedy(t *testing.T) { + longestIncreasingSubsequenceTest(t, dynamic.LongestIncreasingSubsequenceGreedy) +} diff --git a/dynamic/longestincreasingsubsequencegreedy.go b/dynamic/longestincreasingsubsequencegreedy.go new file mode 100644 index 000000000..438836527 --- /dev/null +++ b/dynamic/longestincreasingsubsequencegreedy.go @@ -0,0 +1,43 @@ +package dynamic + +// LongestIncreasingSubsequenceGreedy is a function to find the longest increasing +// subsequence in a given array using a greedy approach. +// The dynamic programming approach is implemented alongside this one. +// Worst Case Time Complexity: O(nlogn) +// Auxiliary Space: O(n), where n is the length of the array(slice). +// Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ +func LongestIncreasingSubsequenceGreedy(nums []int) int { + longestIncreasingSubsequnce := make([]int, 0) + + for _, num := range nums { + // find the leftmost index in longestIncreasingSubsequnce with value >= num + leftmostIndex := lowerBound(longestIncreasingSubsequnce, num) + + if leftmostIndex == len(longestIncreasingSubsequnce) { + longestIncreasingSubsequnce = append(longestIncreasingSubsequnce, num) + } else { + longestIncreasingSubsequnce[leftmostIndex] = num + } + } + + return len(longestIncreasingSubsequnce) +} + +// Function to find the leftmost index in arr with value >= val, mimicking the inbuild lower_bound function in C++ +// Time Complexity: O(logn) +// Auxiliary Space: O(1) +func lowerBound(arr []int, val int) int { + searchWindowLeft, searchWindowRight := 0, len(arr)-1 + + for searchWindowLeft <= searchWindowRight { + middle := (searchWindowLeft + searchWindowRight) / 2 + + if arr[middle] < val { + searchWindowLeft = middle + 1 + } else { + searchWindowRight = middle - 1 + } + } + + return searchWindowRight + 1 +} From 4f29592b5402d834ee6eccfcafe946124902fdb9 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Fri, 11 Mar 2022 07:24:43 +0300 Subject: [PATCH 032/202] merge: Added Square root algorithm using fast inverse square root (#471) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * feat: bitwise sqrt * Updated Documentation in README.md * add comment * fix after review * fix: bitwise sqrt and test Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 3 ++- math/binary/sqrt.go | 24 +++++++++++++++++++ math/binary/sqrt_test.go | 50 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 math/binary/sqrt.go create mode 100644 math/binary/sqrt_test.go diff --git a/README.md b/README.md index a608159be..4521e550b 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 6. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift 7. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. 8. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n -9. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +9. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. +10. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
diff --git a/math/binary/sqrt.go b/math/binary/sqrt.go new file mode 100644 index 000000000..4d352ed49 --- /dev/null +++ b/math/binary/sqrt.go @@ -0,0 +1,24 @@ +// sqrt.go +// description: Square root calculation +// details: +// Calculating the square root using binary operations and a magic number 0x5f3759df [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root) +// author(s) [red_byte](https://github.com/i-redbyte) +// see sqrt_test.go + +package binary + +import ( + "math" +) + +const threeHalves = 1.5 + +func Sqrt(number float32) float32 { + var halfHumber, y float32 + halfHumber = number * 0.5 + z := math.Float32bits(number) + z = 0x5f3759df - (z >> 1) // floating point bit level hacking + y = math.Float32frombits(z) + y = y * (threeHalves - (halfHumber * y * y)) // Newton's approximation + return 1 / y +} diff --git a/math/binary/sqrt_test.go b/math/binary/sqrt_test.go new file mode 100644 index 000000000..426794fd2 --- /dev/null +++ b/math/binary/sqrt_test.go @@ -0,0 +1,50 @@ +// sqrt_test.go +// description: Test for square root calculation +// author(s) [red_byte](https://github.com/i-redbyte) +// see sqrt.go + +package binary + +import ( + "math" + "testing" +) + +const epsilon = 0.2 + +func TestSquareRootCalculation(t *testing.T) { + tests := []struct { + name string + number float32 + want float64 + }{ + {"sqrt(1)", 1, 1}, + {"sqrt(9)", 9, 3}, + {"sqrt(25)", 25, 5}, + {"sqrt(121)", 121, 11}, + {"sqrt(10000)", 10000, 100}, + {"sqrt(169)", 169, 13}, + {"sqrt(0)", 0, 0}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Sqrt(test.number) + delta := math.Abs(test.want - float64(got)) + if delta > epsilon { + t.Errorf("Sqrt() = %v, want %v delta %v", got, test.want, delta) + } + }) + } +} + +func BenchmarkSquareRootCalculation(b *testing.B) { + for i := 0; i < b.N; i++ { + Sqrt(225) + } +} + +func BenchmarkMathSqrt(b *testing.B) { + for i := 0; i < b.N; i++ { + math.Sqrt(225) + } +} From b875ba70940e17418904f25b0c6ad08b674a19aa Mon Sep 17 00:00:00 2001 From: XU ZHIWEI Date: Fri, 11 Mar 2022 19:10:34 +0800 Subject: [PATCH 033/202] feat: implementation of find kth element in array (#472) (#473) * feat: implementation of find kth element in array (#472) * feat: implementation of find kth element in array * feat: implementation of find kth element in array * Updated Documentation in README.md Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Rak Laptudirm --- README.md | 21 +++++---- math/kthnumber.go | 43 +++++++++++++++++ math/kthnumber_test.go | 104 +++++++++++++++++++++++++++++++++++++++++ sort/quicksort.go | 4 +- 4 files changed, 161 insertions(+), 11 deletions(-) create mode 100644 math/kthnumber.go create mode 100644 math/kthnumber_test.go diff --git a/README.md b/README.md index 4521e550b..8b3a9287c 100644 --- a/README.md +++ b/README.md @@ -545,8 +545,10 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Abs`](./math/abs.go#L11): Abs returns absolute value -2. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -3. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +2. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +3. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +4. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +5. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. ---
@@ -861,13 +863,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 6. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. 7. [`MergeIter`](./sort/mergesort.go#L51): No description provided. 8. [`Mergesort`](./sort/mergesort.go#L37): Mergesort Perform mergesort on a slice of ints -9. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -10. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array -11. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array -12. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -13. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. -14. [`ShellSort`](./sort/shellsort.go#L3): No description provided. -15. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. +9. [`Partition`](./sort/quicksort.go#L10): No description provided. +10. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +11. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array +12. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array +13. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +14. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. +15. [`ShellSort`](./sort/shellsort.go#L3): No description provided. +16. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. --- ##### Types diff --git a/math/kthnumber.go b/math/kthnumber.go new file mode 100644 index 000000000..802e2cf50 --- /dev/null +++ b/math/kthnumber.go @@ -0,0 +1,43 @@ +package math + +import ( + "github.com/TheAlgorithms/Go/search" + "github.com/TheAlgorithms/Go/sort" +) + +// FindKthMax returns the kth large element given an integer slice +// with nil `error` if found and returns -1 with `error` `search.ErrNotFound` +// if not found. NOTE: The `nums` slice gets mutated in the process. +func FindKthMax(nums []int, k int) (int, error) { + index := len(nums) - k + return kthNumber(nums, index) +} + +// FindKthMin returns kth small element given an integer slice +// with nil `error` if found and returns -1 with `error` `search.ErrNotFound` +// if not found. NOTE: The `nums` slice gets mutated in the process. +func FindKthMin(nums []int, k int) (int, error) { + index := k - 1 + return kthNumber(nums, index) +} + +// kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort). +func kthNumber(nums []int, k int) (int, error) { + if k < 0 || k >= len(nums) { + return -1, search.ErrNotFound + } + start := 0 + end := len(nums) - 1 + for start <= end { + pivot := sort.Partition(nums, start, end) + if k == pivot { + return nums[pivot], nil + } + if k > pivot { + start = pivot + 1 + continue + } + end = pivot - 1 + } + return -1, search.ErrNotFound +} diff --git a/math/kthnumber_test.go b/math/kthnumber_test.go new file mode 100644 index 000000000..558cf2240 --- /dev/null +++ b/math/kthnumber_test.go @@ -0,0 +1,104 @@ +package math + +import ( + "github.com/TheAlgorithms/Go/search" + "testing" +) + +func TestFindKthMax(t *testing.T) { + sortTests := []struct { + input []int + k int + expected int + err error + name string + }{ + { + input: []int{6, 7, 0, -1, 10, 70, 8, 22, 3, 9}, + k: 3, + expected: 10, + name: "3th largest number", + }, + { + input: []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + k: 3, + expected: -1, + name: "3th largest number", + }, + { + input: []int{-1, -1, -1, -1, -1, -1}, + k: 7, + expected: -1, + err: search.ErrNotFound, + name: "This should be an error", + }, + { + input: []int{}, + k: 1, + expected: -1, + err: search.ErrNotFound, + name: "This should be an error", + }, + } + for _, test := range sortTests { + t.Run(test.name, func(t *testing.T) { + actual, err := FindKthMax(test.input, test.k) + if err != test.err { + t.Errorf("name:%v FindKthMax() = %v, want err: %v", test.name, err, test.err) + } + if actual != test.expected { + t.Errorf("test %s failed", test.name) + t.Errorf("actual %v expected %v", actual, test.expected) + } + }) + } +} + +func TestFindKthMin(t *testing.T) { + sortTests := []struct { + input []int + k int + expected int + err error + name string + }{ + { + input: []int{6, 7, 0, -1, 10, 70, 8, 22, 3, 9}, + k: 3, + expected: 3, + name: "3th smallest number", + }, + { + input: []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + k: 3, + expected: -1, + name: "3th smallest number", + }, + { + input: []int{-1, -1, -1, -1, -1, -1}, + k: 7, + expected: -1, + err: search.ErrNotFound, + name: "This should be an error", + }, + { + input: []int{}, + k: 1, + expected: -1, + err: search.ErrNotFound, + name: "This should be an error", + }, + } + for _, test := range sortTests { + t.Run(test.name, func(t *testing.T) { + actual, err := FindKthMin(test.input, test.k) + if err != test.err { + t.Errorf("name:%v FindKthMin() = %v, want err: %v", test.name, err, test.err) + } + if actual != test.expected { + t.Errorf("test %s failed", test.name) + t.Errorf("actual %v expected %v", actual, test.expected) + } + }) + } +} diff --git a/sort/quicksort.go b/sort/quicksort.go index 6ecbac20e..36319cbea 100644 --- a/sort/quicksort.go +++ b/sort/quicksort.go @@ -7,7 +7,7 @@ package sort -func partition(arr []int, low, high int) int { +func Partition(arr []int, low, high int) int { index := low - 1 pivotElement := arr[high] for i := low; i < high; i++ { @@ -27,7 +27,7 @@ func QuickSortRange(arr []int, low, high int) { } if low < high { - pivot := partition(arr, low, high) + pivot := Partition(arr, low, high) QuickSortRange(arr, low, pivot-1) QuickSortRange(arr, pivot+1, high) } From 3c6401000f114f9b370df952ee6ae890f77ce3f6 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 17 Mar 2022 22:42:33 +0300 Subject: [PATCH 034/202] package name geometry (#474) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * add package description and add function name to comment * Updated Documentation in README.md * rename Intercept method to YIntercept * Updated Documentation in README.md * fix strings * Updated Documentation in README.md Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 21 ++++++++++++--------- math/geometry/straightlines.go | 19 ++++++++++--------- math/geometry/straightlines_test.go | 4 ++-- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 8b3a9287c..4d97baa6f 100644 --- a/README.md +++ b/README.md @@ -382,22 +382,25 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- +##### Package geometry contains geometric algorithms + +--- ##### Functions: -1. [`Distance`](./math/geometry/straightlines.go#L17): Calculates the shortest distance between two points. -2. [`Intercept`](./math/geometry/straightlines.go#L36): Calculates the Y-Intercept of a line from a specific Point. -3. [`IsParallel`](./math/geometry/straightlines.go#L41): Checks if two lines are parallel or not. -4. [`IsPerpendicular`](./math/geometry/straightlines.go#L46): Checks if two lines are perpendicular or not. -5. [`PointDistance`](./math/geometry/straightlines.go#L52): Calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. -6. [`Section`](./math/geometry/straightlines.go#L23): Calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. -7. [`Slope`](./math/geometry/straightlines.go#L31): Calculates the slope (gradient) of a line. +1. [`Distance`](./math/geometry/straightlines.go#L18): Distance calculates the shortest distance between two points. +2. [`IsParallel`](./math/geometry/straightlines.go#L42): IsParallel checks if two lines are parallel or not. +3. [`IsPerpendicular`](./math/geometry/straightlines.go#L47): IsPerpendicular checks if two lines are perpendicular or not. +4. [`PointDistance`](./math/geometry/straightlines.go#L53): PointDistance calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. +5. [`Section`](./math/geometry/straightlines.go#L24): Section calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. +6. [`Slope`](./math/geometry/straightlines.go#L32): Slope calculates the slope (gradient) of a line. +7. [`YIntercept`](./math/geometry/straightlines.go#L37): YIntercept calculates the Y-Intercept of a line from a specific Point. --- ##### Types -1. [`Line`](./math/geometry/straightlines.go#L12): No description provided. +1. [`Line`](./math/geometry/straightlines.go#L13): No description provided. -2. [`Point`](./math/geometry/straightlines.go#L8): No description provided. +2. [`Point`](./math/geometry/straightlines.go#L9): No description provided. --- diff --git a/math/geometry/straightlines.go b/math/geometry/straightlines.go index 355263581..cf1951b07 100644 --- a/math/geometry/straightlines.go +++ b/math/geometry/straightlines.go @@ -1,10 +1,11 @@ +// Package geometry contains geometric algorithms package geometry import ( "math" ) -// Defines a point with x and y coordinates. +// Point defines a point with x and y coordinates. type Point struct { X, Y float64 } @@ -13,12 +14,12 @@ type Line struct { P1, P2 Point } -// Calculates the shortest distance between two points. +// Distance calculates the shortest distance between two points. func Distance(a, b *Point) float64 { return math.Sqrt(math.Pow(a.X-b.X, 2) + math.Pow(a.Y-b.Y, 2)) } -// Calculates the Point that divides a line in specific ratio. +// Section calculates the Point that divides a line in specific ratio. // DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. func Section(p1, p2 *Point, r float64) Point { var point Point @@ -27,27 +28,27 @@ func Section(p1, p2 *Point, r float64) Point { return point } -// Calculates the slope (gradient) of a line. +// Slope calculates the slope (gradient) of a line. func Slope(l *Line) float64 { return (l.P2.Y - l.P1.Y) / (l.P2.X - l.P1.X) } -// Calculates the Y-Intercept of a line from a specific Point. -func Intercept(p *Point, slope float64) float64 { +// YIntercept calculates the Y-Intercept of a line from a specific Point. +func YIntercept(p *Point, slope float64) float64 { return p.Y - (slope * p.X) } -// Checks if two lines are parallel or not. +// IsParallel checks if two lines are parallel or not. func IsParallel(l1, l2 *Line) bool { return Slope(l1) == Slope(l2) } -// Checks if two lines are perpendicular or not. +// IsPerpendicular checks if two lines are perpendicular or not. func IsPerpendicular(l1, l2 *Line) bool { return Slope(l1)*Slope(l2) == -1 } -// Calculates the distance of a given Point from a given line. +// PointDistance calculates the distance of a given Point from a given line. // The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. func PointDistance(p *Point, equation [3]float64) float64 { return math.Abs(equation[0]*p.X+equation[1]*p.Y+equation[2]) / math.Sqrt(math.Pow(equation[0], 2)+math.Pow(equation[1], 2)) diff --git a/math/geometry/straightlines_test.go b/math/geometry/straightlines_test.go index 262bc3147..d71a78e5a 100644 --- a/math/geometry/straightlines_test.go +++ b/math/geometry/straightlines_test.go @@ -37,9 +37,9 @@ func TestIntercept(t *testing.T) { p := Point{0, 3} var slope float64 = -5 var wantedIntercept float64 = 3 - var calculatedIntercept float64 = Intercept(&p, slope) + var calculatedIntercept float64 = YIntercept(&p, slope) if calculatedIntercept != wantedIntercept { - t.Fatalf("Failed to calculate Intercept.") + t.Fatalf("Failed to calculate YIntercept.") } } From 096521a617e96802dee5a2a0d90cd1ed17ed9b22 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Sun, 20 Mar 2022 22:32:55 +0300 Subject: [PATCH 035/202] Feat/cos (#475) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * add package description and add function name to comment * Updated Documentation in README.md * rename Intercept method to YIntercept * Updated Documentation in README.md * fix strings * Updated Documentation in README.md * fix commit * added Cosine function * Updated Documentation in README.md * fix after review * Updated Documentation in README.md * fixes * fix: doc comment Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 9 +++++---- math/cos.go | 17 +++++++++++++++++ math/cos_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) create mode 100644 math/cos.go create mode 100644 math/cos_test.go diff --git a/README.md b/README.md index 4d97baa6f..676a85def 100644 --- a/README.md +++ b/README.md @@ -548,10 +548,11 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Abs`](./math/abs.go#L11): Abs returns absolute value -2. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -3. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -4. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -5. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +2. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) +3. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +4. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +5. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +6. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. ---
diff --git a/math/cos.go b/math/cos.go new file mode 100644 index 000000000..369cd588c --- /dev/null +++ b/math/cos.go @@ -0,0 +1,17 @@ +// author(s) [red_byte](https://github.com/i-redbyte) +// see cos_test.go + +package math + +import "math" + +// Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +// [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) +func Cos(x float64) float64 { + tp := 1.0 / (2.0 * math.Pi) + x *= tp + x -= 0.25 + math.Floor(x+0.25) + x *= 16.0 * (math.Abs(x) - 0.5) + x += 0.225 * x * (math.Abs(x) - 1.0) //Extra precision + return x +} diff --git a/math/cos_test.go b/math/cos_test.go new file mode 100644 index 000000000..c1df66b8d --- /dev/null +++ b/math/cos_test.go @@ -0,0 +1,45 @@ +package math + +import ( + "math" + "testing" +) + +const epsilon = 0.001 + +func TestCos(t *testing.T) { + tests := []struct { + name string + n float64 + want float64 + }{ + {"cos(0)", 0, 1}, + {"cos(90)", 90, -0.447}, + {"cos(180)", 180, -0.598}, + {"cos(1)", 1, 0.540}, + {"cos(1)", math.Pi, -1}, + {"cos(1)", math.Pi / 2, 0}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Cos(test.n) + if math.Abs(got-test.want) >= epsilon { + t.Errorf("Cos() = %v, want %v", got, test.want) + t.Errorf("MATH Cos() = %v", math.Cos(test.n)) + } + }) + } +} + +func BenchmarkCos(b *testing.B) { + for i := 0; i < b.N; i++ { + Cos(180) + } +} + +// BenchmarkMathCos is slower because the standard library `math.Cos` calculates a more accurate value. +func BenchmarkMathCos(b *testing.B) { + for i := 0; i < b.N; i++ { + math.Cos(180) + } +} From 322859fc50fb1a2b1014919222bae869cdf5389c Mon Sep 17 00:00:00 2001 From: Taj Date: Sat, 26 Mar 2022 19:35:51 +0000 Subject: [PATCH 036/202] fix: [generic + sort] All ready for generics (#483) * fix: [generic + sort] All ready for generics * GoDocMD support for Go 1.18 * Bump Go version in workflow * Updated Documentation in README.md * bump go version in GoLangCI lint action * fix: [generic + sort] review feedback * Updated Documentation in README.md * empty commit: stuck github action Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- .github/workflows/godocmd.yml | 4 +- .github/workflows/golang_lint_and_test.yml | 2 + README.md | 33 ++++++------ constraints/contraints.go | 40 ++++++++++++++ go.mod | 2 +- sort/bubblesort.go | 5 +- sort/combSort.go | 5 +- sort/countingsort.go | 6 ++- sort/exchangesort.go | 4 +- sort/insertionsort.go | 4 +- sort/mergesort.go | 19 ++++--- sort/quicksort.go | 18 ++++--- sort/selectionsort.go | 3 +- sort/shellsort.go | 4 +- sort/simplesort.go | 8 +-- sort/sorts_test.go | 63 +++++++++++----------- 16 files changed, 143 insertions(+), 77 deletions(-) create mode 100644 constraints/contraints.go diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index 3b4f0ef4c..b69bf13d9 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -9,10 +9,10 @@ jobs: fetch-depth: 0 - uses: actions/setup-go@v2 with: - go-version: '^1.17' + go-version: '^1.18' - name: Install GoDocMD run: | - go install github.com/tjgurwara99/godocmd@v0.1.2 + go install github.com/tjgurwara99/godocmd@v0.1.3 - name: Configure Github Action run: | git config --global user.name github-action diff --git a/.github/workflows/golang_lint_and_test.yml b/.github/workflows/golang_lint_and_test.yml index 4cb59f712..29a2a9283 100644 --- a/.github/workflows/golang_lint_and_test.yml +++ b/.github/workflows/golang_lint_and_test.yml @@ -15,6 +15,8 @@ jobs: skip: "go.mod,go.sum" - name: Setup Go uses: actions/setup-go@v2 + with: + go-version: '^1.18' - name: Run Golang CI Lint uses: golangci/golangci-lint-action@v2 with: diff --git a/README.md b/README.md index 676a85def..da8fb416b 100644 --- a/README.md +++ b/README.md @@ -859,22 +859,23 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`Comb`](./sort/combSort.go#L14): No description provided. -2. [`Count`](./sort/countingsort.go#L9): No description provided. -3. [`Exchange`](./sort/exchangesort.go#L6): No description provided. -4. [`HeapSort`](./sort/heapsort.go#L121): No description provided. -5. [`ImprovedSimpleSort`](./sort/simplesort.go#L25): ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort -6. [`InsertionSort`](./sort/insertionsort.go#L3): No description provided. -7. [`MergeIter`](./sort/mergesort.go#L51): No description provided. -8. [`Mergesort`](./sort/mergesort.go#L37): Mergesort Perform mergesort on a slice of ints -9. [`Partition`](./sort/quicksort.go#L10): No description provided. -10. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -11. [`QuickSort`](./sort/quicksort.go#L37): QuickSort Sorts the entire array -12. [`QuickSortRange`](./sort/quicksort.go#L24): QuickSortRange Sorts the specified range within the array -13. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -14. [`SelectionSort`](./sort/selectionsort.go#L3): No description provided. -15. [`ShellSort`](./sort/shellsort.go#L3): No description provided. -16. [`SimpleSort`](./sort/simplesort.go#L11): No description provided. +1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. +2. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. +3. [`Count`](./sort/countingsort.go#L11): No description provided. +4. [`Exchange`](./sort/exchangesort.go#L8): No description provided. +5. [`HeapSort`](./sort/heapsort.go#L121): No description provided. +6. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +7. [`Insertion`](./sort/insertionsort.go#L5): No description provided. +8. [`Merge`](./sort/mergesort.go#L40): Merge Perform merge sort on a slice +9. [`MergeIter`](./sort/mergesort.go#L54): No description provided. +10. [`Partition`](./sort/quicksort.go#L12): No description provided. +11. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +12. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +13. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +14. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +15. [`Selection`](./sort/selectionsort.go#L5): No description provided. +16. [`Shell`](./sort/shellsort.go#L5): No description provided. +17. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types diff --git a/constraints/contraints.go b/constraints/contraints.go new file mode 100644 index 000000000..ca902cec5 --- /dev/null +++ b/constraints/contraints.go @@ -0,0 +1,40 @@ +// Package constraints has some useful generic type constraints defined which is very similar to +// [golang.org/x/exp/constraints](https://pkg.go.dev/golang.org/x/exp/constraints) package. +// We refrained from using that until it gets placed into the standard library - currently +// there are some questions regarding this package [ref](https://github.com/golang/go/issues/50792). +package constraints + +// Signed is a generic type constraint for all signed integers. +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// Unsigned is a generic type constraint for all unsigned integers. +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 +} + +// Integer is a generic type constraint for all integers (signed and unsigned.) +type Integer interface { + Signed | Unsigned +} + +// Float is a generic type constraint for all floating point types. +type Float interface { + ~float32 | ~float64 +} + +// Number is a generic type constraint for all numeric types in Go except Complex types. +type Number interface { + Integer | Float +} + +// Ordered is a generic type constraint for all ordered data types in Go. +// Loosely speaking, in mathematics a field is an ordered field if there is a "total +// order" (a binary relation - in this case `<` symbol) such that we will always have +// if a < b then a + c < b + c and if 0 < a, 0 < b then 0 < a.b +// The idea in Go is quite similar, though only limited to Go standard types +// not user defined types. +type Ordered interface { + Integer | ~string | Float +} diff --git a/go.mod b/go.mod index e7de82f0c..23f37df27 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/TheAlgorithms/Go -go 1.17 +go 1.18 diff --git a/sort/bubblesort.go b/sort/bubblesort.go index 83242e5c5..4c40678b7 100644 --- a/sort/bubblesort.go +++ b/sort/bubblesort.go @@ -3,7 +3,10 @@ package sort -func bubbleSort(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +// Bubble is a simple generic definition of Bubble sort algorithm. +func Bubble[T constraints.Ordered](arr []T) []T { swapped := true for swapped { swapped = false diff --git a/sort/combSort.go b/sort/combSort.go index fa7b173d9..76e523e34 100644 --- a/sort/combSort.go +++ b/sort/combSort.go @@ -3,6 +3,8 @@ package sort +import "github.com/TheAlgorithms/Go/constraints" + func getNextGap(gap int) int { gap = (gap * 10) / 13 if gap < 1 { @@ -11,7 +13,8 @@ func getNextGap(gap int) int { return gap } -func Comb(data []int) []int { +// Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. +func Comb[T constraints.Ordered](data []T) []T { n := len(data) gap := n swapped := true diff --git a/sort/countingsort.go b/sort/countingsort.go index 3dae5934a..6961efff8 100644 --- a/sort/countingsort.go +++ b/sort/countingsort.go @@ -6,11 +6,13 @@ package sort -func Count(data []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +func Count[T constraints.Number](data []int) []int { var aMin, aMax = -1000, 1000 count := make([]int, aMax-aMin+1) for _, x := range data { - count[x-aMin]++ + count[x-aMin]++ // this is the reason for having only Number constraint instead of Ordered. } z := 0 for i, c := range count { diff --git a/sort/exchangesort.go b/sort/exchangesort.go index b901490cb..cbf6b9b00 100644 --- a/sort/exchangesort.go +++ b/sort/exchangesort.go @@ -3,7 +3,9 @@ package sort -func Exchange(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +func Exchange[T constraints.Ordered](arr []T) []T { for i := 0; i < len(arr)-1; i++ { for j := i + 1; j < len(arr); j++ { if arr[i] > arr[j] { diff --git a/sort/insertionsort.go b/sort/insertionsort.go index 11f0cd922..b51bc5379 100644 --- a/sort/insertionsort.go +++ b/sort/insertionsort.go @@ -1,6 +1,8 @@ package sort -func InsertionSort(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +func Insertion[T constraints.Ordered](arr []T) []T { for currentIndex := 1; currentIndex < len(arr); currentIndex++ { temporary := arr[currentIndex] iterator := currentIndex diff --git a/sort/mergesort.go b/sort/mergesort.go index 45c17ab04..babff39f1 100644 --- a/sort/mergesort.go +++ b/sort/mergesort.go @@ -1,10 +1,13 @@ package sort -import "github.com/TheAlgorithms/Go/math/min" +import ( + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math/min" +) -func merge(a []int, b []int) []int { +func merge[T constraints.Ordered](a []T, b []T) []T { - var r = make([]int, len(a)+len(b)) + var r = make([]T, len(a)+len(b)) var i = 0 var j = 0 @@ -33,8 +36,8 @@ func merge(a []int, b []int) []int { } -//Mergesort Perform mergesort on a slice of ints -func Mergesort(items []int) []int { +// Merge Perform merge sort on a slice +func Merge[T constraints.Ordered](items []T) []T { if len(items) < 2 { return items @@ -42,13 +45,13 @@ func Mergesort(items []int) []int { } var middle = len(items) / 2 - var a = Mergesort(items[:middle]) - var b = Mergesort(items[middle:]) + var a = Merge(items[:middle]) + var b = Merge(items[middle:]) return merge(a, b) } -func MergeIter(items []int) []int { +func MergeIter[T constraints.Ordered](items []T) []T { for step := 1; step < len(items); step += step { for i := 0; i+step < len(items); i += 2 * step { tmp := merge(items[i:i+step], items[i+step:min.Int(i+2*step, len(items))]) diff --git a/sort/quicksort.go b/sort/quicksort.go index 36319cbea..576db395a 100644 --- a/sort/quicksort.go +++ b/sort/quicksort.go @@ -7,7 +7,9 @@ package sort -func Partition(arr []int, low, high int) int { +import "github.com/TheAlgorithms/Go/constraints" + +func Partition[T constraints.Ordered](arr []T, low, high int) int { index := low - 1 pivotElement := arr[high] for i := low; i < high; i++ { @@ -20,21 +22,21 @@ func Partition(arr []int, low, high int) int { return index + 1 } -// QuickSortRange Sorts the specified range within the array -func QuickSortRange(arr []int, low, high int) { +// QuicksortRange Sorts the specified range within the array +func QuicksortRange[T constraints.Ordered](arr []T, low, high int) { if len(arr) <= 1 { return } if low < high { pivot := Partition(arr, low, high) - QuickSortRange(arr, low, pivot-1) - QuickSortRange(arr, pivot+1, high) + QuicksortRange(arr, low, pivot-1) + QuicksortRange(arr, pivot+1, high) } } -// QuickSort Sorts the entire array -func QuickSort(arr []int) []int { - QuickSortRange(arr, 0, len(arr)-1) +// Quicksort Sorts the entire array +func Quicksort[T constraints.Ordered](arr []T) []T { + QuicksortRange(arr, 0, len(arr)-1) return arr } diff --git a/sort/selectionsort.go b/sort/selectionsort.go index 95fd4ffa1..b86000a9b 100644 --- a/sort/selectionsort.go +++ b/sort/selectionsort.go @@ -1,7 +1,8 @@ package sort -func SelectionSort(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" +func Selection[T constraints.Ordered](arr []T) []T { for i := 0; i < len(arr); i++ { min := i for j := i + 1; j < len(arr); j++ { diff --git a/sort/shellsort.go b/sort/shellsort.go index 28f76dcae..fb04f6f7c 100644 --- a/sort/shellsort.go +++ b/sort/shellsort.go @@ -1,6 +1,8 @@ package sort -func ShellSort(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +func Shell[T constraints.Ordered](arr []T) []T { for d := int(len(arr) / 2); d > 0; d /= 2 { for i := d; i < len(arr); i++ { for j := i; j >= d && arr[j-d] > arr[j]; j -= d { diff --git a/sort/simplesort.go b/sort/simplesort.go index 39f3a55f9..ec54c1db0 100644 --- a/sort/simplesort.go +++ b/sort/simplesort.go @@ -8,7 +8,9 @@ package sort -func SimpleSort(arr []int) []int { +import "github.com/TheAlgorithms/Go/constraints" + +func Simple[T constraints.Ordered](arr []T) []T { for i := 0; i < len(arr); i++ { for j := 0; j < len(arr); j++ { if arr[i] < arr[j] { @@ -20,9 +22,9 @@ func SimpleSort(arr []int) []int { return arr } -// ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last. +// ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. // This improved version is more similar to implementation of insertion sort -func ImprovedSimpleSort(arr []int) []int { +func ImprovedSimple[T constraints.Ordered](arr []T) []T { for i := 1; i < len(arr); i++ { for j := 0; j < len(arr)-1; j++ { if arr[i] < arr[j] { diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 828b907cb..08b6a716d 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -1,6 +1,7 @@ -package sort +package sort_test import ( + "github.com/TheAlgorithms/Go/sort" "reflect" "testing" ) @@ -75,63 +76,63 @@ func testFramework(t *testing.T, sortingFunction func([]int) []int) { //BEGIN TESTS func TestBubble(t *testing.T) { - testFramework(t, bubbleSort) + testFramework(t, sort.Bubble[int]) } func TestExchange(t *testing.T) { - testFramework(t, Exchange) + testFramework(t, sort.Exchange[int]) } func TestInsertion(t *testing.T) { - testFramework(t, InsertionSort) + testFramework(t, sort.Insertion[int]) } func TestMerge(t *testing.T) { - testFramework(t, Mergesort) + testFramework(t, sort.Merge[int]) } func TestMergeIter(t *testing.T) { - testFramework(t, MergeIter) + testFramework(t, sort.MergeIter[int]) } func TestHeap(t *testing.T) { - testFramework(t, HeapSort) + testFramework(t, sort.HeapSort) } func TestCount(t *testing.T) { - testFramework(t, Count) + testFramework(t, sort.Count[int]) } func TestQuick(t *testing.T) { - testFramework(t, QuickSort) + testFramework(t, sort.Quicksort[int]) } func TestShell(t *testing.T) { - testFramework(t, ShellSort) + testFramework(t, sort.Shell[int]) } func TestRadix(t *testing.T) { - testFramework(t, RadixSort) + testFramework(t, sort.RadixSort) } func TestSimple(t *testing.T) { - testFramework(t, SimpleSort) + testFramework(t, sort.Simple[int]) } func TestImprovedSimple(t *testing.T) { - testFramework(t, ImprovedSimpleSort) + testFramework(t, sort.ImprovedSimple[int]) } func TestSelection(t *testing.T) { - testFramework(t, SelectionSort) + testFramework(t, sort.Selection[int]) } func TestComb(t *testing.T) { - testFramework(t, Comb) + testFramework(t, sort.Comb[int]) } func TestPigeonhole(t *testing.T) { - testFramework(t, Pigeonhole) + testFramework(t, sort.Pigeonhole) } //END TESTS @@ -176,62 +177,62 @@ func benchmarkFramework(b *testing.B, f func(arr []int) []int) { //BEGIN BENCHMARKS func BenchmarkBubble(b *testing.B) { - benchmarkFramework(b, bubbleSort) + benchmarkFramework(b, sort.Bubble[int]) } func BenchmarkExchange(b *testing.B) { - benchmarkFramework(b, Exchange) + benchmarkFramework(b, sort.Exchange[int]) } func BenchmarkInsertion(b *testing.B) { - benchmarkFramework(b, InsertionSort) + benchmarkFramework(b, sort.Insertion[int]) } func BenchmarkMerge(b *testing.B) { - benchmarkFramework(b, Mergesort) + benchmarkFramework(b, sort.Merge[int]) } func BenchmarkMergeIter(b *testing.B) { - benchmarkFramework(b, MergeIter) + benchmarkFramework(b, sort.MergeIter[int]) } func BenchmarkHeap(b *testing.B) { - benchmarkFramework(b, HeapSort) + benchmarkFramework(b, sort.HeapSort) } func BenchmarkCount(b *testing.B) { - benchmarkFramework(b, Count) + benchmarkFramework(b, sort.Count[int]) } func BenchmarkQuick(b *testing.B) { - benchmarkFramework(b, QuickSort) + benchmarkFramework(b, sort.Quicksort[int]) } func BenchmarkShell(b *testing.B) { - benchmarkFramework(b, ShellSort) + benchmarkFramework(b, sort.Shell[int]) } func BenchmarkRadix(b *testing.B) { - benchmarkFramework(b, RadixSort) + benchmarkFramework(b, sort.RadixSort) } func BenchmarkSimple(b *testing.B) { - benchmarkFramework(b, SimpleSort) + benchmarkFramework(b, sort.Simple[int]) } func BenchmarkImprovedSimple(b *testing.B) { - benchmarkFramework(b, ImprovedSimpleSort) + benchmarkFramework(b, sort.ImprovedSimple[int]) } // Very Slow, consider commenting func BenchmarkSelection(b *testing.B) { - benchmarkFramework(b, SelectionSort) + benchmarkFramework(b, sort.Selection[int]) } func BenchmarkComb(b *testing.B) { - benchmarkFramework(b, Comb) + benchmarkFramework(b, sort.Comb[int]) } func BenchmarkPigeonhole(b *testing.B) { - benchmarkFramework(b, Pigeonhole) + benchmarkFramework(b, sort.Pigeonhole) } From 5e4bc7eeab0236ddc990185e18f2a8e3325db805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BA=84=E5=85=A8=E8=9B=8B?= Date: Sun, 27 Mar 2022 14:38:55 +0800 Subject: [PATCH 037/202] merge: Add LowerBound and UpperBound algorithms (#482) * feat:add LowerBound and UpperBound * fix:gofmt -s -w binary.go * enhancement:for iterate 0,len(array)-1 instead of pass lowIndex,highIndex Co-authored-by: zhuangyongxin Co-authored-by: Rak Laptudirm --- search/binary.go | 50 ++++++++++++++++++++++++++++++++++++++++--- search/binary_test.go | 44 +++++++++++++++++++++++++++++++++++-- search/testcases.go | 28 ++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 5 deletions(-) diff --git a/search/binary.go b/search/binary.go index 7692813d7..c30e4b291 100644 --- a/search/binary.go +++ b/search/binary.go @@ -20,9 +20,9 @@ func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) { // BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target. // Unlike Binary, this function uses iterative method and not recursive. // If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound. -func BinaryIterative(array []int, target int, lowIndex int, highIndex int) (int, error) { - startIndex := lowIndex - endIndex := highIndex +func BinaryIterative(array []int, target int) (int, error) { + startIndex := 0 + endIndex := len(array) - 1 var mid int for startIndex <= endIndex { mid = int(startIndex + (endIndex-startIndex)/2) @@ -36,3 +36,47 @@ func BinaryIterative(array []int, target int, lowIndex int, highIndex int) (int, } return -1, ErrNotFound } + +//Returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. +//return -1 and ErrNotFound if no such element is found. +func LowerBound(array []int, target int) (int, error) { + startIndex := 0 + endIndex := len(array) - 1 + var mid int + for startIndex <= endIndex { + mid = int(startIndex + (endIndex-startIndex)/2) + if array[mid] < target { + startIndex = mid + 1 + } else { + endIndex = mid - 1 + } + } + + //when target greater than every element in array, startIndex will out of bounds + if startIndex >= len(array) { + return -1, ErrNotFound + } + return startIndex, nil +} + +//Returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. +//return -1 and ErrNotFound if no such element is found. +func UpperBound(array []int, target int) (int, error) { + startIndex := 0 + endIndex := len(array) - 1 + var mid int + for startIndex <= endIndex { + mid = int(startIndex + (endIndex-startIndex)/2) + if array[mid] > target { + endIndex = mid - 1 + } else { + startIndex = mid + 1 + } + } + + //when target greater or equal than every element in array, startIndex will out of bounds + if startIndex >= len(array) { + return -1, ErrNotFound + } + return startIndex, nil +} diff --git a/search/binary_test.go b/search/binary_test.go index ec3e563cc..ea77bf817 100644 --- a/search/binary_test.go +++ b/search/binary_test.go @@ -16,7 +16,31 @@ func TestBinary(t *testing.T) { func TestBinaryIterative(t *testing.T) { for _, test := range searchTests { - actualValue, actualError := BinaryIterative(test.data, test.key, 0, len(test.data)-1) + actualValue, actualError := BinaryIterative(test.data, test.key) + if actualValue != test.expected { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) + } + if actualError != test.expectedError { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) + } + } +} + +func TestLowerBound(t *testing.T) { + for _, test := range lowerBoundTests { + actualValue, actualError := LowerBound(test.data, test.key) + if actualValue != test.expected { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) + } + if actualError != test.expectedError { + t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) + } + } +} + +func TestUpperBound(t *testing.T) { + for _, test := range uppperBoundTests { + actualValue, actualError := UpperBound(test.data, test.key) if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) } @@ -38,6 +62,22 @@ func BenchmarkBinaryIterative(b *testing.B) { testCase := generateBenchmarkTestCase() b.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive for i := 0; i < b.N; i++ { - _, _ = BinaryIterative(testCase, i, 0, len(testCase)-1) + _, _ = BinaryIterative(testCase, i) + } +} + +func BenchmarkLowerBound(b *testing.B) { + testCase := generateBenchmarkTestCase() + b.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive + for i := 0; i < b.N; i++ { + _, _ = LowerBound(testCase, i) + } +} + +func BenchmarkUpperBound(b *testing.B) { + testCase := generateBenchmarkTestCase() + b.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive + for i := 0; i < b.N; i++ { + _, _ = UpperBound(testCase, i) } } diff --git a/search/testcases.go b/search/testcases.go index eacbaeb4f..7e02bc5c8 100644 --- a/search/testcases.go +++ b/search/testcases.go @@ -29,6 +29,34 @@ var searchTests = []searchTest{ {[]int{}, 2, -1, ErrNotFound, "Empty"}, } +var lowerBoundTests = []searchTest{ + //Sanity + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, -25, 0, nil, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 0, nil, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 4, nil, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, 9, nil, "Sanity"}, + {[]int{1, 2, 2, 2, 2, 6, 7, 8, 9, 10}, 2, 1, nil, "Sanity"}, + {[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 2, 0, nil, "Sanity"}, + //Absent + {[]int{1, 4, 5, 6, 7, 10}, 25, -1, ErrNotFound, "Absent"}, + //Empty slice + {[]int{}, 2, -1, ErrNotFound, "Empty"}, +} + +var uppperBoundTests = []searchTest{ + //Sanity + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, -25, 0, nil, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 1, nil, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 5, nil, "Sanity"}, + {[]int{1, 2, 2, 2, 2, 6, 7, 8, 9, 10}, 2, 5, nil, "Sanity"}, + //Absent + {[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 2, -1, ErrNotFound, "Sanity"}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, -1, ErrNotFound, "Sanity"}, + {[]int{1, 4, 5, 6, 7, 10}, 25, -1, ErrNotFound, "Absent"}, + //Empty slice + {[]int{}, 2, -1, ErrNotFound, "Empty"}, +} + // This function generate consistent testcase for benchmark test. func generateBenchmarkTestCase() []int { var testCase []int From f15028bcf4f66d0dd38bc5eadb5ebf48a6cc55a9 Mon Sep 17 00:00:00 2001 From: Paul Leydier <75126792+paul-leydier@users.noreply.github.com> Date: Tue, 29 Mar 2022 08:34:21 +0200 Subject: [PATCH 038/202] feat: Fuzzing test on Base64 encoding and decoding (#486) --- conversion/base64_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/conversion/base64_test.go b/conversion/base64_test.go index ed882634c..96342695a 100644 --- a/conversion/base64_test.go +++ b/conversion/base64_test.go @@ -109,3 +109,15 @@ func TestBase64EncodeDecodeInverse(t *testing.T) { } } } + +func FuzzBase64Encode(f *testing.F) { + f.Add([]byte("hello")) + f.Fuzz(func(t *testing.T, input []byte) { + result := Base64Decode(Base64Encode(input)) + for i := 0; i < len(input); i++ { + if result[i] != input[i] { + t.Fatalf("with input '%s' - expected '%s', got '%s' (mismatch at position %d)", input, input, result, i) + } + } + }) +} From bd8e6d52ba9f340761b6dc061fe43a5e5b7bbfd6 Mon Sep 17 00:00:00 2001 From: Taj Date: Wed, 30 Mar 2022 18:38:44 +0100 Subject: [PATCH 039/202] Fix: restructure checksum package (#485) * fix: [generic + sort] All ready for generics * GoDocMD support for Go 1.18 * Bump Go version in workflow * Updated Documentation in README.md * bump go version in GoLangCI lint action * fix: [generic + sort] review feedback * Updated Documentation in README.md * empty commit: stuck github action * fix: restructuring checksum package * Updated Documentation in README.md Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 39 +++++++++--------------- checksum/crc/crc8_test.go | 59 ------------------------------------ checksum/{crc => }/crc8.go | 7 ++--- checksum/crc8_test.go | 61 ++++++++++++++++++++++++++++++++++++++ checksum/luhn.go | 4 +-- checksum/luhn_test.go | 30 +++++++++++-------- 6 files changed, 97 insertions(+), 103 deletions(-) delete mode 100644 checksum/crc/crc8_test.go rename checksum/{crc => }/crc8.go (88%) create mode 100644 checksum/crc8_test.go diff --git a/README.md b/README.md index da8fb416b..f9f798a61 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`LuhnAlgorithm`](./checksum/luhn.go#L11): LuhnAlgorithm This function calculates the checksum using the Luna algorithm +1. [`CRC8`](./checksum/crc8.go#L25): CRC8 calculates CRC8 checksum of the given data. +2. [`Luhn`](./checksum/luhn.go#L11): Luhn validates the provided data using the Luhn algorithm. + +--- +##### Types + +1. [`CRCModel`](./checksum/crc8.go#L15): No description provided. + ---
@@ -217,30 +224,12 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`Base64Encode`](./conversion/base64.go#L19): Base64Encode encodes the received input bytes slice into a base64 string. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4 3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return it's Decimal equivalent as integer. 4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. -5. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue -6. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. -7. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex -8. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. -9. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. - ---- -
- crc - ---- - -##### Package crc describes algorithms for finding various CRC checksums - ---- -##### Functions: - -1. [`CalculateCRC8`](./checksum/crc/crc8.go#L26): CalculateCRC8 This function calculate CRC8 checksum. - ---- -##### Types - -1. [`CRCModel`](./checksum/crc/crc8.go#L16): No description provided. - +5. [`FuzzBase64Encode`](./conversion/base64_test.go#L113): No description provided. +6. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue +7. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. +8. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex +9. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. +10. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. ---
diff --git a/checksum/crc/crc8_test.go b/checksum/crc/crc8_test.go deleted file mode 100644 index ee6ac2188..000000000 --- a/checksum/crc/crc8_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// crc8_test.go -// description: Test for calculate crc8 -// author(s) [red_byte](https://github.com/i-redbyte) -// see crc8.go - -package crc - -import ( - "fmt" - "testing" -) - -var ( - CRC8 = CRCModel{0x07, 0x00, false, false, 0x00, "CRC-8"} - CRC8CDMA2000 = CRCModel{0x9B, 0xFF, false, false, 0x00, "CRC-8/CDMA2000"} - CRC8DARC = CRCModel{0x39, 0x00, true, true, 0x00, "CRC-8/DARC"} - CRC8DVBS2 = CRCModel{0xD5, 0x00, false, false, 0x00, "CRC-8/DVB-S2"} - CRC8EBU = CRCModel{0x1D, 0xFF, true, true, 0x00, "CRC-8/EBU"} - CRC8ICODE = CRCModel{0x1D, 0xFD, false, false, 0x00, "CRC-8/I-CODE"} - CRC8ITU = CRCModel{0x07, 0x00, false, false, 0x55, "CRC-8/ITU"} - CRC8MAXIM = CRCModel{0x31, 0x00, true, true, 0x00, "CRC-8/MAXIM"} - CRC8ROHC = CRCModel{0x07, 0xFF, true, true, 0x00, "CRC-8/ROHC"} - CRC8WCDMA = CRCModel{0x9B, 0x00, true, true, 0x00, "CRC-8/WCDMA"} -) - -func TestCalculateCRC8(t *testing.T) { - data := []byte("123456789") - tests := []struct { - name string - data []byte - model CRCModel - want uint8 - }{ - {CRC8.Name, data, CRC8, 0xF4}, - {CRC8CDMA2000.Name, data, CRC8CDMA2000, 0xDA}, - {CRC8DARC.Name, data, CRC8DARC, 0x15}, - {CRC8DVBS2.Name, data, CRC8DVBS2, 0xBC}, - {CRC8EBU.Name, data, CRC8EBU, 0x97}, - {CRC8ICODE.Name, data, CRC8ICODE, 0x7E}, - {CRC8ITU.Name, data, CRC8ITU, 0xA1}, - {CRC8MAXIM.Name, data, CRC8MAXIM, 0xA1}, - {CRC8ROHC.Name, data, CRC8ROHC, 0xD0}, - {CRC8WCDMA.Name, data, CRC8WCDMA, 0x25}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - fmt.Println(CalculateCRC8(test.data, test.model)) - if got := CalculateCRC8(test.data, test.model); got != test.want { - t.Errorf("CalculateCRC8() = %v, want %v", got, test.want) - } - }) - } -} - -func BenchmarkCalculateCRC8(b *testing.B) { - for i := 0; i < b.N; i++ { - CalculateCRC8([]byte("123456789"), CRC8) - } -} diff --git a/checksum/crc/crc8.go b/checksum/crc8.go similarity index 88% rename from checksum/crc/crc8.go rename to checksum/crc8.go index 3c69aeec2..fc73a9a40 100644 --- a/checksum/crc/crc8.go +++ b/checksum/crc8.go @@ -7,8 +7,7 @@ // author(s) [red_byte](https://github.com/i-redbyte) // see crc8_test.go -// Package crc describes algorithms for finding various CRC checksums -package crc +package checksum import "math/bits" @@ -22,8 +21,8 @@ type CRCModel struct { Name string } -// CalculateCRC8 This function calculate CRC8 checksum. -func CalculateCRC8(data []byte, model CRCModel) uint8 { +// CRC8 calculates CRC8 checksum of the given data. +func CRC8(data []byte, model CRCModel) uint8 { table := getTable(model) crcResult := model.Init crcResult = addBytes(data, model, crcResult, table) diff --git a/checksum/crc8_test.go b/checksum/crc8_test.go new file mode 100644 index 000000000..15e93e453 --- /dev/null +++ b/checksum/crc8_test.go @@ -0,0 +1,61 @@ +// crc8_test.go +// description: Test for calculate crc8 +// author(s) [red_byte](https://github.com/i-redbyte) +// see crc8.go + +package checksum_test + +import ( + "fmt" + "testing" + + "github.com/TheAlgorithms/Go/checksum" +) + +var ( + CRC8 = checksum.CRCModel{0x07, 0x00, false, false, 0x00, "CRC-8"} + CRC8CDMA2000 = checksum.CRCModel{0x9B, 0xFF, false, false, 0x00, "CRC-8/CDMA2000"} + CRC8DARC = checksum.CRCModel{0x39, 0x00, true, true, 0x00, "CRC-8/DARC"} + CRC8DVBS2 = checksum.CRCModel{0xD5, 0x00, false, false, 0x00, "CRC-8/DVB-S2"} + CRC8EBU = checksum.CRCModel{0x1D, 0xFF, true, true, 0x00, "CRC-8/EBU"} + CRC8ICODE = checksum.CRCModel{0x1D, 0xFD, false, false, 0x00, "CRC-8/I-CODE"} + CRC8ITU = checksum.CRCModel{0x07, 0x00, false, false, 0x55, "CRC-8/ITU"} + CRC8MAXIM = checksum.CRCModel{0x31, 0x00, true, true, 0x00, "CRC-8/MAXIM"} + CRC8ROHC = checksum.CRCModel{0x07, 0xFF, true, true, 0x00, "CRC-8/ROHC"} + CRC8WCDMA = checksum.CRCModel{0x9B, 0x00, true, true, 0x00, "CRC-8/WCDMA"} +) + +func TestCalculateCRC8(t *testing.T) { + data := []byte("123456789") + tests := []struct { + name string + data []byte + model checksum.CRCModel + want uint8 + }{ + {CRC8.Name, data, CRC8, 0xF4}, + {CRC8CDMA2000.Name, data, CRC8CDMA2000, 0xDA}, + {CRC8DARC.Name, data, CRC8DARC, 0x15}, + {CRC8DVBS2.Name, data, CRC8DVBS2, 0xBC}, + {CRC8EBU.Name, data, CRC8EBU, 0x97}, + {CRC8ICODE.Name, data, CRC8ICODE, 0x7E}, + {CRC8ITU.Name, data, CRC8ITU, 0xA1}, + {CRC8MAXIM.Name, data, CRC8MAXIM, 0xA1}, + {CRC8ROHC.Name, data, CRC8ROHC, 0xD0}, + {CRC8WCDMA.Name, data, CRC8WCDMA, 0x25}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + fmt.Println(checksum.CRC8(test.data, test.model)) + if got := checksum.CRC8(test.data, test.model); got != test.want { + t.Errorf("CalculateCRC8() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkCalculateCRC8(b *testing.B) { + for i := 0; i < b.N; i++ { + checksum.CRC8([]byte("123456789"), CRC8) + } +} diff --git a/checksum/luhn.go b/checksum/luhn.go index f3e230ead..e9f7dd6b1 100644 --- a/checksum/luhn.go +++ b/checksum/luhn.go @@ -7,8 +7,8 @@ // Package checksum describes algorithms for finding various checksums package checksum -// LuhnAlgorithm This function calculates the checksum using the Luna algorithm -func LuhnAlgorithm(s []rune) bool { +// Luhn validates the provided data using the Luhn algorithm. +func Luhn(s []byte) bool { n := len(s) number := 0 result := 0 diff --git a/checksum/luhn_test.go b/checksum/luhn_test.go index e928e51b6..e81560a64 100644 --- a/checksum/luhn_test.go +++ b/checksum/luhn_test.go @@ -3,27 +3,31 @@ // author(s) [red_byte](https://github.com/i-redbyte) // see luhn.go -package checksum +package checksum_test -import "testing" +import ( + "testing" -func TestLuhnAlgorithm(t *testing.T) { + "github.com/TheAlgorithms/Go/checksum" +) + +func TestLuhn(t *testing.T) { tests := []struct { name string - s []rune + s []byte want bool }{ - {"check 4242424242424242", []rune("4242424242424242"), true}, - {"check 6200000000000005", []rune("6200000000000005"), true}, - {"check 5534200028533164", []rune("5534200028533164"), true}, - {"check 36227206271667", []rune("36227206271667"), true}, - {"check 471629309440", []rune("471629309440"), false}, - {"check 1111", []rune("1111"), false}, - {"check 12345674", []rune("12345674"), true}, + {"check 4242424242424242", []byte("4242424242424242"), true}, + {"check 6200000000000005", []byte("6200000000000005"), true}, + {"check 5534200028533164", []byte("5534200028533164"), true}, + {"check 36227206271667", []byte("36227206271667"), true}, + {"check 471629309440", []byte("471629309440"), false}, + {"check 1111", []byte("1111"), false}, + {"check 12345674", []byte("12345674"), true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - if got := LuhnAlgorithm(test.s); got != test.want { + if got := checksum.Luhn(test.s); got != test.want { t.Errorf("LuhnAlgorithm() = %v, want %v", got, test.want) } }) @@ -32,6 +36,6 @@ func TestLuhnAlgorithm(t *testing.T) { func BenchmarkBruteForceFactorial(b *testing.B) { for i := 0; i < b.N; i++ { - LuhnAlgorithm([]rune("4242424242424242")) + checksum.Luhn([]byte("4242424242424242")) } } From 628336b7d752df8cb13d4961a30daf552acf3e02 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 31 Mar 2022 09:33:21 +0300 Subject: [PATCH 040/202] Feat/sin (#476) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * add package description and add function name to comment * Updated Documentation in README.md * rename Intercept method to YIntercept * Updated Documentation in README.md * fix strings * Updated Documentation in README.md * fix commit * fix name cos tests and rename epsilon to epsilonCos * feat: sin * Updated Documentation in README.md * fix test for sin * fix epsilon * rename package to test * fix afte review Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 1 + math/cos_test.go | 19 ++++++++++--------- math/sin.go | 11 +++++++++++ math/sin_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 9 deletions(-) create mode 100644 math/sin.go create mode 100644 math/sin_test.go diff --git a/README.md b/README.md index f9f798a61..7e41257dd 100644 --- a/README.md +++ b/README.md @@ -542,6 +542,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. 5. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. 6. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +7. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) ---
diff --git a/math/cos_test.go b/math/cos_test.go index c1df66b8d..16110c855 100644 --- a/math/cos_test.go +++ b/math/cos_test.go @@ -1,7 +1,8 @@ -package math +package math_test import ( - "math" + algmath "github.com/TheAlgorithms/Go/math" + stdmath "math" "testing" ) @@ -17,15 +18,15 @@ func TestCos(t *testing.T) { {"cos(90)", 90, -0.447}, {"cos(180)", 180, -0.598}, {"cos(1)", 1, 0.540}, - {"cos(1)", math.Pi, -1}, - {"cos(1)", math.Pi / 2, 0}, + {"cos(π)", stdmath.Pi, -1}, + {"cos(π/2)", stdmath.Pi / 2, 0}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := Cos(test.n) - if math.Abs(got-test.want) >= epsilon { + got := algmath.Cos(test.n) + if stdmath.Abs(got-test.want) >= epsilon { t.Errorf("Cos() = %v, want %v", got, test.want) - t.Errorf("MATH Cos() = %v", math.Cos(test.n)) + t.Errorf("MATH Cos() = %v", stdmath.Cos(test.n)) } }) } @@ -33,13 +34,13 @@ func TestCos(t *testing.T) { func BenchmarkCos(b *testing.B) { for i := 0; i < b.N; i++ { - Cos(180) + algmath.Cos(180) } } // BenchmarkMathCos is slower because the standard library `math.Cos` calculates a more accurate value. func BenchmarkMathCos(b *testing.B) { for i := 0; i < b.N; i++ { - math.Cos(180) + stdmath.Cos(180) } } diff --git a/math/sin.go b/math/sin.go new file mode 100644 index 000000000..e9713cf5e --- /dev/null +++ b/math/sin.go @@ -0,0 +1,11 @@ +// author(s) [red_byte](https://github.com/i-redbyte) +// see sin_test.go + +package math + +import "math" + +// Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +func Sin(x float64) float64 { + return Cos((math.Pi / 2) - x) +} diff --git a/math/sin_test.go b/math/sin_test.go new file mode 100644 index 000000000..0dc89428f --- /dev/null +++ b/math/sin_test.go @@ -0,0 +1,43 @@ +package math_test + +import ( + algmath "github.com/TheAlgorithms/Go/math" + stdmath "math" + "testing" +) + +func TestSin(t *testing.T) { + tests := []struct { + name string + n float64 + want float64 + }{ + {"sin(0)", 0, 0}, + {"sin(3π/2)", (3 * stdmath.Pi) / 2, -1}, + {"sin(π/2)", stdmath.Pi / 2, 1}, + {"sin(π/6)", stdmath.Pi / 6, 0.5}, + {"sin(90)", 90, 0.893996663600558}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := algmath.Sin(test.n) + if stdmath.Abs(got-test.want) >= epsilon { + t.Errorf("Sin() = %v, want %v", got, test.want) + t.Errorf("MATH Sin() = %v", stdmath.Sin(test.n)) + } + }) + } +} + +func BenchmarkSin(b *testing.B) { + for i := 0; i < b.N; i++ { + algmath.Sin(180) + } +} + +// BenchmarkMathSin is slower because the standard library `math.Sin` calculates a more accurate value. +func BenchmarkMathSin(b *testing.B) { + for i := 0; i < b.N; i++ { + stdmath.Sin(180) + } +} From f38fdca30a5786e41952d35464399ee62fbe5d7c Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Mon, 4 Apr 2022 14:18:26 +0530 Subject: [PATCH 041/202] Add Deterministic Miller-Rabin Primality Test (#484) * feat: add deterministic miller-rabin test * feat: refactor and commenting Tasks: - Refactored code. - Added some more witness groups. - Commented code. * chore: run `gofmt` * fix: remove old code * chore: update tests * fix: deterministic function test * chore: run `gofmt` * chore: update function name in doc comment Co-authored-by: Taj * chore: separate tests for the two versions * chore: `isTrivial` follows the `, ok` idiom * chore: add named returns for better docs * chore: use named returns to make code more concise Co-authored-by: Taj --- math/prime/millerrabinprimalitytest.go | 140 +++++++++++++++----- math/prime/millerrabinprimalitytest_test.go | 60 ++++++--- 2 files changed, 148 insertions(+), 52 deletions(-) diff --git a/math/prime/millerrabinprimalitytest.go b/math/prime/millerrabinprimalitytest.go index 2b358774d..76cb27578 100644 --- a/math/prime/millerrabinprimalitytest.go +++ b/math/prime/millerrabinprimalitytest.go @@ -1,10 +1,11 @@ -// millerrabinprimalitytest.go -// description: An implementation of Miller-Rabin primality test -// details: -// A simple implementation of Miller-Rabin Primality Test -// [Miller-Rabin primality test Wiki](https://en.wikipedia.org/wiki/Miller–Rabin_primality_test) -// author(s) [Taj](https://github.com/tjgurwara99) -// see millerrabinprimalitytest_test.go +// This file implements two versions of the Miller-Rabin primality test. +// One of the implementations is deterministic and the other is probabilistic. +// The Miller-Rabin test is one of the simplest and fastest known primality +// tests and is widely used. +// +// Authors: +// [Taj](https://github.com/tjgurwara99) +// [Rak](https://github.com/raklaptudirm) package prime @@ -14,25 +15,40 @@ import ( "github.com/TheAlgorithms/Go/math/modular" ) -// findD accepts a number and returns the -// odd number d such that num = 2^r * d - 1 -func findRD(num int64) (int64, int64) { - r := int64(0) - d := num - 1 +// formatNum accepts a number and returns the +// odd number d such that num = 2^s * d + 1 +func formatNum(num int64) (d int64, s int64) { + d = num - 1 for num%2 == 0 { d /= 2 - r++ + s++ } - return d, r + return } -// MillerTest This is the intermediate step that repeats within the -// miller rabin primality test for better probabilitic chances of -// receiving the correct result. -func MillerTest(d, num int64) (bool, error) { - random := rand.Int63n(num-1) + 2 +// isTrivial checks if num's primality is easy to determine. +// If it is, it returns true and num's primality. Otherwise +// it returns false and false. +func isTrivial(num int64) (prime bool, trivial bool) { + if num <= 4 { + // 2 and 3 are primes + prime = num == 2 || num == 3 + trivial = true + } else { + prime = false + // number is trivial prime if + // it is divisible by 2 + trivial = num%2 == 0 + } - res, err := modular.Exponentiation(random, d, num) + return +} + +// MillerTest tests whether num is a strong probable prime to a witness. +// Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s +func MillerTest(num, witness int64) (bool, error) { + d, _ := formatNum(num) + res, err := modular.Exponentiation(witness, d, num) if err != nil { return false, err @@ -55,21 +71,41 @@ func MillerTest(d, num int64) (bool, error) { return false, nil } -// MillerRabinTest Probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. -func MillerRabinTest(num, rounds int64) (bool, error) { - if num <= 4 { - if num == 2 || num == 3 { - return true, nil +// MillerRandomTest This is the intermediate step that repeats within the +// miller rabin primality test for better probabilitic chances of +// receiving the correct result with random witnesses. +func MillerRandomTest(num int64) (bool, error) { + random := rand.Int63n(num-1) + 2 + return MillerTest(num, random) +} + +// MillerTestMultiple is like MillerTest but runs the test for multiple +// witnesses. +func MillerTestMultiple(num int64, witnesses ...int64) (bool, error) { + for _, witness := range witnesses { + prime, err := MillerTest(num, witness) + if err != nil { + return false, err + } + + if !prime { + return false, nil } - return false, nil } - if num%2 == 0 { - return false, nil + + return true, nil +} + +// MillerRabinProbabilistic is a probabilistic test for primality +// of an integer based of the algorithm devised by Miller and Rabin. +func MillerRabinProbabilistic(num, rounds int64) (bool, error) { + if prime, trivial := isTrivial(num); trivial { + // num is a trivial number + return prime, nil } - d, _ := findRD(num) for i := int64(0); i < rounds; i++ { - val, err := MillerTest(d, num) + val, err := MillerRandomTest(num) if err != nil { return false, err } @@ -79,3 +115,47 @@ func MillerRabinTest(num, rounds int64) (bool, error) { } return true, nil } + +// MillerRabinDeterministic is a Deterministic version of the Miller-Rabin +// test, which returns correct results for all valid int64 numbers. +func MillerRabinDeterministic(num int64) (bool, error) { + if prime, trivial := isTrivial(num); trivial { + // num is a trivial number + return prime, nil + } + + switch { + case num < 2047: + // witness 2 can determine the primality of any number less than 2047 + return MillerTest(num, 2) + case num < 1_373_653: + // witnesses 2 and 3 can determine the primality + // of any number less than 1,373,653 + return MillerTestMultiple(num, 2, 3) + case num < 9_080_191: + // witnesses 31 and 73 can determine the primality + // of any number less than 9,080,191 + return MillerTestMultiple(num, 31, 73) + case num < 25_326_001: + // witnesses 2, 3, and 5 can determine the + // primality of any number less than 25,326,001 + return MillerTestMultiple(num, 2, 3, 5) + case num < 1_122_004_669_633: + // witnesses 2, 13, 23, and 1,662,803 can determine the + // primality of any number less than 1,122,004,669,633 + return MillerTestMultiple(num, 2, 13, 23, 1_662_803) + case num < 2_152_302_898_747: + // witnesses 2, 3, 5, 7, and 11 can determine the primality + // of any number less than 2,152,302,898,747 + return MillerTestMultiple(num, 2, 3, 5, 7, 11) + case num < 341_550_071_728_321: + // witnesses 2, 3, 5, 7, 11, 13, and 17 can determine the + // primality of any number less than 341,550,071,728,321 + return MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17) + default: + // witnesses 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37 can determine + // the primality of any number less than 318,665,857,834,031,151,167,461 + // which is well above the max int64 9,223,372,036,854,775,807 + return MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37) + } +} diff --git a/math/prime/millerrabinprimalitytest_test.go b/math/prime/millerrabinprimalitytest_test.go index 0773b1149..b4a4ed34f 100644 --- a/math/prime/millerrabinprimalitytest_test.go +++ b/math/prime/millerrabinprimalitytest_test.go @@ -1,29 +1,25 @@ -// millerrabinprimality_test.go -// description: Test for Miller-Rabin Primality Test -// author(s) [Taj](https://github.com/tjgurwara99) -// see millerrabinprimalitytest.go - package prime import "testing" -func TestMillerRabinTest(t *testing.T) { - var tests = []struct { - name string - input int64 - expected bool - rounds int64 - err error - }{ - {"smallest prime", 2, true, 5, nil}, - {"random prime", 3, true, 5, nil}, - {"neither prime nor composite", 1, false, 5, nil}, - {"random non-prime", 10, false, 5, nil}, - {"another random prime", 23, true, 5, nil}, - } +var tests = []struct { + name string + input int64 + expected bool + rounds int64 + err error +}{ + {"smallest prime", 2, true, 5, nil}, + {"random prime", 3, true, 5, nil}, + {"neither prime nor composite", 1, false, 5, nil}, + {"random non-prime", 10, false, 5, nil}, + {"another random prime", 23, true, 5, nil}, +} + +func TestMillerRabinProbabilistic(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - output, err := MillerRabinTest(test.input, test.rounds) + output, err := MillerRabinProbabilistic(test.input, test.rounds) if err != test.err { t.Errorf("For input: %d, unexpected error: %v, expected error: %v", test.input, err, test.err) } @@ -34,8 +30,28 @@ func TestMillerRabinTest(t *testing.T) { } } -func BenchmarkMillerRabinPrimalityTest(b *testing.B) { +func TestMillerRabinDeterministic(t *testing.T) { + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + output, err := MillerRabinDeterministic(test.input) + if err != test.err { + t.Errorf("For input: %d, unexpected error: %v, expected error: %v", test.input, err, test.err) + } + if output != test.expected { + t.Errorf("For input: %d, expected %v", test.input, output) + } + }) + } +} + +func BenchmarkMillerRabinProbabilistic(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = MillerRabinProbabilistic(23, 5) + } +} + +func BenchmarkMillerRabinDeterministic(b *testing.B) { for i := 0; i < b.N; i++ { - _, _ = MillerRabinTest(23, 5) + _, _ = MillerRabinDeterministic(23) } } From 397284b7d13cc9e6ec099ce964e642150a90ccba Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 5 Apr 2022 10:32:20 +0200 Subject: [PATCH 042/202] merge: Remove cclauss from CODEOWNERS (#489) --- .github/CODEOWNERS | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4a0788d2e..fd1f63e16 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -7,5 +7,4 @@ # Order is important. The last matching pattern has the most precedence. -* @siriak @raklaptudirm @tjgurwara99 -/.* @cclauss +* @siriak @raklaptudirm @tjgurwara99 @yanglbme From 028fe09c5ce1198aad665ca3dfbb69ab346406cc Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Wed, 6 Apr 2022 21:25:46 +0530 Subject: [PATCH 043/202] Update repository workflows (#488) --- .../{golang_lint_and_test.yml => ci.yml} | 26 ++++++++++++++----- .github/workflows/godocmd.yml | 9 +++++-- 2 files changed, 26 insertions(+), 9 deletions(-) rename .github/workflows/{golang_lint_and_test.yml => ci.yml} (61%) diff --git a/.github/workflows/golang_lint_and_test.yml b/.github/workflows/ci.yml similarity index 61% rename from .github/workflows/golang_lint_and_test.yml rename to .github/workflows/ci.yml index 29a2a9283..40ebab4a1 100644 --- a/.github/workflows/golang_lint_and_test.yml +++ b/.github/workflows/ci.yml @@ -1,18 +1,21 @@ # https://github.com/golangci/golangci-lint -name: golang_lint_and_test -on: [push, pull_request] +name: Continuous Integration +on: + push: + # prevent duplication of tests with + # `pull_request` event + branches: + - master + pull_request: + jobs: golang_lint_and_test: + name: Code style and tests runs-on: ubuntu-latest strategy: fail-fast: false steps: - uses: actions/checkout@v2 - - name: Codespell - uses: codespell-project/actions-codespell@master - with: - ignore_words_list: "actualy,nwe" - skip: "go.mod,go.sum" - name: Setup Go uses: actions/setup-go@v2 with: @@ -24,3 +27,12 @@ jobs: args: -E gofmt - name: Run tests run: go test ./... + codespell: + name: Check for spelling errors + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: codespell-project/actions-codespell@master + with: + ignore_words_list: "actualy,nwe" + skip: "go.mod,go.sum" diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index b69bf13d9..2ed6aec61 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -1,7 +1,12 @@ -name: godocmd -on: [push] +name: Generate Documentation +on: + push: + branches: + - master + jobs: generate_readme: + name: Markdown Generation runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 From 38dee1373a094b6313c700bb71ea4d62084e9810 Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Thu, 7 Apr 2022 23:17:23 +0530 Subject: [PATCH 044/202] chore: set-up Code Scanning (#491) --- .github/workflows/codeql-analysis.yml | 70 +++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..f1a89f3d2 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,70 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ master ] + schedule: + - cron: '33 2 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'go' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://git.io/codeql-language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 From 30c24e8a134ebab170f789d44f38f04ef52b5774 Mon Sep 17 00:00:00 2001 From: Yassin Achengli <79287426+89453728@users.noreply.github.com> Date: Wed, 13 Apr 2022 19:05:08 +0200 Subject: [PATCH 045/202] Add Parenthesis Checking Algorithm (#492) --- strings/parenthesis/parenthesis.go | 27 +++++++++++++ strings/parenthesis/parenthesis_test.go | 53 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 strings/parenthesis/parenthesis.go create mode 100644 strings/parenthesis/parenthesis_test.go diff --git a/strings/parenthesis/parenthesis.go b/strings/parenthesis/parenthesis.go new file mode 100644 index 000000000..2ae49a641 --- /dev/null +++ b/strings/parenthesis/parenthesis.go @@ -0,0 +1,27 @@ +package parenthesis + +// Parenthesis algorithm checks if every opened parenthesis +// is closed correctly + +// when parcounter is less than 0 is because a closing +// parenthesis is detected without an opening parenthesis +// that surrounds it + +// parcounter will be 0 if all open parenthesis are closed +// correctly +func Parenthesis(text string) bool { + parcounter := 0 + + for _, r := range text { + switch r { + case '(': + parcounter++ + case ')': + parcounter-- + } + if parcounter < 0 { + return false + } + } + return parcounter == 0 +} diff --git a/strings/parenthesis/parenthesis_test.go b/strings/parenthesis/parenthesis_test.go new file mode 100644 index 000000000..b7f5abd6c --- /dev/null +++ b/strings/parenthesis/parenthesis_test.go @@ -0,0 +1,53 @@ +package parenthesis + +import ( + "testing" +) + +var parenthesisTestCases = []struct { + name string + text string + expected bool +}{ + { + "simple test with one level deep", + "(3*9-2)+(3/7^3)", + true, + }, + { + "three nested pharentesis with three deep level", + "(-1*(5+2^(3-4)*(7.44-12)+6.66/(3.43-(1+2)))*(sqrt(3-4)))", + true, + }, + { + "one opened pharentesis without be closed", + "(2*9-17)*((7+3/3)*2*(-1+4)", + false, + }, + { + "one open pharentesis for each close one but not in pairs", + "(4*(39.22-7.4)/6.77))(", + false, + }, + { + "6 deep level", + "(5+33.2)*((8.04-6.5)*(1 - (1^(2-1.22*5.44+(4.33*7.2^(0.34*(-1.23+2)))))))", + true, + }, + { + "inverted pharentesis", + ")()()()()(", + false, + }, +} + +func TestParenthesis(t *testing.T) { + for _, tc := range parenthesisTestCases { + t.Run(tc.name, func(t *testing.T) { + actual := Parenthesis(tc.text) + if actual != tc.expected { + t.Errorf("Expected %t value from test %s with input %s\n", tc.expected, tc.name, tc.text) + } + }) + } +} From 8befb60cbea14d877f4898c9556bbc091fbd3d60 Mon Sep 17 00:00:00 2001 From: hugokung <49091849+hugokung@users.noreply.github.com> Date: Thu, 21 Apr 2022 00:46:14 +0800 Subject: [PATCH 046/202] Fix: segmenttree algorithm bug (#497) --- structure/segmenttree/segmenttree.go | 12 +++++++----- structure/segmenttree/segmenttree_test.go | 8 ++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/structure/segmenttree/segmenttree.go b/structure/segmenttree/segmenttree.go index acdae7b35..2799c5537 100644 --- a/structure/segmenttree/segmenttree.go +++ b/structure/segmenttree/segmenttree.go @@ -11,7 +11,7 @@ import ( "github.com/TheAlgorithms/Go/math/min" ) -const emptyLazyNode = -1 +const emptyLazyNode = 0 //SegmentTree with original Array and the Segment Tree Array type SegmentTree struct { @@ -29,11 +29,12 @@ func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) { if leftNode == rightNode { //leaf node - s.Array[leftNode] = s.LazyTree[node] + s.Array[leftNode] += s.LazyTree[node] } else { //propagate lazy node value for children nodes - s.LazyTree[2*node] = s.LazyTree[node] - s.LazyTree[2*node+1] = s.LazyTree[node] + //may propagate multiple times, children nodes should accumulate lazy node value + s.LazyTree[2*node] += s.LazyTree[node] + s.LazyTree[2*node+1] += s.LazyTree[node] } //clear lazy node @@ -81,7 +82,8 @@ func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex i if (leftNode >= firstIndex) && (rightNode <= lastIndex) { //inside the interval - s.LazyTree[node] = value + //accumulate the lazy node value + s.LazyTree[node] += value s.Propagate(node, leftNode, rightNode) } else { //update left and right nodes diff --git a/structure/segmenttree/segmenttree_test.go b/structure/segmenttree/segmenttree_test.go index c8e2c9e45..b1e21da6c 100644 --- a/structure/segmenttree/segmenttree_test.go +++ b/structure/segmenttree/segmenttree_test.go @@ -60,6 +60,14 @@ func TestSegmentTree(t *testing.T) { queries: []query{{0, 5}, {0, 2}, {2, 4}}, expected: []int{31, 14, 24}, }, + { + description: "test array with size 11 and range updates", + array: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, + updates: []update{{firstIndex: 2, lastIndex: 8, value: 2}, + {firstIndex: 2, lastIndex: 8, value: 2}}, + queries: []query{{3, 5}, {7, 8}, {4, 5}, {8, 8}}, + expected: []int{15, 10, 10, 5}, + }, } for _, test := range segmentTreeTestData { t.Run(test.description, func(t *testing.T) { From 45cbe015a65a882885f8562c4c39022c0eb6330d Mon Sep 17 00:00:00 2001 From: nursyah21 <64634372+nursyah21@users.noreply.github.com> Date: Thu, 21 Apr 2022 19:37:21 +0700 Subject: [PATCH 047/202] added implementation coinchange (#496) * added implementation coinchange * Update coinchange.go * Update coinchange_test.go * Update coinchange_test.go * Update coinchange.go * Update coinchange_test.go --- dynamic/coinchange.go | 17 +++++++++++++++++ dynamic/coinchange_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 dynamic/coinchange.go create mode 100644 dynamic/coinchange_test.go diff --git a/dynamic/coinchange.go b/dynamic/coinchange.go new file mode 100644 index 000000000..1098ea4e1 --- /dev/null +++ b/dynamic/coinchange.go @@ -0,0 +1,17 @@ +package dynamic + +// CoinChange finds the number of possible combinations of coins +// of different values which can get to the target amount. +func CoinChange(coins []int32, amount int32) int32 { + combination := make([]int32, amount) + combination[0] = 1 + + for _, c := range coins { + for i := c; i < amount; i++ { + + combination[i] += combination[i-c] + } + } + + return combination[amount-1] +} diff --git a/dynamic/coinchange_test.go b/dynamic/coinchange_test.go new file mode 100644 index 000000000..174a702f8 --- /dev/null +++ b/dynamic/coinchange_test.go @@ -0,0 +1,31 @@ +package dynamic_test + +import ( + "fmt" + "github.com/TheAlgorithms/Go/dynamic" + "testing" +) + +func TestCoinChange(t *testing.T) { + coinCombination := []int32{1, 2, 5, 10} + targets := []struct { + target int32 + expected int32 + }{ + {4, 2}, + {5, 3}, + {10, 8}, + {15, 19}, + {20, 34}, + } + + for _, v := range targets { + t.Run(fmt.Sprintf("target: %d ", v.target), func(t *testing.T) { + result := dynamic.CoinChange(coinCombination, v.target) + if result != v.expected { + t.Errorf("target: %d Expected %d, got %d", v.target, v.expected, result) + } + }) + } + +} From 4043a4b4cb67873f54854a3008976788a1b9f599 Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Wed, 27 Apr 2022 14:37:20 +0530 Subject: [PATCH 048/202] merge: segmenttree: format test file with `gofmt` (#501) --- structure/segmenttree/segmenttree_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/structure/segmenttree/segmenttree_test.go b/structure/segmenttree/segmenttree_test.go index b1e21da6c..142104b87 100644 --- a/structure/segmenttree/segmenttree_test.go +++ b/structure/segmenttree/segmenttree_test.go @@ -62,10 +62,10 @@ func TestSegmentTree(t *testing.T) { }, { description: "test array with size 11 and range updates", - array: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, + array: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, updates: []update{{firstIndex: 2, lastIndex: 8, value: 2}, {firstIndex: 2, lastIndex: 8, value: 2}}, - queries: []query{{3, 5}, {7, 8}, {4, 5}, {8, 8}}, + queries: []query{{3, 5}, {7, 8}, {4, 5}, {8, 8}}, expected: []int{15, 10, 10, 5}, }, } From ff2211355cc67fb7ce106c53e8f40269628bc8a6 Mon Sep 17 00:00:00 2001 From: Daesar Lau Date: Wed, 27 Apr 2022 21:51:31 +0800 Subject: [PATCH 049/202] insertion sort: make sorting stable (#499) --- go.sum | 0 sort/insertionsort.go | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 go.sum diff --git a/go.sum b/go.sum deleted file mode 100644 index e69de29bb..000000000 diff --git a/sort/insertionsort.go b/sort/insertionsort.go index b51bc5379..13e45eeb9 100644 --- a/sort/insertionsort.go +++ b/sort/insertionsort.go @@ -6,7 +6,7 @@ func Insertion[T constraints.Ordered](arr []T) []T { for currentIndex := 1; currentIndex < len(arr); currentIndex++ { temporary := arr[currentIndex] iterator := currentIndex - for ; iterator > 0 && arr[iterator-1] >= temporary; iterator-- { + for ; iterator > 0 && arr[iterator-1] > temporary; iterator-- { arr[iterator] = arr[iterator-1] } arr[iterator] = temporary From 603f2fdd88e85c0b882a2817e955559bb0d4250c Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Thu, 28 Apr 2022 10:45:27 +0300 Subject: [PATCH 050/202] merge: algorithm: Bitwise log base 2 (#503) * feat: bitwise min * fix: bitwise min, change for vararg * fix: change min tests * fix: benchmark for bitwise * fix: rename tests * fix: add value param * fix: change condition * feat: added description to some functions * Updated Documentation in README.md * fix: change descriptions * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * feat: abs algo * Updated Documentation in README.md * fix: add comment * Updated Documentation in README.md * fix: new comment * Updated Documentation in README.md * fix: rename func and remove package * Updated Documentation in README.md * Update math/abs.go Co-authored-by: Taj * Updated Documentation in README.md * Update math/binary/abs.go Co-authored-by: Taj * Updated Documentation in README.md * fix: rename func and move binary test * add package description and add function name to comment * Updated Documentation in README.md * rename Intercept method to YIntercept * Updated Documentation in README.md * fix strings * Updated Documentation in README.md * fix commit * fix name cos tests and rename epsilon to epsilonCos * feat: sin * Updated Documentation in README.md * fix test for sin * fix epsilon * rename package to test * fix afte review * Updated Documentation in README.md * Updated Documentation in README.md * Updated Documentation in README.md * @feat bitwise logarithm * @fix: rename function name to LogBase2 Co-authored-by: Rak Laptudirm Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- README.md | 58 ++++++++++++++++++++++------------- math/binary/logarithm.go | 18 +++++++++++ math/binary/logarithm_test.go | 48 +++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 22 deletions(-) create mode 100644 math/binary/logarithm.go create mode 100644 math/binary/logarithm_test.go diff --git a/README.md b/README.md index 7e41257dd..0fc3d96e5 100644 --- a/README.md +++ b/README.md @@ -257,22 +257,23 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bin2`](./dynamic/binomialcoefficient.go#L21): Bin2 function -2. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming -3. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach -4. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively. -5. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. -6. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. -7. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit -8. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function -9. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order -10. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ -11. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function -12. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function -13. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function -14. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function -15. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate -16. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) -17. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number +2. [`CoinChange`](./dynamic/coinchange.go#L5): CoinChange finds the number of possible combinations of coins of different values which can get to the target amount. +3. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming +4. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach +5. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively. +6. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. +7. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. +8. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit +9. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function +10. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order +11. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ +12. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function +13. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function +14. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function +15. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function +16. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate +17. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) +18. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number ---
@@ -635,6 +636,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`IsPangram`](./strings/pangram/ispangram.go#L21): No description provided. +--- +
+ parenthesis + +--- + +##### Functions: + +1. [`Parenthesis`](./strings/parenthesis/parenthesis.go#L12): parcounter will be 0 if all open parenthesis are closed correctly + ---
pascal @@ -727,11 +738,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Factorize`](./math/prime/primefactorization.go#L5): Factorize is a function that computes the exponents of each prime in the prime factorization of n 2. [`Generate`](./math/prime/sieve.go#L26): Generate returns a int slice of prime numbers up to the limit 3. [`GenerateChannel`](./math/prime/sieve.go#L9): Generate generates the sequence of integers starting at 2 and sends it to the channel `ch` -4. [`MillerRabinTest`](./math/prime/millerrabinprimalitytest.go#L59): MillerRabinTest Probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. -5. [`MillerTest`](./math/prime/millerrabinprimalitytest.go#L32): MillerTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result. -6. [`NaiveApproach`](./math/prime/primecheck.go#L8): NaiveApproach checks if an integer is prime or not. Returns a bool. -7. [`PairApproach`](./math/prime/primecheck.go#L22): PairApproach checks primality of an integer and returns a bool. More efficient than the naive approach as number of iterations are less. -8. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels +4. [`MillerRabinDeterministic`](./math/prime/millerrabinprimalitytest.go#L121): MillerRabinDeterministic is a Deterministic version of the Miller-Rabin test, which returns correct results for all valid int64 numbers. +5. [`MillerRabinProbabilistic`](./math/prime/millerrabinprimalitytest.go#L101): MillerRabinProbabilistic is a probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. +6. [`MillerRandomTest`](./math/prime/millerrabinprimalitytest.go#L77): MillerRandomTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result with random witnesses. +7. [`MillerTest`](./math/prime/millerrabinprimalitytest.go#L49): MillerTest tests whether num is a strong probable prime to a witness. Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s +8. [`MillerTestMultiple`](./math/prime/millerrabinprimalitytest.go#L84): MillerTestMultiple is like MillerTest but runs the test for multiple witnesses. +9. [`NaiveApproach`](./math/prime/primecheck.go#L8): NaiveApproach checks if an integer is prime or not. Returns a bool. +10. [`PairApproach`](./math/prime/primecheck.go#L22): PairApproach checks primality of an integer and returns a bool. More efficient than the naive approach as number of iterations are less. +11. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels ---
@@ -807,7 +821,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`NewSegmentTree`](./structure/segmenttree/segmenttree.go#L114): No description provided. +1. [`NewSegmentTree`](./structure/segmenttree/segmenttree.go#L116): No description provided. --- ##### Types diff --git a/math/binary/logarithm.go b/math/binary/logarithm.go new file mode 100644 index 000000000..205b0235b --- /dev/null +++ b/math/binary/logarithm.go @@ -0,0 +1,18 @@ +// author(s) [red_byte](https://github.com/i-redbyte) +// see logarithm_test.go + +package binary + +// LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm) +func LogBase2(n uint32) uint32 { + base := [5]uint32{0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000} + exponents := [5]uint32{1, 2, 4, 8, 16} + var result uint32 + for i := 4; i >= 0; i-- { + if n&base[i] != 0 { + n >>= exponents[i] + result |= exponents[i] + } + } + return result +} diff --git a/math/binary/logarithm_test.go b/math/binary/logarithm_test.go new file mode 100644 index 000000000..8aaaabe72 --- /dev/null +++ b/math/binary/logarithm_test.go @@ -0,0 +1,48 @@ +// logarithm_test.go +// description: Test for finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) +// author(s) [red_byte](https://github.com/i-redbyte) +// see logarithm.go + +package binary + +import ( + "math" + "testing" +) + +func TestLogBase2(t *testing.T) { + tests := []struct { + name string + n uint32 + want uint32 + }{ + {"log2(1) = 0", 1, 0}, + {"log2(2) = 1", 2, 1}, + {"log2(4) = 2", 4, 2}, + {"log2(8) = 3", 8, 3}, + {"log2(16) = 4", 16, 4}, + {"log2(32) = 5", 32, 5}, + {"log2(64) = 6", 64, 6}, + {"log2(128) = 7", 128, 7}, + {"log2(256) = 8", 256, 8}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := LogBase2(test.n); got != test.want { + t.Errorf("LogBase2() = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkBitwiseLogBase2(b *testing.B) { + for i := 0; i < b.N; i++ { + LogBase2(1024) + } +} + +func BenchmarkMathPAckageLogBase2(b *testing.B) { + for i := 0; i < b.N; i++ { + math.Log2(1024) + } +} From d00ee5eef862c2bbf07c7de2d0e2bdfe5d1e1cef Mon Sep 17 00:00:00 2001 From: Andrii Siriak Date: Thu, 28 Apr 2022 06:27:15 -0700 Subject: [PATCH 051/202] Fix broken link in CONTRIBUTING.md (#500) --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ea44b249f..15c29be06 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,9 +6,9 @@ Welcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! Before submi ## Contributing -### Maintainer/reviewer +### Maintainers -**Please check the [reviewer code](https://github.com/TheAlgorithms/Go/blob/master/DIRECTORY.md) file for maintainers and reviewers.** +Please check the [`CODEOWNERS`](https://github.com/TheAlgorithms/Go/blob/master/.github/CODEOWNERS) file for a list of repository maintainers. ### Contributor From d696a494f9ac8fe824c52a138cf3359550f6129b Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Mon, 2 May 2022 14:46:59 +0530 Subject: [PATCH 052/202] merge: Consolidate Primality Algorithm testing into single suite (#504) * chore: add testing interface * chore: add benchmark helper * chore: remove individual tests (1) * chore: remove individual tests (2) * chore: add miller rabin test suite * refactor: trial division primality tests * chore: add trial division test suite * refactor: trial division tests now accept `int64` * chore: remove `error` return from `primalityTest` * fix: remove redundant identifier * chore: add function names for debug * chore: fix typo * chore: add explicit type conversions * fix: index out of range in tests * fix: random witness generation --- math/prime/millerrabinprimalitytest_test.go | 57 ----------- ...binprimalitytest.go => millerrabintest.go} | 2 +- math/prime/prime_test.go | 95 +++++++++++++++++++ math/prime/primecheck.go | 34 +++++-- math/prime/primecheck_test.go | 62 ------------ 5 files changed, 121 insertions(+), 129 deletions(-) delete mode 100644 math/prime/millerrabinprimalitytest_test.go rename math/prime/{millerrabinprimalitytest.go => millerrabintest.go} (99%) create mode 100644 math/prime/prime_test.go delete mode 100644 math/prime/primecheck_test.go diff --git a/math/prime/millerrabinprimalitytest_test.go b/math/prime/millerrabinprimalitytest_test.go deleted file mode 100644 index b4a4ed34f..000000000 --- a/math/prime/millerrabinprimalitytest_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package prime - -import "testing" - -var tests = []struct { - name string - input int64 - expected bool - rounds int64 - err error -}{ - {"smallest prime", 2, true, 5, nil}, - {"random prime", 3, true, 5, nil}, - {"neither prime nor composite", 1, false, 5, nil}, - {"random non-prime", 10, false, 5, nil}, - {"another random prime", 23, true, 5, nil}, -} - -func TestMillerRabinProbabilistic(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - output, err := MillerRabinProbabilistic(test.input, test.rounds) - if err != test.err { - t.Errorf("For input: %d, unexpected error: %v, expected error: %v", test.input, err, test.err) - } - if output != test.expected { - t.Errorf("For input: %d, expected: %v", test.input, output) - } - }) - } -} - -func TestMillerRabinDeterministic(t *testing.T) { - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - output, err := MillerRabinDeterministic(test.input) - if err != test.err { - t.Errorf("For input: %d, unexpected error: %v, expected error: %v", test.input, err, test.err) - } - if output != test.expected { - t.Errorf("For input: %d, expected %v", test.input, output) - } - }) - } -} - -func BenchmarkMillerRabinProbabilistic(b *testing.B) { - for i := 0; i < b.N; i++ { - _, _ = MillerRabinProbabilistic(23, 5) - } -} - -func BenchmarkMillerRabinDeterministic(b *testing.B) { - for i := 0; i < b.N; i++ { - _, _ = MillerRabinDeterministic(23) - } -} diff --git a/math/prime/millerrabinprimalitytest.go b/math/prime/millerrabintest.go similarity index 99% rename from math/prime/millerrabinprimalitytest.go rename to math/prime/millerrabintest.go index 76cb27578..1f3a2ef72 100644 --- a/math/prime/millerrabinprimalitytest.go +++ b/math/prime/millerrabintest.go @@ -75,7 +75,7 @@ func MillerTest(num, witness int64) (bool, error) { // miller rabin primality test for better probabilitic chances of // receiving the correct result with random witnesses. func MillerRandomTest(num int64) (bool, error) { - random := rand.Int63n(num-1) + 2 + random := rand.Int63n(num-2) + 2 return MillerTest(num, random) } diff --git a/math/prime/prime_test.go b/math/prime/prime_test.go new file mode 100644 index 000000000..e06f4a6de --- /dev/null +++ b/math/prime/prime_test.go @@ -0,0 +1,95 @@ +package prime + +import ( + "fmt" + "testing" +) + +var primeList = []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127} +var testLimit = 127 + +type primalityTest func(int64) bool + +func primalityTestTestingHelper(t *testing.T, name string, f primalityTest) { + arrayIndex := 0 + for i := 1; i <= testLimit; i++ { + isPrime := i == primeList[arrayIndex] + + testName := fmt.Sprintf("%s(%d)", name, i) + t.Run(testName, func(t *testing.T) { + result := f(int64(i)) + + if isPrime { + arrayIndex++ + } + + if result != isPrime { + t.Errorf("%d: %s function returned %v\n", i, name, result) + } + }) + } +} + +func primalityTestBenchmarkHelper(b *testing.B, f primalityTest) { + for i := 0; i < b.N; i++ { + f(104729) + } +} + +// Miller-Rabin Probabilistic test + +func millerRabinProbabilisticTester(n int64) bool { + result, err := MillerRabinProbabilistic(n, 40) + if err != nil { + panic(err) + } + + return result +} + +func TestMillerRabinProbabilistic(t *testing.T) { + primalityTestTestingHelper(t, "Miller-Rabin Probabilistic", millerRabinProbabilisticTester) +} + +func BenchmarkMillerRabinProbabilistic(b *testing.B) { + primalityTestBenchmarkHelper(b, millerRabinProbabilisticTester) +} + +// Miller-Rabin deterministic test + +func millerRabinDeterministicTester(n int64) bool { + result, err := MillerRabinDeterministic(n) + if err != nil { + panic(err) + } + + return result +} + +func TestMillerRabinDeterministic(t *testing.T) { + primalityTestTestingHelper(t, "Miller-Rabin Deterministic", millerRabinDeterministicTester) +} + +func BenchmarkMillerRabinDeterministic(b *testing.B) { + primalityTestBenchmarkHelper(b, millerRabinDeterministicTester) +} + +// Trial Division test + +func TestTrialDivision(t *testing.T) { + primalityTestTestingHelper(t, "Trial Division", TrialDivision) +} + +func BenchmarkTrialDivision(b *testing.B) { + primalityTestBenchmarkHelper(b, TrialDivision) +} + +// Trial Division (optimized) + +func TestOptimizedTrialDivision(t *testing.T) { + primalityTestTestingHelper(t, "Trial Division (optimized)", OptimizedTrialDivision) +} + +func BenchmarkOptimizedTrialDivision(b *testing.B) { + primalityTestBenchmarkHelper(b, OptimizedTrialDivision) +} diff --git a/math/prime/primecheck.go b/math/prime/primecheck.go index e6b4f96c2..3e2a97280 100644 --- a/math/prime/primecheck.go +++ b/math/prime/primecheck.go @@ -1,15 +1,17 @@ package prime -// A primality test is an algorithm for determining whether an input number is prime.Among other fields of mathematics, it is used for cryptography. -//Unlike integer factorization, primality tests do not generally give prime factors, only stating whether the input number is prime or not. -//Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test +// A primality test is an algorithm for determining whether an input number is prime. Among other +// fields of mathematics, it is used for cryptography. Unlike integer factorization, primality +// tests do not generally give prime factors, only stating whether the input number is prime or not. +// Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test -// NaiveApproach checks if an integer is prime or not. Returns a bool. -func NaiveApproach(n int) bool { +// TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it. +func TrialDivision(n int64) bool { if n < 2 { return false } - for i := 2; i < n; i++ { + + for i := int64(2); i < n; i++ { if n%i == 0 { return false @@ -18,12 +20,26 @@ func NaiveApproach(n int) bool { return true } -// PairApproach checks primality of an integer and returns a bool. More efficient than the naive approach as number of iterations are less. -func PairApproach(n int) bool { +// OptimizedTrialDivision checks primality of an integer using an optimized trial division method. +// The optimizations include not checking divisibility by the even numbers and only checking up to +// the square root of the given number. +func OptimizedTrialDivision(n int64) bool { + // 0 and 1 are not prime if n < 2 { return false } - for i := 2; i*i <= n; i++ { + + // 2 and 3 are prime + if n < 4 { + return true + } + + // all numbers divisible by 2 except 2 are not prime + if n%2 == 0 { + return false + } + + for i := int64(3); i*i <= n; i += 2 { if n%i == 0 { return false } diff --git a/math/prime/primecheck_test.go b/math/prime/primecheck_test.go deleted file mode 100644 index 0cbe310f7..000000000 --- a/math/prime/primecheck_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package prime - -import ( - "testing" -) - -func TestTableNaiveApproach(t *testing.T) { - var tests = []struct { - name string - input int - expected bool - }{ - {"smallest prime", 2, true}, - {"random prime", 3, true}, - {"neither prime nor composite", 1, false}, - {"random non-prime", 10, false}, - {"another random prime", 23, true}, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if output := NaiveApproach(test.input); output != test.expected { - t.Errorf("For input: %d, expected: %v, but got: %v", test.input, test.expected, output) - } - }) - } - -} -func TestTablePairApproach(t *testing.T) { - var tests = []struct { - name string - input int - expected bool - }{ - {"smallest prime", 2, true}, - {"random prime", 3, true}, - {"neither prime nor composite", 1, false}, - {"random non-prime", 10, false}, - {"another random prime", 23, true}, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if output := NaiveApproach(test.input); output != test.expected { - t.Errorf("For input: %d, expected: %v, but got: %v", test.input, test.expected, output) - } - }) - } - -} - -func BenchmarkNaiveApproach(b *testing.B) { - for i := 0; i < b.N; i++ { - NaiveApproach(23) - } -} - -func BenchmarkPairApproach(b *testing.B) { - for i := 0; i < b.N; i++ { - PairApproach(23) - } -} From db857821c21bd53224a85343c7edfaa1524e936a Mon Sep 17 00:00:00 2001 From: Ritik Bhandari Date: Sun, 8 May 2022 13:05:48 +0530 Subject: [PATCH 053/202] merge: replaced 'interface{}' with 'any' using new go1.18 alias (#506) --- CONTRIBUTING.md | 2 +- graph/dijkstra.go | 2 +- sort/heapsort.go | 4 +-- structure/dynamicarray/dynamicarray.go | 12 ++++----- structure/dynamicarray/dynamicarray_test.go | 4 +-- structure/hashmap/hashmap.go | 18 ++++++------- structure/hashmap/hashmap_test.go | 2 +- structure/linkedlist/cyclic.go | 2 +- structure/linkedlist/cyclic_test.go | 4 +-- structure/linkedlist/doubly.go | 10 +++---- structure/linkedlist/shared.go | 4 +-- structure/linkedlist/singlylinkedlist.go | 8 +++--- structure/linkedlist/singlylinkedlist_test.go | 20 +++++++------- structure/queue/queue_test.go | 4 +-- structure/queue/queuearray.go | 10 +++---- structure/queue/queuelinkedlist.go | 10 +++---- structure/queue/queuelinklistwithlist.go | 6 ++--- structure/set/set.go | 26 +++++++++---------- structure/stack/stack_test.go | 6 ++--- structure/stack/stackarray.go | 10 +++---- structure/stack/stacklinkedlist.go | 10 +++---- structure/stack/stacklinkedlistwithlist.go | 6 ++--- 22 files changed, 90 insertions(+), 90 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 15c29be06..1d7b39624 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -93,7 +93,7 @@ import ( // Fprint formats using the default formats for its operands and writes to w. // Spaces are added between operands when neither is a string. // It returns the number of bytes written, and any write error encountered. -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { +func Fprint(w io.Writer, a ...any) (n int, err error) { ... } diff --git a/graph/dijkstra.go b/graph/dijkstra.go index 26b2becbc..685cf02e8 100644 --- a/graph/dijkstra.go +++ b/graph/dijkstra.go @@ -7,7 +7,7 @@ type Item struct { dist int } -func (a Item) More(b interface{}) bool { +func (a Item) More(b any) bool { // reverse direction for minheap return a.dist < b.(Item).dist } diff --git a/sort/heapsort.go b/sort/heapsort.go index 0c44eb515..07a5d9547 100644 --- a/sort/heapsort.go +++ b/sort/heapsort.go @@ -107,11 +107,11 @@ func (h MaxHeap) heapifyDown(i int) { type Comparable interface { Idx() int - More(interface{}) bool + More(any) bool } type Int int -func (a Int) More(b interface{}) bool { +func (a Int) More(b any) bool { return a > b.(Int) } func (a Int) Idx() int { diff --git a/structure/dynamicarray/dynamicarray.go b/structure/dynamicarray/dynamicarray.go index 66822be70..948cf71fc 100644 --- a/structure/dynamicarray/dynamicarray.go +++ b/structure/dynamicarray/dynamicarray.go @@ -21,11 +21,11 @@ var defaultCapacity = 10 type DynamicArray struct { Size int Capacity int - ElementData []interface{} + ElementData []any } // Put function is change/update the value in array with the index and new value -func (da *DynamicArray) Put(index int, element interface{}) error { +func (da *DynamicArray) Put(index int, element any) error { err := da.CheckRangeFromIndex(index) if err != nil { @@ -38,7 +38,7 @@ func (da *DynamicArray) Put(index int, element interface{}) error { } // Add function is add new element to our array -func (da *DynamicArray) Add(element interface{}) { +func (da *DynamicArray) Add(element any) { if da.Size == da.Capacity { da.NewCapacity() } @@ -64,7 +64,7 @@ func (da *DynamicArray) Remove(index int) error { } // Get function is return one element with the index of array -func (da *DynamicArray) Get(index int) (interface{}, error) { +func (da *DynamicArray) Get(index int) (any, error) { err := da.CheckRangeFromIndex(index) if err != nil { @@ -80,7 +80,7 @@ func (da *DynamicArray) IsEmpty() bool { } // GetData function return all value of array -func (da *DynamicArray) GetData() []interface{} { +func (da *DynamicArray) GetData() []any { return da.ElementData[:da.Size] } @@ -100,7 +100,7 @@ func (da *DynamicArray) NewCapacity() { da.Capacity = da.Capacity << 1 } - newDataElement := make([]interface{}, da.Capacity) + newDataElement := make([]any, da.Capacity) copy(newDataElement, da.ElementData) diff --git a/structure/dynamicarray/dynamicarray_test.go b/structure/dynamicarray/dynamicarray_test.go index 976370ba8..e6b30b2b1 100644 --- a/structure/dynamicarray/dynamicarray_test.go +++ b/structure/dynamicarray/dynamicarray_test.go @@ -26,7 +26,7 @@ func TestDynamicArray(t *testing.T) { if numbers.IsEmpty() != false { t.Errorf("Expected be false but got %v", numbers.IsEmpty()) } - var res []interface{} + var res []any res = append(res, 10) res = append(res, 20) res = append(res, 30) @@ -43,7 +43,7 @@ func TestDynamicArray(t *testing.T) { if numbers.IsEmpty() != false { t.Errorf("Expected be false but got %v", numbers.IsEmpty()) } - var res []interface{} + var res []any res = append(res, 10) res = append(res, 30) res = append(res, 40) diff --git a/structure/hashmap/hashmap.go b/structure/hashmap/hashmap.go index 1665a50c7..b0f5dbb1d 100644 --- a/structure/hashmap/hashmap.go +++ b/structure/hashmap/hashmap.go @@ -8,8 +8,8 @@ import ( var defaultCapacity uint64 = 1 << 10 type node struct { - key interface{} - value interface{} + key any + value any next *node } @@ -38,7 +38,7 @@ func Make(size, capacity uint64) HashMap { } // Get returns value associated with given key -func (hm *HashMap) Get(key interface{}) interface{} { +func (hm *HashMap) Get(key any) any { node := hm.getNodeByHash(hm.hash(key)) if node != nil { @@ -49,17 +49,17 @@ func (hm *HashMap) Get(key interface{}) interface{} { } // Put puts new key value in hashmap -func (hm *HashMap) Put(key interface{}, value interface{}) interface{} { +func (hm *HashMap) Put(key any, value any) any { return hm.putValue(hm.hash(key), key, value) } // Contains checks if given key is stored in hashmap -func (hm *HashMap) Contains(key interface{}) bool { +func (hm *HashMap) Contains(key any) bool { node := hm.getNodeByHash(hm.hash(key)) return node != nil } -func (hm *HashMap) putValue(hash uint64, key interface{}, value interface{}) interface{} { +func (hm *HashMap) putValue(hash uint64, key any, value any) any { if hm.capacity == 0 { hm.capacity = defaultCapacity hm.table = make([]*node, defaultCapacity) @@ -106,14 +106,14 @@ func (hm *HashMap) resize() { } } -func newNode(key interface{}, value interface{}) *node { +func newNode(key any, value any) *node { return &node{ key: key, value: value, } } -func newNodeWithNext(key interface{}, value interface{}, next *node) *node { +func newNodeWithNext(key any, value any, next *node) *node { return &node{ key: key, value: value, @@ -121,7 +121,7 @@ func newNodeWithNext(key interface{}, value interface{}, next *node) *node { } } -func (hm *HashMap) hash(key interface{}) uint64 { +func (hm *HashMap) hash(key any) uint64 { h := fnv.New64a() _, _ = h.Write([]byte(fmt.Sprintf("%v", key))) diff --git a/structure/hashmap/hashmap_test.go b/structure/hashmap/hashmap_test.go index 2b0030b7e..1699f8c25 100644 --- a/structure/hashmap/hashmap_test.go +++ b/structure/hashmap/hashmap_test.go @@ -59,7 +59,7 @@ func TestHashMap(t *testing.T) { }) t.Run("Test 7: Checking if the key does not exist Get func returns nil", func(t *testing.T) { - want := interface{}(nil) + want := any(nil) got := mp.Get(2) if got != want { t.Errorf("Key '2' does not exists in the map but it says otherwise") diff --git a/structure/linkedlist/cyclic.go b/structure/linkedlist/cyclic.go index cf0ab22df..d0ef8c4b6 100644 --- a/structure/linkedlist/cyclic.go +++ b/structure/linkedlist/cyclic.go @@ -17,7 +17,7 @@ func NewCyclic() *Cyclic { // point to itself. For other cases, the node will be added // to the end of the list. End of the list is Prev field of // current item. Complexity O(1). -func (cl *Cyclic) Add(val interface{}) { +func (cl *Cyclic) Add(val any) { n := NewNode(val) cl.Size++ if cl.Head == nil { diff --git a/structure/linkedlist/cyclic_test.go b/structure/linkedlist/cyclic_test.go index 162f9d0a1..41e925a95 100644 --- a/structure/linkedlist/cyclic_test.go +++ b/structure/linkedlist/cyclic_test.go @@ -15,8 +15,8 @@ func TestAdd(t *testing.T) { list := NewCyclic() fillList(list, 3) - want := []interface{}{1, 2, 3} - var got []interface{} + want := []any{1, 2, 3} + var got []any var start *Node start = list.Head diff --git a/structure/linkedlist/doubly.go b/structure/linkedlist/doubly.go index 5a76e7cf9..42d24935f 100644 --- a/structure/linkedlist/doubly.go +++ b/structure/linkedlist/doubly.go @@ -24,7 +24,7 @@ func NewDoubly() *Doubly { } // AddAtBeg Add a node to the beginning of the linkedlist -func (ll *Doubly) AddAtBeg(val interface{}) { +func (ll *Doubly) AddAtBeg(val any) { n := NewNode(val) n.Next = ll.Head @@ -37,7 +37,7 @@ func (ll *Doubly) AddAtBeg(val interface{}) { } // AddAtEnd Add a node at the end of the linkedlist -func (ll *Doubly) AddAtEnd(val interface{}) { +func (ll *Doubly) AddAtEnd(val any) { n := NewNode(val) if ll.Head == nil { @@ -53,7 +53,7 @@ func (ll *Doubly) AddAtEnd(val interface{}) { } // DelAtBeg Delete the node at the beginning of the linkedlist -func (ll *Doubly) DelAtBeg() interface{} { +func (ll *Doubly) DelAtBeg() any { if ll.Head == nil { return -1 } @@ -68,7 +68,7 @@ func (ll *Doubly) DelAtBeg() interface{} { } // DetAtEnd Delete a node at the end of the linkedlist -func (ll *Doubly) DelAtEnd() interface{} { +func (ll *Doubly) DelAtEnd() any { // no item if ll.Head == nil { return -1 @@ -90,7 +90,7 @@ func (ll *Doubly) DelAtEnd() interface{} { } // Count Number of nodes in the linkedlist -func (ll *Doubly) Count() interface{} { +func (ll *Doubly) Count() any { var ctr int = 0 for cur := ll.Head; cur != nil; cur = cur.Next { diff --git a/structure/linkedlist/shared.go b/structure/linkedlist/shared.go index de92a8fcb..c09e9fe8a 100644 --- a/structure/linkedlist/shared.go +++ b/structure/linkedlist/shared.go @@ -3,12 +3,12 @@ package linkedlist // Node Structure representing the linkedlist node. // This node is shared across different implementations. type Node struct { - Val interface{} + Val any Prev *Node Next *Node } // Create new node. -func NewNode(val interface{}) *Node { +func NewNode(val any) *Node { return &Node{val, nil, nil} } diff --git a/structure/linkedlist/singlylinkedlist.go b/structure/linkedlist/singlylinkedlist.go index 5b9d71787..f8662408a 100644 --- a/structure/linkedlist/singlylinkedlist.go +++ b/structure/linkedlist/singlylinkedlist.go @@ -21,7 +21,7 @@ func NewSingly() *Singly { } // AddAtBeg adds a new snode with given value at the beginning of the list. -func (ll *Singly) AddAtBeg(val interface{}) { +func (ll *Singly) AddAtBeg(val any) { n := NewNode(val) n.Next = ll.Head ll.Head = n @@ -29,7 +29,7 @@ func (ll *Singly) AddAtBeg(val interface{}) { } // AddAtEnd adds a new snode with given value at the end of the list. -func (ll *Singly) AddAtEnd(val interface{}) { +func (ll *Singly) AddAtEnd(val any) { n := NewNode(val) if ll.Head == nil { @@ -46,7 +46,7 @@ func (ll *Singly) AddAtEnd(val interface{}) { } // DelAtBeg deletes the snode at the head(beginning) of the list and returns its value. Returns -1 if the list is empty. -func (ll *Singly) DelAtBeg() interface{} { +func (ll *Singly) DelAtBeg() any { if ll.Head == nil { return -1 } @@ -59,7 +59,7 @@ func (ll *Singly) DelAtBeg() interface{} { } // DelAtEnd deletes the snode at the tail(end) of the list and returns its value. Returns -1 if the list is empty. -func (ll *Singly) DelAtEnd() interface{} { +func (ll *Singly) DelAtEnd() any { if ll.Head == nil { return -1 } diff --git a/structure/linkedlist/singlylinkedlist_test.go b/structure/linkedlist/singlylinkedlist_test.go index b5c615403..df8004aa0 100644 --- a/structure/linkedlist/singlylinkedlist_test.go +++ b/structure/linkedlist/singlylinkedlist_test.go @@ -12,8 +12,8 @@ func TestSingly(t *testing.T) { list.AddAtBeg(3) t.Run("Test AddAtBeg()", func(t *testing.T) { - want := []interface{}{3, 2, 1} - got := []interface{}{} + want := []any{3, 2, 1} + got := []any{} current := list.Head got = append(got, current.Val) for current.Next != nil { @@ -28,8 +28,8 @@ func TestSingly(t *testing.T) { list.AddAtEnd(4) t.Run("Test AddAtEnd()", func(t *testing.T) { - want := []interface{}{3, 2, 1, 4} - got := []interface{}{} + want := []any{3, 2, 1, 4} + got := []any{} current := list.Head got = append(got, current.Val) for current.Next != nil { @@ -42,7 +42,7 @@ func TestSingly(t *testing.T) { }) t.Run("Test DelAtBeg()", func(t *testing.T) { - want := interface{}(3) + want := any(3) got := list.DelAtBeg() if got != want { t.Errorf("got: %v, want: %v", got, want) @@ -50,7 +50,7 @@ func TestSingly(t *testing.T) { }) t.Run("Test DelAtEnd()", func(t *testing.T) { - want := interface{}(4) + want := any(4) got := list.DelAtEnd() if got != want { t.Errorf("got: %v, want: %v", got, want) @@ -74,8 +74,8 @@ func TestSingly(t *testing.T) { list2.AddAtBeg(6) t.Run("Test Reverse()", func(t *testing.T) { - want := []interface{}{1, 2, 3, 4, 5, 6} - got := []interface{}{} + want := []any{1, 2, 3, 4, 5, 6} + got := []any{} list2.Reverse() current := list2.Head got = append(got, current.Val) @@ -89,8 +89,8 @@ func TestSingly(t *testing.T) { }) t.Run("Test ReversePartition()", func(t *testing.T) { - want := []interface{}{1, 5, 4, 3, 2, 6} - got := []interface{}{} + want := []any{1, 5, 4, 3, 2, 6} + got := []any{} err := list2.ReversePartition(2, 5) if err != nil { diff --git a/structure/queue/queue_test.go b/structure/queue/queue_test.go index 469fede41..11cda8ca6 100644 --- a/structure/queue/queue_test.go +++ b/structure/queue/queue_test.go @@ -109,7 +109,7 @@ func TestQueue(t *testing.T) { } }) - ListQueue = []interface{}{} + ListQueue = []any{} t.Run("Test Queue isEmpty", func(t *testing.T) { @@ -125,7 +125,7 @@ func TestQueue(t *testing.T) { } }) - ListQueue = []interface{}{} + ListQueue = []any{} t.Run("Test Queue Length", func(t *testing.T) { if LenQueue() != 0 { t.Errorf("Test Queue Length is wrong the result must be %v but got %v", 0, LenQueue()) diff --git a/structure/queue/queuearray.go b/structure/queue/queuearray.go index 27d0cf609..f1813c8e6 100644 --- a/structure/queue/queuearray.go +++ b/structure/queue/queuearray.go @@ -9,27 +9,27 @@ package queue -var ListQueue []interface{} +var ListQueue []any // EnQueue it will be added new value into our list -func EnQueue(n interface{}) { +func EnQueue(n any) { ListQueue = append(ListQueue, n) } // DeQueue it will be removed the first value that added into the list -func DeQueue() interface{} { +func DeQueue() any { data := ListQueue[0] ListQueue = ListQueue[1:] return data } // FrontQueue return the Front value -func FrontQueue() interface{} { +func FrontQueue() any { return ListQueue[0] } // BackQueue return the Back value -func BackQueue() interface{} { +func BackQueue() any { return ListQueue[len(ListQueue)-1] } diff --git a/structure/queue/queuelinkedlist.go b/structure/queue/queuelinkedlist.go index 7c7dbc4d1..18c04d3f5 100644 --- a/structure/queue/queuelinkedlist.go +++ b/structure/queue/queuelinkedlist.go @@ -11,7 +11,7 @@ package queue // Node will be store the value and the next node as well type Node struct { - Data interface{} + Data any Next *Node } @@ -23,7 +23,7 @@ type Queue struct { } // enqueue it will be added new value into queue -func (ll *Queue) enqueue(n interface{}) { +func (ll *Queue) enqueue(n any) { var newNode Node // create new Node newNode.Data = n // set the data @@ -40,7 +40,7 @@ func (ll *Queue) enqueue(n interface{}) { } // dequeue it will be removed the first value into queue (First In First Out) -func (ll *Queue) dequeue() interface{} { +func (ll *Queue) dequeue() any { if ll.isEmpty() { return -1 // if is empty return -1 } @@ -67,11 +67,11 @@ func (ll *Queue) len() int { } // frontQueue it will return the front data -func (ll *Queue) frontQueue() interface{} { +func (ll *Queue) frontQueue() any { return ll.head.Data } // backQueue it will return the back data -func (ll *Queue) backQueue() interface{} { +func (ll *Queue) backQueue() any { return ll.tail.Data } diff --git a/structure/queue/queuelinklistwithlist.go b/structure/queue/queuelinklistwithlist.go index c1216c3a9..c27bb8bef 100644 --- a/structure/queue/queuelinklistwithlist.go +++ b/structure/queue/queuelinklistwithlist.go @@ -22,7 +22,7 @@ type LQueue struct { } // Enqueue will be added new value -func (lq *LQueue) Enqueue(value interface{}) { +func (lq *LQueue) Enqueue(value any) { lq.queue.PushBack(value) } @@ -40,7 +40,7 @@ func (lq *LQueue) Dequeue() error { } // Front it will return the front value -func (lq *LQueue) Front() (interface{}, error) { +func (lq *LQueue) Front() (any, error) { if !lq.Empty() { val := lq.queue.Front().Value return val, nil @@ -50,7 +50,7 @@ func (lq *LQueue) Front() (interface{}, error) { } // Back it will return the back value -func (lq *LQueue) Back() (interface{}, error) { +func (lq *LQueue) Back() (any, error) { if !lq.Empty() { val := lq.queue.Back().Value return val, nil diff --git a/structure/set/set.go b/structure/set/set.go index 00ffd0629..9adef5c48 100644 --- a/structure/set/set.go +++ b/structure/set/set.go @@ -4,9 +4,9 @@ package set // New gives new set. -func New(items ...interface{}) Set { +func New(items ...any) Set { st := set{ - elements: make(map[interface{}]bool), + elements: make(map[any]bool), } for _, item := range items { st.Add(item) @@ -17,15 +17,15 @@ func New(items ...interface{}) Set { // Set is an interface of possible methods on 'set'. type Set interface { // Add: adds new element to the set - Add(item interface{}) + Add(item any) // Delete: deletes the passed element from the set if present - Delete(item interface{}) + Delete(item any) // Len: gives the length of the set (total no. of elements in set) Len() int - // GetItems: gives the array( []interface{} ) of elements of the set. - GetItems() []interface{} + // GetItems: gives the array( []any ) of elements of the set. + GetItems() []any // In: checks whether item is present in set or not. - In(item interface{}) bool + In(item any) bool // IsSubsetOf: checks whether set is subset of set2 or not. IsSubsetOf(set2 Set) bool // IsSupersetOf: checks whether set is superset of set2 or not. @@ -45,19 +45,19 @@ type Set interface { } type set struct { - elements map[interface{}]bool + elements map[any]bool } -func (st *set) Add(value interface{}) { +func (st *set) Add(value any) { st.elements[value] = true } -func (st *set) Delete(value interface{}) { +func (st *set) Delete(value any) { delete(st.elements, value) } -func (st *set) GetItems() []interface{} { - keys := make([]interface{}, 0, len(st.elements)) +func (st *set) GetItems() []any { + keys := make([]any, 0, len(st.elements)) for k := range st.elements { keys = append(keys, k) } @@ -68,7 +68,7 @@ func (st *set) Len() int { return len(st.elements) } -func (st *set) In(value interface{}) bool { +func (st *set) In(value any) bool { if _, in := st.elements[value]; in { return true } diff --git a/structure/stack/stack_test.go b/structure/stack/stack_test.go index 6bc01ed79..e5a77e70b 100644 --- a/structure/stack/stack_test.go +++ b/structure/stack/stack_test.go @@ -24,7 +24,7 @@ func TestStackLinkedList(t *testing.T) { t.Run("Stack Push", func(t *testing.T) { result := newStack.show() - expected := []interface{}{2, 1} + expected := []any{2, 1} for x := range result { if result[x] != expected[x] { t.Errorf("Stack Push is not work, got %v but expected %v", result, expected) @@ -73,8 +73,8 @@ func TestStackArray(t *testing.T) { stackPush(3) t.Run("Stack Push", func(t *testing.T) { - if !reflect.DeepEqual([]interface{}{3, 2}, stackArray) { - t.Errorf("Stack Push is not work we expected %v but got %v", []interface{}{3, 2}, stackArray) + if !reflect.DeepEqual([]any{3, 2}, stackArray) { + t.Errorf("Stack Push is not work we expected %v but got %v", []any{3, 2}, stackArray) } }) diff --git a/structure/stack/stackarray.go b/structure/stack/stackarray.go index 197871cd6..5aba01cf4 100644 --- a/structure/stack/stackarray.go +++ b/structure/stack/stackarray.go @@ -9,11 +9,11 @@ package stack -var stackArray []interface{} +var stackArray []any // stackPush push to first index of array -func stackPush(n interface{}) { - stackArray = append([]interface{}{n}, stackArray...) +func stackPush(n any) { + stackArray = append([]any{n}, stackArray...) } // stackLength return length of array @@ -22,7 +22,7 @@ func stackLength() int { } // stackPeak return last input of array -func stackPeak() interface{} { +func stackPeak() any { return stackArray[0] } @@ -32,7 +32,7 @@ func stackEmpty() bool { } // stackPop return last input and remove it in array -func stackPop() interface{} { +func stackPop() any { pop := stackArray[0] stackArray = stackArray[1:] return pop diff --git a/structure/stack/stacklinkedlist.go b/structure/stack/stacklinkedlist.go index 9148cc7ad..4c4973884 100644 --- a/structure/stack/stacklinkedlist.go +++ b/structure/stack/stacklinkedlist.go @@ -11,7 +11,7 @@ package stack // Node structure type Node struct { - Val interface{} + Val any Next *Node } @@ -22,7 +22,7 @@ type Stack struct { } // push add value to last index -func (ll *Stack) push(n interface{}) { +func (ll *Stack) push(n any) { newStack := &Node{} // new node newStack.Val = n @@ -33,7 +33,7 @@ func (ll *Stack) push(n interface{}) { } // pop remove last item as first output -func (ll *Stack) pop() interface{} { +func (ll *Stack) pop() any { result := ll.top.Val if ll.top.Next == nil { ll.top = nil @@ -56,12 +56,12 @@ func (ll *Stack) len() int { } // peak return last input value -func (ll *Stack) peak() interface{} { +func (ll *Stack) peak() any { return ll.top.Val } // show all value as an interface array -func (ll *Stack) show() (in []interface{}) { +func (ll *Stack) show() (in []any) { current := ll.top for current != nil { diff --git a/structure/stack/stacklinkedlistwithlist.go b/structure/stack/stacklinkedlistwithlist.go index 6afb778f8..0a758d8c6 100644 --- a/structure/stack/stacklinkedlistwithlist.go +++ b/structure/stack/stacklinkedlistwithlist.go @@ -20,12 +20,12 @@ type SList struct { } // Push add a value into our stack -func (sl *SList) Push(val interface{}) { +func (sl *SList) Push(val any) { sl.stack.PushFront(val) } // Peak is return last value that insert into our stack -func (sl *SList) Peak() (interface{}, error) { +func (sl *SList) Peak() (any, error) { if !sl.Empty() { element := sl.stack.Front() return element.Value, nil @@ -35,7 +35,7 @@ func (sl *SList) Peak() (interface{}, error) { // Pop is return last value that insert into our stack //also it will remove it in our stack -func (sl *SList) Pop() (interface{}, error) { +func (sl *SList) Pop() (any, error) { if !sl.Empty() { // get last element that insert into stack element := sl.stack.Front() From 07eee88553943ed548d6c7d7c62e25e4e72b62cf Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Tue, 10 May 2022 22:46:29 +0530 Subject: [PATCH 054/202] chore: remove codeql workflow (#507) --- .github/workflows/codeql-analysis.yml | 70 --------------------------- 1 file changed, 70 deletions(-) delete mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index f1a89f3d2..000000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,70 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [ master ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ master ] - schedule: - - cron: '33 2 * * 6' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'go' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://git.io/codeql-language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v3 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v2 - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 From 94ee68a86581a8cc55a5fd6d4bc5f2116205eabe Mon Sep 17 00:00:00 2001 From: duongoku Date: Sun, 22 May 2022 03:17:06 +0700 Subject: [PATCH 055/202] add abbreviation problem in dynamic (#508) --- dynamic/abbreviation.go | 45 ++++++++++++++++++++++++++++++++++++ dynamic/abbreviation_test.go | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 dynamic/abbreviation.go create mode 100644 dynamic/abbreviation_test.go diff --git a/dynamic/abbreviation.go b/dynamic/abbreviation.go new file mode 100644 index 000000000..ebfe92171 --- /dev/null +++ b/dynamic/abbreviation.go @@ -0,0 +1,45 @@ +// File: abbreviation.go +// Description: Abbreviation problem +// Details: +// https://www.hackerrank.com/challenges/abbr/problem +// Problem description (from hackerrank): +// You can perform the following operations on the string, a: +// 1. Capitalize zero or more of a's lowercase letters. +// 2. Delete all of the remaining lowercase letters in a. +// Given 2 strings a and b, determine if it's possible to make a equal to be using above operations. +// Example: +// Given a = "ABcde" and b = "ABCD" +// We can capitalize "c" and "d" in a to get "ABCde" then delete all the lowercase letters (which is only "e") in a to get "ABCD" which equals b. +// Author: [duongoku](https://github.com/duongoku) +// See abbreviation_test.go for test cases + +package dynamic + +// strings for getting uppercases and lowercases +import ( + "strings" +) + +// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise +func Abbreviation(a string, b string) bool { + dp := make([][]bool, len(a)+1) + for i := range dp { + dp[i] = make([]bool, len(b)+1) + } + dp[0][0] = true + + for i := 0; i < len(a); i++ { + for j := 0; j <= len(b); j++ { + if dp[i][j] { + if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) { + dp[i+1][j+1] = true + } + if string(a[i]) == strings.ToLower(string(a[i])) { + dp[i+1][j] = true + } + } + } + } + + return dp[len(a)][len(b)] +} diff --git a/dynamic/abbreviation_test.go b/dynamic/abbreviation_test.go new file mode 100644 index 000000000..38824d33a --- /dev/null +++ b/dynamic/abbreviation_test.go @@ -0,0 +1,41 @@ +package dynamic + +import ( + "fmt" + "testing" +) + +func TestAbbreviation(t *testing.T) { + tests := []struct { + a string + b string + expected bool + }{ + {"uOHlGMdUBc", "uOalGMdUBCasdcavsdf", false}, + {"kotgDIUagj", "DIU", true}, + {"WPTffVkSNl", "WPTVSN", true}, + {"CoJsPURrVX", "CPUVX", false}, + {"xasreDHndqvCnFfX", "DHndqvCnFX", false}, + {"XFEaWCxpeepGjOnCCsFh", "XFEAWCPEPGOCCSF", true}, + {"", "", true}, + {"a", "", true}, + {"a", "b", false}, + {"a", "a", false}, + {"A", "A", true}, + } + count := len(tests) + for i := 0; i < count; i++ { + name := fmt.Sprintf( + "Test case #%d: string a = \"%s\", string b = \"%s\"", + i+1, + tests[i].a, + tests[i].b, + ) + t.Run(name, func(t *testing.T) { + result := Abbreviation(tests[i].a, tests[i].b) + if result != tests[i].expected { + t.Errorf("Expected the %t, got %t", tests[i].expected, result) + } + }) + } +} From 3a41a76f0cae4cb677334a34714c129ec05cf5ad Mon Sep 17 00:00:00 2001 From: Taj Date: Mon, 27 Jun 2022 06:18:30 +0100 Subject: [PATCH 056/202] merge: manually disabled the problematic linters for Go 1.18 (#509) * fix: manually disabled the problematic linters * chore: add trailing newline Co-authored-by: Rak Laptudirm --- .golangci.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..aa9001693 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,8 @@ +run: + go: 1.18 +linters: + disable: + - gosimple + - staticcheck + - structcheck + - unused From d05e0135ac4a778d262d312103b7449d9121b027 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Ti=E1=BA=BFn=20=C4=90=E1=BA=A1t?= Date: Thu, 7 Jul 2022 09:12:26 +0700 Subject: [PATCH 057/202] feat: Lowest Common Ancestor (LCA) algorithm (#512) --- README.md | 84 +++++----- graph/lowestcommonancestor.go | 121 ++++++++++++++ graph/lowestcommonancestor_test.go | 250 +++++++++++++++++++++++++++++ 3 files changed, 418 insertions(+), 37 deletions(-) create mode 100644 graph/lowestcommonancestor.go create mode 100644 graph/lowestcommonancestor_test.go diff --git a/README.md b/README.md index 0fc3d96e5..8eee9e312 100644 --- a/README.md +++ b/README.md @@ -93,12 +93,13 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number 3. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. 4. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 -5. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations -6. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift -7. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -8. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n -9. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. -10. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +5. [`LogBase2`](./math/binary/logarithm.go#L7): LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm) +6. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations +7. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift +8. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. +9. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n +10. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. +11. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
@@ -256,24 +257,25 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`Bin2`](./dynamic/binomialcoefficient.go#L21): Bin2 function -2. [`CoinChange`](./dynamic/coinchange.go#L5): CoinChange finds the number of possible combinations of coins of different values which can get to the target amount. -3. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming -4. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach -5. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively. -6. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. -7. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. -8. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit -9. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function -10. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order -11. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ -12. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function -13. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function -14. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function -15. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function -16. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate -17. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) -18. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number +1. [`Abbreviation`](./dynamic/abbreviation.go#L24): Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise +2. [`Bin2`](./dynamic/binomialcoefficient.go#L21): Bin2 function +3. [`CoinChange`](./dynamic/coinchange.go#L5): CoinChange finds the number of possible combinations of coins of different values which can get to the target amount. +4. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming +5. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach +6. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively. +7. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. +8. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. +9. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit +10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function +11. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order +12. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ +13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function +14. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function +15. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function +16. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function +17. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate +18. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) +19. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number ---
@@ -411,10 +413,12 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 5. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm 6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. 7. [`KruskalMST`](./graph/kruskal.go#L87): KruskalMST will return a minimum spanning tree along with its total cost to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is the number of edges in the graph and n is number of nodes in it. -8. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) -9. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made -10. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. -11. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b +8. [`LowestCommonAncestor`](./graph/lowestcommonancestor.go#L111): For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. +9. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) +10. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made +11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. +12. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. +13. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b --- ##### Types @@ -429,7 +433,13 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 5. [`Item`](./graph/dijkstra.go#L5): No description provided. -6. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. +6. [`Query`](./graph/lowestcommonancestor_test.go#L9): No description provided. + +7. [`Tree`](./graph/lowestcommonancestor.go#L25): No description provided. + +8. [`TreeEdge`](./graph/lowestcommonancestor.go#L12): No description provided. + +9. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. --- @@ -738,14 +748,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Factorize`](./math/prime/primefactorization.go#L5): Factorize is a function that computes the exponents of each prime in the prime factorization of n 2. [`Generate`](./math/prime/sieve.go#L26): Generate returns a int slice of prime numbers up to the limit 3. [`GenerateChannel`](./math/prime/sieve.go#L9): Generate generates the sequence of integers starting at 2 and sends it to the channel `ch` -4. [`MillerRabinDeterministic`](./math/prime/millerrabinprimalitytest.go#L121): MillerRabinDeterministic is a Deterministic version of the Miller-Rabin test, which returns correct results for all valid int64 numbers. -5. [`MillerRabinProbabilistic`](./math/prime/millerrabinprimalitytest.go#L101): MillerRabinProbabilistic is a probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. -6. [`MillerRandomTest`](./math/prime/millerrabinprimalitytest.go#L77): MillerRandomTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result with random witnesses. -7. [`MillerTest`](./math/prime/millerrabinprimalitytest.go#L49): MillerTest tests whether num is a strong probable prime to a witness. Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s -8. [`MillerTestMultiple`](./math/prime/millerrabinprimalitytest.go#L84): MillerTestMultiple is like MillerTest but runs the test for multiple witnesses. -9. [`NaiveApproach`](./math/prime/primecheck.go#L8): NaiveApproach checks if an integer is prime or not. Returns a bool. -10. [`PairApproach`](./math/prime/primecheck.go#L22): PairApproach checks primality of an integer and returns a bool. More efficient than the naive approach as number of iterations are less. -11. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels +4. [`MillerRabinDeterministic`](./math/prime/millerrabintest.go#L121): MillerRabinDeterministic is a Deterministic version of the Miller-Rabin test, which returns correct results for all valid int64 numbers. +5. [`MillerRabinProbabilistic`](./math/prime/millerrabintest.go#L101): MillerRabinProbabilistic is a probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin. +6. [`MillerRandomTest`](./math/prime/millerrabintest.go#L77): MillerRandomTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result with random witnesses. +7. [`MillerTest`](./math/prime/millerrabintest.go#L49): MillerTest tests whether num is a strong probable prime to a witness. Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s +8. [`MillerTestMultiple`](./math/prime/millerrabintest.go#L84): MillerTestMultiple is like MillerTest but runs the test for multiple witnesses. +9. [`OptimizedTrialDivision`](./math/prime/primecheck.go#L26): OptimizedTrialDivision checks primality of an integer using an optimized trial division method. The optimizations include not checking divisibility by the even numbers and only checking up to the square root of the given number. +10. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels +11. [`TrialDivision`](./math/prime/primecheck.go#L9): TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it. ---
diff --git a/graph/lowestcommonancestor.go b/graph/lowestcommonancestor.go new file mode 100644 index 000000000..8ce575187 --- /dev/null +++ b/graph/lowestcommonancestor.go @@ -0,0 +1,121 @@ +// lowestcommonancestor.go +// description: Implementation of Lowest common ancestor (LCA) algorithm. +// detail: +// Let `T` be a tree. The LCA of `u` and `v` in T is the shared ancestor of `u` and `v` +// that is located farthest from the root. +// references: [cp-algorithms](https://cp-algorithms.com/graph/lca_binary_lifting.html) +// author(s) [Dat](https://github.com/datbeohbbh) +// see lowestcommonancestor_test.go for a test implementation. + +package graph + +type TreeEdge struct { + from int + to int +} + +type ITree interface { + dfs(int, int) + addEdge(int, int) + GetDepth(int) int + GetDad(int) int + GetLCA(int, int) int +} + +type Tree struct { + numbersVertex int + root int + MAXLOG int + depth []int + dad []int + jump [][]int + edges [][]int +} + +func (tree *Tree) addEdge(u, v int) { + tree.edges[u] = append(tree.edges[u], v) + tree.edges[v] = append(tree.edges[v], u) +} + +func (tree *Tree) dfs(u, par int) { + tree.jump[0][u] = par + tree.dad[u] = par + for _, v := range tree.edges[u] { + if v != par { + tree.depth[v] = tree.depth[u] + 1 + tree.dfs(v, u) + } + } +} + +func (tree *Tree) GetDepth(u int) int { + return tree.depth[u] +} + +func (tree *Tree) GetDad(u int) int { + return tree.dad[u] +} + +func (tree *Tree) GetLCA(u, v int) int { + if tree.GetDepth(u) < tree.GetDepth(v) { + u, v = v, u + } + + for j := tree.MAXLOG - 1; j >= 0; j-- { + if tree.GetDepth(tree.jump[j][u]) >= tree.GetDepth(v) { + u = tree.jump[j][u] + } + } + + if u == v { + return u + } + + for j := tree.MAXLOG - 1; j >= 0; j-- { + if tree.jump[j][u] != tree.jump[j][v] { + u = tree.jump[j][u] + v = tree.jump[j][v] + } + } + + return tree.jump[0][u] +} + +func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) { + tree = new(Tree) + tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0 + tree.depth = make([]int, numbersVertex) + tree.dad = make([]int, numbersVertex) + + for (1 << tree.MAXLOG) <= numbersVertex { + (tree.MAXLOG) += 1 + } + (tree.MAXLOG) += 1 + + tree.jump = make([][]int, tree.MAXLOG) + for j := 0; j < tree.MAXLOG; j++ { + tree.jump[j] = make([]int, numbersVertex) + } + + tree.edges = make([][]int, numbersVertex) + for _, e := range edges { + tree.addEdge(e.from, e.to) + } + + return tree +} + +// For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. +// Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. +// These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. +func LowestCommonAncestor(tree *Tree) { + // call dfs to compute depth from the root to each node and the parent of each node. + tree.dfs(tree.root, tree.root) + + // compute jump[j][u] + for j := 1; j < tree.MAXLOG; j++ { + for u := 0; u < tree.numbersVertex; u++ { + tree.jump[j][u] = tree.jump[j-1][tree.jump[j-1][u]] + } + } +} diff --git a/graph/lowestcommonancestor_test.go b/graph/lowestcommonancestor_test.go new file mode 100644 index 000000000..c7149e46e --- /dev/null +++ b/graph/lowestcommonancestor_test.go @@ -0,0 +1,250 @@ +package graph + +import ( + "math/rand" + "testing" + "time" +) + +type Query struct { + u int + v int + expected int +} + +func TestLCA(t *testing.T) { + testSuites := []struct { + numbersVertex int + root int + edges []TreeEdge + queries []Query + }{ + { + numbersVertex: 2, + root: 0, + edges: []TreeEdge{ + { + from: 0, + to: 1, + }, + }, + queries: []Query{ + { + u: 0, + v: 0, + expected: 0, + }, + { + u: 0, + v: 1, + expected: 0, + }, + { + u: 1, + v: 1, + expected: 1, + }, + }, + }, { + numbersVertex: 1, + root: 0, + edges: []TreeEdge{}, + queries: []Query{ + { + u: 0, + v: 0, + expected: 0, + }, + }, + }, { + numbersVertex: 9, + root: 7, + edges: []TreeEdge{ + { + from: 0, + to: 1, + }, + { + from: 0, + to: 2, + }, + { + from: 2, + to: 3, + }, + { + from: 2, + to: 4, + }, + { + from: 2, + to: 6, + }, + { + from: 3, + to: 5, + }, + { + from: 6, + to: 7, + }, + { + from: 6, + to: 8, + }, + }, + queries: []Query{ + { + u: 1, + v: 0, + expected: 0, + }, + { + u: 8, + v: 2, + expected: 6, + }, + { + u: 1, + v: 5, + expected: 2, + }, + { + u: 4, + v: 7, + expected: 7, + }, + { + u: 0, + v: 8, + expected: 6, + }, + }, + }, + } + // Test #2: + // 7 + // / + // 6 + // / \ + // 2 8 + // / | \ + // 0 3 4 + // / | + // 1 5 + for idx, test := range testSuites { + tree := NewTree(test.numbersVertex, test.root, test.edges) + LowestCommonAncestor(tree) + + for qi, query := range test.queries { + actual := tree.GetLCA(query.u, query.v) + expected := query.expected + if actual != expected { + t.Errorf("\nTest #%d:\nQuery #%d: u = %d, v = %d\nExpected %d, but actual %d", idx, qi, query.u, query.v, expected, actual) + } + } + } +} + +func generateTree() *Tree { + rand.Seed(time.Now().UnixNano()) + + const MAXVERTEX int = 2000 + var numbersVertex int = rand.Intn(MAXVERTEX) + 1 + var root int = rand.Intn(numbersVertex) + var edges []TreeEdge + + var fullGraph []TreeEdge + for u := 0; u < numbersVertex; u++ { + for v := 0; v < numbersVertex; v++ { + fullGraph = append(fullGraph, TreeEdge{ + from: u, + to: v, + }) + } + } + rand.Shuffle(len(fullGraph), func(i, j int) { + fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i] + }) + + par := make([]int, numbersVertex) + for u := 0; u < numbersVertex; u++ { + par[u] = u + } + + var findp func(int) int + findp = func(u int) int { + if u == par[u] { + return u + } else { + par[u] = findp(par[u]) + return par[u] + } + } + + join := func(u, v int) bool { + u, v = findp(u), findp(v) + if u == v { + return false + } + par[v] = u + return true + } + + for _, e := range fullGraph { + if join(e.from, e.to) == true { + edges = append(edges, e) + } + } + + return NewTree(numbersVertex, root, edges) +} + +func generateQuery(tree *Tree) []Query { + rand.Seed(time.Now().UnixNano()) + const MAXQUERY = 50 + var queries []Query + + bruteforceLCA := func(u, v int) int { + for u != v { + if tree.GetDepth(u) > tree.GetDepth(v) { + u = tree.GetDad(u) + } else { + v = tree.GetDad(v) + } + } + return u + } + + for q := 1; q <= MAXQUERY; q++ { + u := rand.Intn(tree.numbersVertex) + v := rand.Intn(tree.numbersVertex) + queries = append(queries, Query{ + u: u, + v: v, + expected: bruteforceLCA(u, v), + }) + } + + return queries +} + +// Test with the tree with up to 2000 vertices. +func TestLCAWithLargeTree(t *testing.T) { + const MAXTEST int = 20 + + for test := 1; test <= MAXTEST; test++ { + tree := generateTree() + LowestCommonAncestor(tree) + + queries := generateQuery(tree) + + for qi, query := range queries { + actual := tree.GetLCA(query.u, query.v) + expected := query.expected + if actual != expected { + t.Errorf("\nTest #%d:\nQuery #%d: u = %d, v = %d\nExpected %d, but actual %d", test, qi, query.u, query.v, expected, actual) + } + } + } +} From b419e51309d680766e05f72621228ecc08faf6c5 Mon Sep 17 00:00:00 2001 From: AFMahmuda Date: Tue, 26 Jul 2022 04:30:51 +0800 Subject: [PATCH 058/202] fix CONTRIBUTING.md (#514) * fix: CONTRIBUTING.md markdown styling Co-authored-by: Arif Fathur Mahmuda --- CONTRIBUTING.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1d7b39624..738f6cb7f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,10 +7,12 @@ Welcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! Before submi ## Contributing ### Maintainers +--- Please check the [`CODEOWNERS`](https://github.com/TheAlgorithms/Go/blob/master/.github/CODEOWNERS) file for a list of repository maintainers. ### Contributor +--- Being a contributor at The Algorithms, we request you to follow the points mentioned below: @@ -19,13 +21,18 @@ Being a contributor at The Algorithms, we request you to follow the points menti - Your work will be distributed under the [MIT License](https://github.com/TheAlgorithms/Go/blob/master/LICENSE) once your pull request has been merged. - Please follow the repository guidelines and standards mentioned below. -**New implementation** New implementations are welcome! +#### New implementation -You can add new algorithms or data structures that are **not present in the repository** or that can **improve** the old implementations (**documentation**, **improving test cases**, removing bugs, or in any other reasonable sense) +- New implementations are welcome! -**Issues** Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request, and it will be evaluated by project maintainers. +- You can add new algorithms or data structures that are **not present in the repository** or that can **improve** the old implementations (**documentation**, **improving test cases**, removing bugs, or in any other reasonable sense) + +#### Issues + +- Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request, and it will be evaluated by project maintainers. ### Making Changes +--- #### Code @@ -56,6 +63,7 @@ You can add new algorithms or data structures that are **not present in the repo - Please try to add one or more `Test` functions that will invoke the algorithm implementation on random test data with the expected output. ### Benchmark +--- - Make sure to add examples and benchmark cases in your `filename_test.go` or `filename_bench.go` if you want separated test and benchmark files. - If you find an algorithm or document without benchmarks, please feel free to create a pull request or issue describing suggested changes. @@ -158,6 +166,7 @@ Common prefixes: - test: Correct existing tests or add new ones ### For New Gophers +--- #### Installing Go @@ -192,6 +201,7 @@ go build . ``` ### Pull Requests +--- - Check out our [pull request template](https://github.com/TheAlgorithms/Go/blob/master/.github/PULL_REQUEST_TEMPLATE/pull_request.md ) From 14aa19417f8ca1fdeb4bb28c9cb62f9c80a5c79b Mon Sep 17 00:00:00 2001 From: Samuel NTA Gyamfi <49637763+Onlyartist9@users.noreply.github.com> Date: Thu, 4 Aug 2022 11:50:05 +0000 Subject: [PATCH 059/202] Fixed typo in name of algorithm. (#516) --- cipher/diffiehellman/diffiehellmankeyexchange.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cipher/diffiehellman/diffiehellmankeyexchange.go b/cipher/diffiehellman/diffiehellmankeyexchange.go index ae26b1f09..2621e3cca 100644 --- a/cipher/diffiehellman/diffiehellmankeyexchange.go +++ b/cipher/diffiehellman/diffiehellmankeyexchange.go @@ -1,4 +1,4 @@ -// Package diffiehellman implements Deffie Hellman Key Exchange Algorithm +// Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm // for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI package diffiehellman From b913b5e40e95b8c47d085070fed56c8d3f240a5b Mon Sep 17 00:00:00 2001 From: Taj Date: Sat, 6 Aug 2022 05:24:06 +0100 Subject: [PATCH 060/202] bump: go 1.19 and fix: fmt issues (#519) --- .golangci.yml | 2 +- go.mod | 2 +- graph/articulationpoints.go | 2 +- graph/floydwarshall_test.go | 6 +++--- math/binary/checkisnumberpoweroftwo.go | 8 +++++--- math/pythagoras/pythagoras.go | 4 ++-- math/pythagoras/pythagoras_test.go | 2 +- other/nested/nestedbrackets.go | 6 +++--- search/binary.go | 8 ++++---- search/interpolation.go | 11 +++++++---- structure/segmenttree/segmenttree.go | 20 ++++++++++---------- structure/segmenttree/segmenttree_test.go | 2 +- structure/stack/stacklinkedlistwithlist.go | 2 +- 13 files changed, 40 insertions(+), 35 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index aa9001693..b334bee16 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,5 +1,5 @@ run: - go: 1.18 + go: 1.19 linters: disable: - gosimple diff --git a/go.mod b/go.mod index 23f37df27..5a3e15ba4 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/TheAlgorithms/Go -go 1.18 +go 1.19 diff --git a/graph/articulationpoints.go b/graph/articulationpoints.go index 8c295d639..618107890 100644 --- a/graph/articulationpoints.go +++ b/graph/articulationpoints.go @@ -50,7 +50,7 @@ func ArticulationPoint(graph *Graph) []bool { // articulationPointHelper is a recursive function to traverse the graph // and mark articulation points. Based on the depth first search transversal // of the graph, however modified to keep track and update the -// `child_cnt`, `discovery_time`` and `earliest_discovery` slices defined above +// `child_cnt`, `discovery_time` and `earliest_discovery` slices defined above func articulationPointHelper( apHelperInstance *apHelper, vertex int, diff --git a/graph/floydwarshall_test.go b/graph/floydwarshall_test.go index 17d82930e..a4a28aae5 100644 --- a/graph/floydwarshall_test.go +++ b/graph/floydwarshall_test.go @@ -7,13 +7,13 @@ import ( const float64EqualityThreshold = 1e-9 -//almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold -//reference: https://stackoverflow.com/a/47969546 +// almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold +// reference: https://stackoverflow.com/a/47969546 func almostEqual(a, b float64) bool { return math.Abs(a-b) <= float64EqualityThreshold } -//IsAlmostEqualTo verifies if two WeightedGraphs can be considered almost equal +// IsAlmostEqualTo verifies if two WeightedGraphs can be considered almost equal func (a *WeightedGraph) IsAlmostEqualTo(b WeightedGraph) bool { if len(*a) != len(b) { return false diff --git a/math/binary/checkisnumberpoweroftwo.go b/math/binary/checkisnumberpoweroftwo.go index 46c459cf8..63ecc6e3b 100644 --- a/math/binary/checkisnumberpoweroftwo.go +++ b/math/binary/checkisnumberpoweroftwo.go @@ -11,9 +11,11 @@ package binary // like 10...0 in binary, and numbers one less than the power of 2 // are represented like 11...1. // Therefore, using the and function: -// 10...0 -// & 01...1 -// 00...0 -> 0 +// +// 10...0 +// & 01...1 +// 00...0 -> 0 +// // This is also true for 0, which is not a power of 2, for which we // have to add and extra condition. func IsPowerOfTwo(x int) bool { diff --git a/math/pythagoras/pythagoras.go b/math/pythagoras/pythagoras.go index fb3c51c4c..54e6ef0ca 100644 --- a/math/pythagoras/pythagoras.go +++ b/math/pythagoras/pythagoras.go @@ -4,14 +4,14 @@ import ( "math" ) -//Vector defines a tuple with 3 values in 3d-space +// Vector defines a tuple with 3 values in 3d-space type Vector struct { x float64 y float64 z float64 } -//Distance calculates the distance between to vectors with the Pythagoras theorem +// Distance calculates the distance between to vectors with the Pythagoras theorem func Distance(a, b Vector) float64 { res := math.Pow(b.x-a.x, 2.0) + math.Pow(b.y-a.y, 2.0) + math.Pow(b.z-a.z, 2.0) return math.Sqrt(res) diff --git a/math/pythagoras/pythagoras_test.go b/math/pythagoras/pythagoras_test.go index 1ae7e1185..3365c4a31 100644 --- a/math/pythagoras/pythagoras_test.go +++ b/math/pythagoras/pythagoras_test.go @@ -18,7 +18,7 @@ var distanceTest = []struct { {"random short vectors", Vector{1, 1, 1}, Vector{2, 2, 2}, 1.73}, } -//TestDistance tests the Function Distance with 2 vectors +// TestDistance tests the Function Distance with 2 vectors func TestDistance(t *testing.T) { t.Parallel() // marks TestDistance as capable of running in parallel with other tests for _, tt := range distanceTest { diff --git a/other/nested/nestedbrackets.go b/other/nested/nestedbrackets.go index f127acc93..ec912938c 100644 --- a/other/nested/nestedbrackets.go +++ b/other/nested/nestedbrackets.go @@ -8,9 +8,9 @@ package nested // // A sequence of brackets `s` is considered properly nested // if any of the following conditions are true: -// - `s` is empty; -// - `s` has the form (U) or [U] or {U} where U is a properly nested string; -// - `s` has the form VW where V and W are properly nested strings. +// - `s` is empty; +// - `s` has the form (U) or [U] or {U} where U is a properly nested string; +// - `s` has the form VW where V and W are properly nested strings. // // For example, the string "()()[()]" is properly nested but "[(()]" is not. // diff --git a/search/binary.go b/search/binary.go index c30e4b291..3b9241af6 100644 --- a/search/binary.go +++ b/search/binary.go @@ -37,8 +37,8 @@ func BinaryIterative(array []int, target int) (int, error) { return -1, ErrNotFound } -//Returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. -//return -1 and ErrNotFound if no such element is found. +// Returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. +// return -1 and ErrNotFound if no such element is found. func LowerBound(array []int, target int) (int, error) { startIndex := 0 endIndex := len(array) - 1 @@ -59,8 +59,8 @@ func LowerBound(array []int, target int) (int, error) { return startIndex, nil } -//Returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. -//return -1 and ErrNotFound if no such element is found. +// Returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. +// return -1 and ErrNotFound if no such element is found. func UpperBound(array []int, target int) (int, error) { startIndex := 0 endIndex := len(array) - 1 diff --git a/search/interpolation.go b/search/interpolation.go index 963e68000..722d77e2a 100644 --- a/search/interpolation.go +++ b/search/interpolation.go @@ -4,11 +4,14 @@ package search // if the entity is present, it will return the index of the entity, if not -1 will be returned. // see: https://en.wikipedia.org/wiki/Interpolation_search // Complexity -// Worst: O(N) -// Average: O(log(log(N)) if the elements are uniformly distributed -// Best: O(1) +// +// Worst: O(N) +// Average: O(log(log(N)) if the elements are uniformly distributed +// Best: O(1) +// // Example -// fmt.Println(InterpolationSearch([]int{1, 2, 9, 20, 31, 45, 63, 70, 100},100)) +// +// fmt.Println(InterpolationSearch([]int{1, 2, 9, 20, 31, 45, 63, 70, 100},100)) func Interpolation(sortedData []int, guess int) (int, error) { if len(sortedData) == 0 { return -1, ErrNotFound diff --git a/structure/segmenttree/segmenttree.go b/structure/segmenttree/segmenttree.go index 2799c5537..b55f69f0e 100644 --- a/structure/segmenttree/segmenttree.go +++ b/structure/segmenttree/segmenttree.go @@ -13,14 +13,14 @@ import ( const emptyLazyNode = 0 -//SegmentTree with original Array and the Segment Tree Array +// SegmentTree with original Array and the Segment Tree Array type SegmentTree struct { Array []int SegmentTree []int LazyTree []int } -//Propagate lazy tree node values +// Propagate lazy tree node values func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) { if s.LazyTree[node] != emptyLazyNode { //add lazy node value multiplied by (right-left+1), which represents all interval @@ -42,8 +42,8 @@ func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) { } } -//Query on interval [firstIndex, leftIndex] -//node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 +// Query on interval [firstIndex, leftIndex] +// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 func (s *SegmentTree) Query(node int, leftNode int, rightNode int, firstIndex int, lastIndex int) int { if (firstIndex > lastIndex) || (leftNode > rightNode) { //outside the interval @@ -67,10 +67,10 @@ func (s *SegmentTree) Query(node int, leftNode int, rightNode int, firstIndex in return leftNodeSum + rightNodeSum } -//Update Segment Tree -//node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 -//index is the Array index that you want to update -//value is the value that you want to override +// Update Segment Tree +// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 +// index is the Array index that you want to update +// value is the value that you want to override func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex int, lastIndex int, value int) { //propagate lazy tree s.Propagate(node, leftNode, rightNode) @@ -96,8 +96,8 @@ func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex i } } -//Build Segment Tree -//node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 +// Build Segment Tree +// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 func (s *SegmentTree) Build(node int, left int, right int) { if left == right { //leaf node diff --git a/structure/segmenttree/segmenttree_test.go b/structure/segmenttree/segmenttree_test.go index 142104b87..33bfef546 100644 --- a/structure/segmenttree/segmenttree_test.go +++ b/structure/segmenttree/segmenttree_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -//Query interval +// Query interval type query struct { firstIndex int lastIndex int diff --git a/structure/stack/stacklinkedlistwithlist.go b/structure/stack/stacklinkedlistwithlist.go index 0a758d8c6..ba3ce6580 100644 --- a/structure/stack/stacklinkedlistwithlist.go +++ b/structure/stack/stacklinkedlistwithlist.go @@ -34,7 +34,7 @@ func (sl *SList) Peak() (any, error) { } // Pop is return last value that insert into our stack -//also it will remove it in our stack +// also it will remove it in our stack func (sl *SList) Pop() (any, error) { if !sl.Empty() { // get last element that insert into stack From 16c92748a3db40d1c6f916e390342d02e21c22d0 Mon Sep 17 00:00:00 2001 From: Paulden Date: Sat, 6 Aug 2022 19:23:37 +0800 Subject: [PATCH 061/202] add patience sorting algorithm (#517) * add patience sorting algorithm * fix: fix patience sorting code style * fix:fix patience sorting formatting error --- sort/patiencesort.go | 67 ++++++++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 8 ++++++ 2 files changed, 75 insertions(+) create mode 100644 sort/patiencesort.go diff --git a/sort/patiencesort.go b/sort/patiencesort.go new file mode 100644 index 000000000..efae67ff0 --- /dev/null +++ b/sort/patiencesort.go @@ -0,0 +1,67 @@ +// Package sort +// Patience sorting is a sorting algorithm inspired by the card game patience. +// +// For more details check out those links below here: +// GeeksForGeeks article : https://www.geeksforgeeks.org/patience-sorting/ +// Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting +// authors [guuzaa](https://github.com/guuzaa) +// see patiencesort.go +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +func Patience[T constraints.Ordered](arr []T) []T { + if len(arr) <= 1 { + return arr + } + + var piles [][]T + + for _, card := range arr { + left, right := 0, len(piles) + for left < right { + mid := left + (right-left)/2 + if piles[mid][len(piles[mid])-1] >= card { + right = mid + } else { + left = mid + 1 + } + } + + if left == len(piles) { + piles = append(piles, []T{card}) + } else { + piles[left] = append(piles[left], card) + } + } + + return mergePiles(piles) +} + +func mergePiles[T constraints.Ordered](piles [][]T) []T { + var ret []T + + for len(piles) > 0 { + minID := 0 + minValue := piles[minID][len(piles[minID])-1] + + for i := 1; i < len(piles); i++ { + if minValue <= piles[i][len(piles[i])-1] { + continue + } + + minValue = piles[i][len(piles[i])-1] + minID = i + } + + ret = append(ret, minValue) + + piles[minID] = piles[minID][:len(piles[minID])-1] + + if len(piles[minID]) == 0 { + piles = append(piles[:minID], piles[minID+1:]...) + } + } + + return ret +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 08b6a716d..467d054ce 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -135,6 +135,10 @@ func TestPigeonhole(t *testing.T) { testFramework(t, sort.Pigeonhole) } +func TestPatience(t *testing.T) { + testFramework(t, sort.Patience[int]) +} + //END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -236,3 +240,7 @@ func BenchmarkComb(b *testing.B) { func BenchmarkPigeonhole(b *testing.B) { benchmarkFramework(b, sort.Pigeonhole) } + +func BenchmarkPatience(b *testing.B) { + benchmarkFramework(b, sort.Patience[int]) +} From 2ad5f9c0a3f13791c291fc5d3d9be973312e8327 Mon Sep 17 00:00:00 2001 From: Jason07311 <52784322+Jason07311@users.noreply.github.com> Date: Sun, 7 Aug 2022 23:24:24 +0800 Subject: [PATCH 062/202] merge: Added mean algorithm and test code (#521) * Added mean algorithm and test code Mean algorithm 4 test cases included with test codes * Implement Suggestions from tjgurwara99 fix: Removed the print message under validation fix: Removed print message under validating condition for empty array fix: The first letter of function name is capitalized fix: Added another test cases with no values fix: Added Generics docs: Moved the mean.go and mean_test.go to be directly under maths package docs: Added comment to indicate the validating condition for empty array in the algorithm * Implement Next Suggestion & Bug Fixes fix: Fixed the typo of package name in both files fix: Replace the import of constraints with github existing constraints fix: Simplified the return codes docs: Removed unnecessary comments docs: Removed extra folder of mean and files within * Removed the useless codes of interface fix: Implemented the embedded constraints within github/TheAlogithm/Go and removed the extra codes * Updated the package of mean_test.go fix: Updated the package to math_test fix: Updated the access of Mean to math.Mean fix: Added github path for math --- math/mean.go | 21 +++++++++++++++++++ math/mean_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 math/mean.go create mode 100644 math/mean_test.go diff --git a/math/mean.go b/math/mean.go new file mode 100644 index 000000000..4bd0e40ed --- /dev/null +++ b/math/mean.go @@ -0,0 +1,21 @@ +package math + +import ( + "github.com/TheAlgorithms/Go/constraints" +) + +func Mean[T constraints.Number](values []T) float64 { + + if len(values) == 0 { + return 0 + } + + var summation float64 = 0 + + for _, singleValue := range values { + summation += float64(singleValue) + } + + return summation / float64(len(values)) + +} diff --git a/math/mean_test.go b/math/mean_test.go new file mode 100644 index 000000000..8f74511ef --- /dev/null +++ b/math/mean_test.go @@ -0,0 +1,52 @@ +package math_test + +import ( + "github.com/TheAlgorithms/Go/math" + "testing" +) + +func TestMean(t *testing.T) { + testCases := []struct { + name string + testValues []float64 + average float64 + }{ + { + name: "All 0s", + testValues: []float64{0, 0, 0, 0, 0}, + average: 0, + }, + { + name: "With integer values", + testValues: []float64{1, 2, 3, 4, 5}, + average: 3.0, + }, + { + name: "With negative values", + testValues: []float64{-1, 2, -3, 4, 5}, + average: 1.4, + }, + { + name: "With floating values", + testValues: []float64{1.1, 2.2, 3.3, 4.4, 5.5}, + average: 3.3, + }, + { + name: "With no values", + testValues: []float64{}, + average: 0, + }, + } + + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + returnedAverage := math.Mean(test.testValues) + if returnedAverage != test.average { + t.Errorf("\nFailed test: %s\ntestValues: %v\naverage: %v\nbut received: %v\n", + test.name, test.testValues, test.average, returnedAverage) + } + + }) + } + +} From aaf7fd89269659fa0d3ad54fe75a033cb9a0f00d Mon Sep 17 00:00:00 2001 From: jo3zeph <86296674+jo3zeph@users.noreply.github.com> Date: Mon, 8 Aug 2022 14:36:19 +0800 Subject: [PATCH 063/202] Added median.go (#522) * Added Roundoff Simple showcase of Roundoff operation in GoLang feat: add roundoff.go test: add roundoff_test.go docs: added comments on both roundoff.go and roundoff_test.go * Revert "Added Roundoff" This reverts commit c50fa899d619c7954259c6e5112a58a16b503166. * Added median.go feat: added median.go test: added median_test.go docs: added comments on both median.go and median_test.go * Performed suggested fixes and improvements on median.go and median_test.go fix median.go on using switch case, formatting, applied generics fix median_test.go on formatting and using edge case doc median_test.go on comments for test cases * Update to math/median.go Co-authored-by: Taj * Revert "Update to math/median.go" This reverts commit 7c7c4f561a3a75a0158f26050db00c4ea070db61. * Fix median.go Fix: median.go (import local packages and rectify newly affected issues) * Update median.go Fix: median.go removed redundant codes * Fix: median.go and median_test.go Fix: median.go (removed all deemed irrelevant comments) Fix: median.go (removed all deemed irrelevant comments and changed package + fixed newly affected issues) * Update median.go fix: median.go (return values directly) Co-authored-by: Taj --- go.sum | 0 math/median.go | 28 +++++++++++++++++++++++ math/median_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 go.sum create mode 100644 math/median.go create mode 100644 math/median_test.go diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..e69de29bb diff --git a/math/median.go b/math/median.go new file mode 100644 index 000000000..d8cd02796 --- /dev/null +++ b/math/median.go @@ -0,0 +1,28 @@ +// author(s) [jo3zeph](https://github.com/jo3zeph) +// description: Find the median from a set of values +// see median_test.go + +package math + +import ( + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/sort" +) + +func Median[T constraints.Number](values []T) float64 { + + sort.Bubble(values) + + l := len(values) + + switch { + case l == 0: + return 0 + + case l%2 == 0: + return float64((values[l/2-1] + values[l/2]) / 2) + + default: + return float64(values[l/2]) + } +} diff --git a/math/median_test.go b/math/median_test.go new file mode 100644 index 000000000..5210caec4 --- /dev/null +++ b/math/median_test.go @@ -0,0 +1,56 @@ +// author(s) [jo3zeph](https://github.com/jo3zeph) +// median_test.go +// see median.go + +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +func TestMedian(t *testing.T) { + testCases := []struct { + name string + testValues []float64 + answer float64 + }{ + + { + name: "Series of numbers in ascending order", + testValues: []float64{12, 14, 16, 18, 19}, + answer: 16, + }, + + { + name: "Series of numbers in random order", + testValues: []float64{21, 10, 22, 33, 11, 88}, + answer: 21.5, + }, + + { + name: "Series of decimals in random order", + testValues: []float64{11.2, 32.5, 2.5, 37.8, 21.8, 5.2}, + answer: 16.5, + }, + + { + testValues: []float64{}, + }, + } + + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + + returnedMedian := math.Median(test.testValues) + + t.Log(test.testValues, " ", returnedMedian) + + if returnedMedian != test.answer { + t.Errorf("Test failed. Median should have been %v but received %v", + test.answer, returnedMedian) + } + }) + } +} From feb2246c4605f9c9b4e00a491b2930524bbda2be Mon Sep 17 00:00:00 2001 From: CalvinNJK <87193669+CalvinNJK@users.noreply.github.com> Date: Tue, 9 Aug 2022 13:49:08 +0800 Subject: [PATCH 064/202] Added mode.go & mode_test.go (#523) --- math/mode.go | 49 ++++++++++++++++++++++++ math/mode_test.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 math/mode.go create mode 100644 math/mode_test.go diff --git a/math/mode.go b/math/mode.go new file mode 100644 index 000000000..c0745c33d --- /dev/null +++ b/math/mode.go @@ -0,0 +1,49 @@ +// mode.go +// author(s): [CalvinNJK] (https://github.com/CalvinNJK) +// description: Finding Mode Value In an Array +// see mode.go + +package math + +import ( + "errors" + + "github.com/TheAlgorithms/Go/constraints" +) + +// ErrEmptySlice is the error returned by functions in math package when +// an empty slice is provided to it as argument when the function expects +// a non-empty slice. +var ErrEmptySlice = errors.New("empty slice provided") + +func Mode[T constraints.Number](numbers []T) (T, error) { + + countMap := make(map[T]int) + + n := len(numbers) + + if n == 0 { + return 0, ErrEmptySlice + } + + for _, number := range numbers { + if _, check := countMap[number]; check { + countMap[number]++ + } else { + countMap[number] = 1 + } + } + + var mode T + count := 0 + + for k, v := range countMap { + if v > count { + count = v + mode = k + } + } + + return mode, nil + +} diff --git a/math/mode_test.go b/math/mode_test.go new file mode 100644 index 000000000..5db0eb5df --- /dev/null +++ b/math/mode_test.go @@ -0,0 +1,94 @@ +// mode.go +// author(s): [CalvinNJK] (https://github.com/CalvinNJK) +// description: Test for Finding Mode Value In an Array + +package math_test + +import ( + "errors" + "testing" + + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math" +) + +type testCase[T constraints.Number] struct { + name string + numbers []T + mode T + err error +} + +func testModeFramework[T constraints.Number](t *testing.T, testCases []testCase[T]) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + returnMode, err := math.Mode(test.numbers) + if returnMode != test.mode { + t.Errorf("\n Failed test %s,\n Numbers: %v,\n Correct Mode: %v,\n Returned Mode: %v\n", + test.name, test.numbers, test.mode, returnMode) + } + if !errors.Is(err, test.err) { + t.Errorf("\n Failed test %s,\n Numbers: %v,\n Correct Error: %v,\n Returned Error: %v\n", + test.name, test.numbers, test.err, err) + } + }) + } +} +func TestMode(t *testing.T) { + // test cases for integer values + intTestCases := []testCase[int]{ + { + name: "An array of positive whole numbers", + numbers: []int{10, 52, 10, 92, 10, 75, 60, 10, 44, 29}, + mode: 10, + err: nil, + }, + { + name: "An array of negative whole numbers", + numbers: []int{-19, -12, -74, -19, -22, -56, -19, -19, -68, -93}, + mode: -19, + err: nil, + }, + { + name: "An array of positive & negative whole numbers", + numbers: []int{18, -28, 33, -28, 2, 39, 48, -49, -87, 78, -28}, + mode: -28, + err: nil, + }, + { + name: "If array has no value", + numbers: []int{}, + mode: 0, + err: math.ErrEmptySlice, + }, + } + testModeFramework(t, intTestCases) + // test cases for float64 values + floatTestCases := []testCase[float64]{ + { + name: "An array of positive real numbers", + numbers: []float64{1.5, 2.88, 84.4, 77.2, 29.8, 46.2, 33.7, 88.4, 88.4}, + mode: 88.4, + err: nil, + }, + { + name: "An array of negative real numbers", + numbers: []float64{-98.1, -26.8, -54.45, -26.8, -1.5, -26.8, -33, -19.5, -26.8}, + mode: -26.8, + err: nil, + }, + { + name: "An array of positive and negative real numbers", + numbers: []float64{-17, 28.9, -5.2, -19.5, 77.3, -5.2, 39.3, 28.5, -59.77, -5.2}, + mode: -5.2, + err: nil, + }, + { + name: "If array has no value", + numbers: []float64{}, + mode: 0, + err: math.ErrEmptySlice, + }, + } + testModeFramework(t, floatTestCases) +} From 251f3404e1ec22329985e432635ae34e0cf2bd1b Mon Sep 17 00:00:00 2001 From: Vaishnavi Amira Yada <108050528+Vaishnaviamirayada@users.noreply.github.com> Date: Sun, 21 Aug 2022 01:58:16 +0530 Subject: [PATCH 065/202] doc: Add a useful resource (#525) --- structure/linkedlist/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/structure/linkedlist/Readme.md b/structure/linkedlist/Readme.md index 32f784c96..cb6c1f6e7 100644 --- a/structure/linkedlist/Readme.md +++ b/structure/linkedlist/Readme.md @@ -2,7 +2,7 @@ *** ## What is it? *** -Linked list is a data structure that is a linear chain of data elements whose order is not given by their phyisical placement in memory. This structure is built up of nodes which point to the element ahead or behind this particular node (depending on the type of Linked List). +[Linked list](https://www.scaler.com/topics/linked-list/) is a data structure that is a linear chain of data elements whose order is not given by their phyisical placement in memory. This structure is built up of nodes which point to the element ahead or behind this particular node (depending on the type of Linked List). # Types of Linked List implemented within this repository From 93434be9df4441004814d96d571863f5c481c146 Mon Sep 17 00:00:00 2001 From: Taj Date: Sun, 28 Aug 2022 06:29:40 +0100 Subject: [PATCH 066/202] fix: spellcheck (#527) --- README.md | 36 +++++++++++++++++------------- other/password/generator.go | 4 ++-- structure/linkedlist/doc.go | 2 +- structure/trie/trie_bench_test.go | 37 +------------------------------ 4 files changed, 24 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 8eee9e312..19c15407d 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Abs`](./math/binary/abs.go#L10): Abs returns absolute value using binary operation Principle of operation: 1) Get the mask by right shift by the base 2) Base is the size of an integer variable in bits, for example, for int32 it will be 32, for int64 it will be 64 3) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. 4) Add the mask to the given number. 5) XOR of mask + n and mask gives the absolute value. 2. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number -3. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L19): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. -4. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L26): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 +3. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L21): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. +4. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L28): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 5. [`LogBase2`](./math/binary/logarithm.go#L7): LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm) 6. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations 7. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift @@ -238,7 +238,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package diffiehellman implements Deffie Hellman Key Exchange Algorithm for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI +##### Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI --- ##### Functions: @@ -501,7 +501,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package linkedlist demonstates different implementations on linkedlists. +##### Package linkedlist demonstrates different implementations on linkedlists. --- ##### Functions: @@ -552,8 +552,11 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 3. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. 4. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. 5. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -6. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. -7. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +6. [`Mean`](./math/mean.go#L7): No description provided. +7. [`Median`](./math/median.go#L12): No description provided. +8. [`Mode`](./math/mode.go#L19): No description provided. +9. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +10. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) ---
@@ -623,7 +626,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`IsBalanced`](./other/nested/nestedbrackets.go#L20): IsBalanced returns true if provided input string is properly nested. Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. A sequence of brackets `s` is considered properly nested if any of the following conditions are true: - `s` is empty; - `s` has the form (U) or [U] or {U} where U is a properly nested string; - `s` has the form VW where V and W are properly nested strings. For example, the string "()()[()]" is properly nested but "[(()]" is not. **Note** Providing characters other then brackets would return false, despite brackets sequence in the string. Make sure to filter input before usage. +1. [`IsBalanced`](./other/nested/nestedbrackets.go#L20): IsBalanced returns true if provided input string is properly nested. Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. A sequence of brackets `s` is considered properly nested if any of the following conditions are true: - `s` is empty; - `s` has the form (U) or [U] or {U} where U is a properly nested string; - `s` has the form VW where V and W are properly nested strings. For example, the string "()()[()]" is properly nested but "[(()]" is not. **Note** Providing characters other then brackets would return false, despite brackets sequence in the string. Make sure to filter input before usage. ---
@@ -765,7 +768,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Distance`](./math/pythagoras/pythagoras.go#L15): Distance calculates the distance between to vectors with the Pythagoras theorem +1. [`Distance`](./math/pythagoras/pythagoras.go#L15): Distance calculates the distance between to vectors with the Pythagoras theorem --- ##### Types @@ -868,7 +871,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package sort a package for demonstrating sorting algorithms in Go +##### Package sort a package for demonstrating sorting algorithms in Go Package sort Patience sorting is a sorting algorithm inspired by the card game patience. For more details check out those links below here: GeeksForGeeks article : https://www.geeksforgeeks.org/patience-sorting/ Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting authors [guuzaa](https://github.com/guuzaa) see patiencesort.go --- ##### Functions: @@ -883,13 +886,14 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 8. [`Merge`](./sort/mergesort.go#L40): Merge Perform merge sort on a slice 9. [`MergeIter`](./sort/mergesort.go#L54): No description provided. 10. [`Partition`](./sort/quicksort.go#L12): No description provided. -11. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -12. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array -13. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array -14. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -15. [`Selection`](./sort/selectionsort.go#L5): No description provided. -16. [`Shell`](./sort/shellsort.go#L5): No description provided. -17. [`Simple`](./sort/simplesort.go#L13): No description provided. +11. [`Patience`](./sort/patiencesort.go#L13): No description provided. +12. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. +13. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +14. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +15. [`RadixSort`](./sort/radixsort.go#L35): No description provided. +16. [`Selection`](./sort/selectionsort.go#L5): No description provided. +17. [`Shell`](./sort/shellsort.go#L5): No description provided. +18. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types diff --git a/other/password/generator.go b/other/password/generator.go index 0a8023c26..46237364f 100644 --- a/other/password/generator.go +++ b/other/password/generator.go @@ -25,7 +25,7 @@ func Generate(minLength int, maxLength int) string { newPassword := make([]byte, intLength) randomData := make([]byte, intLength+intLength/4) - clen := byte(len(chars)) + charLen := byte(len(chars)) maxrb := byte(256 - (256 % len(chars))) i := 0 for { @@ -36,7 +36,7 @@ func Generate(minLength int, maxLength int) string { if c >= maxrb { continue } - newPassword[i] = chars[c%clen] + newPassword[i] = chars[c%charLen] i++ if i == intLength { return string(newPassword) diff --git a/structure/linkedlist/doc.go b/structure/linkedlist/doc.go index 580adf068..d4c56c0e1 100644 --- a/structure/linkedlist/doc.go +++ b/structure/linkedlist/doc.go @@ -1,2 +1,2 @@ -// Package linkedlist demonstates different implementations on linkedlists. +// Package linkedlist demonstrates different implementations on linkedlists. package linkedlist diff --git a/structure/trie/trie_bench_test.go b/structure/trie/trie_bench_test.go index f3af3aaa1..be59496ee 100644 --- a/structure/trie/trie_bench_test.go +++ b/structure/trie/trie_bench_test.go @@ -6,42 +6,15 @@ import ( "testing" ) -// CAUTION : make sure to limit the benchamrks to 3000 iterations, +// CAUTION : make sure to limit the benchmarks to 3000 iterations, // or removal will mostly process an empty Trie, giving absurd results. -// go test -v -bench=. -benchmem -benchtime=3000x - -// === RUN TestTrieInsert -// --- PASS: TestTrieInsert (0.00s) -// === RUN TestTrieRemove -// --- PASS: TestTrieRemove (0.00s) -// === RUN ExampleNode -// --- PASS: ExampleNode (0.00s) -// goos: linux -// goarch: amd64 -// pkg: github.com/TheAlgorithms/Go/structure/trie -// BenchmarkTrie_Insert -// BenchmarkTrie_Insert-8 3000 1559881 ns/op 1370334 B/op 25794 allocs/op -// BenchmarkTrie_Find_non_existant -// BenchmarkTrie_Find_non_existant-8 3000 59.1 ns/op 0 B/op 0 allocs/op -// BenchmarkTrie_Find_existant -// BenchmarkTrie_Find_existant-8 3000 238 ns/op 0 B/op 0 allocs/op -// BenchmarkTrie_Remove_lazy -// BenchmarkTrie_Remove_lazy-8 3000 126 ns/op 0 B/op 0 allocs/op -// BenchmarkTrie_Remove_and_Compact -// BenchmarkTrie_Remove_and_Compact-8 3000 213945 ns/op 0 B/op 0 allocs/op -// PASS -// ok github.com/TheAlgorithms/Go/structure/trie 5.355s - func BenchmarkTrie_Insert(b *testing.B) { - - // prepare random words for insertion insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) } - // Reset timer and run benchmark for insertion b.ResetTimer() for i := 0; i < b.N; i++ { n := NewNode() @@ -51,7 +24,6 @@ func BenchmarkTrie_Insert(b *testing.B) { func BenchmarkTrie_Find_non_existant(b *testing.B) { - // prepare random words for insertion insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) @@ -59,7 +31,6 @@ func BenchmarkTrie_Find_non_existant(b *testing.B) { n := NewNode() n.Insert(insert...) - // Reset timer and run benchmark for finding non existing b.ResetTimer() for i := 0; i < b.N; i++ { n.Find("0.3213213244346546546546565465465") // does not exists @@ -67,7 +38,6 @@ func BenchmarkTrie_Find_non_existant(b *testing.B) { } func BenchmarkTrie_Find_existant(b *testing.B) { - // prepare and insert random words insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) @@ -75,7 +45,6 @@ func BenchmarkTrie_Find_existant(b *testing.B) { n := NewNode() n.Insert(insert...) - // Reset timer and run benchmark for finding existing words b.ResetTimer() for i := 0; i < b.N; i++ { n.Find(insert[i%3000]) // always exists ! @@ -83,7 +52,6 @@ func BenchmarkTrie_Find_existant(b *testing.B) { } func BenchmarkTrie_Remove_lazy(b *testing.B) { - // prepare and insert random words insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) @@ -91,7 +59,6 @@ func BenchmarkTrie_Remove_lazy(b *testing.B) { n := NewNode() n.Insert(insert...) - // Reset timer and run benchmark for lazily removing words b.ResetTimer() for i := 0; i < b.N; i++ { n.Remove(insert[i%3000]) // exists, at least until removed ... @@ -99,7 +66,6 @@ func BenchmarkTrie_Remove_lazy(b *testing.B) { } func BenchmarkTrie_Remove_and_Compact(b *testing.B) { - // prepare and insert random words insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) @@ -107,7 +73,6 @@ func BenchmarkTrie_Remove_and_Compact(b *testing.B) { n := NewNode() n.Insert(insert...) - // Reset timer and run benchmark for removing words and immediately compacting b.ResetTimer() for i := 0; i < b.N; i++ { n.Remove(insert[i%3000]) From 72ff3a7f4f0fdb9ce9ac810eb0807c6a0cab9df7 Mon Sep 17 00:00:00 2001 From: Moein Halvaei <50274938+mo1ein@users.noreply.github.com> Date: Sun, 28 Aug 2022 14:15:02 +0430 Subject: [PATCH 067/202] merge: Add char-occurrence algorithm (#526) * feat: Add char-occurrence algorithm * fix: test package name * fix: clean code style * fix: remove extra value for print * fix: change package name to strings * fix: use short var names * fix: put testCases inside test func * fix: add documentation comment * fix: import strings package * fix: clear documention * fix: fix typo * fix: clear description * fix: remove details --- strings/charoccurrence.go | 21 ++++++++++++++++++ strings/charoccurrence_test.go | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 strings/charoccurrence.go create mode 100644 strings/charoccurrence_test.go diff --git a/strings/charoccurrence.go b/strings/charoccurrence.go new file mode 100644 index 000000000..71c3056b1 --- /dev/null +++ b/strings/charoccurrence.go @@ -0,0 +1,21 @@ +// charoccurrence.go +// description: An algorithm which counts the number +// of times a character occurred in a string. +// author(s) [Moein](https://github.com/mo1ein) +// see charoccurrence_test.go + +package strings + +// CountChars counts the number of a times a character +// has occurred in the provided string argument and +// returns a map with `rune` as keys and the count as value. +func CountChars(text string) map[rune]int { + charMap := make(map[rune]int, 0) + for _, c := range text { + if _, ok := charMap[c]; !ok { + charMap[c] = 0 + } + charMap[c]++ + } + return charMap +} diff --git a/strings/charoccurrence_test.go b/strings/charoccurrence_test.go new file mode 100644 index 000000000..0f284acda --- /dev/null +++ b/strings/charoccurrence_test.go @@ -0,0 +1,39 @@ +package strings_test + +import ( + "github.com/TheAlgorithms/Go/strings" + "reflect" + "testing" +) + +func TestCountChars(t *testing.T) { + var testCases = []struct { + name string + input string + expected map[rune]int + }{ + { + "english text", + "hello world!", + map[rune]int{32: 1, 33: 1, 100: 1, 101: 1, 104: 1, 108: 3, 111: 2, 114: 1, 119: 1}, + }, + { + "chinese text", + " 世界 ", + map[rune]int{32: 2, 19990: 1, 30028: 1}, + }, + { + "persian text", + "سلام دنیا!", + map[rune]int{32: 1, 33: 1, 1575: 2, 1583: 1, 1587: 1, 1604: 1, 1605: 1, 1606: 1, 1740: 1}, + }, + } + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + funcResult := strings.CountChars(test.input) + if !reflect.DeepEqual(test.expected, funcResult) { + t.Errorf("expected: %v, got %v", test.expected, funcResult) + } + }) + } +} From f850556d904a8b7126e2705cf0ca2cd5402ad926 Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Fri, 9 Sep 2022 21:36:10 +0530 Subject: [PATCH 068/202] feat: Add mobius function (#532) --- math/mobius.go | 38 ++++++++++++++++++++++++++++++++++++++ math/mobius_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 math/mobius.go create mode 100644 math/mobius_test.go diff --git a/math/mobius.go b/math/mobius.go new file mode 100644 index 000000000..76b50da14 --- /dev/null +++ b/math/mobius.go @@ -0,0 +1,38 @@ +// mobius.go +// description: Returns μ(n) +// details: +// For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity. +// It has values in {−1, 0, 1} depending on the factorization of n into prime factors: +// μ(n) = +1 if n is a square-free positive integer with an even number of prime factors. +// μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. +// μ(n) = 0 if n has a squared prime factor. +// wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see mobius_test.go + +package math + +import ( + "github.com/TheAlgorithms/Go/math/prime" +) + +// Mu is the Mobius function +// This function returns μ(n) for given number +func Mu(n int) int { + if n <= 1 { + return 1 + } + var primeFactorCount int + for i := 1; i <= n; i++ { + if n%i == 0 && prime.OptimizedTrialDivision(int64(i)) { + if n%(i*i) == 0 { + return 0 + } + primeFactorCount += 1 + } + } + if primeFactorCount%2 == 0 { + return 1 + } + return -1 +} diff --git a/math/mobius_test.go b/math/mobius_test.go new file mode 100644 index 000000000..271b9c74f --- /dev/null +++ b/math/mobius_test.go @@ -0,0 +1,41 @@ +// mobius_test.go +// description: Returns μ(n) +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see mobius.go + +package math_test + +import ( + "testing" + + algmath "github.com/TheAlgorithms/Go/math" +) + +func TestMu(t *testing.T) { + var tests = []struct { + n int + expected int + }{ + {-1, 1}, + {0, 1}, + {2, -1}, + {3, -1}, + {95, 1}, + {97, -1}, + {98, 0}, + {99, 0}, + {100, 0}, + } + for _, test := range tests { + result := algmath.Mu(test.n) + t.Log(test.n, " ", result) + if result != test.expected { + t.Errorf("Wrong result! Expected:%v, returned:%v ", test.expected, result) + } + } +} +func BenchmarkMu(b *testing.B) { + for i := 0; i < b.N; i++ { + algmath.Mu(65536) + } +} From 6c8e82210656cb1b341ab00fc59682dff2418514 Mon Sep 17 00:00:00 2001 From: crunchypi <53178205+crunchypi@users.noreply.github.com> Date: Fri, 9 Sep 2022 18:06:27 +0200 Subject: [PATCH 069/202] add generics (#528) --- structure/linkedlist/cyclic.go | 26 +++++----- structure/linkedlist/cyclic_test.go | 16 +++---- structure/linkedlist/doubly.go | 38 ++++++++------- structure/linkedlist/doubly_test.go | 30 +++++++----- structure/linkedlist/shared.go | 12 ++--- structure/linkedlist/singlylinkedlist.go | 48 ++++++++++--------- structure/linkedlist/singlylinkedlist_test.go | 14 ++++-- 7 files changed, 101 insertions(+), 83 deletions(-) diff --git a/structure/linkedlist/cyclic.go b/structure/linkedlist/cyclic.go index d0ef8c4b6..14bc518cc 100644 --- a/structure/linkedlist/cyclic.go +++ b/structure/linkedlist/cyclic.go @@ -3,21 +3,21 @@ package linkedlist import "fmt" // Cyclic Struct which cycles the linked list in this implementation. -type Cyclic struct { +type Cyclic[T any] struct { Size int - Head *Node + Head *Node[T] } // Create new list. -func NewCyclic() *Cyclic { - return &Cyclic{0, nil} +func NewCyclic[T any]() *Cyclic[T] { + return &Cyclic[T]{} } // Inserting the first node is a special case. It will // point to itself. For other cases, the node will be added // to the end of the list. End of the list is Prev field of // current item. Complexity O(1). -func (cl *Cyclic) Add(val any) { +func (cl *Cyclic[T]) Add(val T) { n := NewNode(val) cl.Size++ if cl.Head == nil { @@ -46,7 +46,7 @@ func (cl *Cyclic) Add(val any) { // places is the same as moving N - P places back. // Therefore, if P > N / 2, you can turn the list by N-P places back. // Complexity O(n). -func (cl *Cyclic) Rotate(places int) { +func (cl *Cyclic[T]) Rotate(places int) { if cl.Size > 0 { if places < 0 { multiple := cl.Size - 1 - places/cl.Size @@ -71,9 +71,9 @@ func (cl *Cyclic) Rotate(places int) { } // Delete the current item. -func (cl *Cyclic) Delete() bool { +func (cl *Cyclic[T]) Delete() bool { var deleted bool - var prevItem, thisItem, nextItem *Node + var prevItem, thisItem, nextItem *Node[T] if cl.Size == 0 { return deleted @@ -97,15 +97,15 @@ func (cl *Cyclic) Delete() bool { } // Destroy all items in the list. -func (cl *Cyclic) Destroy() { +func (cl *Cyclic[T]) Destroy() { for cl.Delete() { continue } } // Show list body. -func (cl *Cyclic) Walk() *Node { - var start *Node +func (cl *Cyclic[T]) Walk() *Node[T] { + var start *Node[T] start = cl.Head for i := 0; i < cl.Size; i++ { @@ -117,13 +117,13 @@ func (cl *Cyclic) Walk() *Node { // https://en.wikipedia.org/wiki/Josephus_problem // This is a struct-based solution for Josephus problem. -func JosephusProblem(cl *Cyclic, k int) int { +func JosephusProblem(cl *Cyclic[int], k int) int { for cl.Size > 1 { cl.Rotate(k) cl.Delete() cl.Rotate(-1) } - retval := cl.Head.Val.(int) + retval := cl.Head.Val cl.Destroy() return retval } diff --git a/structure/linkedlist/cyclic_test.go b/structure/linkedlist/cyclic_test.go index 41e925a95..882dbd8ad 100644 --- a/structure/linkedlist/cyclic_test.go +++ b/structure/linkedlist/cyclic_test.go @@ -5,19 +5,19 @@ import ( "testing" ) -func fillList(list *Cyclic, n int) { +func fillList(list *Cyclic[int], n int) { for i := 1; i <= n; i++ { list.Add(i) } } func TestAdd(t *testing.T) { - list := NewCyclic() + list := NewCyclic[int]() fillList(list, 3) want := []any{1, 2, 3} var got []any - var start *Node + var start *Node[int] start = list.Head for i := 0; i < list.Size; i++ { @@ -30,7 +30,7 @@ func TestAdd(t *testing.T) { } func TestWalk(t *testing.T) { - list := NewCyclic() + list := NewCyclic[int]() fillList(list, 3) want := 1 @@ -46,7 +46,7 @@ func TestRotate(t *testing.T) { param int wantToReturn int } - list := NewCyclic() + list := NewCyclic[int]() fillList(list, 3) testCases := []testCase{ @@ -69,7 +69,7 @@ func TestRotate(t *testing.T) { } func TestDelete(t *testing.T) { - list := NewCyclic() + list := NewCyclic[int]() fillList(list, 3) want := 2 @@ -85,7 +85,7 @@ func TestDelete(t *testing.T) { } func TestDestroy(t *testing.T) { - list := NewCyclic() + list := NewCyclic[int]() fillList(list, 3) wantSize := 0 list.Destroy() @@ -119,7 +119,7 @@ func TestJosephusProblem(t *testing.T) { } for _, tCase := range testCases { - list := NewCyclic() + list := NewCyclic[int]() fillList(list, tCase.listCount) got := JosephusProblem(list, tCase.param) if got != tCase.wantToReturn { diff --git a/structure/linkedlist/doubly.go b/structure/linkedlist/doubly.go index 42d24935f..0550ddba1 100644 --- a/structure/linkedlist/doubly.go +++ b/structure/linkedlist/doubly.go @@ -15,16 +15,16 @@ import "fmt" // `import "github.com/TheAlgorithms/Go/structure/linkedlist"` // // and call linkedlist.Doubly to create a new doubly linked list. -type Doubly struct { - Head *Node +type Doubly[T any] struct { + Head *Node[T] } -func NewDoubly() *Doubly { - return &Doubly{nil} +func NewDoubly[T any]() *Doubly[T] { + return &Doubly[T]{} } // AddAtBeg Add a node to the beginning of the linkedlist -func (ll *Doubly) AddAtBeg(val any) { +func (ll *Doubly[T]) AddAtBeg(val T) { n := NewNode(val) n.Next = ll.Head @@ -37,7 +37,7 @@ func (ll *Doubly) AddAtBeg(val any) { } // AddAtEnd Add a node at the end of the linkedlist -func (ll *Doubly) AddAtEnd(val any) { +func (ll *Doubly[T]) AddAtEnd(val T) { n := NewNode(val) if ll.Head == nil { @@ -53,9 +53,10 @@ func (ll *Doubly) AddAtEnd(val any) { } // DelAtBeg Delete the node at the beginning of the linkedlist -func (ll *Doubly) DelAtBeg() any { +func (ll *Doubly[T]) DelAtBeg() (T, bool) { if ll.Head == nil { - return -1 + var r T + return r, false } cur := ll.Head @@ -64,14 +65,15 @@ func (ll *Doubly) DelAtBeg() any { if ll.Head != nil { ll.Head.Prev = nil } - return cur.Val + return cur.Val, true } // DetAtEnd Delete a node at the end of the linkedlist -func (ll *Doubly) DelAtEnd() any { +func (ll *Doubly[T]) DelAtEnd() (T, bool) { // no item if ll.Head == nil { - return -1 + var r T + return r, false } // only one item @@ -86,11 +88,11 @@ func (ll *Doubly) DelAtEnd() any { retval := cur.Next.Val cur.Next = nil - return retval + return retval, true } // Count Number of nodes in the linkedlist -func (ll *Doubly) Count() any { +func (ll *Doubly[T]) Count() int { var ctr int = 0 for cur := ll.Head; cur != nil; cur = cur.Next { @@ -101,8 +103,8 @@ func (ll *Doubly) Count() any { } // Reverse Reverse the order of the linkedlist -func (ll *Doubly) Reverse() { - var Prev, Next *Node +func (ll *Doubly[T]) Reverse() { + var Prev, Next *Node[T] cur := ll.Head for cur != nil { @@ -117,7 +119,7 @@ func (ll *Doubly) Reverse() { } // Display display the linked list -func (ll *Doubly) Display() { +func (ll *Doubly[T]) Display() { for cur := ll.Head; cur != nil; cur = cur.Next { fmt.Print(cur.Val, " ") } @@ -126,11 +128,11 @@ func (ll *Doubly) Display() { } // DisplayReverse Display the linkedlist in reverse order -func (ll *Doubly) DisplayReverse() { +func (ll *Doubly[T]) DisplayReverse() { if ll.Head == nil { return } - var cur *Node + var cur *Node[T] for cur = ll.Head; cur.Next != nil; cur = cur.Next { } diff --git a/structure/linkedlist/doubly_test.go b/structure/linkedlist/doubly_test.go index b48eda812..e30663dda 100644 --- a/structure/linkedlist/doubly_test.go +++ b/structure/linkedlist/doubly_test.go @@ -6,7 +6,7 @@ import ( ) func TestDoubly(t *testing.T) { - newList := NewDoubly() + newList := NewDoubly[int]() newList.AddAtBeg(1) newList.AddAtBeg(2) @@ -20,11 +20,11 @@ func TestDoubly(t *testing.T) { // check from Next address current := newList.Head - got = append(got, current.Val.(int)) + got = append(got, current.Val) for current.Next != nil { current = current.Next - got = append(got, current.Val.(int)) + got = append(got, current.Val) } if !reflect.DeepEqual(got, wantNext) { @@ -33,11 +33,11 @@ func TestDoubly(t *testing.T) { // check from Prev address got = []int{} - got = append(got, current.Val.(int)) + got = append(got, current.Val) for current.Prev != nil { current = current.Prev - got = append(got, current.Val.(int)) + got = append(got, current.Val) } if !reflect.DeepEqual(got, wantPrev) { @@ -51,10 +51,10 @@ func TestDoubly(t *testing.T) { want := []int{3, 2, 1, 4} got := []int{} current := newList.Head - got = append(got, current.Val.(int)) + got = append(got, current.Val) for current.Next != nil { current = current.Next - got = append(got, current.Val.(int)) + got = append(got, current.Val) } if !reflect.DeepEqual(got, want) { t.Errorf("got: %v, want: %v", got, want) @@ -63,7 +63,10 @@ func TestDoubly(t *testing.T) { t.Run("Test DelAtBeg", func(t *testing.T) { want := 3 - got := newList.DelAtBeg() + got, ok := newList.DelAtBeg() + if !ok { + t.Error("unexpected not-ok") + } if got != want { t.Errorf("got: %v, want: %v", got, want) } @@ -71,7 +74,10 @@ func TestDoubly(t *testing.T) { t.Run("Test DelAtEnd", func(t *testing.T) { want := 4 - got := newList.DelAtEnd() + got, ok := newList.DelAtEnd() + if !ok { + t.Error("unexpected not-ok") + } if got != want { t.Errorf("got: %v, want: %v", got, want) } @@ -85,7 +91,7 @@ func TestDoubly(t *testing.T) { } }) - newList2 := NewDoubly() + newList2 := NewDoubly[int]() newList2.AddAtBeg(1) newList2.AddAtBeg(2) newList2.AddAtBeg(3) @@ -94,10 +100,10 @@ func TestDoubly(t *testing.T) { got := []int{} newList2.Reverse() current := newList2.Head - got = append(got, current.Val.(int)) + got = append(got, current.Val) for current.Next != nil { current = current.Next - got = append(got, current.Val.(int)) + got = append(got, current.Val) } if !reflect.DeepEqual(got, want) { t.Errorf("got: %v, want: %v", got, want) diff --git a/structure/linkedlist/shared.go b/structure/linkedlist/shared.go index c09e9fe8a..03e52f7bf 100644 --- a/structure/linkedlist/shared.go +++ b/structure/linkedlist/shared.go @@ -2,13 +2,13 @@ package linkedlist // Node Structure representing the linkedlist node. // This node is shared across different implementations. -type Node struct { - Val any - Prev *Node - Next *Node +type Node[T any] struct { + Val T + Prev *Node[T] + Next *Node[T] } // Create new node. -func NewNode(val any) *Node { - return &Node{val, nil, nil} +func NewNode[T any](val T) *Node[T] { + return &Node[T]{val, nil, nil} } diff --git a/structure/linkedlist/singlylinkedlist.go b/structure/linkedlist/singlylinkedlist.go index f8662408a..18d661799 100644 --- a/structure/linkedlist/singlylinkedlist.go +++ b/structure/linkedlist/singlylinkedlist.go @@ -7,29 +7,29 @@ import ( ) // Singly structure with length of the list and its head -type Singly struct { +type Singly[T any] struct { length int // Note that Node here holds both Next and Prev Node // however only the Next node is used in Singly methods. - Head *Node + Head *Node[T] } // NewSingly returns a new instance of a linked list -func NewSingly() *Singly { - return &Singly{} +func NewSingly[T any]() *Singly[T] { + return &Singly[T]{} } // AddAtBeg adds a new snode with given value at the beginning of the list. -func (ll *Singly) AddAtBeg(val any) { - n := NewNode(val) +func (ll *Singly[T]) AddAtBeg(val T) { + n := NewNode[T](val) n.Next = ll.Head ll.Head = n ll.length++ } // AddAtEnd adds a new snode with given value at the end of the list. -func (ll *Singly) AddAtEnd(val any) { +func (ll *Singly[T]) AddAtEnd(val T) { n := NewNode(val) if ll.Head == nil { @@ -45,23 +45,27 @@ func (ll *Singly) AddAtEnd(val any) { ll.length++ } -// DelAtBeg deletes the snode at the head(beginning) of the list and returns its value. Returns -1 if the list is empty. -func (ll *Singly) DelAtBeg() any { +// DelAtBeg deletes the snode at the head(beginning) of the list +// and returns its value. Returns false if the list is empty. +func (ll *Singly[T]) DelAtBeg() (T, bool) { if ll.Head == nil { - return -1 + var r T + return r, false } cur := ll.Head ll.Head = cur.Next ll.length-- - return cur.Val + return cur.Val, true } -// DelAtEnd deletes the snode at the tail(end) of the list and returns its value. Returns -1 if the list is empty. -func (ll *Singly) DelAtEnd() any { +// DelAtEnd deletes the snode at the tail(end) of the list +// and returns its value. Returns false if the list is empty. +func (ll *Singly[T]) DelAtEnd() (T, bool) { if ll.Head == nil { - return -1 + var r T + return r, false } if ll.Head.Next == nil { @@ -76,18 +80,18 @@ func (ll *Singly) DelAtEnd() any { retval := cur.Next.Val cur.Next = nil ll.length-- - return retval + return retval, true } // Count returns the current size of the list. -func (ll *Singly) Count() int { +func (ll *Singly[T]) Count() int { return ll.length } // Reverse reverses the list. -func (ll *Singly) Reverse() { - var prev, Next *Node +func (ll *Singly[T]) Reverse() { + var prev, Next *Node[T] cur := ll.Head for cur != nil { @@ -101,12 +105,12 @@ func (ll *Singly) Reverse() { } // ReversePartition Reverse the linked list from the ath to the bth node -func (ll *Singly) ReversePartition(left, right int) error { +func (ll *Singly[T]) ReversePartition(left, right int) error { err := ll.CheckRangeFromIndex(left, right) if err != nil { return err } - tmpNode := NewNode(-1) + tmpNode := &Node[T]{} tmpNode.Next = ll.Head pre := tmpNode for i := 0; i < left-1; i++ { @@ -122,7 +126,7 @@ func (ll *Singly) ReversePartition(left, right int) error { ll.Head = tmpNode.Next return nil } -func (ll *Singly) CheckRangeFromIndex(left, right int) error { +func (ll *Singly[T]) CheckRangeFromIndex(left, right int) error { if left > right { return errors.New("left boundary must smaller than right") } else if left < 1 { @@ -134,7 +138,7 @@ func (ll *Singly) CheckRangeFromIndex(left, right int) error { } // Display prints out the elements of the list. -func (ll *Singly) Display() { +func (ll *Singly[T]) Display() { for cur := ll.Head; cur != nil; cur = cur.Next { fmt.Print(cur.Val, " ") } diff --git a/structure/linkedlist/singlylinkedlist_test.go b/structure/linkedlist/singlylinkedlist_test.go index df8004aa0..705770d9c 100644 --- a/structure/linkedlist/singlylinkedlist_test.go +++ b/structure/linkedlist/singlylinkedlist_test.go @@ -6,7 +6,7 @@ import ( ) func TestSingly(t *testing.T) { - list := NewSingly() + list := NewSingly[int]() list.AddAtBeg(1) list.AddAtBeg(2) list.AddAtBeg(3) @@ -43,7 +43,10 @@ func TestSingly(t *testing.T) { t.Run("Test DelAtBeg()", func(t *testing.T) { want := any(3) - got := list.DelAtBeg() + got, ok := list.DelAtBeg() + if !ok { + t.Error("unexpected not-ok") + } if got != want { t.Errorf("got: %v, want: %v", got, want) } @@ -51,7 +54,10 @@ func TestSingly(t *testing.T) { t.Run("Test DelAtEnd()", func(t *testing.T) { want := any(4) - got := list.DelAtEnd() + got, ok := list.DelAtEnd() + if !ok { + t.Error("unexpected not-ok") + } if got != want { t.Errorf("got: %v, want: %v", got, want) } @@ -65,7 +71,7 @@ func TestSingly(t *testing.T) { } }) - list2 := Singly{} + list2 := Singly[int]{} list2.AddAtBeg(1) list2.AddAtBeg(2) list2.AddAtBeg(3) From 94e8490ea0a1620c6b70a91846043f2c16cd5b48 Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Thu, 15 Sep 2022 22:39:00 +0530 Subject: [PATCH 070/202] algorithm: binomial coefficient (#539) * feat: Add binomial coefficient implementation * test: Add tests for binomial coefficient * fix: Fix typing error in binomialcoefficient.go * fix: Add linter fixes to BenchmarkBinomialCoefficient() * fix: Fix import statement in binomialcoefficient_test.go * fix: Fix return statement * test: Add detailed unit tests for binomial coefficient * fix: Replace all occurrences of C with Combinations * fix: Move error variable outside Combinations function * refactor: Add t.Run block * refactor: Remove log statement * refactor: Refactor unit tests * fix: Change error variable name from error to err --- math/binomialcoefficient.go | 33 +++++++++++++++++++++++++ math/binomialcoefficient_test.go | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 math/binomialcoefficient.go create mode 100644 math/binomialcoefficient_test.go diff --git a/math/binomialcoefficient.go b/math/binomialcoefficient.go new file mode 100644 index 000000000..d3c123a6f --- /dev/null +++ b/math/binomialcoefficient.go @@ -0,0 +1,33 @@ +// binomialcoefficient.go +// description: Returns C(n, k) +// details: +// a binomial coefficient C(n,k) gives number ways +// in which k objects can be chosen from n objects. +// wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see binomialcoefficient_test.go + +package math + +import ( + "errors" +) + +var ErrPosArgsOnly error = errors.New("arguments must be positive") + +// C is Binomial Coefficient function +// This function returns C(n, k) for given n and k +func Combinations(n int, k int) (int, error) { + if n < 0 || k < 0 { + return -1, ErrPosArgsOnly + } + if k > (n - k) { + k = n - k + } + res := 1 + for i := 0; i < k; i++ { + res *= (n - i) + res /= (i + 1) + } + return res, nil +} diff --git a/math/binomialcoefficient_test.go b/math/binomialcoefficient_test.go new file mode 100644 index 000000000..20b9c4373 --- /dev/null +++ b/math/binomialcoefficient_test.go @@ -0,0 +1,42 @@ +// binomialcoefficient_test.go +// description: Returns C(n, k) +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see binomialcoefficient.go + +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +func TestCombinations(t *testing.T) { + var tests = []struct { + name string + n int + k int + expectedValue int + expectedError error + }{ + {"n = 5, k = 2", 5, 2, 10, nil}, + {"n = 7, k = 4", 7, 4, 35, nil}, + {"n = 0, k = 0", 0, 0, 1, nil}, + {"n = -1, k = 1", -1, 1, -1, math.ErrPosArgsOnly}, + {"n = 1, k = -1", 1, -1, -1, math.ErrPosArgsOnly}, + {"n = -1, k = -1", -1, -1, -1, math.ErrPosArgsOnly}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := math.Combinations(test.n, test.k) + if result != test.expectedValue || test.expectedError != err { + t.Errorf("expected error: %s, got: %s; expected value: %v, got: %v", test.expectedError, err, test.expectedValue, result) + } + }) + } +} +func BenchmarkCombinations(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = math.Combinations(65536, 65536) + } +} From 1acfe4c456b79b7d50482d0ce38f84de9a4adc56 Mon Sep 17 00:00:00 2001 From: Ilya Sokolov Date: Fri, 16 Sep 2022 10:23:43 +0300 Subject: [PATCH 071/202] Add Pollard's Rho Factorization algorithm (#530) --- README.md | 13 ++++++++ math/pollard.go | 43 ++++++++++++++++++++++++ math/pollard_test.go | 79 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 math/pollard.go create mode 100644 math/pollard_test.go diff --git a/README.md b/README.md index 19c15407d..6dc6e9f1f 100644 --- a/README.md +++ b/README.md @@ -920,6 +920,19 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 3. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided. +--- +
+ strings + +--- + +##### Package strings is a package that contains all algorithms that are used to analyse and manipulate strings. + +--- +##### Functions: + +1. [`CountChars`](./strings/charoccurrence.go#L12): CountChars counts the number of a times a character has occurred in the provided string argument and returns a map with `rune` as keys and the count as value. + ---
transposition diff --git a/math/pollard.go b/math/pollard.go new file mode 100644 index 000000000..434a0f24f --- /dev/null +++ b/math/pollard.go @@ -0,0 +1,43 @@ +// pollard.go +// description: Pollard's rho algorithm +// details: +// implementation of Pollard's rho algorithm for integer factorization-[Pollard's rho algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) +// author(s) [red_byte](https://github.com/i-redbyte) +// see pollard_test.go + +package math + +import ( + "errors" + "math/big" +) + +// DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n +func DefaultPolynomial(n *big.Int) func(*big.Int) *big.Int { + bigOne := big.NewInt(1) + bigTwo := big.NewInt(2) + return func(x *big.Int) *big.Int { + xSquared := new(big.Int).Exp(x, bigTwo, n) // see: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Core_ideas + xSquared.Add(xSquared, bigOne) + xSquared.Mod(xSquared, n) + return xSquared + } +} + +// PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm +// using the default parameters x = y = 2 +func PollardsRhoFactorization(n *big.Int, f func(n *big.Int) func(x *big.Int) *big.Int) (*big.Int, error) { + x, y, d := big.NewInt(2), big.NewInt(2), big.NewInt(1) + bigOne := big.NewInt(1) + g := f(n) + for d.Cmp(bigOne) == 0 { + x = g(x) + y = g(g(y)) + sub := new(big.Int).Sub(x, y) + d.GCD(nil, nil, sub.Abs(sub), n) + } + if d.Cmp(n) == 0 { + return nil, errors.New("factorization failed") + } + return d, nil +} diff --git a/math/pollard_test.go b/math/pollard_test.go new file mode 100644 index 000000000..d77d81b22 --- /dev/null +++ b/math/pollard_test.go @@ -0,0 +1,79 @@ +// pollard_test.go +// description: Test for Pollard's rho algorithm +// author(s) [red_byte](https://github.com/i-redbyte) +// see pollard.go + +package math + +import ( + "math/big" + "reflect" + "testing" +) + +func TestDefaultPolynomial(t *testing.T) { + tests := []struct { + name string + x *big.Int + n *big.Int + want *big.Int + }{ + {"Polynomial for n = 1772; x = 535", big.NewInt(535), big.NewInt(1772), big.NewInt(934)}, + {"Polynomial for n = 666; x = 53135", big.NewInt(53135), big.NewInt(666), big.NewInt(380)}, + {"Polynomial for n = 666; x = 13", big.NewInt(13), big.NewInt(666), big.NewInt(170)}, + {"Polynomial for n = 1917; x = 2510", big.NewInt(2510), big.NewInt(1917), big.NewInt(839)}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := DefaultPolynomial(test.n)(test.x); !reflect.DeepEqual(got, test.want) { + t.Errorf("DefaultPolynomial() = %v, want %v", got, test.want) + } + }) + } +} + +func TestRho(t *testing.T) { + tests := []struct { + name string + n *big.Int + g func(n *big.Int) func(*big.Int) *big.Int + want *big.Int + wantErr bool + }{ + {"Factor of n: 11235 ", big.NewInt(11235), DefaultPolynomial, big.NewInt(21), false}, + {"Factor of n: 111155 ", big.NewInt(111155), DefaultPolynomial, big.NewInt(11), false}, + {"Factor of n: 8080 ", big.NewInt(8080), DefaultPolynomial, big.NewInt(16), false}, + {"Factor of n: 8536 ", big.NewInt(8536), DefaultPolynomial, big.NewInt(88), false}, + {"Factor of n: 666 ", big.NewInt(666), DefaultPolynomial, big.NewInt(3), false}, + {"Factor of n: 2 ", big.NewInt(2), DefaultPolynomial, big.NewInt(2), true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := PollardsRhoFactorization(test.n, test.g) + if err != nil && !test.wantErr { + t.Errorf("PollardsRhoFactorization() error = %v, wantErr %v", err, test.wantErr) + return + } else if err != nil && test.wantErr { + return + } + if !reflect.DeepEqual(got, test.want) { + t.Errorf("PollardsRhoFactorization() got = %v, want %v", got, test.want) + } + }) + } +} + +func BenchmarkDefaultPolynomial(b *testing.B) { + for i := 0; i < b.N; i++ { + DefaultPolynomial(big.NewInt(535))(big.NewInt(11235)) + } +} + +func BenchmarkRho(b *testing.B) { + for i := 0; i < b.N; i++ { + _, err := PollardsRhoFactorization(big.NewInt(535), DefaultPolynomial) + if err != nil { + return + } + } +} From 6a99cd70c53ce155cfe812909525b74628d63779 Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Wed, 21 Sep 2022 00:14:34 +0530 Subject: [PATCH 072/202] algorithm: Liouville lambda function (#540) --- math/liouville.go | 35 +++++++++++++++++++++++++++++++++++ math/liouville_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 math/liouville.go create mode 100644 math/liouville_test.go diff --git a/math/liouville.go b/math/liouville.go new file mode 100644 index 000000000..908a4deac --- /dev/null +++ b/math/liouville.go @@ -0,0 +1,35 @@ +// liouville.go +// description: Returns λ(n) +// details: +// For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity. +// It has values in {−1, 1} depending on the factorization of n into prime factors: +// λ(n) = +1 if n is a positive integer with an even number of prime factors. +// λ(n) = −1 if n is a positive integer with an odd number of prime factors. +// wikipedia: https://en.wikipedia.org/wiki/Liouville_function +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see liouville_test.go + +package math + +import ( + "errors" + + "github.com/TheAlgorithms/Go/math/prime" +) + +var ErrNonZeroArgsOnly error = errors.New("arguments cannot be zero") + +// Lambda is the liouville function +// This function returns λ(n) for given number +func LiouvilleLambda(n int) (int, error) { + switch { + case n < 0: + return 0, ErrPosArgsOnly + case n == 0: + return 0, ErrNonZeroArgsOnly + case len(prime.Factorize(int64(n)))%2 == 0: + return 1, nil + default: + return -1, nil + } +} diff --git a/math/liouville_test.go b/math/liouville_test.go new file mode 100644 index 000000000..41d327c3e --- /dev/null +++ b/math/liouville_test.go @@ -0,0 +1,39 @@ +// liouville_test.go +// description: Returns λ(n) +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see liouville.go + +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +func TestLiouvilleLambda(t *testing.T) { + var tests = []struct { + name string + n int + expectedValue int + expectedError error + }{ + {"n = 10", 10, 1, nil}, + {"n = 11", 11, -1, nil}, + {"n = -1", -1, 0, math.ErrPosArgsOnly}, + {"n = 0", 0, 0, math.ErrNonZeroArgsOnly}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := math.LiouvilleLambda(test.n) + if result != test.expectedValue || test.expectedError != err { + t.Errorf("expected error: %s, got: %s; expected value: %v, got: %v", test.expectedError, err, test.expectedValue, result) + } + }) + } +} +func BenchmarkLiouvilleLambda(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = math.LiouvilleLambda(65536) + } +} From eaa2be2ffe9295b9eb996ec49af6e0e2e6381595 Mon Sep 17 00:00:00 2001 From: Taj Date: Fri, 23 Sep 2022 09:44:50 +0100 Subject: [PATCH 073/202] feat: re-enable all linters (#541) * Updated Documentation in README.md * fix: golangci-lint disabled linters and checks * Updated Documentation in README.md * fix: documentation comment issue * Updated Documentation in README.md Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- .golangci.yml | 6 ------ README.md | 25 +++++++++++++++---------- math/mode.go | 6 +----- sort/patiencesort.go | 2 +- 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b334bee16..586ace461 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,8 +1,2 @@ run: go: 1.19 -linters: - disable: - - gosimple - - staticcheck - - structcheck - - unused diff --git a/README.md b/README.md index 6dc6e9f1f..66de9cad0 100644 --- a/README.md +++ b/README.md @@ -548,15 +548,20 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Abs`](./math/abs.go#L11): Abs returns absolute value -2. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) -3. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -4. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -5. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -6. [`Mean`](./math/mean.go#L7): No description provided. -7. [`Median`](./math/median.go#L12): No description provided. -8. [`Mode`](./math/mode.go#L19): No description provided. -9. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. -10. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +2. [`Combinations`](./math/binomialcoefficient.go#L20): C is Binomial Coefficient function This function returns C(n, k) for given n and k +3. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) +4. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n +5. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +6. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +7. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +8. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number +9. [`Mean`](./math/mean.go#L7): No description provided. +10. [`Median`](./math/median.go#L12): No description provided. +11. [`Mode`](./math/mode.go#L19): No description provided. +12. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number +13. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +14. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 +15. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) ---
@@ -871,7 +876,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package sort a package for demonstrating sorting algorithms in Go Package sort Patience sorting is a sorting algorithm inspired by the card game patience. For more details check out those links below here: GeeksForGeeks article : https://www.geeksforgeeks.org/patience-sorting/ Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting authors [guuzaa](https://github.com/guuzaa) see patiencesort.go +##### Package sort a package for demonstrating sorting algorithms in Go --- ##### Functions: diff --git a/math/mode.go b/math/mode.go index c0745c33d..164084bb6 100644 --- a/math/mode.go +++ b/math/mode.go @@ -27,11 +27,7 @@ func Mode[T constraints.Number](numbers []T) (T, error) { } for _, number := range numbers { - if _, check := countMap[number]; check { - countMap[number]++ - } else { - countMap[number] = 1 - } + countMap[number]++ } var mode T diff --git a/sort/patiencesort.go b/sort/patiencesort.go index efae67ff0..746c84931 100644 --- a/sort/patiencesort.go +++ b/sort/patiencesort.go @@ -1,4 +1,3 @@ -// Package sort // Patience sorting is a sorting algorithm inspired by the card game patience. // // For more details check out those links below here: @@ -6,6 +5,7 @@ // Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting // authors [guuzaa](https://github.com/guuzaa) // see patiencesort.go + package sort import "github.com/TheAlgorithms/Go/constraints" From 4d9b1e48789f24959739ef03b52b26d074a98de8 Mon Sep 17 00:00:00 2001 From: Abel Date: Mon, 3 Oct 2022 21:46:09 +0800 Subject: [PATCH 074/202] feat: add fuzzing for cipher/xor (#546) --- cipher/xor/xor_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/cipher/xor/xor_test.go b/cipher/xor/xor_test.go index 999755188..5f98964e1 100644 --- a/cipher/xor/xor_test.go +++ b/cipher/xor/xor_test.go @@ -1,6 +1,7 @@ package xor import ( + "bytes" "fmt" "reflect" "testing" @@ -103,3 +104,14 @@ func TestXorCipherDecrypt(t *testing.T) { }) } } + +func FuzzXOR(f *testing.F) { + f.Add([]byte("The Quick Brown Fox Jumps over the Lazy Dog."), byte('X')) + f.Fuzz(func(t *testing.T, input []byte, key byte) { + cipherText := Encrypt(key, input) + result := Decrypt(key, cipherText) + if !bytes.Equal(input, result) { + t.Errorf("Before: %s, after: %s, key: %d", input, result, key) + } + }) +} From 51f0485f9289676e23d4c7cbf4a868e4704a27d6 Mon Sep 17 00:00:00 2001 From: safesuk Date: Fri, 7 Oct 2022 18:50:57 +0700 Subject: [PATCH 075/202] feat: add lerp (#545) * add lerp * fix: add description --- math/lerp.go | 8 ++++++++ math/lerp_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 math/lerp.go create mode 100644 math/lerp_test.go diff --git a/math/lerp.go b/math/lerp.go new file mode 100644 index 000000000..1d2b59908 --- /dev/null +++ b/math/lerp.go @@ -0,0 +1,8 @@ +package math + +// Lerp or Linear interpolation +// This function will return new value in 't' percentage between 'v0' and 'v1' +func Lerp(v0, v1, t float64) float64 { + // see: https://en.wikipedia.org/wiki/Linear_interpolation + return (1-t)*v0 + t*v1 +} diff --git a/math/lerp_test.go b/math/lerp_test.go new file mode 100644 index 000000000..3a6ac25fd --- /dev/null +++ b/math/lerp_test.go @@ -0,0 +1,29 @@ +package math_test + +import ( + "testing" + + algmath "github.com/TheAlgorithms/Go/math" +) + +func TestLerp(t *testing.T) { + tests := []struct { + name string + testValues []float64 + answer float64 + }{ + {"Lerp(1,1,1)", []float64{1, 1, 1}, 1}, + {"Lerp(0,1,1)", []float64{0, 1, 1}, 1}, + {"Lerp(0,1,0.5)", []float64{0, 1, 0.5}, 0.5}, + {"Lerp(0,1,0.1)", []float64{0, 1, 0.1}, 0.1}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := algmath.Lerp(test.testValues[0], test.testValues[1], test.testValues[2]) + if got != test.answer { + t.Errorf("Lerp(%f,%f,%f) = %v, want %v", got, test.testValues[0], + test.testValues[1], test.testValues[2], test.answer) + } + }) + } +} From af1519c2041b5dc5e6efcb9d9a96ed6d9d26659e Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Sun, 9 Oct 2022 17:48:52 +0530 Subject: [PATCH 076/202] algorithm: Twin prime (#550) --- math/prime/twin.go | 20 ++++++++++++++++++++ math/prime/twin_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 math/prime/twin.go create mode 100644 math/prime/twin_test.go diff --git a/math/prime/twin.go b/math/prime/twin.go new file mode 100644 index 000000000..1326746e4 --- /dev/null +++ b/math/prime/twin.go @@ -0,0 +1,20 @@ +// twin.go +// description: Returns Twin Prime of n +// details: +// For any integer n, twin prime is (n + 2) +// if and only if both n and (n + 2) both are prime +// wikipedia: https://en.wikipedia.org/wiki/Twin_prime +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see twin_test.go + +package prime + +// This function returns twin prime for given number +// returns (n + 2) if both n and (n + 2) are prime +// -1 otherwise +func Twin(n int) (int, bool) { + if OptimizedTrialDivision(int64(n)) && OptimizedTrialDivision(int64(n+2)) { + return n + 2, true + } + return -1, false +} diff --git a/math/prime/twin_test.go b/math/prime/twin_test.go new file mode 100644 index 000000000..7c1923dcb --- /dev/null +++ b/math/prime/twin_test.go @@ -0,0 +1,39 @@ +// twin_test.go +// description: Returns Twin Prime of n +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see twin.go + +package prime_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/prime" +) + +func TestTwin(t *testing.T) { + var tests = []struct { + name string + n int + expectedValue int + hasTwin bool + }{ + {"n = 3, should return 5", 3, 5, true}, + {"n = 4, should return -1", 4, -1, false}, + {"n = 5, should return 7", 5, 7, true}, + {"n = 17, should return 19", 17, 19, true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, hasTwin := prime.Twin(test.n) + if result != test.expectedValue || hasTwin != test.hasTwin { + t.Errorf("expected value: %v and %v, got: %v and %v", test.expectedValue, test.hasTwin, result, hasTwin) + } + }) + } +} +func BenchmarkTwin(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = prime.Twin(65536) + } +} From 44b39e09ddf43a23fde630679c9bad20948b422b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20H=E1=BA=A3i=20L=C3=A2m?= Date: Wed, 12 Oct 2022 11:51:00 +0700 Subject: [PATCH 077/202] feat: Use generic for pigeonholesort and max min Int (#565) --- math/max/max.go | 4 +++- math/min/min.go | 4 +++- sort/pigeonholesort.go | 9 ++++++--- sort/sorts_test.go | 4 ++-- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/math/max/max.go b/math/max/max.go index 0449a2d6b..d93aa5601 100644 --- a/math/max/max.go +++ b/math/max/max.go @@ -1,7 +1,9 @@ package max +import "github.com/TheAlgorithms/Go/constraints" + // Int is a function which returns the maximum of all the integers provided as arguments. -func Int(values ...int) int { +func Int[T constraints.Integer](values ...T) T { max := values[0] for _, value := range values { if value > max { diff --git a/math/min/min.go b/math/min/min.go index 03fd090ba..3ef21272b 100644 --- a/math/min/min.go +++ b/math/min/min.go @@ -1,7 +1,9 @@ package min +import "github.com/TheAlgorithms/Go/constraints" + // Int is a function which returns the minimum of all the integers provided as arguments. -func Int(values ...int) int { +func Int[T constraints.Integer](values ...T) T { min := values[0] for _, value := range values { if value < min { diff --git a/sort/pigeonholesort.go b/sort/pigeonholesort.go index bfc20244e..12941cdc9 100644 --- a/sort/pigeonholesort.go +++ b/sort/pigeonholesort.go @@ -4,12 +4,15 @@ package sort import ( + "github.com/TheAlgorithms/Go/constraints" "github.com/TheAlgorithms/Go/math/max" "github.com/TheAlgorithms/Go/math/min" ) // Pigeonhole sorts a slice using pigeonhole sorting algorithm. -func Pigeonhole(arr []int) []int { +// NOTE: To maintain time complexity O(n + N), this is the reason for having +// only Integer constraint instead of Ordered. +func Pigeonhole[T constraints.Integer](arr []T) []T { if len(arr) == 0 { return arr } @@ -19,7 +22,7 @@ func Pigeonhole(arr []int) []int { size := max - min + 1 - holes := make([]int, size) + holes := make([]T, size) for _, element := range arr { holes[element-min]++ @@ -27,7 +30,7 @@ func Pigeonhole(arr []int) []int { i := 0 - for j := 0; j < size; j++ { + for j := T(0); j < size; j++ { for holes[j] > 0 { holes[j]-- arr[i] = j + min diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 467d054ce..1c07ddb2b 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -132,7 +132,7 @@ func TestComb(t *testing.T) { } func TestPigeonhole(t *testing.T) { - testFramework(t, sort.Pigeonhole) + testFramework(t, sort.Pigeonhole[int]) } func TestPatience(t *testing.T) { @@ -238,7 +238,7 @@ func BenchmarkComb(b *testing.B) { } func BenchmarkPigeonhole(b *testing.B) { - benchmarkFramework(b, sort.Pigeonhole) + benchmarkFramework(b, sort.Pigeonhole[int]) } func BenchmarkPatience(b *testing.B) { From 873b9eca0aaad59bdf7b18ffed9db8f08fd71d37 Mon Sep 17 00:00:00 2001 From: VictorAssunc Date: Wed, 12 Oct 2022 08:02:46 -0300 Subject: [PATCH 078/202] feat(cipher/caesar): add fuzzy test to caesar cipher (#559) --- cipher/caesar/caesar.go | 10 +++++----- cipher/caesar/caesar_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/cipher/caesar/caesar.go b/cipher/caesar/caesar.go index 21da4f5a9..8c1cb47f7 100644 --- a/cipher/caesar/caesar.go +++ b/cipher/caesar/caesar.go @@ -9,12 +9,12 @@ func Encrypt(input string, key int) string { key8 := byte(key%26+26) % 26 var outputBuffer []byte - // r is a rune, which is the equivalent of uint32. - for _, r := range input { - newByte := byte(r) - if 'A' <= r && r <= 'Z' { + // b is a byte, which is the equivalent of uint8. + for _, b := range []byte(input) { + newByte := b + if 'A' <= b && b <= 'Z' { outputBuffer = append(outputBuffer, 'A'+(newByte-'A'+key8)%26) - } else if 'a' <= r && r <= 'z' { + } else if 'a' <= b && b <= 'z' { outputBuffer = append(outputBuffer, 'a'+(newByte-'a'+key8)%26) } else { outputBuffer = append(outputBuffer, newByte) diff --git a/cipher/caesar/caesar_test.go b/cipher/caesar/caesar_test.go index e28a3fe11..4d03ea3ec 100644 --- a/cipher/caesar/caesar_test.go +++ b/cipher/caesar/caesar_test.go @@ -2,7 +2,9 @@ package caesar import ( "fmt" + "math/rand" "testing" + "time" ) func TestEncrypt(t *testing.T) { @@ -152,3 +154,14 @@ func Example() { // Encrypt=> key: 10, input: The Quick Brown Fox Jumps over the Lazy Dog., encryptedText: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq. // Decrypt=> key: 10, input: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq., decryptedText: The Quick Brown Fox Jumps over the Lazy Dog. } + +func FuzzCaesar(f *testing.F) { + rand.Seed(time.Now().Unix()) + f.Add("The Quick Brown Fox Jumps over the Lazy Dog.") + f.Fuzz(func(t *testing.T, input string) { + key := rand.Intn(26) + if result := Decrypt(Encrypt(input, key), key); result != input { + t.Fatalf("With input: '%s' and key: %d\n\tExpected: '%s'\n\tGot: '%s'", input, key, input, result) + } + }) +} From c86b40dda9255444137460674c0e237f51f4459d Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 13 Oct 2022 05:04:21 +0200 Subject: [PATCH 079/202] test: add tests for longestcommonsubsequence.go (#556) --- dynamic/longestcommonsubsequence_test.go | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 dynamic/longestcommonsubsequence_test.go diff --git a/dynamic/longestcommonsubsequence_test.go b/dynamic/longestcommonsubsequence_test.go new file mode 100644 index 000000000..361f2b004 --- /dev/null +++ b/dynamic/longestcommonsubsequence_test.go @@ -0,0 +1,55 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseLCS struct { + stringA string + stringB string + expected int +} + +func getLCSTestCases() []testCaseLCS { + return []testCaseLCS{ + {"ABCDGH", "AEDFHR", 3}, + {"AGGTAB", "GXTXAYB", 4}, + {"programming", "gaming", 6}, + {"physics", "smartphone", 2}, + {"computer", "food", 1}, + {"123", "12345", 3}, + {"XYZ", "XYZ", 3}, + {"XYZ", "XYZa", 3}, + {"XYZ", "aXYZ", 3}, + {"0123", "abc", 0}, + {"abcdef", "aXbXcXXXdeXXf", 6}, + {"", "abc", 0}, + {"", "", 0}, + } +} + +func TestLongestCommonSubsequence(t *testing.T) { + t.Run("Simple test", func(t *testing.T) { + for _, tc := range getLCSTestCases() { + actual := dynamic.LongestCommonSubsequence( + tc.stringA, tc.stringB, + len(tc.stringA), len(tc.stringB)) + if actual != tc.expected { + t.Errorf("expected: %d, but got: %d", tc.expected, actual) + } + } + }) + + t.Run("Symmetry test", func(t *testing.T) { + for _, tc := range getLCSTestCases() { + actual := dynamic.LongestCommonSubsequence( + tc.stringB, tc.stringA, + len(tc.stringB), len(tc.stringA)) + if actual != tc.expected { + t.Errorf("expected: %d, but got: %d", tc.expected, actual) + } + } + }) +} From 746173e57fe169ebdb00fed1bf8b7dd2e44d30c1 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 13 Oct 2022 05:05:07 +0200 Subject: [PATCH 080/202] test: add tests for rodcutting.go (#555) --- dynamic/rodcutting_test.go | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 dynamic/rodcutting_test.go diff --git a/dynamic/rodcutting_test.go b/dynamic/rodcutting_test.go new file mode 100644 index 000000000..96321df40 --- /dev/null +++ b/dynamic/rodcutting_test.go @@ -0,0 +1,39 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type rodCuttingTestCase struct { + price []int + length int + expected int +} + +func getRodCuttingTestCases() []rodCuttingTestCase { + return []rodCuttingTestCase{ + {[]int{0, 1, 5, 8, 9}, 4, 10}, + {[]int{0, 2, 5, 7, 8, 0}, 5, 12}, + {[]int{0, 1, 5, 8, 9, 10, 17, 17, 20}, 8, 22}, + {[]int{0, 3, 5, 8, 9, 10, 17, 17, 20}, 8, 24}, + } +} + +func cutRodSolTestFunc(t *testing.T, cutRodSolFunc func([]int, int) int) { + for _, tc := range getRodCuttingTestCases() { + actual := cutRodSolFunc(tc.price, tc.length) + if actual != tc.expected { + t.Errorf("expected: %d, got: %d", tc.expected, actual) + } + } +} + +func TestCutRodRec(t *testing.T) { + cutRodSolTestFunc(t, dynamic.CutRodRec) +} + +func TestCutRodDp(t *testing.T) { + cutRodSolTestFunc(t, dynamic.CutRodDp) +} From ae98d523dd3889afb06da7c762a414c00f063043 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 13 Oct 2022 05:07:06 +0200 Subject: [PATCH 081/202] feat: add perfectnumber (#554) --- math/perfectnumber.go | 36 +++++++++ math/perfectnumber_test.go | 151 +++++++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+) create mode 100644 math/perfectnumber.go create mode 100644 math/perfectnumber_test.go diff --git a/math/perfectnumber.go b/math/perfectnumber.go new file mode 100644 index 000000000..e21c89b64 --- /dev/null +++ b/math/perfectnumber.go @@ -0,0 +1,36 @@ +// perfectnumber.go +// description: provides the function IsPerfectNumber and related utilities +// details: +// provides the functions +// - IsPerfectNumber which checks if the input is a perfect number, +// - SumOfProperDivisors which returns the sum of proper divisors of the input. +// A number is called perfect, if it is a sum of its proper divisors, +// cf. https://en.wikipedia.org/wiki/Perfect_number, +// https://mathworld.wolfram.com/PerfectNumber.html +// https://oeis.org/A000396 +// author(s) [Piotr Idzik](https://github.com/vil02) +// see perfectnumber_test.go + +package math + +// Returns the sum of proper divisors of inNumber. +func SumOfProperDivisors(inNumber uint) uint { + var res = uint(0) + if inNumber > 1 { + res = uint(1) + } + for curDivisor := uint(2); curDivisor*curDivisor <= inNumber; curDivisor++ { + if inNumber%curDivisor == 0 { + res += curDivisor + if curDivisor*curDivisor != inNumber { + res += inNumber / curDivisor + } + } + } + return res +} + +// Checks if inNumber is a perfect number +func IsPerfectNumber(inNumber uint) bool { + return inNumber > 0 && SumOfProperDivisors(inNumber) == inNumber +} diff --git a/math/perfectnumber_test.go b/math/perfectnumber_test.go new file mode 100644 index 000000000..c0041d0ae --- /dev/null +++ b/math/perfectnumber_test.go @@ -0,0 +1,151 @@ +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +type testCaseSumOfProperDivisors struct { + input uint + expected uint +} + +// getSumOfProperDivisorsTestCases returns an array of test data +// for the tests of the function SumOfProperDivisors. +// Data was verified using [A001065]. +// [A001065]: https://oeis.org/A001065/b001065.txt +func getSumOfProperDivisorsTestCases() []testCaseSumOfProperDivisors { + return []testCaseSumOfProperDivisors{ + {0, 0}, + {1, 0}, + {2, 1}, + {3, 1}, + {4, 3}, + {5, 1}, + {6, 6}, + {7, 1}, + {8, 7}, + {9, 4}, + {10, 8}, + {11, 1}, + {12, 16}, + {13, 1}, + {14, 10}, + {15, 9}, + {16, 15}, + {17, 1}, + {18, 21}, + {19, 1}, + {20, 22}, + {21, 11}, + {22, 14}, + {23, 1}, + {24, 36}, + {25, 6}, + {26, 16}, + {27, 13}, + {28, 28}, + {29, 1}, + {30, 42}, + {31, 1}, + {32, 31}, + {33, 15}, + {34, 20}, + {35, 13}, + {36, 55}, + {37, 1}, + {38, 22}, + {39, 17}, + {40, 50}, + {41, 1}, + {42, 54}, + {43, 1}, + {44, 40}, + {45, 33}, + {46, 26}, + {47, 1}, + {48, 76}, + {49, 8}, + {50, 43}, + {51, 21}, + {52, 46}, + {53, 1}, + {54, 66}, + {55, 17}, + {56, 64}, + {57, 23}, + {58, 32}, + {59, 1}, + {60, 108}, + {800, 1153}, + {8204, 8260}, + {9646, 8498}, + {9756, 14996}, + {9829, 1}, + {9954, 15006}, + {10000, 14211}, + } +} + +func TestSumOfProperDivisors(t *testing.T) { + for _, tc := range getSumOfProperDivisorsTestCases() { + actual := math.SumOfProperDivisors(tc.input) + if actual != tc.expected { + t.Errorf( + "Expected SumOfProperDivisors(%d) to be: %d, but got: %d", + tc.input, tc.expected, actual) + } + } +} + +func BenchmarkSumOfProperDivisors(b *testing.B) { + for i := 0; i < b.N; i++ { + math.SumOfProperDivisors(800) + } +} + +type isPerfectNumberTestCase struct { + number uint + isPerfect bool +} + +// getIsPerfectNumberTestCases returns an array of test data +// for the tests of the function IsPerfectNumber +// Data was verified using [A000396]. +// [A000396]: https://oeis.org/A000396 +func getIsPerfectNumberTestCases() []isPerfectNumberTestCase { + return []isPerfectNumberTestCase{ + {6, true}, + {28, true}, + {496, true}, + {8128, true}, + {33550336, true}, + {0, false}, + {1, false}, + {2, false}, + {3, false}, + {4, false}, + {5, false}, + {7, false}, + {100, false}, + {219, false}, + {997, false}, + {33550335, false}, + {33550337, false}, + } +} + +func TestIsPerfectNumber(t *testing.T) { + for _, tc := range getIsPerfectNumberTestCases() { + if math.IsPerfectNumber(tc.number) != tc.isPerfect { + t.Errorf("Unexpected output for %d", tc.number) + } + } +} + +func BenchmarkIsPerfectNumber(b *testing.B) { + for i := 0; i < b.N; i++ { + math.IsPerfectNumber(8128) + } +} From e2332789099665ac40e83d0c30d964e41a97d692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20H=E1=BA=A3i=20L=C3=A2m?= Date: Thu, 13 Oct 2022 10:07:42 +0700 Subject: [PATCH 082/202] feat:Use generic for radixsort (#566) --- sort/radixsort.go | 22 +++++++++++++++------- sort/sorts_test.go | 4 ++-- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/sort/radixsort.go b/sort/radixsort.go index 7b731cdb1..4dbd21d64 100644 --- a/sort/radixsort.go +++ b/sort/radixsort.go @@ -1,10 +1,18 @@ +// radixsort.go +// description: Implementation of in-place radixsort algorithm +// details: +// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort) + package sort -import "github.com/TheAlgorithms/Go/math/max" +import ( + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math/max" +) -func countSort(arr []int, exp int) []int { +func countSort[T constraints.Integer](arr []T, exp T) []T { var digits [10]int - var output = make([]int, len(arr)) + var output = make([]T, len(arr)) for _, item := range arr { digits[(item/exp)%10]++ @@ -21,22 +29,22 @@ func countSort(arr []int, exp int) []int { return output } -func unsignedRadixSort(arr []int) []int { +func unsignedRadixSort[T constraints.Integer](arr []T) []T { if len(arr) == 0 { return arr } maxElement := max.Int(arr...) - for exp := 1; maxElement/exp > 0; exp *= 10 { + for exp := T(1); maxElement/exp > 0; exp *= 10 { arr = countSort(arr, exp) } return arr } -func RadixSort(arr []int) []int { +func RadixSort[T constraints.Integer](arr []T) []T { if len(arr) < 1 { return arr } - var negatives, nonNegatives []int + var negatives, nonNegatives []T for _, item := range arr { if item < 0 { diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 1c07ddb2b..34f2966e2 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -112,7 +112,7 @@ func TestShell(t *testing.T) { } func TestRadix(t *testing.T) { - testFramework(t, sort.RadixSort) + testFramework(t, sort.RadixSort[int]) } func TestSimple(t *testing.T) { @@ -217,7 +217,7 @@ func BenchmarkShell(b *testing.B) { } func BenchmarkRadix(b *testing.B) { - benchmarkFramework(b, sort.RadixSort) + benchmarkFramework(b, sort.RadixSort[int]) } func BenchmarkSimple(b *testing.B) { From 3e2af4fc317c1fe3b9807ce0030e3744536fae62 Mon Sep 17 00:00:00 2001 From: Corentin Giaufer Saubert <43623834+CorentinGS@users.noreply.github.com> Date: Thu, 13 Oct 2022 05:08:03 +0200 Subject: [PATCH 083/202] feat: Parallel MergeSort using goroutines (#558) --- sort/mergesort.go | 26 ++++++++++++++++++++++++++ sort/sorts_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/sort/mergesort.go b/sort/mergesort.go index babff39f1..9a875b428 100644 --- a/sort/mergesort.go +++ b/sort/mergesort.go @@ -3,6 +3,7 @@ package sort import ( "github.com/TheAlgorithms/Go/constraints" "github.com/TheAlgorithms/Go/math/min" + "sync" ) func merge[T constraints.Ordered](a []T, b []T) []T { @@ -60,3 +61,28 @@ func MergeIter[T constraints.Ordered](items []T) []T { } return items } + +// ParallelMerge Perform merge sort on a slice using goroutines +func ParallelMerge[T constraints.Ordered](items []T) []T { + if len(items) < 2 { + return items + } + + if len(items) < 2048 { + return Merge(items) + } + + var wg sync.WaitGroup + wg.Add(1) + + var middle = len(items) / 2 + var a []T + go func() { + defer wg.Done() + a = ParallelMerge(items[:middle]) + }() + var b = ParallelMerge(items[middle:]) + + wg.Wait() + return merge(a, b) +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 34f2966e2..3c7e89caa 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -2,8 +2,10 @@ package sort_test import ( "github.com/TheAlgorithms/Go/sort" + "math/rand" "reflect" "testing" + "time" ) func testFramework(t *testing.T, sortingFunction func([]int) []int) { @@ -95,6 +97,26 @@ func TestMergeIter(t *testing.T) { testFramework(t, sort.MergeIter[int]) } +func TestMergeParallel(t *testing.T) { + testFramework(t, sort.ParallelMerge[int]) + + // Test parallel merge sort with a large slice + t.Run("ParallelMerge on large slice", func(t *testing.T) { + rand.Seed(time.Now().UnixNano()) + size := 100000 + randomLargeSlice := make([]int, size) + for i := range randomLargeSlice { + randomLargeSlice[i] = rand.Intn(size) + } + sortedSlice := sort.ParallelMerge[int](randomLargeSlice) + for i := 0; i < len(sortedSlice)-1; i++ { + if sortedSlice[i] > sortedSlice[i+1] { + t.Errorf("ParallelMerge failed") + } + } + }) +} + func TestHeap(t *testing.T) { testFramework(t, sort.HeapSort) } @@ -200,6 +222,10 @@ func BenchmarkMergeIter(b *testing.B) { benchmarkFramework(b, sort.MergeIter[int]) } +func BenchmarkMergeParallel(b *testing.B) { + benchmarkFramework(b, sort.ParallelMerge[int]) +} + func BenchmarkHeap(b *testing.B) { benchmarkFramework(b, sort.HeapSort) } From 942a6885da7710ca79e31fb3abbca1c2f62b03a7 Mon Sep 17 00:00:00 2001 From: Chanwit Piromplad Date: Thu, 13 Oct 2022 16:37:53 +0700 Subject: [PATCH 084/202] feat: add lru cache (#547) * feat: add lru cache * fix: double linkedlist for support LRU cache * fix: move to cache folder * fix: rename function to NewLRU * fix: head in double linkedlist to pointer * Apply suggestions from code review Co-authored-by: Taj Co-authored-by: Taj --- cache/lru.go | 65 +++++++++++++ cache/lru_test.go | 59 ++++++++++++ structure/linkedlist/doubly.go | 143 +++++++++++++++++++--------- structure/linkedlist/doubly_test.go | 14 +-- 4 files changed, 227 insertions(+), 54 deletions(-) create mode 100644 cache/lru.go create mode 100644 cache/lru_test.go diff --git a/cache/lru.go b/cache/lru.go new file mode 100644 index 000000000..d937118f9 --- /dev/null +++ b/cache/lru.go @@ -0,0 +1,65 @@ +package cache + +import ( + "github.com/TheAlgorithms/Go/structure/linkedlist" +) + +type item struct { + key string + value any +} + +type LRU struct { + dl *linkedlist.Doubly[any] + capacity int + maxCapacity int + storage map[string]*linkedlist.Node[any] +} + +// NewLRU represent initiate lru cache with capacity +func NewLRU(capacity int) LRU { + return LRU{ + dl: linkedlist.NewDoubly[any](), + storage: make(map[string]*linkedlist.Node[any], capacity), + capacity: 0, + maxCapacity: capacity, + } +} + +// Get value from lru +// if not found, return nil +func (c *LRU) Get(key string) any { + v, ok := c.storage[key] + if ok { + c.dl.MoveToBack(v) + return v.Val.(item).value + } + + return nil +} + +// Put cache with key and value to lru +func (c *LRU) Put(key string, value any) { + e, ok := c.storage[key] + if ok { + n := e.Val.(item) + n.value = value + e.Val = n + c.dl.MoveToBack(e) + return + } + + if c.capacity >= c.maxCapacity { + e := c.dl.Front() + dk := e.Val.(item).key + c.dl.Remove(e) + delete(c.storage, dk) + c.capacity-- + } + + n := item{key: key, value: value} + c.dl.AddAtEnd(n) + ne := c.dl.Back() + c.storage[key] = ne + c.capacity++ +} diff --git a/cache/lru_test.go b/cache/lru_test.go new file mode 100644 index 000000000..34ab3752b --- /dev/null +++ b/cache/lru_test.go @@ -0,0 +1,59 @@ +package cache_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/cache" +) + +func TestLRU(t *testing.T) { + cache := cache.NewLRU(3) + + t.Run("Test 1: Put number and Get is correct", func(t *testing.T) { + key, value := "1", 1 + cache.Put(key, value) + got := cache.Get(key) + + if got != value { + t.Errorf("expected: %v, got: %v", value, got) + } + }) + + t.Run("Test 2: Get data not stored in cache should return nil", func(t *testing.T) { + got := cache.Get("2") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + }) + + t.Run("Test 3: Put data over capacity and Get should return nil", func(t *testing.T) { + cache.Put("2", 2) + cache.Put("3", 3) + cache.Put("4", 4) + + got := cache.Get("1") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + }) + + t.Run("test 4: Put key over capacity but recent key exists", func(t *testing.T) { + cache.Put("4", 4) + cache.Put("3", 3) + cache.Put("2", 2) + cache.Put("1", 1) + + got := cache.Get("4") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + + expected := 3 + got = cache.Get("3") + + if got != expected { + t.Errorf("expected: %v, got: %v", expected, got) + } + + }) +} diff --git a/structure/linkedlist/doubly.go b/structure/linkedlist/doubly.go index 0550ddba1..a14513751 100644 --- a/structure/linkedlist/doubly.go +++ b/structure/linkedlist/doubly.go @@ -19,83 +19,97 @@ type Doubly[T any] struct { Head *Node[T] } -func NewDoubly[T any]() *Doubly[T] { - return &Doubly[T]{} +// Init initializes double linked list +func (ll *Doubly[T]) Init() *Doubly[T] { + ll.Head = &Node[T]{} + ll.Head.Next = ll.Head + ll.Head.Prev = ll.Head + + return ll } -// AddAtBeg Add a node to the beginning of the linkedlist -func (ll *Doubly[T]) AddAtBeg(val T) { - n := NewNode(val) - n.Next = ll.Head +func NewDoubly[T any]() *Doubly[T] { + return new(Doubly[T]).Init() +} - if ll.Head != nil { - ll.Head.Prev = n +// lazyInit lazily initializes a zero List value. +func (ll *Doubly[T]) lazyInit() { + if ll.Head.Next == nil { + ll.Init() } +} - ll.Head = n +func (ll *Doubly[T]) insert(n, at *Node[T]) *Node[T] { + n.Prev = at + n.Next = at.Next + n.Prev.Next = n + n.Next.Prev = n + return n +} + +func (ll *Doubly[T]) insertValue(val T, at *Node[T]) *Node[T] { + return ll.insert(NewNode(val), at) +} + +// AddAtBeg Add a node to the beginning of the linkedlist +func (ll *Doubly[T]) AddAtBeg(val T) { + ll.lazyInit() + ll.insertValue(val, ll.Head) } // AddAtEnd Add a node at the end of the linkedlist func (ll *Doubly[T]) AddAtEnd(val T) { - n := NewNode(val) + ll.lazyInit() + ll.insertValue(val, ll.Head.Prev) +} - if ll.Head == nil { - ll.Head = n - return - } +func (ll *Doubly[T]) Remove(n *Node[T]) T { + n.Prev.Next = n.Next + n.Next.Prev = n.Prev + n.Next = nil + n.Prev = nil - cur := ll.Head - for ; cur.Next != nil; cur = cur.Next { - } - cur.Next = n - n.Prev = cur + return n.Val } // DelAtBeg Delete the node at the beginning of the linkedlist func (ll *Doubly[T]) DelAtBeg() (T, bool) { - if ll.Head == nil { + // no item + if ll.Head.Next == nil { var r T return r, false } - cur := ll.Head - ll.Head = cur.Next - - if ll.Head != nil { - ll.Head.Prev = nil - } - return cur.Val, true + n := ll.Head.Next + val := n.Val + ll.Remove(n) + return val, true } // DetAtEnd Delete a node at the end of the linkedlist func (ll *Doubly[T]) DelAtEnd() (T, bool) { // no item - if ll.Head == nil { + if ll.Head.Prev == nil { var r T return r, false } - // only one item - if ll.Head.Next == nil { - return ll.DelAtBeg() - } - - // more than one, go to second last - cur := ll.Head - for ; cur.Next.Next != nil; cur = cur.Next { - } - - retval := cur.Next.Val - cur.Next = nil - return retval, true + n := ll.Head.Prev + val := n.Val + ll.Remove(n) + return val, true } // Count Number of nodes in the linkedlist func (ll *Doubly[T]) Count() int { var ctr int = 0 - for cur := ll.Head; cur != nil; cur = cur.Next { + if ll.Head.Next == nil { + return 0 + } + + for cur := ll.Head.Next; cur != ll.Head; cur = cur.Next { ctr += 1 } @@ -120,7 +134,7 @@ func (ll *Doubly[T]) Reverse() { // Display display the linked list func (ll *Doubly[T]) Display() { - for cur := ll.Head; cur != nil; cur = cur.Next { + for cur := ll.Head.Next; cur != ll.Head; cur = cur.Next { fmt.Print(cur.Val, " ") } @@ -133,12 +147,47 @@ func (ll *Doubly[T]) DisplayReverse() { return } var cur *Node[T] - for cur = ll.Head; cur.Next != nil; cur = cur.Next { - } - - for ; cur != nil; cur = cur.Prev { + for cur = ll.Head.Prev; cur != ll.Head; cur = cur.Prev { fmt.Print(cur.Val, " ") } fmt.Print("\n") } + +func (ll *Doubly[T]) Front() *Node[T] { + if ll.Count() == 0 { + return nil + } + + return ll.Head.Next +} + +func (ll *Doubly[T]) Back() *Node[T] { + if ll.Count() == 0 { + return nil + } + + return ll.Head.Prev +} + +func (ll *Doubly[T]) MoveToBack(n *Node[T]) { + if ll.Head.Prev == n { + return + } + + ll.move(n, ll.Head.Prev) +} + +func (ll *Doubly[T]) move(n, at *Node[T]) { + if n == at { + return + } + + n.Prev.Next = n.Next + n.Next.Prev = n.Prev + + n.Prev = at + n.Next = at.Next + n.Prev.Next = n + n.Next.Prev = n +} diff --git a/structure/linkedlist/doubly_test.go b/structure/linkedlist/doubly_test.go index e30663dda..4778be74e 100644 --- a/structure/linkedlist/doubly_test.go +++ b/structure/linkedlist/doubly_test.go @@ -18,11 +18,11 @@ func TestDoubly(t *testing.T) { got := []int{} // check from Next address - current := newList.Head + current := newList.Head.Next got = append(got, current.Val) - for current.Next != nil { + for current.Next != newList.Head { current = current.Next got = append(got, current.Val) } @@ -35,7 +35,7 @@ func TestDoubly(t *testing.T) { got = []int{} got = append(got, current.Val) - for current.Prev != nil { + for current.Prev != newList.Head { current = current.Prev got = append(got, current.Val) } @@ -50,9 +50,9 @@ func TestDoubly(t *testing.T) { t.Run("Test AddAtEnd", func(t *testing.T) { want := []int{3, 2, 1, 4} got := []int{} - current := newList.Head + current := newList.Head.Next got = append(got, current.Val) - for current.Next != nil { + for current.Next != newList.Head { current = current.Next got = append(got, current.Val) } @@ -99,9 +99,9 @@ func TestDoubly(t *testing.T) { want := []int{1, 2, 3} got := []int{} newList2.Reverse() - current := newList2.Head + current := newList2.Head.Next got = append(got, current.Val) - for current.Next != nil { + for current.Next != newList2.Head { current = current.Next got = append(got, current.Val) } From 57d49d59cf8f4d0c494f92c0465cacc66f9316e2 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 15 Oct 2022 11:09:27 +0200 Subject: [PATCH 085/202] refactor: simplity signature of `LongestCommonSubsequence` (#567) * refactor: simplity signature of LongestCommonSubsequence * style: use camelCase * style: remove commented-out code --- dynamic/longestcommonsubsequence.go | 32 +++++++++++------------- dynamic/longestcommonsubsequence_test.go | 9 +++---- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/dynamic/longestcommonsubsequence.go b/dynamic/longestcommonsubsequence.go index 447af9f7f..8ca739811 100644 --- a/dynamic/longestcommonsubsequence.go +++ b/dynamic/longestcommonsubsequence.go @@ -4,19 +4,24 @@ package dynamic +import ( + "unicode/utf8" +) + // LongestCommonSubsequence function -func LongestCommonSubsequence(a string, b string, m int, n int) int { - // m is the length of string a and n is the length of string b +func LongestCommonSubsequence(a string, b string) int { + var aLen = utf8.RuneCountInString(a) + var bLen = utf8.RuneCountInString(b) - // here we are making a 2d slice of size (m+1)*(n+1) - lcs := make([][]int, m+1) - for i := 0; i <= m; i++ { - lcs[i] = make([]int, n+1) + // here we are making a 2d slice of size (aLen+1)*(bLen+1) + lcs := make([][]int, aLen+1) + for i := 0; i <= aLen; i++ { + lcs[i] = make([]int, bLen+1) } // block that implements LCS - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { + for i := 0; i <= aLen; i++ { + for j := 0; j <= bLen; j++ { if i == 0 || j == 0 { lcs[i][j] = 0 } else if a[i-1] == b[j-1] { @@ -27,14 +32,5 @@ func LongestCommonSubsequence(a string, b string, m int, n int) int { } } // returning the length of longest common subsequence - return lcs[m][n] + return lcs[aLen][bLen] } - -// func main(){ -// // declaring two strings and asking for input - -// var a,b string -// fmt.Scan(&a, &b) -// // calling the LCS function -// fmt.Println("The length of longest common subsequence is:", longestCommonSubsequence(a,b, len(a), len(b))) -// } diff --git a/dynamic/longestcommonsubsequence_test.go b/dynamic/longestcommonsubsequence_test.go index 361f2b004..1c102c3be 100644 --- a/dynamic/longestcommonsubsequence_test.go +++ b/dynamic/longestcommonsubsequence_test.go @@ -27,15 +27,14 @@ func getLCSTestCases() []testCaseLCS { {"abcdef", "aXbXcXXXdeXXf", 6}, {"", "abc", 0}, {"", "", 0}, + {"££", "££", 2}, } } func TestLongestCommonSubsequence(t *testing.T) { t.Run("Simple test", func(t *testing.T) { for _, tc := range getLCSTestCases() { - actual := dynamic.LongestCommonSubsequence( - tc.stringA, tc.stringB, - len(tc.stringA), len(tc.stringB)) + actual := dynamic.LongestCommonSubsequence(tc.stringA, tc.stringB) if actual != tc.expected { t.Errorf("expected: %d, but got: %d", tc.expected, actual) } @@ -44,9 +43,7 @@ func TestLongestCommonSubsequence(t *testing.T) { t.Run("Symmetry test", func(t *testing.T) { for _, tc := range getLCSTestCases() { - actual := dynamic.LongestCommonSubsequence( - tc.stringB, tc.stringA, - len(tc.stringB), len(tc.stringA)) + actual := dynamic.LongestCommonSubsequence(tc.stringB, tc.stringA) if actual != tc.expected { t.Errorf("expected: %d, but got: %d", tc.expected, actual) } From 03c8ce84d6b45153b4709997c4c1e7d54d5792c4 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 15 Oct 2022 21:50:08 +0200 Subject: [PATCH 086/202] tests: Modular Inverse (#570) * test: add missing test cases * fix: handle the case b == 0 * style: fix typos * style: remove duplicated code * style: rename b to m * style: remove misleading comment --- math/modular/inverse.go | 9 ++++--- math/modular/inverse_test.go | 46 ++++++++++++++++++++++-------------- 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/math/modular/inverse.go b/math/modular/inverse.go index e0aa73b1a..819ffda8d 100644 --- a/math/modular/inverse.go +++ b/math/modular/inverse.go @@ -13,15 +13,14 @@ import ( "github.com/TheAlgorithms/Go/math/gcd" ) -// ErrorIntOverflow For asserting that the values do not overflow in Int64 var ErrorInverse = errors.New("no Modular Inverse exists") // Inverse Modular function -func Inverse(a, b int64) (int64, error) { - gcd, x, _ := gcd.Extended(a, b) - if gcd != 1 { +func Inverse(a, m int64) (int64, error) { + gcd, x, _ := gcd.Extended(a, m) + if gcd != 1 || m == 0 { return 0, ErrorInverse } - return ((b + (x % b)) % b), nil // this is necessary because of Go's use of architecture specific instruction for the % operator. + return ((m + (x % m)) % m), nil // this is necessary because of Go's use of architecture specific instruction for the % operator. } diff --git a/math/modular/inverse_test.go b/math/modular/inverse_test.go index e27166dbc..a8025e97c 100644 --- a/math/modular/inverse_test.go +++ b/math/modular/inverse_test.go @@ -6,24 +6,34 @@ package modular import "testing" +import "fmt" func TestInverse(t *testing.T) { - t.Run("Testing a = 3 and m = 11: ", func(t *testing.T) { - inv, err := Inverse(3, 11) - if err != nil { - t.Fatalf("Error was raised when it shouldn't: %v", err) - } - if inv != 4 { - t.Fatalf("Test failed:\n\tExpected values: %v\n\tReturned value: %v", 4, inv) - } - }) - t.Run("Testing a = 10 and m = 17: ", func(t *testing.T) { - inv, err := Inverse(10, 17) - if err != nil { - t.Fatalf("Error was raised when it shouldn't: %v", err) - } - if inv != 12 { - t.Fatalf("Test failed:\n\tExpected values: %v\n\tReturned value: %v", 12, inv) - } - }) + testCases := []struct { + a int64 + m int64 + expectedValue int64 + expectedError error + }{ + {3, 11, 4, nil}, + {10, 17, 12, nil}, + {2, 6, 0, ErrorInverse}, + {1, 0, 0, ErrorInverse}, + } + for _, tc := range testCases { + testName := fmt.Sprintf("Testing a = %d and m = %d: ", tc.a, tc.m) + t.Run(testName, func(t *testing.T) { + inv, err := Inverse(tc.a, tc.m) + if err != tc.expectedError { + if tc.expectedError == nil { + t.Fatalf("Error was raised when it shouldn't: %v", err) + } else { + t.Fatalf("Error was not raised when it should") + } + } + if inv != tc.expectedValue { + t.Fatalf("expected: %d, got: %d", tc.expectedValue, inv) + } + }) + } } From 6e6d4d7b4b94d4bf8c23b1f4bbdbdb71f767352a Mon Sep 17 00:00:00 2001 From: pnr Date: Sun, 16 Oct 2022 03:35:29 +0700 Subject: [PATCH 087/202] refactor heapsort to support generic (#553) * refactor: generic heapsort * revert: remove generic test * revert: max heap * refactor: make max heap more generic * fix: zero index * revert: generic MaxHeap * revert: heapifyDown --- sort/heapsort.go | 75 ++++++++++++++++++++++++---------------------- sort/sorts_test.go | 4 +-- 2 files changed, 41 insertions(+), 38 deletions(-) diff --git a/sort/heapsort.go b/sort/heapsort.go index 07a5d9547..741b4e4e8 100644 --- a/sort/heapsort.go +++ b/sort/heapsort.go @@ -1,21 +1,13 @@ package sort +import "github.com/TheAlgorithms/Go/constraints" + type MaxHeap struct { slice []Comparable heapSize int indices map[int]int } -func buildMaxHeap(slice0 []int) MaxHeap { - var slice []Comparable - for _, i := range slice0 { - slice = append(slice, Int(i)) - } - h := MaxHeap{} - h.Init(slice) - return h -} - func (h *MaxHeap) Init(slice []Comparable) { if slice == nil { slice = make([]Comparable, 0) @@ -73,6 +65,16 @@ func (h MaxHeap) updateidx(i int) { h.indices[h.slice[i].Idx()] = i } +func (h *MaxHeap) swap(i, j int) { + h.slice[i], h.slice[j] = h.slice[j], h.slice[i] + h.updateidx(i) + h.updateidx(j) +} + +func (h MaxHeap) more(i, j int) bool { + return h.slice[i].More(h.slice[j]) +} + func (h MaxHeap) heapifyUp(i int) { if i == 0 { return @@ -80,28 +82,29 @@ func (h MaxHeap) heapifyUp(i int) { p := i / 2 if h.slice[i].More(h.slice[p]) { - h.slice[i], h.slice[p] = h.slice[p], h.slice[i] - h.updateidx(i) - h.updateidx(p) + h.swap(i, p) h.heapifyUp(p) } } func (h MaxHeap) heapifyDown(i int) { + heapifyDown(h.slice, h.heapSize, i, h.more, h.swap) +} + +func heapifyDown[T any](slice []T, N, i int, moreFunc func(i, j int) bool, swapFunc func(i, j int)) { l, r := 2*i+1, 2*i+2 max := i - if l < h.heapSize && h.slice[l].More(h.slice[max]) { + if l < N && moreFunc(l, max) { max = l } - if r < h.heapSize && h.slice[r].More(h.slice[max]) { + if r < N && moreFunc(r, max) { max = r } if max != i { - h.slice[i], h.slice[max] = h.slice[max], h.slice[i] - h.updateidx(i) - h.updateidx(max) - h.heapifyDown(max) + swapFunc(i, max) + + heapifyDown(slice, N, max, moreFunc, swapFunc) } } @@ -109,26 +112,26 @@ type Comparable interface { Idx() int More(any) bool } -type Int int -func (a Int) More(b any) bool { - return a > b.(Int) -} -func (a Int) Idx() int { - return int(a) -} +func HeapSort[T constraints.Ordered](slice []T) []T { + N := len(slice) -func HeapSort(slice []int) []int { - h := buildMaxHeap(slice) - for i := len(h.slice) - 1; i >= 1; i-- { - h.slice[0], h.slice[i] = h.slice[i], h.slice[0] - h.heapSize-- - h.heapifyDown(0) + moreFunc := func(i, j int) bool { + return slice[i] > slice[j] + } + swapFunc := func(i, j int) { + slice[i], slice[j] = slice[j], slice[i] + } + + // build a maxheap + for i := N/2 - 1; i >= 0; i-- { + heapifyDown(slice, N, i, moreFunc, swapFunc) } - res := []int{} - for _, i := range h.slice { - res = append(res, int(i.(Int))) + for i := N - 1; i > 0; i-- { + slice[i], slice[0] = slice[0], slice[i] + heapifyDown(slice, i, 0, moreFunc, swapFunc) } - return res + + return slice } diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 3c7e89caa..ecee3d33c 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -118,7 +118,7 @@ func TestMergeParallel(t *testing.T) { } func TestHeap(t *testing.T) { - testFramework(t, sort.HeapSort) + testFramework(t, sort.HeapSort[int]) } func TestCount(t *testing.T) { @@ -227,7 +227,7 @@ func BenchmarkMergeParallel(b *testing.B) { } func BenchmarkHeap(b *testing.B) { - benchmarkFramework(b, sort.HeapSort) + benchmarkFramework(b, sort.HeapSort[int]) } func BenchmarkCount(b *testing.B) { From d61cee077bf76f9bc5c16ee4eb88385d1796b03c Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sun, 16 Oct 2022 10:10:28 +0200 Subject: [PATCH 088/202] tests: math/pi/Spigot (#573) --- math/pi/spigotpi_test.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/math/pi/spigotpi_test.go b/math/pi/spigotpi_test.go index ad845da15..c48b7dc24 100644 --- a/math/pi/spigotpi_test.go +++ b/math/pi/spigotpi_test.go @@ -14,12 +14,22 @@ func TestSpigot(t *testing.T) { result string n int }{ + {"314", 3}, + {"31415", 5}, {"314159", 6}, {"31415926535", 11}, {"314159265358", 12}, {"314159265358979323846", 21}, - {"314", 3}, - {"31415", 5}, + {"3141592653589793238462643", 25}, + {"314159265358979323846264338327950", 33}, + {"31415926535897932384626433832795028841971693993751" + + "05820974944592307816406286208998628034825342117067" + + "98214808651328230664709384460955058223172535940812" + + "84811174502841027019385211055596446229489549303819" + + "64428810975665933446128475648233786783165271201909" + + "14564856692346034861045432664821339360726024914127" + + "37245870066063155881748815209209628292540917153643" + + "678925903600", 362}, } for _, tv := range tests { t.Run(strconv.Itoa(tv.n)+":"+tv.result, func(t *testing.T) { From e63fa32e97b8207f52bc0b2a7fc84855880c3fc0 Mon Sep 17 00:00:00 2001 From: Paulden Date: Wed, 19 Oct 2022 19:26:52 +0800 Subject: [PATCH 089/202] Add Red-Black Tree (#551) --- README.md | 87 ++- structure/avl/avl.go | 220 -------- structure/avl/avl_test.go | 277 ---------- structure/binarysearchtree/bstree.go | 179 ------- structure/binarysearchtree/bstree_test.go | 235 -------- structure/binarysearchtree/node.go | 13 - structure/tree/avl.go | 188 +++++++ structure/tree/avl_test.go | 275 ++++++++++ structure/tree/bstree.go | 78 +++ structure/tree/bstree_test.go | 149 +++++ structure/tree/rbtree.go | 353 ++++++++++++ structure/tree/rbtree_test.go | 220 ++++++++ structure/tree/tree.go | 283 ++++++++++ structure/tree/tree_test.go | 626 ++++++++++++++++++++++ 14 files changed, 2210 insertions(+), 973 deletions(-) delete mode 100644 structure/avl/avl.go delete mode 100644 structure/avl/avl_test.go delete mode 100644 structure/binarysearchtree/bstree.go delete mode 100644 structure/binarysearchtree/bstree_test.go delete mode 100644 structure/binarysearchtree/node.go create mode 100644 structure/tree/avl.go create mode 100644 structure/tree/avl_test.go create mode 100644 structure/tree/bstree.go create mode 100644 structure/tree/bstree_test.go create mode 100644 structure/tree/rbtree.go create mode 100644 structure/tree/rbtree_test.go create mode 100644 structure/tree/tree.go create mode 100644 structure/tree/tree_test.go diff --git a/README.md b/README.md index 66de9cad0..04ef156d0 100644 --- a/README.md +++ b/README.md @@ -56,28 +56,6 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`IsArmstrong`](./math/armstrong/isarmstrong.go#L14): No description provided. ---- -
- avl - ---- - -##### Package avl is a Adelson-Velskii and Landis tree implemnation avl is self-balancing tree, i.e for all node in a tree, height difference between its left and right child will not exceed 1 more information : https://en.wikipedia.org/wiki/AVL_tree - ---- -##### Functions: - -1. [`Delete`](./structure/avl/avl.go#L72): Delete : remove given key from the tree -2. [`Get`](./structure/avl/avl.go#L20): Get : return node with given key -3. [`Insert`](./structure/avl/avl.go#L35): Insert a new item -4. [`NewTree`](./structure/avl/avl.go#L15): NewTree create a new AVL tree - ---- -##### Types - -1. [`Node`](./structure/avl/avl.go#L8): No description provided. - - ---
binary @@ -101,33 +79,6 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 10. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. 11. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---- -
- binarytree - ---- - -##### Functions: - -1. [`AccessNodesByLayer`](./structure/binarysearchtree/bstree.go#L145): AccessNodesByLayer Function that access nodes layer by layer instead of printing the results as one line. -2. [`BstDelete`](./structure/binarysearchtree/bstree.go#L44): BstDelete removes the node -3. [`InOrder`](./structure/binarysearchtree/bstree.go#L79): Travers the tree in the following order left --> root --> right -4. [`InOrderSuccessor`](./structure/binarysearchtree/bstree.go#L35): InOrderSuccessor Goes to the left -5. [`Insert`](./structure/binarysearchtree/bstree.go#L17): Insert a value in the BSTree -6. [`LevelOrder`](./structure/binarysearchtree/bstree.go#L138): No description provided. -7. [`Max`](./structure/binarysearchtree/bstree.go#L174): Max Function that returns max of two numbers - possibly already declared. -8. [`NewNode`](./structure/binarysearchtree/node.go#L11): NewNode Returns a new pointer to an empty Node -9. [`PostOrder`](./structure/binarysearchtree/bstree.go#L113): Travers the tree in the following order left --> right --> root -10. [`PreOrder`](./structure/binarysearchtree/bstree.go#L96): Travers the tree in the following order root --> left --> right - ---- -##### Types - -1. [`BSTree`](./structure/binarysearchtree/bstree.go#L4): No description provided. - -2. [`Node`](./structure/binarysearchtree/node.go#L4): No description provided. - - ---
caesar @@ -957,6 +908,43 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`NoTextToEncryptError`](./cipher/transposition/transposition.go#L15): No description provided. +--- +
+ tree + +--- + +##### For more details check out those links below here: Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree authors [guuzaa](https://github.com/guuzaa) + +--- +##### Functions: + +1. [`NewAVL`](./structure/tree/avl.go#L13): NewAVL create a novel AVL tree +2. [`NewBinarySearch`](./structure/tree/bstree.go#L18): NewBinarySearch create a novel Binary-Search tree +3. [`NewRB`](./structure/tree/rbtree.go#L23): Create a new Red-Black Tree + +--- +##### Types + +1. [`AVL`](./structure/tree/avl.go#L8): No description provided. + +2. [`BinarySearch`](./structure/tree/bstree.go#L13): No description provided. + +3. [`Node`](./structure/tree/tree.go#L25): No description provided. + +4. [`RB`](./structure/tree/rbtree.go#L18): No description provided. + + +--- +
+ tree_test + +--- + +##### Functions: + +1. [`FuzzRBTree`](./structure/tree/rbtree_test.go#L90): No description provided. + ---
trie @@ -989,6 +977,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Decrypt`](./cipher/xor/xor.go#L19): Decrypt decrypts with Xor encryption 2. [`Encrypt`](./cipher/xor/xor.go#L10): Encrypt encrypts with Xor encryption after converting each character to byte The returned value might not be readable because there is no guarantee which is within the ASCII range If using other type such as string, []int, or some other types, add the statements for converting the type to []byte. +3. [`FuzzXOR`](./cipher/xor/xor_test.go#L108): No description provided. ---
diff --git a/structure/avl/avl.go b/structure/avl/avl.go deleted file mode 100644 index bdb17c81f..000000000 --- a/structure/avl/avl.go +++ /dev/null @@ -1,220 +0,0 @@ -// Package avl is a Adelson-Velskii and Landis tree implemnation -// avl is self-balancing tree, i.e for all node in a tree, height difference -// between its left and right child will not exceed 1 -// more information : https://en.wikipedia.org/wiki/AVL_tree -package avl - -// Node of a tree -type Node struct { - Key int - Height int - Left, Right *Node -} - -// NewTree create a new AVL tree -func NewTree() *Node { - return nil -} - -// Get : return node with given key -func Get(root *Node, key int) *Node { - if root == nil { - return nil - } - if root.Key == key { - return root - } else if root.Key < key { - root = root.Right - } else { - root = root.Left - } - return Get(root, key) -} - -// Insert a new item -func Insert(root **Node, key int) { - if *root == nil { - *root = &Node{ - Key: key, - Height: 1, - } - return - } - if (*root).Key < key { - Insert(&(*root).Right, key) - } else if (*root).Key > key { - Insert(&(*root).Left, key) - } - - // update height - (*root).Height = height(*root) - - bFactor := balanceFactor(*root) - - if bFactor == 2 { // L - bFactor = balanceFactor((*root).Left) - if bFactor == 1 { // LL - llRotation(root) - } else if bFactor == -1 { // LR - lrRotation(root) - } - } else if bFactor == -2 { // R - bFactor = balanceFactor((*root).Right) - if bFactor == 1 { // RL - rlRotation(root) - } else if bFactor == -1 { // RR - rrRotation(root) - } - } -} - -// Delete : remove given key from the tree -func Delete(root **Node, key int) { - if root == nil { - return - } - if (*root).Key < key { - Delete(&(*root).Right, key) - } else if (*root).Key > key { - Delete(&(*root).Left, key) - } else { - // 3 cases - // 1. No Child - // 2. With One Child - // 3. With Two Child - if (*root).Left == nil && (*root).Right == nil { - *root = nil - } else if (*root).Left == nil { - *root = (*root).Right - } else if (*root).Right == nil { - *root = (*root).Left - } else { - minVal := min((*root).Right) - (*root).Key = minVal - Delete(root, minVal) - } - return - } - - // update height - (*root).Height = height(*root) - - bFactor := balanceFactor(*root) - - if bFactor == 2 { // L - switch balanceFactor((*root).Left) { - case 1: // LL - llRotation(root) - case -1: // LR - lrRotation(root) - case 0: // LL OR LR - llRotation(root) - } - } else if bFactor == -2 { // L - switch balanceFactor((*root).Right) { - case 1: // RL - rlRotation(root) - case -1: // RR - rrRotation(root) - case 0: // RL OR RR - rrRotation(root) - } - } -} - -// rotations -// 1. LL -// 2. LR -// 3. RR -// 4. RL -func llRotation(root **Node) { - b := (*root).Left - br := b.Right - b.Right = *root - (*root).Left = br - (*root).Height = height(*root) - b.Height = height(b) - *root = b -} -func lrRotation(root **Node) { - c := (*root).Left.Right - cl := c.Left - cr := c.Right - - c.Left = (*root).Left - c.Right = (*root) - c.Left.Right = cl - - (*root).Left = cr - - (*root).Height = height(*root) - c.Left.Height = height(c.Left) - c.Height = height(c) - - *root = c - -} -func rrRotation(root **Node) { - b := (*root).Right - bl := b.Left - b.Left = *root - - (*root).Right = bl - (*root).Height = height(*root) - b.Height = height(b) - *root = b - -} -func rlRotation(root **Node) { - c := (*root).Right.Left - cl := c.Left - cr := c.Right - - c.Right = (*root).Right - c.Right.Left = cr - c.Left = *root - (*root).Right = cl - - (*root).Height = height(*root) - c.Right.Height = height(c.Right) - c.Height = height(c) - *root = c -} - -// balanceFactor : -ve balance factor means subtree root is heavy toward left -// and +ve balance factor means subtree root is heavy toward right side -func balanceFactor(root *Node) int { - var leftHeight, rightHeight int - if root.Left != nil { - leftHeight = root.Left.Height - } - if root.Right != nil { - rightHeight = root.Right.Height - } - return leftHeight - rightHeight -} - -func height(root *Node) int { - if root == nil { - return 0 - } - var leftHeight, rightHeight int - if root.Left != nil { - leftHeight = root.Left.Height - } - if root.Right != nil { - rightHeight = root.Right.Height - } - max := leftHeight - if rightHeight > leftHeight { - max = rightHeight - } - return 1 + max -} - -func min(root *Node) int { - if root.Left == nil { - return root.Key - } - return min(root.Left) -} diff --git a/structure/avl/avl_test.go b/structure/avl/avl_test.go deleted file mode 100644 index 199d008e7..000000000 --- a/structure/avl/avl_test.go +++ /dev/null @@ -1,277 +0,0 @@ -package avl - -import ( - "testing" -) - -func TestInsert(t *testing.T) { - t.Run("LLRotaion-Test", func(t *testing.T) { - root := NewTree() - Insert(&root, 5) - Insert(&root, 4) - Insert(&root, 3) - - if root.Key != 4 { - t.Errorf("root should have value = 4") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 3 { - t.Errorf("left child should have value = 3") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 5 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - - }) - t.Run("LRRotaion-Test", func(t *testing.T) { - root := NewTree() - Insert(&root, 5) - Insert(&root, 3) - Insert(&root, 4) - - if root.Key != 4 { - t.Errorf("root should have value = 4") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 3 { - t.Errorf("left child should have value = 3") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 5 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - }) - - t.Run("RRRotaion-Test", func(t *testing.T) { - root := NewTree() - Insert(&root, 3) - Insert(&root, 4) - Insert(&root, 5) - - if root.Key != 4 { - t.Errorf("root should have value = 4") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 3 { - t.Errorf("left child should have value = 3") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 5 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - }) - t.Run("RLRotaion-Test", func(t *testing.T) { - root := NewTree() - Insert(&root, 3) - Insert(&root, 5) - Insert(&root, 4) - - if root.Key != 4 { - t.Errorf("root should have value = 4") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 3 { - t.Errorf("left child should have value = 3") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 5 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - }) -} - -func TestDelete(t *testing.T) { - t.Run("LLRotaion-Test", func(t *testing.T) { - root := NewTree() - - Insert(&root, 5) - Insert(&root, 4) - Insert(&root, 3) - Insert(&root, 2) - - Delete(&root, 5) - - if root.Key != 3 { - t.Errorf("root should have value = 3") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 2 { - t.Errorf("left child should have value = 2") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 4 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - }) - - t.Run("LRRotaion-Test", func(t *testing.T) { - root := NewTree() - - Insert(&root, 10) - Insert(&root, 8) - Insert(&root, 6) - Insert(&root, 7) - - Delete(&root, 10) - - if root.Key != 7 { - t.Errorf("root should have value = 7") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 6 { - t.Errorf("left child should have value = 6") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 8 { - t.Errorf("right child should have value = 8") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - - }) - - t.Run("RRRotaion-Test", func(t *testing.T) { - root := NewTree() - - Insert(&root, 2) - Insert(&root, 3) - Insert(&root, 4) - Insert(&root, 5) - - Delete(&root, 2) - - if root.Key != 4 { - t.Errorf("root should have value = 4") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 3 { - t.Errorf("left child should have value = 3") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 5 { - t.Errorf("right child should have value = 5") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - - }) - - t.Run("RLRotaion-Test", func(t *testing.T) { - root := NewTree() - - Insert(&root, 7) - Insert(&root, 6) - Insert(&root, 9) - Insert(&root, 8) - - Delete(&root, 6) - - if root.Key != 8 { - t.Errorf("root should have value = 8") - } - if root.Height != 2 { - t.Errorf("height of root should be = 2") - } - - if root.Left.Key != 7 { - t.Errorf("left child should have value = 7") - } - if root.Left.Height != 1 { - t.Errorf("height of left child should be 1") - } - - if root.Right.Key != 9 { - t.Errorf("right child should have value = 9") - } - if root.Right.Height != 1 { - t.Errorf("height of right should be 1") - } - - }) -} - -func TestGet(t *testing.T) { - - root := NewTree() - - if Get(root, 5) != nil { - t.Error("no item should exists in newly created AVL tree") - } - - Insert(&root, 5) - Insert(&root, 4) - Insert(&root, 3) - - n := Get(root, 4) - if n.Key != 4 { - t.Error("key should be 4") - } - if n.Right.Key != 5 { - t.Error("right child should have value 5") - } - - if n.Left.Key != 3 { - t.Error("left child should have value 3") - } - -} diff --git a/structure/binarysearchtree/bstree.go b/structure/binarysearchtree/bstree.go deleted file mode 100644 index 0e0b511d9..000000000 --- a/structure/binarysearchtree/bstree.go +++ /dev/null @@ -1,179 +0,0 @@ -package binarytree - -// BSTree Returns a binary search tree structure which contains only a root Node -type BSTree struct { - Root *Node -} - -// calculateDepth helper function for BSTree's depth() -func calculateDepth(n *Node, depth int) int { - if n == nil { - return depth - } - return Max(calculateDepth(n.left, depth+1), calculateDepth(n.right, depth+1)) -} - -// Insert a value in the BSTree -func Insert(root *Node, val int) *Node { - if root == nil { - return NewNode(val) - } - if val < root.val { - root.left = Insert(root.left, val) - } else { - root.right = Insert(root.right, val) - } - return root -} - -// Depth returns the calculated depth of a binary saerch tree -func (t *BSTree) Depth() int { - return calculateDepth(t.Root, 0) -} - -// InOrderSuccessor Goes to the left -func InOrderSuccessor(root *Node) *Node { - cur := root - for cur.left != nil { - cur = cur.left - } - return cur -} - -// BstDelete removes the node -func BstDelete(root *Node, val int) *Node { - if root == nil { - return nil - } - if val < root.val { - root.left = BstDelete(root.left, val) - } else if val > root.val { - root.right = BstDelete(root.right, val) - } else { - // this is the node to delete - // node with one child - if root.left == nil { - return root.right - } else if root.right == nil { - return root.left - } else { - n := root.right - d := InOrderSuccessor(n) - d.left = root.left - return root.right - } - } - return root -} - -// InOrder add's children to a node in order left first then right recursively -func inOrderRecursive(n *Node, traversal *[]int) { - if n != nil { - inOrderRecursive(n.left, traversal) - *traversal = append(*traversal, n.val) - inOrderRecursive(n.right, traversal) - } -} - -// Travers the tree in the following order left --> root --> right -func InOrder(root *Node) []int { - traversal := make([]int, 0) - inOrderRecursive(root, &traversal) - return traversal -} - -// PreOrder Preorder -func preOrderRecursive(n *Node, traversal *[]int) { - if n == nil { - return - } - *traversal = append(*traversal, n.val) - preOrderRecursive(n.left, traversal) - preOrderRecursive(n.right, traversal) -} - -// Travers the tree in the following order root --> left --> right -func PreOrder(root *Node) []int { - traversal := make([]int, 0) - preOrderRecursive(root, &traversal) - return traversal -} - -// PostOrder PostOrder -func postOrderRecursive(n *Node, traversal *[]int) { - if n == nil { - return - } - postOrderRecursive(n.left, traversal) - postOrderRecursive(n.right, traversal) - *traversal = append(*traversal, n.val) -} - -// Travers the tree in the following order left --> right --> root -func PostOrder(root *Node) []int { - traversal := make([]int, 0) - postOrderRecursive(root, &traversal) - return traversal -} - -// LevelOrder LevelOrder -func levelOrderRecursive(root *Node, traversal *[]int) { - var q []*Node // queue - var n *Node // temporary node - - q = append(q, root) - - for len(q) != 0 { - n, q = q[0], q[1:] - *traversal = append(*traversal, n.val) - if n.left != nil { - q = append(q, n.left) - } - if n.right != nil { - q = append(q, n.right) - } - } -} - -func LevelOrder(root *Node) []int { - traversal := make([]int, 0) - levelOrderRecursive(root, &traversal) - return traversal -} - -// AccessNodesByLayer Function that access nodes layer by layer instead of printing the results as one line. -func AccessNodesByLayer(root *Node) [][]int { - var res [][]int - if root == nil { - return res - } - var q []*Node - var n *Node - var idx = 0 - q = append(q, root) - - for len(q) != 0 { - res = append(res, []int{}) - qLen := len(q) - for i := 0; i < qLen; i++ { - n, q = q[0], q[1:] - res[idx] = append(res[idx], n.val) - if n.left != nil { - q = append(q, n.left) - } - if n.right != nil { - q = append(q, n.right) - } - } - idx++ - } - return res -} - -// Max Function that returns max of two numbers - possibly already declared. -func Max(a, b int) int { - if a > b { - return a - } - return b -} diff --git a/structure/binarysearchtree/bstree_test.go b/structure/binarysearchtree/bstree_test.go deleted file mode 100644 index f813063c6..000000000 --- a/structure/binarysearchtree/bstree_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package binarytree - -import ( - "reflect" - "testing" -) - -func TestInsert(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - - if root.val != 90 { - t.Errorf("root should have value = 90") - } - - if root.left.val != 80 { - t.Errorf("left child should have value = 80") - } - - if root.right.val != 100 { - t.Errorf("right child should have value = 100") - } - - if BSTree.Depth() != 2 { - t.Errorf("tree should have depth = 1") - } -} - -func TestDelete(t *testing.T) { - t.Run("Delete a node with no child", func(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - - BstDelete(root, 100) - - if root.val != 90 { - t.Errorf("root should have value = 90") - } - - if root.left.val != 80 { - t.Errorf("left child should have value = 80") - } - - if root.right != nil { - t.Errorf("right child should have value = nil") - } - - if BSTree.Depth() != 2 { - t.Errorf("Depth should have value = 2") - } - }) - - t.Run("Delete a node with one child", func(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - - BstDelete(root, 80) - - if root.val != 90 { - t.Errorf("root should have value = 90") - } - - if root.right.val != 100 { - t.Errorf("right child should have value = 100") - } - - if root.left.val != 70 { - t.Errorf("left child should have value = 70") - } - - if BSTree.Depth() != 2 { - t.Errorf("Depth should have value = 2") - } - }) - - t.Run("Delete a node with two children", func(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - - BstDelete(root, 80) - - if root.val != 90 { - t.Errorf("root should have value = 90") - } - - if root.left.val != 85 { - t.Errorf("left child should have value = 85") - } - - if root.right.val != 100 { - t.Errorf("right child should have value = 100") - } - - if BSTree.Depth() != 3 { - t.Errorf("Depth should have value = 3") - } - }) -} - -func TestInOrder(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - Insert(root, 95) - Insert(root, 105) - - a := InOrder(root) - b := []int{70, 80, 85, 90, 95, 100, 105} - - if !reflect.DeepEqual(a, b) { - t.Errorf("Nodes should have value = [70 80 85 90 95 100 105]") - } -} - -func TestPreOrder(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - Insert(root, 95) - Insert(root, 105) - - a := PreOrder(root) - b := []int{90, 80, 70, 85, 100, 95, 105} - - if !reflect.DeepEqual(a, b) { - t.Errorf("Nodes should have value = [90 80 70 85 100 95 105]") - } -} - -func TestPostOrder(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - Insert(root, 95) - Insert(root, 105) - - a := PostOrder(root) - b := []int{70, 85, 80, 95, 105, 100, 90} - - if !reflect.DeepEqual(a, b) { - t.Errorf("Nodes should have value = [70 85 80 95 105 100 90]") - } -} - -func TestLevelOrder(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - Insert(root, 95) - Insert(root, 105) - - a := LevelOrder(root) - b := []int{90, 80, 100, 70, 85, 95, 105} - - if !reflect.DeepEqual(a, b) { - t.Errorf("Nodes should have value = [90 80 100 70 85 95 105]") - } -} - -func TestAccessNodesByLayer(t *testing.T) { - BSTree := BSTree{ - Root: NewNode(90), - } - - root := BSTree.Root - - Insert(root, 80) - Insert(root, 100) - Insert(root, 70) - Insert(root, 85) - Insert(root, 95) - Insert(root, 105) - - a := AccessNodesByLayer(root) - b := [][]int{{90}, {80, 100}, {70, 85, 95, 105}} - - if !reflect.DeepEqual(a, b) { - t.Errorf("Nodes should have value = [[90] [80 100] [70 85 95 105]]") - } -} diff --git a/structure/binarysearchtree/node.go b/structure/binarysearchtree/node.go deleted file mode 100644 index 71d37ac8f..000000000 --- a/structure/binarysearchtree/node.go +++ /dev/null @@ -1,13 +0,0 @@ -package binarytree - -// Node structure for Nodes -type Node struct { - val int - left *Node - right *Node -} - -// NewNode Returns a new pointer to an empty Node -func NewNode(val int) *Node { - return &Node{val, nil, nil} -} diff --git a/structure/tree/avl.go b/structure/tree/avl.go new file mode 100644 index 000000000..7cb62d885 --- /dev/null +++ b/structure/tree/avl.go @@ -0,0 +1,188 @@ +package tree + +import ( + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math/max" +) + +type AVL[T constraints.Ordered] struct { + *binaryTree[T] +} + +// NewAVL create a novel AVL tree +func NewAVL[T constraints.Ordered]() *AVL[T] { + return &AVL[T]{ + binaryTree: &binaryTree[T]{ + Root: nil, + NIL: nil, + }, + } +} + +// Push a chain of Node's into the AVL Tree +func (avl *AVL[T]) Push(keys ...T) { + for _, k := range keys { + avl.Root = avl.pushHelper(avl.Root, k) + } +} + +// Delete a Node from the AVL Tree +func (avl *AVL[T]) Delete(key T) bool { + if !avl.Has(key) { + return false + } + + avl.Root = avl.deleteHelper(avl.Root, key) + return true +} + +func (avl *AVL[T]) pushHelper(root *Node[T], key T) *Node[T] { + if root == nil { + return &Node[T]{ + Key: key, + Height: 1, + } + } + + switch { + case key < root.Key: + root.Left = avl.pushHelper(root.Left, key) + case key > root.Key: + root.Right = avl.pushHelper(root.Right, key) + default: + return root + } + + // balance the tree + root.Height = avl.height(root) + bFactor := avl.balanceFactor(root) + if bFactor > 1 { + switch { + case key < root.Left.Key: + return avl.rightRotate(root) + case key > root.Left.Key: + root.Left = avl.leftRotate(root.Left) + return avl.rightRotate(root) + } + } + + if bFactor < -1 { + switch { + case key > root.Right.Key: + return avl.leftRotate(root) + case key < root.Right.Key: + root.Right = avl.rightRotate(root.Right) + return avl.leftRotate(root) + } + } + + return root +} + +func (avl *AVL[T]) deleteHelper(root *Node[T], key T) *Node[T] { + if root == nil { + return root + } + + switch { + case key < root.Key: + root.Left = avl.deleteHelper(root.Left, key) + case key > root.Key: + root.Right = avl.deleteHelper(root.Right, key) + default: + if root.Left == nil || root.Right == nil { + tmp := root.Left + if root.Left != nil { + tmp = root.Right + } + + if tmp == nil { + root = nil + } else { + *root = *tmp + } + } else { + tmp := avl.minimum(root.Right) + root.Key = tmp.Key + root.Right = avl.deleteHelper(root.Right, tmp.Key) + } + } + + if root == nil { + return root + } + + // balance the tree + root.Height = avl.height(root) + bFactor := avl.balanceFactor(root) + switch { + case bFactor > 1: + switch { + case avl.balanceFactor(root.Left) >= 0: + return avl.rightRotate(root) + default: + root.Left = avl.leftRotate(root.Left) + return avl.rightRotate(root) + } + case bFactor < -1: + switch { + case avl.balanceFactor(root.Right) <= 0: + return avl.leftRotate(root) + default: + root.Right = avl.rightRotate(root.Right) + return avl.leftRotate(root) + } + } + + return root +} + +func (avl *AVL[T]) height(root *Node[T]) int { + if root == nil { + return 0 + } + + var leftHeight, rightHeight int + if root.Left != nil { + leftHeight = root.Left.Height + } + if root.Right != nil { + rightHeight = root.Right.Height + } + return 1 + max.Int(leftHeight, rightHeight) +} + +// balanceFactor : negative balance factor means subtree Root is heavy toward Left +// and positive balance factor means subtree Root is heavy toward Right side +func (avl *AVL[T]) balanceFactor(root *Node[T]) int { + var leftHeight, rightHeight int + if root.Left != nil { + leftHeight = root.Left.Height + } + if root.Right != nil { + rightHeight = root.Right.Height + } + return leftHeight - rightHeight +} + +func (avl *AVL[T]) leftRotate(root *Node[T]) *Node[T] { + y := root.Right + yl := y.Left + y.Left = root + root.Right = yl + + root.Height = avl.height(root) + y.Height = avl.height(y) + return y +} + +func (avl *AVL[T]) rightRotate(root *Node[T]) *Node[T] { + y := root.Left + yr := y.Right + y.Right = root + root.Left = yr + + root.Height = avl.height(root) + y.Height = avl.height(y) + return y +} diff --git a/structure/tree/avl_test.go b/structure/tree/avl_test.go new file mode 100644 index 000000000..cbbc3581e --- /dev/null +++ b/structure/tree/avl_test.go @@ -0,0 +1,275 @@ +package tree_test + +import ( + "testing" + + bt "github.com/TheAlgorithms/Go/structure/tree" +) + +func TestAVLPush(t *testing.T) { + t.Run("LLRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + tree.Push(5, 4, 3) + + root := tree.Root + if root.Key != 4 { + t.Errorf("Root should have value = 4, not %v", root.Key) + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2, not %d", root.Height) + } + + if root.Left.Key != 3 { + t.Errorf("Left child should have value = 3") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 5 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + + }) + t.Run("LRRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + tree.Push(5, 3, 4) + + root := tree.Root + if root.Key != 4 { + t.Errorf("Root should have value = 4") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 3 { + t.Errorf("Left child should have value = 3") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 5 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + }) + + t.Run("RRRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + tree.Push(3) + tree.Push(4) + tree.Push(5) + + root := tree.Root + if root.Key != 4 { + t.Errorf("Root should have value = 4") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 3 { + t.Errorf("Left child should have value = 3") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 5 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + }) + t.Run("RLRotaion-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + tree.Push(3) + tree.Push(5) + tree.Push(4) + + root := tree.Root + if root.Key != 4 { + t.Errorf("Root should have value = 4") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 3 { + t.Errorf("Left child should have value = 3") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 5 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + }) +} + +func TestAVLDelete(t *testing.T) { + t.Run("LLRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + + tree.Push(5) + tree.Push(4) + tree.Push(3) + tree.Push(2) + + if !tree.Delete(5) { + t.Errorf("There is a node, whose value is 5") + } + + if tree.Delete(50) { + t.Errorf("There is no node, whose value is 50") + } + + root := tree.Root + if root.Key != 3 { + t.Errorf("Root should have value = 3") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 2 { + t.Errorf("Left child should have value = 2") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 4 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + }) + + t.Run("LRRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + + tree.Push(10) + tree.Push(8) + tree.Push(6) + tree.Push(7) + + if !tree.Delete(10) { + t.Errorf("There is a node, whose value is 10") + } + + if tree.Delete(5) { + t.Errorf("There is no node, whose value is 5") + } + + root := tree.Root + if root.Key != 7 { + t.Errorf("Root should have value = 7") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 6 { + t.Errorf("Left child should have value = 6") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 8 { + t.Errorf("Right child should have value = 8") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + + }) + + t.Run("RRRotation-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + + tree.Push(2) + tree.Push(3) + tree.Push(4) + tree.Push(5) + + if !tree.Delete(2) { + t.Errorf("There is a node, whose value is 2") + } + + if tree.Delete(15) { + t.Errorf("There is no node, whose value is 15") + } + + root := tree.Root + if root.Key != 4 { + t.Errorf("Root should have value = 4") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 3 { + t.Errorf("Left child should have value = 3") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 5 { + t.Errorf("Right child should have value = 5") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + + }) + + t.Run("RLRotaion-Test", func(t *testing.T) { + tree := bt.NewAVL[int]() + + tree.Push(7) + tree.Push(6) + tree.Push(9) + tree.Push(8) + + tree.Delete(6) + + root := tree.Root + if root.Key != 8 { + t.Errorf("Root should have value = 8") + } + if root.Height != 2 { + t.Errorf("Height of Root should be = 2") + } + + if root.Left.Key != 7 { + t.Errorf("Left child should have value = 7") + } + if root.Left.Height != 1 { + t.Errorf("Height of Left child should be 1") + } + + if root.Right.Key != 9 { + t.Errorf("Right child should have value = 9") + } + if root.Right.Height != 1 { + t.Errorf("Height of Right should be 1") + } + + }) +} diff --git a/structure/tree/bstree.go b/structure/tree/bstree.go new file mode 100644 index 000000000..72c0e4da2 --- /dev/null +++ b/structure/tree/bstree.go @@ -0,0 +1,78 @@ +// Binary search tree. +// +// For more details check out those links below here: +// Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree +// see bstree.go + +package tree + +import ( + "github.com/TheAlgorithms/Go/constraints" +) + +type BinarySearch[T constraints.Ordered] struct { + *binaryTree[T] +} + +// NewBinarySearch create a novel Binary-Search tree +func NewBinarySearch[T constraints.Ordered]() *BinarySearch[T] { + return &BinarySearch[T]{ + binaryTree: &binaryTree[T]{ + Root: nil, + NIL: nil, + }, + } +} + +// Push a chain of Node's into the BinarySearch +func (t *BinarySearch[T]) Push(keys ...T) { + for _, key := range keys { + t.Root = t.pushHelper(t.Root, key) + } +} + +// Delete removes the node of val +func (t *BinarySearch[T]) Delete(val T) bool { + if !t.Has(val) { + return false + } + t.deleteHelper(t.Root, val) + return true +} + +func (t *BinarySearch[T]) pushHelper(root *Node[T], val T) *Node[T] { + if root == nil { + return &Node[T]{Key: val, Left: nil, Right: nil} + } + if val < root.Key { + root.Left = t.pushHelper(root.Left, val) + } else { + root.Right = t.pushHelper(root.Right, val) + } + return root +} + +func (t *BinarySearch[T]) deleteHelper(root *Node[T], val T) *Node[T] { + if root == nil { + return nil + } + if val < root.Key { + root.Left = t.deleteHelper(root.Left, val) + } else if val > root.Key { + root.Right = t.deleteHelper(root.Right, val) + } else { + // this is the node to delete + // node with one child + if root.Left == nil { + return root.Right + } else if root.Right == nil { + return root.Left + } else { + n := root.Right + d := t.minimum(n) + d.Left = root.Left + return root.Right + } + } + return root +} diff --git a/structure/tree/bstree_test.go b/structure/tree/bstree_test.go new file mode 100644 index 000000000..094406487 --- /dev/null +++ b/structure/tree/bstree_test.go @@ -0,0 +1,149 @@ +package tree_test + +import ( + "testing" + + bt "github.com/TheAlgorithms/Go/structure/tree" +) + +func TestPush(t *testing.T) { + bst := bt.NewBinarySearch[int]() + + bst.Push(90) + bst.Push(80) + bst.Push(100) + + if bst.Root.Key != 90 { + t.Errorf("Root should have value = 90") + } + + if bst.Root.Left.Key != 80 { + t.Errorf("Left child should have value = 80") + } + + if bst.Root.Right.Key != 100 { + t.Errorf("Right child should have value = 100") + } + + if bst.Depth() != 2 { + t.Errorf("tree should have depth = 1") + } +} + +func TestDelete(t *testing.T) { + t.Run("Delete a node with no child", func(t *testing.T) { + bst := bt.NewBinarySearch[int]() + + bst.Push(90) + bst.Push(80) + bst.Push(100) + + if !bst.Delete(100) { + t.Errorf("There is a node, whose value is 100") + } + + if bst.Delete(105) { + t.Errorf("There is no node, whose value is 105") + } + + root := bst.Root + if root.Key != 90 { + t.Errorf("Root should have value = 90") + } + + if root.Left.Key != 80 { + t.Errorf("Left child should have value = 80") + } + + if root.Right != nil { + t.Errorf("Right child should have value = nil") + } + + if bst.Depth() != 2 { + t.Errorf("Depth should have value = 2") + } + + bst.Delete(80) + + if root.Key != 90 { + t.Errorf("Root should have value = 90") + } + + if root.Left != nil { + t.Errorf("Left child should have value = nil") + } + + if bst.Depth() != 1 { + t.Errorf("Depth should have value = 1") + } + }) + + t.Run("Delete a node with one child", func(t *testing.T) { + bst := bt.NewBinarySearch[int]() + + bst.Push(90) + bst.Push(80) + bst.Push(100) + bst.Push(70) + + if bst.Delete(102) { + t.Errorf("There is no node, whose value is 102") + } + + if !bst.Delete(80) { + t.Errorf("There is a node, whose value is 80") + } + + root := bst.Root + if root.Key != 90 { + t.Errorf("Root should have value = 90") + } + + if root.Right.Key != 100 { + t.Errorf("Right child should have value = 100") + } + + if root.Left.Key != 70 { + t.Errorf("Left child should have value = 70") + } + + if bst.Depth() != 2 { + t.Errorf("Depth should have value = 2") + } + }) + + t.Run("Delete a node with two children", func(t *testing.T) { + bst := bt.NewBinarySearch[int]() + + bst.Push(90) + bst.Push(80) + bst.Push(100) + bst.Push(70) + bst.Push(85) + + if !bst.Delete(80) { + t.Errorf("There is a node, whose value is 80") + } + + if bst.Delete(102) { + t.Errorf("There is no node, whose value is 102") + } + + root := bst.Root + if root.Key != 90 { + t.Errorf("Root should have value = 90") + } + + if root.Left.Key != 85 { + t.Errorf("Left child should have value = 85") + } + + if root.Right.Key != 100 { + t.Errorf("Right child should have value = 100") + } + + if bst.Depth() != 3 { + t.Errorf("Depth should have value = 3") + } + }) +} diff --git a/structure/tree/rbtree.go b/structure/tree/rbtree.go new file mode 100644 index 000000000..252c99930 --- /dev/null +++ b/structure/tree/rbtree.go @@ -0,0 +1,353 @@ +// Red-Black Tree is a kind of self-balancing binary search tree. +// Each node stores "Color" ("red" or "black"), used to ensure that the tree remains balanced during insertions and deletions. +// +// For more details check out those links below here: +// Programiz article : https://www.programiz.com/dsa/red-black-tree +// Wikipedia article: https://en.wikipedia.org/wiki/Red_black_tree +// authors [guuzaa](https://github.com/guuzaa) +// see rbtree.go + +package tree + +import ( + "fmt" + + "github.com/TheAlgorithms/Go/constraints" +) + +type RB[T constraints.Ordered] struct { + *binaryTree[T] +} + +// Create a new Red-Black Tree +func NewRB[T constraints.Ordered]() *RB[T] { + leaf := &Node[T]{Color: Black, Left: nil, Right: nil} + return &RB[T]{ + binaryTree: &binaryTree[T]{ + Root: leaf, + NIL: leaf, + }, + } +} + +// Push a chain of Node's into the Red-Black Tree +func (t *RB[T]) Push(keys ...T) { + for _, key := range keys { + t.pushHelper(t.Root, key) + } +} + +// Delete a node of Red-Black Tree +// Returns false if the node does not exist, otherwise returns true. +func (t *RB[T]) Delete(data T) bool { + return t.deleteHelper(t.Root, data) +} + +// Return the Predecessor of the node of Key +// if there is no predecessor, return default value of type T and false +// otherwise return the Key of predecessor and true +func (t *RB[T]) Predecessor(key T) (T, bool) { + node, ok := t.searchTreeHelper(t.Root, key) + if !ok { + return t.NIL.Key, ok + } + return t.predecessorHelper(node) +} + +// Return the Successor of the node of Key +// if there is no successor, return default value of type T and false +// otherwise return the Key of successor and true +func (t *RB[T]) Successor(key T) (T, bool) { + node, ok := t.searchTreeHelper(t.Root, key) + if !ok { + return t.NIL.Key, ok + } + + return t.successorHelper(node) +} + +func (t *RB[T]) pushHelper(x *Node[T], key T) { + node := &Node[T]{ + Key: key, + Left: t.NIL, + Right: t.NIL, + Parent: nil, + Color: Red, + } + + var y *Node[T] + for !t.isNil(x) { + y = x + if node.Key < x.Key { + x = x.Left + } else { + x = x.Right + } + + } + + node.Parent = y + if y == nil { + t.Root = node + } else if node.Key < y.Key { + y.Left = node + } else { + y.Right = node + } + + if node.Parent == nil { + node.Color = Black + return + } + + if node.Parent.Parent == nil { + return + } + + t.pushFix(node) +} + +func (t *RB[T]) leftRotate(x *Node[T]) { + y := x.Right + x.Right = y.Left + + if !t.isNil(y.Left) { + y.Left.Parent = x + } + + y.Parent = x.Parent + if x.Parent == nil { + t.Root = y + } else if x == x.Parent.Left { + x.Parent.Left = y + } else { + x.Parent.Right = y + } + + y.Left = x + x.Parent = y +} + +func (t *RB[T]) rightRotate(x *Node[T]) { + y := x.Left + x.Left = y.Right + if !t.isNil(y.Right) { + y.Right.Parent = x + } + + y.Parent = x.Parent + if x.Parent == nil { + t.Root = y + } else if x == y.Parent.Right { + y.Parent.Right = y + } else { + y.Parent.Left = y + } + + y.Right = x + x.Parent = y +} + +func (t *RB[T]) pushFix(k *Node[T]) { + var u *Node[T] + for k.Parent.Color == Red { + if k.Parent == k.Parent.Parent.Right { + u = k.Parent.Parent.Left + if u != nil && u.Color == Red { + u.Color = Black + k.Parent.Color = Black + k.Parent.Parent.Color = Red + k = k.Parent.Parent + } else { + if k == k.Parent.Left { + k = k.Parent + t.rightRotate(k) + } + k.Parent.Color = Black + k.Parent.Parent.Color = Red + t.leftRotate(k.Parent.Parent) + } + } else { + u = k.Parent.Parent.Right + if u != nil && u.Color == Red { + u.Color = Black + k.Parent.Color = Black + k.Parent.Parent.Color = Red + k = k.Parent.Parent + } else { + if k == k.Parent.Right { + k = k.Parent + t.leftRotate(k) + } + k.Parent.Color = Black + k.Parent.Parent.Color = Red + t.rightRotate(k.Parent.Parent) + } + } + if k == t.Root { + break + } + } + + t.Root.Color = Black +} + +func (t *RB[T]) deleteHelper(node *Node[T], key T) bool { + z := t.NIL + for !t.isNil(node) { + switch { + case node.Key == key: + z = node + fallthrough + case node.Key <= key: + node = node.Right + case node.Key > key: + node = node.Left + } + } + + if t.isNil(z) { + fmt.Println("Key not found in the tree") + return false + } + + var x *Node[T] + y := z + yOriginColor := y.Color + if t.isNil(z.Left) { + x = z.Right + t.rbTransplant(z, z.Right) + } else if t.isNil(z.Right) { + x = z.Left + t.rbTransplant(z, z.Left) + } else { + y = t.minimum(z.Right) + yOriginColor = y.Color + x = y.Right + if y.Parent == z { + x.Parent = y + } else { + t.rbTransplant(y, y.Right) + y.Right = z.Right + y.Right.Parent = y + } + + t.rbTransplant(z, y) + y.Left = z.Left + y.Left.Parent = y + y.Color = z.Color + } + + if yOriginColor == Black { + t.deleteFix(x) + } + + return true +} + +func (t *RB[T]) deleteFix(x *Node[T]) { + var s *Node[T] + for x != t.Root && x.Color == Black { + if x == x.Parent.Left { + s = x.Parent.Right + if s.Color == Red { + s.Color = Black + x.Parent.Color = Red + t.leftRotate(x.Parent) + s = x.Parent.Right + } + + if s.Left.Color == Black && s.Right.Color == Black { + s.Color = Red + x = x.Parent + } else { + if s.Right.Color == Black { + s.Left.Color = Black + s.Color = Red + t.rightRotate(s) + s = x.Parent.Right + } + + s.Color = x.Parent.Color + x.Parent.Color = Black + s.Right.Color = Black + t.leftRotate(x.Parent) + x = t.Root + } + } else { + s = x.Parent.Left + if s.Color == Red { + s.Color = Black + x.Parent.Color = Red + t.rightRotate(x.Parent) + s = x.Parent.Left + } + + if s.Right.Color == Black && s.Left.Color == Black { + s.Color = Red + x = x.Parent + } else { + if s.Left.Color == Black { + s.Right.Color = Black + s.Color = Red + t.leftRotate(s) + s = x.Parent.Left + } + + s.Color = x.Parent.Color + x.Parent.Color = Black + s.Left.Color = Black + t.rightRotate(x.Parent) + x = t.Root + } + } + } + + x.Color = Black +} + +func (t *RB[T]) rbTransplant(u, v *Node[T]) { + switch { + case u.Parent == nil: + t.Root = v + case u == u.Parent.Left: + u.Parent.Left = v + default: + u.Parent.Right = v + } + v.Parent = u.Parent +} + +func (t *RB[T]) predecessorHelper(node *Node[T]) (T, bool) { + if !t.isNil(node.Left) { + return t.maximum(node.Left).Key, true + } + + p := node.Parent + for p != nil && !t.isNil(p) && node == p.Left { + node = p + p = p.Parent + } + + if p == nil { + return t.NIL.Key, false + } + return p.Key, true +} + +func (t *RB[T]) successorHelper(node *Node[T]) (T, bool) { + if !t.isNil(node.Right) { + return t.minimum(node.Right).Key, true + } + + p := node.Parent + for p != nil && !t.isNil(p) && node == p.Right { + node = p + p = p.Parent + } + + if p == nil { + return t.NIL.Key, false + } + return p.Key, true +} diff --git a/structure/tree/rbtree_test.go b/structure/tree/rbtree_test.go new file mode 100644 index 000000000..25a8c37e1 --- /dev/null +++ b/structure/tree/rbtree_test.go @@ -0,0 +1,220 @@ +package tree_test + +import ( + "math/rand" + "sort" + "testing" + "time" + + bt "github.com/TheAlgorithms/Go/structure/tree" +) + +func TestRBTreePush(t *testing.T) { + tree := bt.NewRB[int]() + + ret := tree.InOrder() + + if !sort.IntsAreSorted(ret) || len(ret) != 0 { + t.Errorf("Error with Push: %v", ret) + } + + if r, ok := tree.Min(); ok { + t.Errorf("Error with Min: %v", r) + } + + if r, ok := tree.Max(); ok { + t.Errorf("Error with Max: %v", r) + } + + nums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 88, 1 << 32} + + tree.Push(nums...) + + ret = tree.InOrder() + + if !sort.IntsAreSorted(ret) || len(ret) != len(nums) { + t.Errorf("Error with Push: %v", ret) + } + + if r, ok := tree.Min(); !ok || ret[0] != r { + t.Errorf("Error with Min: %v", r) + } + + if r, ok := tree.Max(); !ok || ret[len(ret)-1] != r { + t.Errorf("Error with Max: %v", r) + } +} + +func TestRBTreeDelete(t *testing.T) { + tree := bt.NewRB[int]() + var ok bool + + nums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 88, 1 << 32} + tree.Push(nums...) + + ok = tree.Delete(188) + + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-1 { + t.Errorf("Error with Delete: %v", ret) + } + + ok = tree.Delete(188) + if ret := tree.InOrder(); ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-1 { + t.Errorf("Error with Delete: %v", ret) + } + + ok = tree.Delete(1<<63 - 1) + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-2 { + t.Errorf("Error with Delete: %v", ret) + } + + ok = tree.Delete(4) + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-3 { + t.Errorf("Error with Delete: %v", ret) + } + + ok = tree.Delete(4) + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-4 { + t.Errorf("Error with Delete: %v", ret) + } + + if ret, ok := tree.Max(); !ok || ret != (1<<32) { + t.Errorf("Error with Delete, max: %v, want: %v", ret, (1 << 32)) + } + + if ret, ok := tree.Min(); !ok || ret != -(1<<62) { + t.Errorf("Error with Delete, min: %v, want: %v", ret, (1 << 32)) + } +} + +func FuzzRBTree(f *testing.F) { + testcases := []int{100, 200, 1000, 10000} + for _, tc := range testcases { + f.Add(tc) + } + + f.Fuzz(func(t *testing.T, a int) { + rand.Seed(time.Now().Unix()) + tree := bt.NewRB[int]() + nums := rand.Perm(a) + tree.Push(nums...) + + rets := tree.InOrder() + if !sort.IntsAreSorted(rets) { + t.Error("Error with Push") + } + + if res, ok := tree.Min(); !ok || res != rets[0] { + t.Errorf("Error with Min, get %d, want: %d", res, rets[0]) + } + + if res, ok := tree.Max(); !ok || res != rets[a-1] { + t.Errorf("Error with Max, get %d, want: %d", res, rets[a-1]) + } + + for i := 0; i < a-1; i++ { + ok := tree.Delete(nums[i]) + rets = tree.InOrder() + if !ok || !sort.IntsAreSorted(rets) { + t.Errorf("Error With Delete") + } + } + }) +} + +func TestRBTreePredecessorAndSuccessor(t *testing.T) { + tree := bt.NewRB[int]() + + nums := []int{10, 8, 88, 888, 4, -1, 100} + tree.Push(nums...) + + if ret, ok := tree.Predecessor(100); !ok && ret == 88 { + t.Errorf("Error with Predecessor") + } + + if _, ok := tree.Predecessor(-1); ok { + t.Errorf("Error with Predecessor") + } + + if _, ok := tree.Predecessor(-12); ok { + t.Errorf("Error with Predecessor") + } + + if ret, ok := tree.Predecessor(4); !ok && ret == -1 { + t.Errorf("Error with Predecessor") + } + + if ret, ok := tree.Successor(4); !ok && ret == 8 { + t.Errorf("Error with Successor") + } + + if ret, ok := tree.Successor(8); !ok && ret == 88 { + t.Errorf("Error with Successor") + } + + if ret, ok := tree.Successor(88); !ok && ret == 100 { + t.Errorf("Error with Successor") + } + + if ret, ok := tree.Successor(100); !ok && ret == 888 { + t.Errorf("Error with Successor") + } + + if ret, ok := tree.Successor(-1); !ok && ret == 4 { + t.Errorf("Error with Successor") + } + + if _, ok := tree.Successor(888); ok { + t.Errorf("Error with Successor") + } + + if _, ok := tree.Successor(188); ok { + t.Errorf("Error with Successor") + } +} + +func TestRBTreeString(t *testing.T) { + tree := bt.NewRB[string]() + + if tree.Has("Golang") { + t.Errorf("Error with Has when T is string.") + } + + strs := []string{"Hello", "World", "Golang", "Python", "Rust", "C", "JavaScript", "Haskell", "Pascal", "ZZ"} + for _, str := range strs { + tree.Push(str) + } + + if !tree.Has("Golang") { + t.Errorf("Error with Has when T is string.") + } + + if tree.Has("Pasc") { + t.Errorf("Error with Has when T is string.") + } + + if ok := tree.Delete("Hello"); !ok { + t.Errorf("Error with Delete when T is string.") + } + + if ok := tree.Delete("Pasc"); ok { + t.Errorf("Error with Delete when T is string.") + } + + if tree.Has("Hello") { + t.Errorf("Error with Has when T is string.") + } + + ret := tree.InOrder() + if !sort.StringsAreSorted(ret) { + t.Errorf("Error with Push when T is string") + } + + if ret, ok := tree.Min(); !ok || ret != "C" { + t.Errorf("Error with Min when T is string") + } + + if ret, ok := tree.Max(); !ok || ret != "ZZ" { + t.Errorf("Error with Max when T is string") + } +} diff --git a/structure/tree/tree.go b/structure/tree/tree.go new file mode 100644 index 000000000..b7ec06fc8 --- /dev/null +++ b/structure/tree/tree.go @@ -0,0 +1,283 @@ +// Binary-Search tree is the tree, with the key of each internal node +// being greater than keys in the respective node's left subtree +// and less than the ones in its right subtree. + +// For more details check out those links below here: +// Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree +// authors [guuzaa](https://github.com/guuzaa) +package tree + +import ( + "fmt" + + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math/max" +) + +type Color byte + +const ( + Red Color = iota + Black +) + +// Node of a binary tree +type Node[T constraints.Ordered] struct { + Key T + Parent *Node[T] // for Red-Black Tree + Left *Node[T] + Right *Node[T] + Color Color // for Red-Black Tree + Height int // for AVL Tree +} + +// binaryTree is a base-struct for BinarySearch, AVL, RB, etc. +// Note: to avoid instantiation, we make the base struct un-exported. +type binaryTree[T constraints.Ordered] struct { + Root *Node[T] + NIL *Node[T] // NIL denotes the leaf node of Red-Black Tree +} + +// Get a Node from the binary-search Tree +func (t *binaryTree[T]) Get(key T) (*Node[T], bool) { + return t.searchTreeHelper(t.Root, key) +} + +// Determines the tree has the node of Key +func (t *binaryTree[T]) Has(key T) bool { + _, ok := t.searchTreeHelper(t.Root, key) + return ok +} + +// Traverses the tree in the following order Root --> Left --> Right +func (t *binaryTree[T]) PreOrder() []T { + traversal := make([]T, 0) + t.preOrderRecursive(t.Root, &traversal) + return traversal +} + +// Traverses the tree in the following order Left --> Root --> Right +func (t *binaryTree[T]) InOrder() []T { + return t.inOrderHelper(t.Root) +} + +// Traverses the tree in the following order Left --> Right --> Root +func (t *binaryTree[T]) PostOrder() []T { + traversal := make([]T, 0) + t.postOrderRecursive(t.Root, &traversal) + return traversal +} + +// Depth returns the calculated depth of a binary search tree +func (t *binaryTree[T]) Depth() int { + return t.calculateDepth(t.Root, 0) +} + +// Returns the Max value of the tree +func (t *binaryTree[T]) Max() (T, bool) { + ret := t.maximum(t.Root) + if t.isNil(ret) { + return t.NIL.Key, false + } + + return ret.Key, true +} + +// Return the Min value of the tree +func (t *binaryTree[T]) Min() (T, bool) { + ret := t.minimum(t.Root) + if t.isNil(ret) { + return t.NIL.Key, false + } + + return ret.Key, true +} + +// LevelOrder returns the level order traversal of the tree +func (t *binaryTree[T]) LevelOrder() []T { + traversal := make([]T, 0) + t.levelOrderHelper(t.Root, &traversal) + return traversal +} + +// AccessNodesByLayer accesses nodes layer by layer (2-D array), instead of printing the results as 1-D array. +func (t *binaryTree[T]) AccessNodesByLayer() [][]T { + root := t.Root + if t.isNil(root) { + return [][]T{} + } + var q []*Node[T] + var n *Node[T] + var idx = 0 + q = append(q, root) + var res [][]T + + for len(q) != 0 { + res = append(res, []T{}) + qLen := len(q) + for i := 0; i < qLen; i++ { + n, q = q[0], q[1:] + res[idx] = append(res[idx], n.Key) + if !t.isNil(n.Left) { + q = append(q, n.Left) + } + if !t.isNil(n.Right) { + q = append(q, n.Right) + } + } + idx++ + } + return res +} + +// Print the tree horizontally +func (t *binaryTree[T]) Print() { + t.printHelper(t.Root, "", false) +} + +// Determines node is a leaf node +func (t *binaryTree[T]) isNil(node *Node[T]) bool { + return node == t.NIL +} + +func (t *binaryTree[T]) searchTreeHelper(node *Node[T], key T) (*Node[T], bool) { + if node == nil || t.isNil(node) { + return node, false + } + + if key == node.Key { + return node, true + } + + if key < node.Key { + return t.searchTreeHelper(node.Left, key) + } + return t.searchTreeHelper(node.Right, key) +} + +// The iterative inorder; +// The recursive way is similar to the preOrderRecursive +func (t *binaryTree[T]) inOrderHelper(node *Node[T]) []T { + var stack []*Node[T] + var ret []T + + for !t.isNil(node) || len(stack) > 0 { + for !t.isNil(node) { + stack = append(stack, node) + node = node.Left + } + + node = stack[len(stack)-1] + stack = stack[:len(stack)-1] + ret = append(ret, node.Key) + node = node.Right + } + + return ret +} + +func (t *binaryTree[T]) preOrderRecursive(n *Node[T], traversal *[]T) { + if t.isNil(n) { + return + } + + *traversal = append(*traversal, n.Key) + t.preOrderRecursive(n.Left, traversal) + t.preOrderRecursive(n.Right, traversal) +} + +func (t *binaryTree[T]) postOrderRecursive(n *Node[T], traversal *[]T) { + if t.isNil(n) { + return + } + + t.postOrderRecursive(n.Left, traversal) + t.postOrderRecursive(n.Right, traversal) + *traversal = append(*traversal, n.Key) +} + +func (t *binaryTree[T]) calculateDepth(n *Node[T], depth int) int { + if t.isNil(n) { + return depth + } + + return max.Int(t.calculateDepth(n.Left, depth+1), t.calculateDepth(n.Right, depth+1)) +} + +// Returns the minimum value of node of the tree +func (t *binaryTree[T]) minimum(node *Node[T]) *Node[T] { + if t.isNil(node) { + return node + } + + for !t.isNil(node.Left) { + node = node.Left + } + return node +} + +// Returns the maximum value of node of the tree +func (t *binaryTree[T]) maximum(node *Node[T]) *Node[T] { + if t.isNil(node) { + return node + } + + for !t.isNil(node.Right) { + node = node.Right + } + return node +} + +func (t *binaryTree[T]) levelOrderHelper(root *Node[T], traversal *[]T) { + var q []*Node[T] // queue + var tmp *Node[T] + + q = append(q, root) + + for len(q) != 0 { + tmp, q = q[0], q[1:] + *traversal = append(*traversal, tmp.Key) + if !t.isNil(tmp.Left) { + q = append(q, tmp.Left) + } + + if !t.isNil(tmp.Right) { + q = append(q, tmp.Right) + } + } +} + +// Reference: https://stackoverflow.com/a/51730733/15437172 +func (t *binaryTree[T]) printHelper(root *Node[T], indent string, isLeft bool) { + if t.isNil(root) { + return + } + + fmt.Print(indent) + if isLeft { + fmt.Print("├──") + indent += "│ " + } else { + fmt.Print("└──") + indent += " " + } + + if t.isRBTree() { + color := "Black" + if root.Color == Red { + color = "Red" + } + + fmt.Println(root.Key, "(", color, ")") + } else { + fmt.Println(root.Key) + } + + t.printHelper(root.Left, indent, true) + t.printHelper(root.Right, indent, false) +} + +// Determines the tree is RB +func (t *binaryTree[T]) isRBTree() bool { + return t.NIL != nil +} diff --git a/structure/tree/tree_test.go b/structure/tree/tree_test.go new file mode 100644 index 000000000..2426e57e6 --- /dev/null +++ b/structure/tree/tree_test.go @@ -0,0 +1,626 @@ +package tree_test + +import ( + "math/rand" + "reflect" + "sort" + "testing" + + bt "github.com/TheAlgorithms/Go/structure/tree" +) + +func TestTreeGetOrHas(t *testing.T) { + lens := []int{100, 1_000, 10_000, 100_000} + for _, ll := range lens { + nums := rand.Perm(ll) + t.Run("Test Binary Search Tree", func(t *testing.T) { + bsTree := bt.NewBinarySearch[int]() + bsTree.Push(nums...) + for _, num := range nums { + if !bsTree.Has(num) { + t.Errorf("Error with Has or Push method") + } + } + min, _ := bsTree.Min() + max, _ := bsTree.Max() + + if _, ok := bsTree.Get(min - 1); ok { + t.Errorf("Error with Get method") + } + + if _, ok := bsTree.Get(max + 1); ok { + t.Errorf("Error with Get method") + } + }) + + t.Run("Test Red-Black Tree", func(t *testing.T) { + rbTree := bt.NewRB[int]() + rbTree.Push(nums...) + for _, num := range nums { + if !rbTree.Has(num) { + t.Errorf("Error with Has or Push method") + } + } + }) + + t.Run("Test AVL Tree", func(t *testing.T) { + avlTree := bt.NewAVL[int]() + avlTree.Push(nums...) + for _, num := range nums { + if !avlTree.Has(num) { + t.Errorf("Error with Has or Push method") + } + } + }) + } +} + +func TestTreePreOrder(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{90, 80, 70, 1, 21, 31, 41, 51, 61, 71, 85, 100, 95, 105}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}}, + } + for _, tt := range tests { + tree := bt.NewBinarySearch[int]() + tree.Push(tt.input...) + if ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("Error with PreOrder") + } + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{70, 41, 21, 1, 31, 51, 61, 90, 80, 71, 85, 100, 95, 105}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 3, 2, 1, 5, 4, 6, 9, 8, 10}}, + } + for _, tt := range tests { + tree := bt.NewAVL[int]() + tree.Push(tt.input...) + if ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("Error with PreOrder") + } + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{80, 41, 21, 1, 31, 61, 51, 70, 71, 90, 85, 100, 95, 105}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 5, 3, 2, 1, 4, 6, 9, 8, 10}}, + } + for _, tt := range tests { + tree := bt.NewRB[int]() + tree.Push(tt.input...) + if ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("Error with PreOrder") + } + } + }) +} + +func TestTreeInOrder(t *testing.T) { + lens := []int{100, 1_000, 10_000, 100_000} + for _, ll := range lens { + nums := rand.Perm(ll) + + t.Run("Test Binary Search Tree", func(t *testing.T) { + bsTree := bt.NewBinarySearch[int]() + bsTree.Push(nums...) + if ret := bsTree.InOrder(); !sort.IntsAreSorted(ret) { + t.Errorf("Error with InOrder") + } + }) + + t.Run("Test Red-Black Tree", func(t *testing.T) { + rbTree := bt.NewRB[int]() + rbTree.Push(nums...) + if ret := rbTree.InOrder(); !sort.IntsAreSorted(ret) { + t.Errorf("Error with InOrder") + } + }) + + t.Run("Test AVL Tree", func(t *testing.T) { + avlTree := bt.NewAVL[int]() + avlTree.Push(nums...) + if ret := avlTree.InOrder(); !sort.IntsAreSorted(ret) { + t.Errorf("Error with InOrder") + } + }) + } +} + +func TestTreePostOrder(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{61, 51, 41, 31, 21, 1, 71, 70, 85, 80, 95, 105, 100, 90}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}, + } + for i, tt := range tests { + tree := bt.NewBinarySearch[int]() + tree.Push(tt.input...) + if ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with Post", i) + } + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{1, 31, 21, 61, 51, 41, 71, 85, 80, 95, 105, 100, 90, 70}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 6, 5, 3, 8, 10, 9, 7}}, + } + for i, tt := range tests { + tree := bt.NewAVL[int]() + tree.Push(tt.input...) + if ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with PostOrder", i) + } + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{1, 31, 21, 51, 71, 70, 61, 41, 85, 95, 105, 100, 90, 80}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 3, 6, 5, 8, 10, 9, 7}}, + } + for i, tt := range tests { + tree := bt.NewRB[int]() + tree.Push(tt.input...) + if ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with PostOrder", i) + } + } + }) +} + +func TestTreeLevelOrder(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{90, 80, 100, 70, 85, 95, 105, 1, 71, 21, 31, 41, 51, 61}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}}, + } + for i, tt := range tests { + tree := bt.NewBinarySearch[int]() + tree.Push(tt.input...) + if ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with LevelOrder", i) + } + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{70, 41, 90, 21, 51, 80, 100, 1, 31, 61, 71, 85, 95, 105}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 3, 9, 2, 5, 8, 10, 1, 4, 6}}, + } + for i, tt := range tests { + tree := bt.NewAVL[int]() + tree.Push(tt.input...) + if ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with LevelOrder", i) + } + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{80, 41, 90, 21, 61, 85, 100, 1, 31, 51, 70, 95, 105, 71}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 5, 9, 3, 6, 8, 10, 2, 4, 1}}, + } + for i, tt := range tests { + tree := bt.NewRB[int]() + tree.Push(tt.input...) + if ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with LevelOrder %v", i, ret) + } + } + }) +} + +func TestTreeMinAndMax(t *testing.T) { + lens := []int{500, 1_000, 10_000} + for _, ll := range lens { + nums := rand.Perm(ll) + sort.Ints(nums) + + t.Run("Test Binary Search Tree", func(t *testing.T) { + bsTree := bt.NewBinarySearch[int]() + bsTree.Push(nums...) + if min, ok := bsTree.Min(); !ok || min != nums[0] { + t.Errorf("Error with Min method.") + } + if max, ok := bsTree.Max(); !ok || max != nums[ll-1] { + t.Errorf("Error with Max method.") + } + }) + + t.Run("Test Red-Black Tree", func(t *testing.T) { + rbTree := bt.NewRB[int]() + rbTree.Push(nums...) + if min, ok := rbTree.Min(); !ok || min != nums[0] { + t.Errorf("Error with Min method.") + } + if max, ok := rbTree.Max(); !ok || max != nums[ll-1] { + t.Errorf("Error with Max method.") + } + }) + + t.Run("Test AVL Tree", func(t *testing.T) { + avlTree := bt.NewAVL[int]() + avlTree.Push(nums...) + if min, ok := avlTree.Min(); !ok || min != nums[0] { + t.Errorf("Error with Min method.") + } + + if max, ok := avlTree.Max(); !ok || max != nums[ll-1] { + t.Errorf("Error with Max method.") + } + }) + } +} + +func TestTreeDepth(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want int + }{ + {[]int{}, 0}, + {[]int{90, 80, 100, 70, 85, 95, 105}, 3}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 9}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 10}, + } + for _, tt := range tests { + tree := bt.NewBinarySearch[int]() + tree.Push(tt.input...) + if ret := tree.Depth(); ret != tt.want { + t.Errorf("Error with Depth") + } + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want int + }{ + {[]int{}, 0}, + {[]int{90, 80, 100, 70, 85, 95, 105}, 3}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 4}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 4}, + } + for i, tt := range tests { + tree := bt.NewAVL[int]() + tree.Push(tt.input...) + if ret := tree.Depth(); ret != tt.want { + t.Errorf("#%d Error with Depth", i) + } + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want int + }{ + {[]int{}, 0}, + {[]int{90, 80, 100, 70, 85, 95, 105}, 3}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 5}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 5}, + } + for i, tt := range tests { + tree := bt.NewRB[int]() + tree.Push(tt.input...) + if ret := tree.Depth(); ret != tt.want { + t.Errorf("#%d Error with Depth", i) + } + } + }) +} + +func TestTreePrint(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{61, 51, 41, 31, 21, 1, 71, 70, 85, 80, 95, 105, 100, 90}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}, + } + for _, tt := range tests { + tree := bt.NewBinarySearch[int]() + t.Log(reflect.TypeOf(tree).String()) + tree.Push(tt.input...) + tree.Print() + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{1, 31, 21, 61, 51, 41, 71, 85, 80, 95, 105, 100, 90, 70}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 6, 5, 3, 8, 10, 9, 7}}, + } + for _, tt := range tests { + tree := bt.NewAVL[int]() + t.Log(reflect.TypeOf(tree).String()) + tree.Push(tt.input...) + tree.Print() + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want []int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + []int{1, 31, 21, 51, 71, 70, 61, 41, 85, 95, 105, 100, 90, 80}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 3, 6, 5, 8, 10, 9, 7}}, + } + for _, tt := range tests { + tree := bt.NewRB[int]() + t.Log(reflect.TypeOf(tree).String() == "*tree.RB[int]") + tree.Push(tt.input...) + tree.Print() + } + }) +} + +func TestTreeAccessNodesByLayer(t *testing.T) { + t.Run("Test for Binary-Search Tree", func(t *testing.T) { + tests := []struct { + input []int + want [][]int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + [][]int{{90}, {80, 100}, {70, 85, 95, 105}, {1, 71}, {21}, {31}, {41}, {51}, {61}}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{10}, {9}, {8}, {7}, {6}, {5}, {4}, {3}, {2}, {1}}}, + {[]int{}, [][]int{}}, + } + for i, tt := range tests { + tree := bt.NewBinarySearch[int]() + tree.Push(tt.input...) + if ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with AccessNoedsByLayer", i) + } + } + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tests := []struct { + input []int + want [][]int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + [][]int{{70}, {41, 90}, {21, 51, 80, 100}, {1, 31, 61, 71, 85, 95, 105}}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{7}, {3, 9}, {2, 5, 8, 10}, {1, 4, 6}}}, + {[]int{}, [][]int{}}, + } + for i, tt := range tests { + tree := bt.NewAVL[int]() + tree.Push(tt.input...) + if ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with AccessNoedsByLayer", i) + } + } + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tests := []struct { + input []int + want [][]int + }{ + {[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}}, + {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, + [][]int{{80}, {41, 90}, {21, 61, 85, 100}, {1, 31, 51, 70, 95, 105}, {71}}}, + {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{7}, {5, 9}, {3, 6, 8, 10}, {2, 4}, {1}}}, + {[]int{}, [][]int{}}, + } + for i, tt := range tests { + tree := bt.NewRB[int]() + t.Log(reflect.TypeOf(tree).String() == "*tree.RB[int]") + tree.Push(tt.input...) + if ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) { + t.Errorf("#%d Error with AccessNoedsByLayer, %v", i, ret) + } + } + }) +} + +// Benchmark the comparisons between BST, AVL and RB Tree +const testNum = 10_000 + +func BenchmarkBSTree_Insert(b *testing.B) { + helper := func() { + tree := bt.NewBinarySearch[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkBSTree_Has(b *testing.B) { + helper := func() { + tree := bt.NewBinarySearch[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Has(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkBSTree_Delete(b *testing.B) { + helper := func() { + tree := bt.NewBinarySearch[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Delete(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkRBTree_Insert(b *testing.B) { + helper := func() { + tree := bt.NewRB[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkRBTree_Has(b *testing.B) { + helper := func() { + tree := bt.NewRB[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Has(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkRBTree_Delete(b *testing.B) { + helper := func() { + tree := bt.NewRB[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Delete(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkAVLTree_Insert(b *testing.B) { + helper := func() { + tree := bt.NewAVL[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } + +} + +func BenchmarkAVLTree_Has(b *testing.B) { + helper := func() { + tree := bt.NewAVL[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Has(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} + +func BenchmarkAVLTree_Delete(b *testing.B) { + helper := func() { + tree := bt.NewAVL[int]() + for i := 1; i <= testNum; i++ { + tree.Push(i) + } + + for i := 1; i <= testNum; i++ { + tree.Delete(i) + } + } + + for i := 0; i < b.N; i++ { + helper() + } +} From ff6275bac67cc1927ece6f999ef99467136d0fa0 Mon Sep 17 00:00:00 2001 From: zafar hussain Date: Thu, 20 Oct 2022 06:22:30 +0500 Subject: [PATCH 090/202] chore: update Discord invite link (#576) Co-authored-by: David Leal --- CONTRIBUTING.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 738f6cb7f..2a2565430 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## Before contributing -Welcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/Go/issues/new/choose) or ask in our [Discord server](https://discord.gg/c7MnfGFGa6) / [Gitter](https://gitter.im/TheAlgorithms), and clearly state your concerns. +Welcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/Go/issues/new/choose) or ask in our [Discord server](https://the-algorithms.com/discord/) / [Gitter](https://gitter.im/TheAlgorithms), and clearly state your concerns. ## Contributing diff --git a/README.md b/README.md index 04ef156d0..41d5ee29c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![godocmd](https://github.com/tjgurwara99/Go/workflows/godocmd/badge.svg) ![](https://img.shields.io/github/repo-size/TheAlgorithms/Go.svg?label=Repo%20size&style=flat-square)  ![update_directory_md](https://github.com/TheAlgorithms/Go/workflows/update_directory_md/badge.svg) -[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6)  +[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://the-algorithms.com/discord/)  ### Algorithms implemented in Go (for education) From f401e73a692941824e67e5cd24ef8441c196adb5 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 20 Oct 2022 13:30:37 +0200 Subject: [PATCH 091/202] fix: correct the implementation of `LcsDp` (#577) --- dynamic/longestpalindromicsubsequence.go | 23 +++++------ dynamic/longestpalindromicsubsequence_test.go | 40 +++++++++++++++++++ 2 files changed, 49 insertions(+), 14 deletions(-) create mode 100644 dynamic/longestpalindromicsubsequence_test.go diff --git a/dynamic/longestpalindromicsubsequence.go b/dynamic/longestpalindromicsubsequence.go index 9ec9af31f..bc5df07b6 100644 --- a/dynamic/longestpalindromicsubsequence.go +++ b/dynamic/longestpalindromicsubsequence.go @@ -3,8 +3,7 @@ package dynamic -// LpsRec function -func LpsRec(word string, i, j int) int { +func lpsRec(word string, i, j int) int { if i == j { return 1 } @@ -12,9 +11,14 @@ func LpsRec(word string, i, j int) int { return 0 } if word[i] == word[j] { - return 2 + LpsRec(word, i+1, j-1) + return 2 + lpsRec(word, i+1, j-1) } - return Max(LpsRec(word, i, j-1), LpsRec(word, i+1, j)) + return Max(lpsRec(word, i, j-1), lpsRec(word, i+1, j)) +} + +// LpsRec function +func LpsRec(word string) int { + return lpsRec(word, 0, len(word)-1) } // LpsDp function @@ -43,14 +47,5 @@ func LpsDp(word string) int { } } - return dp[1][N-1] -} - -/* -func main() { - // word := "aaabbbbababbabbabbabf" - word := "aaaabbbba" - fmt.Printf("%d\n", lpsRec(word, 0, len(word)-1)) - fmt.Printf("%d\n", lpsDp(word)) + return dp[0][N-1] } -*/ diff --git a/dynamic/longestpalindromicsubsequence_test.go b/dynamic/longestpalindromicsubsequence_test.go new file mode 100644 index 000000000..34a8f2590 --- /dev/null +++ b/dynamic/longestpalindromicsubsequence_test.go @@ -0,0 +1,40 @@ +package dynamic_test + +import ( + "fmt" + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +func lpsTestTemplate(t *testing.T, algorithm func(input string) int) { + testCases := []struct { + input string + expected int + }{ + {"BBABCBCAB", 7}, + {"BBBAB", 4}, + {"ABBD", 2}, + {"GEEKSFORGEEKS", 5}, + {"abcdefgh", 1}, + {"bbbab", 4}, + {"cbbd", 2}, + {"racexyzcxar", 7}, + } + for _, tc := range testCases { + t.Run(fmt.Sprint("test with ", tc.input), func(t *testing.T) { + result := algorithm(tc.input) + if tc.expected != result { + t.Fatalf("expected %d, got %d", tc.expected, result) + } + }) + } +} + +func TestLpsRec(t *testing.T) { + lpsTestTemplate(t, dynamic.LpsRec) +} + +func TestLpsDp(t *testing.T) { + lpsTestTemplate(t, dynamic.LpsDp) +} From 138937e523db90a794326bd9617b5ced161a61dc Mon Sep 17 00:00:00 2001 From: David Leal Date: Sat, 22 Oct 2022 19:30:33 -0500 Subject: [PATCH 092/202] docs: convert issue templates to issue forms (#581) * docs: convert issue templates to issue forms * fix: minor template issues --- .github/ISSUE_TEMPLATE/bug_report.md | 27 ----------- .github/ISSUE_TEMPLATE/bug_report.yml | 45 +++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 1 + .../new-optimize-implementation.md | 20 --------- .github/ISSUE_TEMPLATE/new_implementation.yml | 38 ++++++++++++++++ .github/ISSUE_TEMPLATE/other.yml | 22 +++++++++ 6 files changed, 106 insertions(+), 47 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml delete mode 100644 .github/ISSUE_TEMPLATE/new-optimize-implementation.md create mode 100644 .github/ISSUE_TEMPLATE/new_implementation.yml create mode 100644 .github/ISSUE_TEMPLATE/other.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 160740ee5..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: bug -assignees: '' - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Additional context** -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..047b3e299 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,45 @@ +name: "Bug report" +description: "Create a report to help us improve" +title: "[BUG]" +labels: ["bug"] +body: + - type: textarea + id: description + attributes: + label: "Description" + description: "A clear and concise description of what the bug is." + validations: + required: true + - type: textarea + id: steps + attributes: + label: "Steps to reproduce" + description: "Steps to reproduce the behavior (if applicable)" + placeholder: | + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: false + - type: textarea + id: exceptedbhv + attributes: + label: "Excepted behavior" + description: "A clear and concise description of what you expected to happen." + validations: + required: true + - type: textarea + id: screenshots + attributes: + label: "Screenshots" + description: "If applicable, add screenshots to help explain your problem." + validations: + required: false + - type: textarea + id: context + attributes: + label: "Additional context" + description: "Add any other context about the problem here." + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..3ba13e0ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/new-optimize-implementation.md b/.github/ISSUE_TEMPLATE/new-optimize-implementation.md deleted file mode 100644 index db6cb5224..000000000 --- a/.github/ISSUE_TEMPLATE/new-optimize-implementation.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: New/Optimize implementation -about: Propose an enhancement or a new algorithm implementation. -title: '' -labels: enhancement -assignees: '' - ---- - -**Description** -Provide a clear and concise description of the issue. - -For new implementation: -- Name and problem statement for the algorithm. - -For enhancement: -- Specify what needs to be changed and why. For example: - - Adding tests. - - Optimizing logic. - - Refactoring file and folders for better structure. diff --git a/.github/ISSUE_TEMPLATE/new_implementation.yml b/.github/ISSUE_TEMPLATE/new_implementation.yml new file mode 100644 index 000000000..b2153a022 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new_implementation.yml @@ -0,0 +1,38 @@ +name: "New or optimize implementation" +description: "Propose an enhancement or a new algorithm implementation." +title: "[ENHANCEMENT]" +labels: ["enhancement"] +body: + - type: textarea + id: description + attributes: + label: What would you like to share? + description: Provide a clear and concise explanation of your issue. + validations: + required: true + - type: markdown + attributes: + value: | + " + For new implementations, please specify the name and problem statement for the algorithm. + For algorithm enhancements, specify what needs to be changed and why. For example: + + - Adding tests. + - Optimizing logic. + - Refactoring the file and folders for better structure. + + " + - type: textarea + id: issuedetails + attributes: + label: "Extra issue details" + description: "Write down all the issue/algorithm details mentioned above." + validations: + required: true + - type: textarea + id: extrainfo + attributes: + label: Additional information + description: Is there anything else we should know about this issue? + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/other.yml b/.github/ISSUE_TEMPLATE/other.yml new file mode 100644 index 000000000..14824ba9f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/other.yml @@ -0,0 +1,22 @@ +name: Other +description: Use this for any other issues. Do NOT create blank issues +title: "[OTHER]" +labels: ["awaiting triage"] +body: + - type: markdown + attributes: + value: "# Other issue" + - type: textarea + id: issuedescription + attributes: + label: What would you like to share? + description: Provide a clear and concise explanation of your issue. + validations: + required: true + - type: textarea + id: extrainfo + attributes: + label: Additional information + description: Is there anything else we should know about this issue? + validations: + required: false From b9ee52cb7798050f00af822d01de43402b6defa2 Mon Sep 17 00:00:00 2001 From: AHSKR <87699700+kalyan-arepalle@users.noreply.github.com> Date: Mon, 24 Oct 2022 17:31:38 +0530 Subject: [PATCH 093/202] feat: add sets algorithms for proper subset and proper superset check (#587) * feat: add sets algorithms for proper subset and proper superset check * review changes --- structure/set/set.go | 20 ++++++++++++++++++++ structure/set/set_test.go | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/structure/set/set.go b/structure/set/set.go index 9adef5c48..811ec717e 100644 --- a/structure/set/set.go +++ b/structure/set/set.go @@ -28,8 +28,14 @@ type Set interface { In(item any) bool // IsSubsetOf: checks whether set is subset of set2 or not. IsSubsetOf(set2 Set) bool + // IsProperSubsetOf: checks whether set is proper subset of set2 or not. + // ex: [1,2,3] proper subset of [1,2,3,4] -> true + IsProperSubsetOf(set2 Set) bool // IsSupersetOf: checks whether set is superset of set2 or not. IsSupersetOf(set2 Set) bool + // IsProperSupersetOf: checks whether set is proper superset of set2 or not. + // ex: [1,2,3,4] proper superset of [1,2,3] -> true + IsProperSupersetOf(set2 Set) bool // Union: gives new union set of both sets. // ex: [1,2,3] union [3,4,5] -> [1,2,3,4,5] Union(set2 Set) Set @@ -88,10 +94,24 @@ func (st *set) IsSubsetOf(superSet Set) bool { return true } +func (st *set) IsProperSubsetOf(superSet Set) bool { + if st.Len() == superSet.Len() { + return false + } + return st.IsSubsetOf(superSet) +} + func (st *set) IsSupersetOf(subSet Set) bool { return subSet.IsSubsetOf(st) } +func (st *set) IsProperSupersetOf(subSet Set) bool { + if st.Len() == subSet.Len() { + return false + } + return st.IsSupersetOf(subSet) +} + func (st *set) Union(st2 Set) Set { unionSet := New() for _, item := range st.GetItems() { diff --git a/structure/set/set_test.go b/structure/set/set_test.go index b07fe89a2..4b12a8f55 100644 --- a/structure/set/set_test.go +++ b/structure/set/set_test.go @@ -82,6 +82,16 @@ func TestIsSubsetOf(t *testing.T) { } } +func TestIsProperSubsetOf(t *testing.T) { + s1, s2 := New(1, 2, 3), New(1, 2, 3, 4) + if !s1.IsProperSubsetOf(s2) { + t.Errorf("expecting %v to be a proper subset of %v", s1, s2) + } + if s3 := New(3, 2, 1); s1.IsProperSubsetOf(s3) { + t.Errorf("expecting %v not to be a proper subset of %v", s1, s3) + } +} + func TestIsSupersetOf(t *testing.T) { s1, s2 := New(1, 2, 3), New(1, 2, 3, 4) if !s2.IsSupersetOf(s1) { @@ -95,6 +105,16 @@ func TestIsSupersetOf(t *testing.T) { } } +func TestIsProperSupersetOf(t *testing.T) { + s1, s2 := New(1, 2, 3), New(1, 2, 3, 4) + if !s2.IsProperSupersetOf(s1) { + t.Errorf("expecting %v to be a proper superset of %v", s2, s1) + } + if s3 := New(3, 2, 1); s1.IsProperSupersetOf(s3) { + t.Errorf("expecting %v not to be a proper superset of %v", s1, s3) + } +} + func TestUnion(t *testing.T) { td := []struct { name string From 51c95328394679b58855e134d83babb58d3ef6df Mon Sep 17 00:00:00 2001 From: David Leal Date: Mon, 24 Oct 2022 13:36:07 -0500 Subject: [PATCH 094/202] chore: remove unneeded quotes --- .github/ISSUE_TEMPLATE/new_implementation.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/new_implementation.yml b/.github/ISSUE_TEMPLATE/new_implementation.yml index b2153a022..e8da888e8 100644 --- a/.github/ISSUE_TEMPLATE/new_implementation.yml +++ b/.github/ISSUE_TEMPLATE/new_implementation.yml @@ -13,15 +13,12 @@ body: - type: markdown attributes: value: | - " For new implementations, please specify the name and problem statement for the algorithm. For algorithm enhancements, specify what needs to be changed and why. For example: - Adding tests. - Optimizing logic. - Refactoring the file and folders for better structure. - - " - type: textarea id: issuedetails attributes: From 213cfa61123f0ef71c74a2893679f91b033df618 Mon Sep 17 00:00:00 2001 From: Michele Caci Date: Tue, 25 Oct 2022 13:54:46 +0200 Subject: [PATCH 095/202] feat(cipher/rot13): add fuzz test to rot13 cipher (#588) --- README.md | 84 +++++++++++++++++++++++--------------- cipher/rot13/rot13_test.go | 14 ++++++- 2 files changed, 64 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 41d5ee29c..2f5ea82cc 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,22 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 10. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. 11. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +--- +
+ cache + +--- + +##### Functions: + +1. [`NewLRU`](./cache/lru.go#L20): NewLRU represent initiate lru cache with capacity + +--- +##### Types + +1. [`LRU`](./cache/lru.go#L12): No description provided. + + ---
caesar @@ -92,6 +108,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Decrypt`](./cipher/caesar/caesar.go#L27): Decrypt decrypts by left shift of "key" each character of "input" 2. [`Encrypt`](./cipher/caesar/caesar.go#L6): Encrypt encrypts by right shift of "key" each character of "input" +3. [`FuzzCaesar`](./cipher/caesar/caesar_test.go#L158): No description provided. ---
@@ -217,11 +234,11 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 7. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. 8. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. 9. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit -10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L8): LongestCommonSubsequence function +10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L12): LongestCommonSubsequence function 11. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order 12. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ -13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L21): LpsDp function -14. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L7): LpsRec function +13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L25): LpsDp function +14. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L20): LpsRec function 15. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function 16. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function 17. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate @@ -459,7 +476,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`JosephusProblem`](./structure/linkedlist/cyclic.go#L120): https://en.wikipedia.org/wiki/Josephus_problem This is a struct-based solution for Josephus problem. 2. [`NewCyclic`](./structure/linkedlist/cyclic.go#L12): Create new list. -3. [`NewDoubly`](./structure/linkedlist/doubly.go#L22): No description provided. +3. [`NewDoubly`](./structure/linkedlist/doubly.go#L31): No description provided. 4. [`NewNode`](./structure/linkedlist/shared.go#L12): Create new node. 5. [`NewSingly`](./structure/linkedlist/singlylinkedlist.go#L19): NewSingly returns a new instance of a linked list @@ -504,15 +521,18 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n 5. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. 6. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -7. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -8. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number -9. [`Mean`](./math/mean.go#L7): No description provided. -10. [`Median`](./math/median.go#L12): No description provided. -11. [`Mode`](./math/mode.go#L19): No description provided. -12. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number -13. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. -14. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 -15. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +7. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number +8. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +9. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1' +10. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number +11. [`Mean`](./math/mean.go#L7): No description provided. +12. [`Median`](./math/median.go#L12): No description provided. +13. [`Mode`](./math/mode.go#L19): No description provided. +14. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number +15. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +16. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 +17. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +18. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. ---
@@ -523,7 +543,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bitwise`](./math/max/bitwisemax.go#L11): Bitwise computes using bitwise operator the maximum of all the integer input and returns it -2. [`Int`](./math/max/max.go#L4): Int is a function which returns the maximum of all the integers provided as arguments. +2. [`Int`](./math/max/max.go#L6): Int is a function which returns the maximum of all the integers provided as arguments. ---
@@ -547,7 +567,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bitwise`](./math/min/bitwisemin.go#L11): Bitwise This function returns the minimum integer using bit operations -2. [`Int`](./math/min/min.go#L4): Int is a function which returns the minimum of all the integers provided as arguments. +2. [`Int`](./math/min/min.go#L6): Int is a function which returns the minimum of all the integers provided as arguments. ---
@@ -558,7 +578,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Exponentiation`](./math/modular/exponentiation.go#L22): Exponentiation returns base^exponent % mod -2. [`Inverse`](./math/modular/inverse.go#L20): Inverse Modular function +2. [`Inverse`](./math/modular/inverse.go#L19): Inverse Modular function 3. [`Multiply64BitInt`](./math/modular/exponentiation.go#L51): Multiply64BitInt Checking if the integer multiplication overflows --- @@ -715,6 +735,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 9. [`OptimizedTrialDivision`](./math/prime/primecheck.go#L26): OptimizedTrialDivision checks primality of an integer using an optimized trial division method. The optimizations include not checking divisibility by the even numbers and only checking up to the square root of the given number. 10. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels 11. [`TrialDivision`](./math/prime/primecheck.go#L9): TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it. +12. [`Twin`](./math/prime/twin.go#L15): This function returns twin prime for given number returns (n + 2) if both n and (n + 2) are prime -1 otherwise ---
@@ -836,29 +857,26 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. 3. [`Count`](./sort/countingsort.go#L11): No description provided. 4. [`Exchange`](./sort/exchangesort.go#L8): No description provided. -5. [`HeapSort`](./sort/heapsort.go#L121): No description provided. +5. [`HeapSort`](./sort/heapsort.go#L116): No description provided. 6. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort 7. [`Insertion`](./sort/insertionsort.go#L5): No description provided. -8. [`Merge`](./sort/mergesort.go#L40): Merge Perform merge sort on a slice -9. [`MergeIter`](./sort/mergesort.go#L54): No description provided. -10. [`Partition`](./sort/quicksort.go#L12): No description provided. -11. [`Patience`](./sort/patiencesort.go#L13): No description provided. -12. [`Pigeonhole`](./sort/pigeonholesort.go#L12): Pigeonhole sorts a slice using pigeonhole sorting algorithm. -13. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array -14. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array -15. [`RadixSort`](./sort/radixsort.go#L35): No description provided. -16. [`Selection`](./sort/selectionsort.go#L5): No description provided. -17. [`Shell`](./sort/shellsort.go#L5): No description provided. -18. [`Simple`](./sort/simplesort.go#L13): No description provided. +8. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice +9. [`MergeIter`](./sort/mergesort.go#L55): No description provided. +10. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines +11. [`Partition`](./sort/quicksort.go#L12): No description provided. +12. [`Patience`](./sort/patiencesort.go#L13): No description provided. +13. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. +14. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +15. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +16. [`RadixSort`](./sort/radixsort.go#L43): No description provided. +17. [`Selection`](./sort/selectionsort.go#L5): No description provided. +18. [`Shell`](./sort/shellsort.go#L5): No description provided. +19. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types -1. [`Int`](#L0): - - Methods: - 1. [`More`](./sort/heapsort.go#L114): No description provided. -2. [`MaxHeap`](./sort/heapsort.go#L3): No description provided. +1. [`MaxHeap`](./sort/heapsort.go#L5): No description provided. --- diff --git a/cipher/rot13/rot13_test.go b/cipher/rot13/rot13_test.go index 1e5716357..235039bbb 100644 --- a/cipher/rot13/rot13_test.go +++ b/cipher/rot13/rot13_test.go @@ -64,7 +64,19 @@ func TestRot13Decrypt(t *testing.T) { func assertRot13Output(t *testing.T, input, expected string) { actual := rot13(input) if actual != expected { - t.Fatalf("With input string '%s' was expecting '%s' but actual was '%s'", + t.Fatalf("With input string %q was expecting %q but actual was %q", input, expected, actual) } } + +func FuzzRot13(f *testing.F) { + for _, rot13TestInput := range rot13TestData { + f.Add(rot13TestInput.input) + } + f.Fuzz(func(t *testing.T, input string) { + if result := rot13(rot13(input)); result != input { + t.Fatalf("With input string %q was expecting %q but actual was %q", + input, input, result) + } + }) +} From 5a42d85e310f81051c1995c4be212a365a2dc02e Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Wed, 26 Oct 2022 14:23:24 +0200 Subject: [PATCH 096/202] fix: handle multibyte chars propertly in `LongestCommonSubsequence` (#578) --- dynamic/longestcommonsubsequence.go | 13 +++++++------ dynamic/longestcommonsubsequence_test.go | 2 ++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dynamic/longestcommonsubsequence.go b/dynamic/longestcommonsubsequence.go index 8ca739811..739aeb8c1 100644 --- a/dynamic/longestcommonsubsequence.go +++ b/dynamic/longestcommonsubsequence.go @@ -4,14 +4,15 @@ package dynamic -import ( - "unicode/utf8" -) +func strToRuneSlice(s string) (r []rune, size int) { + r = []rune(s) + return r, len(r) +} // LongestCommonSubsequence function func LongestCommonSubsequence(a string, b string) int { - var aLen = utf8.RuneCountInString(a) - var bLen = utf8.RuneCountInString(b) + aRunes, aLen := strToRuneSlice(a) + bRunes, bLen := strToRuneSlice(b) // here we are making a 2d slice of size (aLen+1)*(bLen+1) lcs := make([][]int, aLen+1) @@ -24,7 +25,7 @@ func LongestCommonSubsequence(a string, b string) int { for j := 0; j <= bLen; j++ { if i == 0 || j == 0 { lcs[i][j] = 0 - } else if a[i-1] == b[j-1] { + } else if aRunes[i-1] == bRunes[j-1] { lcs[i][j] = lcs[i-1][j-1] + 1 } else { lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1]) diff --git a/dynamic/longestcommonsubsequence_test.go b/dynamic/longestcommonsubsequence_test.go index 1c102c3be..5112f1270 100644 --- a/dynamic/longestcommonsubsequence_test.go +++ b/dynamic/longestcommonsubsequence_test.go @@ -28,6 +28,8 @@ func getLCSTestCases() []testCaseLCS { {"", "abc", 0}, {"", "", 0}, {"££", "££", 2}, + {"x笑x笑", "aaa笑a笑", 2}, + {"xYxY", "aaaYaY", 2}, } } From 298ce1b402eaa2184d147a58d145644893b8f273 Mon Sep 17 00:00:00 2001 From: Chetan Patil <31822501+Chetan07j@users.noreply.github.com> Date: Wed, 26 Oct 2022 21:31:15 +0200 Subject: [PATCH 097/202] algorithm: distance between two points (#568) * feat: cartesian plane algorithm two point distance added * test: function tests and bechmark test added * Fix: typo mistake Co-authored-by: Rak Laptudirm * fix: review comments incorporated * fix: review suggestions * fix: linter issues * fix: updated comment as per code changes * test: added test for error, updated benchmark test * fix: test package name and error handling Co-authored-by: Rak Laptudirm --- math/geometry/distance.go | 36 +++++++++++++++ math/geometry/distance_test.go | 80 ++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 math/geometry/distance.go create mode 100644 math/geometry/distance_test.go diff --git a/math/geometry/distance.go b/math/geometry/distance.go new file mode 100644 index 000000000..5b1c3c82e --- /dev/null +++ b/math/geometry/distance.go @@ -0,0 +1,36 @@ +// distance.go +// Find Euclidean distance between two points +// author(s) [Chetan Patil](https://github.com/Chetan07j) + +// Package geometry contains geometric algorithms +package geometry + +import ( + "errors" + "math" +) + +// EuclideanPoint defines a point with x and y coordinates. +type EuclideanPoint []float64 + +var ErrDimMismatch = errors.New("mismatched dimensions") + +// EuclideanDistance returns the Euclidean distance between points in +// any `n` dimensional Euclidean space. +func EuclideanDistance(p1 EuclideanPoint, p2 EuclideanPoint) (float64, error) { + n := len(p1) + + if len(p2) != n { + return -1, ErrDimMismatch + } + + var total float64 = 0 + + for i, x_i := range p1 { + // using Abs since the value could be negative but we require the magnitude + diff := math.Abs(x_i - p2[i]) + total += diff * diff + } + + return math.Sqrt(total), nil +} diff --git a/math/geometry/distance_test.go b/math/geometry/distance_test.go new file mode 100644 index 000000000..bea9ebba5 --- /dev/null +++ b/math/geometry/distance_test.go @@ -0,0 +1,80 @@ +package geometry_test + +import ( + "errors" + "testing" + + geometry "github.com/TheAlgorithms/Go/math/geometry" +) + +type args struct { + p1 geometry.EuclideanPoint + p2 geometry.EuclideanPoint +} + +func TestFindDistanceBetweenTwoPoints(t *testing.T) { + tests := []struct { + name string + args args + want float64 + wantErr bool + }{ + { + "(0,0) and (2,-2)", + args{ + geometry.EuclideanPoint{0, 0}, + geometry.EuclideanPoint{2, -2}, + }, + 2.8284271247461903, + false, + }, + { + "(-20,23) and (-15,68)", + args{ + geometry.EuclideanPoint{-20, 23}, + geometry.EuclideanPoint{-15, 68}, + }, + 45.27692569068709, + false, + }, + { + "(2,2) and (14,11)", + args{ + geometry.EuclideanPoint{2, 2}, + geometry.EuclideanPoint{14, 11}, + }, + 15, + false, + }, + { + "Return error for mismatched dimensions(2,2) and ()", + args{ + geometry.EuclideanPoint{2, 2}, + geometry.EuclideanPoint{}, + }, + -1, + true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := geometry.EuclideanDistance(tt.args.p1, tt.args.p2) + if (err != nil) != tt.wantErr && errors.Is(err, geometry.ErrDimMismatch) { + t.Errorf("EuclideanDistance() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("EuclideanDistance() = %v, want %v", got, tt.want) + } + }) + } +} + +func BenchmarkFindDistanceBetweenTwoPoints(b *testing.B) { + p1 := geometry.EuclideanPoint{0, 0} + p2 := geometry.EuclideanPoint{2, -2} + + for i := 0; i < b.N; i++ { + _, _ = geometry.EuclideanDistance(p1, p2) + } +} From 089c427640b047fb63d520a606cb233365f9deed Mon Sep 17 00:00:00 2001 From: Royce Date: Sun, 30 Oct 2022 12:31:30 -0400 Subject: [PATCH 098/202] docs: Documentation changes (#598) Bolded "removing bugs" on line 28. --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a2565430..0eb6982c1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ Being a contributor at The Algorithms, we request you to follow the points menti - New implementations are welcome! -- You can add new algorithms or data structures that are **not present in the repository** or that can **improve** the old implementations (**documentation**, **improving test cases**, removing bugs, or in any other reasonable sense) +- You can add new algorithms or data structures that are **not present in the repository** or that can **improve** the old implementations (**documentation**, **improving test cases**, **removing bugs**, or in any other reasonable sense) #### Issues From 1d2c0545ac9065639125a5e5bcc1f8d002986da3 Mon Sep 17 00:00:00 2001 From: Michele Caci Date: Mon, 31 Oct 2022 17:43:56 +0100 Subject: [PATCH 099/202] tests(cipher/rsa): add fuzz test to rsa cipher (#591) * Updated Documentation in README.md * feat(cipher/rsa): add fuzz test to rsa Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Taj --- cipher/rsa/rsa_test.go | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/cipher/rsa/rsa_test.go b/cipher/rsa/rsa_test.go index fde10be33..43ce90245 100644 --- a/cipher/rsa/rsa_test.go +++ b/cipher/rsa/rsa_test.go @@ -35,30 +35,28 @@ var rsaTestData = []struct { }, } -func TestEncryptDecrypt(t *testing.T) { +func testPrecondition(t *testing.T) (int64, int64, int64) { // Both prime numbers + t.Helper() p := int64(61) q := int64(53) - n := p * q - delta := lcm.Lcm(p-1, q-1) - e := int64(17) // Coprime with delta - if gcd.Recursive(e, delta) != 1 { - t.Fatal("Algorithm failed in preamble stage:\n\tPrime numbers are chosen statically and it shouldn't fail at this stage") + t.Fatal("something went wrong: prime numbers are chosen statically and it shouldn't fail at this stage") } - d, err := modular.Inverse(e, delta) - if err != nil { - t.Fatalf("Algorithm failed in preamble stage:\n\tProblem with a modular directory dependency: %v", err) + t.Fatalf("something went wrong: problem with %q: %v", "modular.Inverse", err) } + return e, d, n +} +func TestEncryptDecrypt(t *testing.T) { for _, test := range rsaTestData { t.Run(test.description, func(t *testing.T) { - + e, d, n := testPrecondition(t) message := []rune(test.input) encrypted, err := Encrypt(message, e, n) if err != nil { @@ -77,3 +75,23 @@ func TestEncryptDecrypt(t *testing.T) { }) } } + +func FuzzRsa(f *testing.F) { + for _, rsaTestInput := range rsaTestData { + f.Add(rsaTestInput.input) + } + f.Fuzz(func(t *testing.T, input string) { + e, d, n := testPrecondition(t) + encrypted, err := Encrypt([]rune(input), e, n) + if err != nil { + t.Fatalf("failed to encrypt string: %v", err) + } + decrypted, err := Decrypt(encrypted, d, n) + if err != nil { + t.Fatalf("failed to decrypt string: %v", err) + } + if decrypted != input { + t.Fatalf("expected: %q, got: %q", input, decrypted) + } + }) +} From 7eb041010aed929cbe9140d018e99b2baf5d040b Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:18:11 +0530 Subject: [PATCH 100/202] algorithm: Aliquot Sum (#594) * feat: Add Aliquot Sum implementation * test: Add test for Aliquot Sum algorithm * fix: Add separate case for n=1 * refactor: Refactor condition in for loop Co-authored-by: Rak Laptudirm --- math/aliquot_test.go | 39 +++++++++++++++++++++++++++++++++++++++ math/aliquotsum.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 math/aliquot_test.go create mode 100644 math/aliquotsum.go diff --git a/math/aliquot_test.go b/math/aliquot_test.go new file mode 100644 index 000000000..0c6abd956 --- /dev/null +++ b/math/aliquot_test.go @@ -0,0 +1,39 @@ +// aliquotsum_test.go +// description: Returns s(n) +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see aliquotsum.go + +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +func TestAliquotSum(t *testing.T) { + var tests = []struct { + name string + n int + expectedValue int + expectedError error + }{ + {"n = 10", 10, 8, nil}, + {"n = 11", 11, 1, nil}, + {"n = -1", -1, 0, math.ErrPosArgsOnly}, + {"n = 0", 0, 0, math.ErrNonZeroArgsOnly}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := math.AliquotSum(test.n) + if result != test.expectedValue || test.expectedError != err { + t.Errorf("expected error: %s, got: %s; expected value: %v, got: %v", test.expectedError, err, test.expectedValue, result) + } + }) + } +} +func BenchmarkAliquotSum(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = math.AliquotSum(65536) + } +} diff --git a/math/aliquotsum.go b/math/aliquotsum.go new file mode 100644 index 000000000..707b818a2 --- /dev/null +++ b/math/aliquotsum.go @@ -0,0 +1,31 @@ +// aliquotsum.go +// description: Returns s(n) +// details: +// the aliquot sum s(n) of a positive integer n +// is the sum of all proper divisors of n, +// that is, all divisors of n other than n itself +// wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see aliquotsum_test.go + +package math + +// This function returns s(n) for given number +func AliquotSum(n int) (int, error) { + switch { + case n < 0: + return 0, ErrPosArgsOnly + case n == 0: + return 0, ErrNonZeroArgsOnly + case n == 1: + return 0, nil + default: + var sum int + for i := 1; i <= n/2; i++ { + if n%i == 0 { + sum += i + } + } + return sum, nil + } +} From aa85e4e535c1595b3f860baac4790f19fc07fa40 Mon Sep 17 00:00:00 2001 From: KedarisettiSreeVamsi <34485436+KedarisettiSreeVamsi@users.noreply.github.com> Date: Wed, 9 Nov 2022 20:49:58 +0530 Subject: [PATCH 101/202] update: delete middle func for linked list (#560) * Added code for delete in middle for linkedlist * update to previous commit of linked list * Changes as requested to linkedlist * removed delete in middle code Co-authored-by: Rak Laptudirm --- structure/linkedlist/doubly.go | 33 ++++++++++++++++++++++ structure/linkedlist/singlylinkedlist.go | 36 +++++++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/structure/linkedlist/doubly.go b/structure/linkedlist/doubly.go index a14513751..6864dacf0 100644 --- a/structure/linkedlist/doubly.go +++ b/structure/linkedlist/doubly.go @@ -101,6 +101,39 @@ func (ll *Doubly[T]) DelAtEnd() (T, bool) { return val, true } +// DelByPos deletes node at middle based on position in list +// and returns value. If empty or position of node is less than linked list length, returns false +func (ll *Doubly[T]) DelByPos(pos int) (T, bool) { + + switch { + case ll.Head == nil: + var r T + return r, false + case pos-1 == 0: + return ll.DelAtBeg() + case pos-1 == ll.Count(): + return ll.DelAtEnd() + case pos-1 > ll.Count(): + var r T + return r, false + } + var prev *Node[T] + var val T + cur := ll.Head + count := 0 + + for count < pos-1 { + prev = cur + cur = cur.Next + count++ + } + + cur.Next.Prev = prev + val = cur.Val + prev.Next = cur.Next + return val, true +} + // Count Number of nodes in the linkedlist func (ll *Doubly[T]) Count() int { var ctr int = 0 diff --git a/structure/linkedlist/singlylinkedlist.go b/structure/linkedlist/singlylinkedlist.go index 18d661799..9f951737f 100644 --- a/structure/linkedlist/singlylinkedlist.go +++ b/structure/linkedlist/singlylinkedlist.go @@ -22,7 +22,7 @@ func NewSingly[T any]() *Singly[T] { // AddAtBeg adds a new snode with given value at the beginning of the list. func (ll *Singly[T]) AddAtBeg(val T) { - n := NewNode[T](val) + n := NewNode(val) n.Next = ll.Head ll.Head = n ll.length++ @@ -84,6 +84,40 @@ func (ll *Singly[T]) DelAtEnd() (T, bool) { } +// DelByPos deletes the node at the middle based on position in the list +// and returns its value. Returns false if the list is empty or length is not more than given position +func (ll *Singly[T]) DelByPos(pos int) (T, bool) { + switch { + case ll.Head == nil: + var r T + return r, false + case pos-1 > ll.length: + var r T + return r, false + case pos-1 == 0: + return ll.DelAtBeg() + case pos-1 == ll.Count(): + return ll.DelAtEnd() + } + + var prev *Node[T] + var val T + cur := ll.Head + count := 0 + + for count < pos-1 { + prev = cur + cur = cur.Next + count++ + } + + val = cur.Val + prev.Next = cur.Next + ll.length-- + + return val, true +} + // Count returns the current size of the list. func (ll *Singly[T]) Count() int { return ll.length From 7523f410d9dca40b55a0da2e756ba37e8cb11b38 Mon Sep 17 00:00:00 2001 From: Michele Caci Date: Fri, 11 Nov 2022 05:12:49 +0100 Subject: [PATCH 102/202] feat(cipher/polybius): add fuzz test to polybius cipher (#600) --- README.md | 15 ++++++++++- cipher/polybius/polybius.go | 21 ++++++++++++---- cipher/polybius/polybius_test.go | 43 ++++++++++++++++++++++++++++++-- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 2f5ea82cc..06be382be 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 7. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity. 8. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided. 9. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit -10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L12): LongestCommonSubsequence function +10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L13): LongestCommonSubsequence function 11. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order 12. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ 13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L25): LpsDp function @@ -778,6 +778,19 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 3. [`Queue`](./structure/queue/queuelinkedlist.go#L19): No description provided. +--- +
+ rot13 + +--- + +##### Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ref: https://en.wikipedia.org/wiki/ROT13 + +--- +##### Functions: + +1. [`FuzzRot13`](./cipher/rot13/rot13_test.go#L72): No description provided. + ---
rsa diff --git a/cipher/polybius/polybius.go b/cipher/polybius/polybius.go index 7c2760334..7b57ab344 100644 --- a/cipher/polybius/polybius.go +++ b/cipher/polybius/polybius.go @@ -19,11 +19,22 @@ type Polybius struct { // If the size of "chars" is longer than "size", // "chars" are truncated to "size". func NewPolybius(key string, size int, chars string) (*Polybius, error) { + if size < 0 { + return nil, fmt.Errorf("provided size %d cannot be negative", size) + } key = strings.ToUpper(key) + if size > len(chars) { + return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars)) + } + for _, r := range chars { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') { + return nil, fmt.Errorf("provided string %q should only contain latin characters", chars) + } + } chars = strings.ToUpper(chars)[:size] - for idx, ch := range chars { - if strings.Contains(chars[idx+1:], string(ch)) { - return nil, fmt.Errorf("\"chars\" contains same character: %c", ch) + for i, r := range chars { + if strings.ContainsRune(chars[i+1:], r) { + return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r) } } @@ -63,7 +74,7 @@ func (p *Polybius) Decrypt(text string) (string, error) { func (p *Polybius) encipher(char rune) (string, error) { index := strings.IndexRune(p.key, char) if index < 0 { - return "", fmt.Errorf("%c does not exist in keys", char) + return "", fmt.Errorf("%q does not exist in keys", char) } row := index / p.size col := index % p.size @@ -83,5 +94,5 @@ func (p *Polybius) decipher(chars []rune) (string, error) { if col < 0 { return "", fmt.Errorf("%c does not exist in characters", chars[1]) } - return string([]rune(p.key)[row*p.size+col]), nil + return string(p.key[row*p.size+col]), nil } diff --git a/cipher/polybius/polybius_test.go b/cipher/polybius/polybius_test.go index 89b4769fc..03fb4ca00 100644 --- a/cipher/polybius/polybius_test.go +++ b/cipher/polybius/polybius_test.go @@ -3,6 +3,7 @@ package polybius import ( "fmt" "log" + "strings" "testing" ) @@ -54,7 +55,7 @@ func TestNewPolybius(t *testing.T) { name: "invalid key", size: 5, characters: "HogeFuga", key: "abcdefghi", wantErr: "len(key): 9 must be as long as size squared: 25", }, { - name: "invalid characters", size: 5, characters: "HogeH", key: "abcdefghijklmnopqrstuvwxy", wantErr: "\"chars\" contains same character: H", + name: "invalid characters", size: 5, characters: "HogeH", key: "abcdefghijklmnopqrstuvwxy", wantErr: "\"OGEH\" contains same character 'H'", }, } @@ -79,7 +80,7 @@ func TestPolybiusEncrypt(t *testing.T) { name: "correct encryption", text: "HogeFugaPiyoSpam", want: "OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG", }, { - name: "invalid encryption", text: "hogz", want: "failed encipher: Z does not exist in keys", + name: "invalid encryption", text: "hogz", want: "failed encipher: 'Z' does not exist in keys", }, } // initialize @@ -149,3 +150,41 @@ func TestPolybiusDecrypt(t *testing.T) { }) } } + +func FuzzPolybius(f *testing.F) { + const ( + size = 5 + characters = "HogeF" + key = "abcdefghijklmnopqrstuvwxy" + ) + f.Add(size, characters, key) + f.Fuzz(func(t *testing.T, size int, characters, key string) { + p, err := NewPolybius(key, size, characters) + switch { + case err == nil: + case strings.Contains(err.Error(), "cannot be negative"), + strings.Contains(err.Error(), "is too small"), + strings.Contains(err.Error(), "should only contain latin characters"), + strings.Contains(err.Error(), "contains same character"), + strings.Contains(err.Error(), "must be as long as size squared"): + return + default: + t.Fatalf("unexpected error when creating a new polybius variable: %v", err) + } + encrypted, err := p.Encrypt(characters) + switch { + case err == nil: + case strings.Contains(err.Error(), "does not exist in keys"): + return + default: + t.Fatalf("unexpected error during encryption: %v", err) + } + decrypted, err := p.Decrypt(encrypted) + if err != nil { + t.Fatalf("unexpected error during decryption: %v", err) + } + if decrypted != strings.ToUpper(characters) { + t.Errorf("Expecting output to match with %q but was %q", characters, decrypted) + } + }) +} From f2296d57fb07dc482f6ea4b67eb37da45d36973e Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Fri, 11 Nov 2022 17:23:08 +0530 Subject: [PATCH 103/202] algorithm: Pronic number (#595) --- math/pronicnumber.go | 21 ++ math/pronicnumber_test.go | 438 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 459 insertions(+) create mode 100644 math/pronicnumber.go create mode 100644 math/pronicnumber_test.go diff --git a/math/pronicnumber.go b/math/pronicnumber.go new file mode 100644 index 000000000..90850d28e --- /dev/null +++ b/math/pronicnumber.go @@ -0,0 +1,21 @@ +// pronicnumber.go +// description: Returns true if the number is pronic and false otherwise +// details: +// Pronic number: For any integer n, if there exists integer m +// such that n = m * (m + 1) then n is called a pronic number. +// wikipedia: https://en.wikipedia.org/wiki/Pronic_number +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see pronicnumber_test.go + +package math + +import stdMath "math" + +// PronicNumber returns true if argument passed to the function is pronic and false otherwise. +func PronicNumber(n int) bool { + if n < 0 || n%2 == 1 { + return false + } + x := int(stdMath.Sqrt(float64(n))) + return n == x*(x+1) +} diff --git a/math/pronicnumber_test.go b/math/pronicnumber_test.go new file mode 100644 index 000000000..34880d68e --- /dev/null +++ b/math/pronicnumber_test.go @@ -0,0 +1,438 @@ +// pronicnumber_test.go +// author: Akshay Dubey (https://github.com/itsAkshayDubey) +// see pronicnumber.go + +package math_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math" +) + +func TestPronicNumber(t *testing.T) { + var tests = []struct { + name string + n int + expectedValue bool + }{ + {"-12 is not pronic", -12, false}, + {"0 is pronic", 0, true}, + {"1 is not pronic", 1, false}, + {"2 is pronic", 2, true}, + {"3 is not pronic", 3, false}, + {"4 is not pronic", 4, false}, + {"5 is not pronic", 5, false}, + {"6 is pronic", 6, true}, + {"7 is not pronic", 7, false}, + {"8 is not pronic", 8, false}, + {"9 is not pronic", 9, false}, + {"10 is not pronic", 10, false}, + {"11 is not pronic", 11, false}, + {"12 is pronic", 12, true}, + {"13 is not pronic", 13, false}, + {"14 is not pronic", 14, false}, + {"15 is not pronic", 15, false}, + {"16 is not pronic", 16, false}, + {"17 is not pronic", 17, false}, + {"18 is not pronic", 18, false}, + {"19 is not pronic", 19, false}, + {"20 is pronic", 20, true}, + {"21 is not pronic", 21, false}, + {"22 is not pronic", 22, false}, + {"23 is not pronic", 23, false}, + {"24 is not pronic", 24, false}, + {"25 is not pronic", 25, false}, + {"26 is not pronic", 26, false}, + {"27 is not pronic", 27, false}, + {"28 is not pronic", 28, false}, + {"29 is not pronic", 29, false}, + {"30 is pronic", 30, true}, + {"31 is not pronic", 31, false}, + {"32 is not pronic", 32, false}, + {"33 is not pronic", 33, false}, + {"34 is not pronic", 34, false}, + {"35 is not pronic", 35, false}, + {"36 is not pronic", 36, false}, + {"37 is not pronic", 37, false}, + {"38 is not pronic", 38, false}, + {"39 is not pronic", 39, false}, + {"40 is not pronic", 40, false}, + {"41 is not pronic", 41, false}, + {"42 is pronic", 42, true}, + {"43 is not pronic", 43, false}, + {"44 is not pronic", 44, false}, + {"45 is not pronic", 45, false}, + {"46 is not pronic", 46, false}, + {"47 is not pronic", 47, false}, + {"48 is not pronic", 48, false}, + {"49 is not pronic", 49, false}, + {"50 is not pronic", 50, false}, + {"51 is not pronic", 51, false}, + {"52 is not pronic", 52, false}, + {"53 is not pronic", 53, false}, + {"54 is not pronic", 54, false}, + {"55 is not pronic", 55, false}, + {"56 is pronic", 56, true}, + {"57 is not pronic", 57, false}, + {"58 is not pronic", 58, false}, + {"59 is not pronic", 59, false}, + {"60 is not pronic", 60, false}, + {"61 is not pronic", 61, false}, + {"62 is not pronic", 62, false}, + {"63 is not pronic", 63, false}, + {"64 is not pronic", 64, false}, + {"65 is not pronic", 65, false}, + {"66 is not pronic", 66, false}, + {"67 is not pronic", 67, false}, + {"68 is not pronic", 68, false}, + {"69 is not pronic", 69, false}, + {"70 is not pronic", 70, false}, + {"71 is not pronic", 71, false}, + {"72 is pronic", 72, true}, + {"73 is not pronic", 73, false}, + {"74 is not pronic", 74, false}, + {"75 is not pronic", 75, false}, + {"76 is not pronic", 76, false}, + {"77 is not pronic", 77, false}, + {"78 is not pronic", 78, false}, + {"79 is not pronic", 79, false}, + {"80 is not pronic", 80, false}, + {"81 is not pronic", 81, false}, + {"82 is not pronic", 82, false}, + {"83 is not pronic", 83, false}, + {"84 is not pronic", 84, false}, + {"85 is not pronic", 85, false}, + {"86 is not pronic", 86, false}, + {"87 is not pronic", 87, false}, + {"88 is not pronic", 88, false}, + {"89 is not pronic", 89, false}, + {"90 is pronic", 90, true}, + {"91 is not pronic", 91, false}, + {"92 is not pronic", 92, false}, + {"93 is not pronic", 93, false}, + {"94 is not pronic", 94, false}, + {"95 is not pronic", 95, false}, + {"96 is not pronic", 96, false}, + {"97 is not pronic", 97, false}, + {"98 is not pronic", 98, false}, + {"99 is not pronic", 99, false}, + {"100 is not pronic", 100, false}, + {"101 is not pronic", 101, false}, + {"102 is not pronic", 102, false}, + {"103 is not pronic", 103, false}, + {"104 is not pronic", 104, false}, + {"105 is not pronic", 105, false}, + {"106 is not pronic", 106, false}, + {"107 is not pronic", 107, false}, + {"108 is not pronic", 108, false}, + {"109 is not pronic", 109, false}, + {"110 is pronic", 110, true}, + {"111 is not pronic", 111, false}, + {"112 is not pronic", 112, false}, + {"113 is not pronic", 113, false}, + {"114 is not pronic", 114, false}, + {"115 is not pronic", 115, false}, + {"116 is not pronic", 116, false}, + {"117 is not pronic", 117, false}, + {"118 is not pronic", 118, false}, + {"119 is not pronic", 119, false}, + {"120 is not pronic", 120, false}, + {"121 is not pronic", 121, false}, + {"122 is not pronic", 122, false}, + {"123 is not pronic", 123, false}, + {"124 is not pronic", 124, false}, + {"125 is not pronic", 125, false}, + {"126 is not pronic", 126, false}, + {"127 is not pronic", 127, false}, + {"128 is not pronic", 128, false}, + {"129 is not pronic", 129, false}, + {"130 is not pronic", 130, false}, + {"131 is not pronic", 131, false}, + {"132 is pronic", 132, true}, + {"133 is not pronic", 133, false}, + {"134 is not pronic", 134, false}, + {"135 is not pronic", 135, false}, + {"136 is not pronic", 136, false}, + {"137 is not pronic", 137, false}, + {"138 is not pronic", 138, false}, + {"139 is not pronic", 139, false}, + {"140 is not pronic", 140, false}, + {"141 is not pronic", 141, false}, + {"142 is not pronic", 142, false}, + {"143 is not pronic", 143, false}, + {"144 is not pronic", 144, false}, + {"145 is not pronic", 145, false}, + {"146 is not pronic", 146, false}, + {"147 is not pronic", 147, false}, + {"148 is not pronic", 148, false}, + {"149 is not pronic", 149, false}, + {"150 is not pronic", 150, false}, + {"151 is not pronic", 151, false}, + {"152 is not pronic", 152, false}, + {"153 is not pronic", 153, false}, + {"154 is not pronic", 154, false}, + {"155 is not pronic", 155, false}, + {"156 is pronic", 156, true}, + {"157 is not pronic", 157, false}, + {"158 is not pronic", 158, false}, + {"159 is not pronic", 159, false}, + {"160 is not pronic", 160, false}, + {"161 is not pronic", 161, false}, + {"162 is not pronic", 162, false}, + {"163 is not pronic", 163, false}, + {"164 is not pronic", 164, false}, + {"165 is not pronic", 165, false}, + {"166 is not pronic", 166, false}, + {"167 is not pronic", 167, false}, + {"168 is not pronic", 168, false}, + {"169 is not pronic", 169, false}, + {"170 is not pronic", 170, false}, + {"171 is not pronic", 171, false}, + {"172 is not pronic", 172, false}, + {"173 is not pronic", 173, false}, + {"174 is not pronic", 174, false}, + {"175 is not pronic", 175, false}, + {"176 is not pronic", 176, false}, + {"177 is not pronic", 177, false}, + {"178 is not pronic", 178, false}, + {"179 is not pronic", 179, false}, + {"180 is not pronic", 180, false}, + {"181 is not pronic", 181, false}, + {"182 is pronic", 182, true}, + {"183 is not pronic", 183, false}, + {"184 is not pronic", 184, false}, + {"185 is not pronic", 185, false}, + {"186 is not pronic", 186, false}, + {"187 is not pronic", 187, false}, + {"188 is not pronic", 188, false}, + {"189 is not pronic", 189, false}, + {"190 is not pronic", 190, false}, + {"191 is not pronic", 191, false}, + {"192 is not pronic", 192, false}, + {"193 is not pronic", 193, false}, + {"194 is not pronic", 194, false}, + {"195 is not pronic", 195, false}, + {"196 is not pronic", 196, false}, + {"197 is not pronic", 197, false}, + {"198 is not pronic", 198, false}, + {"199 is not pronic", 199, false}, + {"200 is not pronic", 200, false}, + {"201 is not pronic", 201, false}, + {"202 is not pronic", 202, false}, + {"203 is not pronic", 203, false}, + {"204 is not pronic", 204, false}, + {"205 is not pronic", 205, false}, + {"206 is not pronic", 206, false}, + {"207 is not pronic", 207, false}, + {"208 is not pronic", 208, false}, + {"209 is not pronic", 209, false}, + {"210 is pronic", 210, true}, + {"211 is not pronic", 211, false}, + {"212 is not pronic", 212, false}, + {"213 is not pronic", 213, false}, + {"214 is not pronic", 214, false}, + {"215 is not pronic", 215, false}, + {"216 is not pronic", 216, false}, + {"217 is not pronic", 217, false}, + {"218 is not pronic", 218, false}, + {"219 is not pronic", 219, false}, + {"220 is not pronic", 220, false}, + {"221 is not pronic", 221, false}, + {"222 is not pronic", 222, false}, + {"223 is not pronic", 223, false}, + {"224 is not pronic", 224, false}, + {"225 is not pronic", 225, false}, + {"226 is not pronic", 226, false}, + {"227 is not pronic", 227, false}, + {"228 is not pronic", 228, false}, + {"229 is not pronic", 229, false}, + {"230 is not pronic", 230, false}, + {"231 is not pronic", 231, false}, + {"232 is not pronic", 232, false}, + {"233 is not pronic", 233, false}, + {"234 is not pronic", 234, false}, + {"235 is not pronic", 235, false}, + {"236 is not pronic", 236, false}, + {"237 is not pronic", 237, false}, + {"238 is not pronic", 238, false}, + {"239 is not pronic", 239, false}, + {"240 is pronic", 240, true}, + {"241 is not pronic", 241, false}, + {"242 is not pronic", 242, false}, + {"243 is not pronic", 243, false}, + {"244 is not pronic", 244, false}, + {"245 is not pronic", 245, false}, + {"246 is not pronic", 246, false}, + {"247 is not pronic", 247, false}, + {"248 is not pronic", 248, false}, + {"249 is not pronic", 249, false}, + {"250 is not pronic", 250, false}, + {"251 is not pronic", 251, false}, + {"252 is not pronic", 252, false}, + {"253 is not pronic", 253, false}, + {"254 is not pronic", 254, false}, + {"255 is not pronic", 255, false}, + {"256 is not pronic", 256, false}, + {"257 is not pronic", 257, false}, + {"258 is not pronic", 258, false}, + {"259 is not pronic", 259, false}, + {"260 is not pronic", 260, false}, + {"261 is not pronic", 261, false}, + {"262 is not pronic", 262, false}, + {"263 is not pronic", 263, false}, + {"264 is not pronic", 264, false}, + {"265 is not pronic", 265, false}, + {"266 is not pronic", 266, false}, + {"267 is not pronic", 267, false}, + {"268 is not pronic", 268, false}, + {"269 is not pronic", 269, false}, + {"270 is not pronic", 270, false}, + {"271 is not pronic", 271, false}, + {"272 is pronic", 272, true}, + {"273 is not pronic", 273, false}, + {"274 is not pronic", 274, false}, + {"275 is not pronic", 275, false}, + {"276 is not pronic", 276, false}, + {"277 is not pronic", 277, false}, + {"278 is not pronic", 278, false}, + {"279 is not pronic", 279, false}, + {"280 is not pronic", 280, false}, + {"281 is not pronic", 281, false}, + {"282 is not pronic", 282, false}, + {"283 is not pronic", 283, false}, + {"284 is not pronic", 284, false}, + {"285 is not pronic", 285, false}, + {"286 is not pronic", 286, false}, + {"287 is not pronic", 287, false}, + {"288 is not pronic", 288, false}, + {"289 is not pronic", 289, false}, + {"290 is not pronic", 290, false}, + {"291 is not pronic", 291, false}, + {"292 is not pronic", 292, false}, + {"293 is not pronic", 293, false}, + {"294 is not pronic", 294, false}, + {"295 is not pronic", 295, false}, + {"296 is not pronic", 296, false}, + {"297 is not pronic", 297, false}, + {"298 is not pronic", 298, false}, + {"299 is not pronic", 299, false}, + {"300 is not pronic", 300, false}, + {"301 is not pronic", 301, false}, + {"302 is not pronic", 302, false}, + {"303 is not pronic", 303, false}, + {"304 is not pronic", 304, false}, + {"305 is not pronic", 305, false}, + {"306 is pronic", 306, true}, + {"307 is not pronic", 307, false}, + {"308 is not pronic", 308, false}, + {"309 is not pronic", 309, false}, + {"310 is not pronic", 310, false}, + {"311 is not pronic", 311, false}, + {"312 is not pronic", 312, false}, + {"313 is not pronic", 313, false}, + {"314 is not pronic", 314, false}, + {"315 is not pronic", 315, false}, + {"316 is not pronic", 316, false}, + {"317 is not pronic", 317, false}, + {"318 is not pronic", 318, false}, + {"319 is not pronic", 319, false}, + {"320 is not pronic", 320, false}, + {"321 is not pronic", 321, false}, + {"322 is not pronic", 322, false}, + {"323 is not pronic", 323, false}, + {"324 is not pronic", 324, false}, + {"325 is not pronic", 325, false}, + {"326 is not pronic", 326, false}, + {"327 is not pronic", 327, false}, + {"328 is not pronic", 328, false}, + {"329 is not pronic", 329, false}, + {"330 is not pronic", 330, false}, + {"331 is not pronic", 331, false}, + {"332 is not pronic", 332, false}, + {"333 is not pronic", 333, false}, + {"334 is not pronic", 334, false}, + {"335 is not pronic", 335, false}, + {"336 is not pronic", 336, false}, + {"337 is not pronic", 337, false}, + {"338 is not pronic", 338, false}, + {"339 is not pronic", 339, false}, + {"340 is not pronic", 340, false}, + {"341 is not pronic", 341, false}, + {"342 is pronic", 342, true}, + {"343 is not pronic", 343, false}, + {"344 is not pronic", 344, false}, + {"345 is not pronic", 345, false}, + {"346 is not pronic", 346, false}, + {"347 is not pronic", 347, false}, + {"348 is not pronic", 348, false}, + {"349 is not pronic", 349, false}, + {"350 is not pronic", 350, false}, + {"351 is not pronic", 351, false}, + {"352 is not pronic", 352, false}, + {"353 is not pronic", 353, false}, + {"354 is not pronic", 354, false}, + {"355 is not pronic", 355, false}, + {"356 is not pronic", 356, false}, + {"357 is not pronic", 357, false}, + {"358 is not pronic", 358, false}, + {"359 is not pronic", 359, false}, + {"360 is not pronic", 360, false}, + {"361 is not pronic", 361, false}, + {"362 is not pronic", 362, false}, + {"363 is not pronic", 363, false}, + {"364 is not pronic", 364, false}, + {"365 is not pronic", 365, false}, + {"366 is not pronic", 366, false}, + {"367 is not pronic", 367, false}, + {"368 is not pronic", 368, false}, + {"369 is not pronic", 369, false}, + {"370 is not pronic", 370, false}, + {"371 is not pronic", 371, false}, + {"372 is not pronic", 372, false}, + {"373 is not pronic", 373, false}, + {"374 is not pronic", 374, false}, + {"375 is not pronic", 375, false}, + {"376 is not pronic", 376, false}, + {"377 is not pronic", 377, false}, + {"378 is not pronic", 378, false}, + {"379 is not pronic", 379, false}, + {"380 is pronic", 380, true}, + {"381 is not pronic", 381, false}, + {"382 is not pronic", 382, false}, + {"383 is not pronic", 383, false}, + {"384 is not pronic", 384, false}, + {"385 is not pronic", 385, false}, + {"386 is not pronic", 386, false}, + {"387 is not pronic", 387, false}, + {"388 is not pronic", 388, false}, + {"389 is not pronic", 389, false}, + {"390 is not pronic", 390, false}, + {"391 is not pronic", 391, false}, + {"392 is not pronic", 392, false}, + {"393 is not pronic", 393, false}, + {"394 is not pronic", 394, false}, + {"395 is not pronic", 395, false}, + {"396 is not pronic", 396, false}, + {"397 is not pronic", 397, false}, + {"398 is not pronic", 398, false}, + {"399 is not pronic", 399, false}, + {"400 is not pronic", 400, false}, + {"2147441940 is pronic", 2147441940, true}, + {"9223372033963249500 is pronic", 9223372033963249500, true}, + {"9223372033963249664 is not pronic", 9223372033963249664, false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result := math.PronicNumber(test.n) + if result != test.expectedValue { + t.Errorf("expected value: %v, got: %v", test.expectedValue, result) + } + }) + } +} +func BenchmarkPronicNumber(b *testing.B) { + for i := 0; i < b.N; i++ { + math.PronicNumber(65536) + } +} From 79ff8f173b423af91b639d36c8efbc5d8456c2dd Mon Sep 17 00:00:00 2001 From: M3talM0nk3y Date: Sun, 13 Nov 2022 12:46:30 -0500 Subject: [PATCH 104/202] algorithm: check if string is isogram (#599) --- strings/isisogram.go | 71 +++++++++++++++++++++ strings/isisogram_test.go | 131 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 strings/isisogram.go create mode 100644 strings/isisogram_test.go diff --git a/strings/isisogram.go b/strings/isisogram.go new file mode 100644 index 000000000..1a3c1a55a --- /dev/null +++ b/strings/isisogram.go @@ -0,0 +1,71 @@ +// Checks if a given string is an isogram. +// A first-order isogram is a word in which no letter of the alphabet occurs more than once. +// A second-order isogram is a word in which each letter appears twice. +// A third-order isogram is a word in which each letter appears three times. +// wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms +// Author: M3talM0nk3y + +package strings + +import ( + "errors" + "regexp" + "strings" +) + +type IsogramOrder int + +const ( + First IsogramOrder = iota + 1 + Second + Third +) + +func hasDigit(text string) bool { + re := regexp.MustCompile(`\d`) + return re.MatchString(text) +} + +func hasSymbol(text string) bool { + re := regexp.MustCompile(`[-!@#$%^&*()+]`) + return re.MatchString(text) +} + +func IsIsogram(text string, order IsogramOrder) (bool, error) { + if order < First || order > Third { + return false, errors.New("Invalid isogram order provided") + } + + text = strings.ToLower(text) + text = strings.Join(strings.Fields(text), "") + + if hasDigit(text) || hasSymbol(text) { + return false, errors.New("Cannot contain numbers or symbols") + } + + letters := make(map[string]int) + for _, c := range text { + l := string(c) + if _, ok := letters[l]; ok { + letters[l] += 1 + + if letters[l] > 3 { + return false, nil + } + + continue + } + letters[l] = 1 + } + + mapVals := make(map[int]bool) + for _, v := range letters { + mapVals[v] = true + } + + if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 { + return true, nil + } + + return false, nil +} diff --git a/strings/isisogram_test.go b/strings/isisogram_test.go new file mode 100644 index 000000000..0b54333e6 --- /dev/null +++ b/strings/isisogram_test.go @@ -0,0 +1,131 @@ +package strings_test + +import ( + "errors" + "testing" + + "github.com/TheAlgorithms/Go/strings" +) + +var testCases = []struct { + name string + input string + order strings.IsogramOrder + expectedVal bool + expectedErr error +}{ + { + "Alphanumeric string 1", + "copy1", + 1, + false, + errors.New("Cannot contain numbers or symbols"), + }, + { + "Alphanumeric string 2", + "copy1sentence", + 1, + false, + errors.New("Cannot contain numbers or symbols"), + }, + { + "Alphanumeric string 3", + "copy1 sentence with space", + 1, + false, + errors.New("Cannot contain numbers or symbols"), + }, + { + "Alphabetic string 1", + "allowance", + 1, + false, + nil, + }, + { + "Alphabetic string 2", + "My Doodle", + 1, + false, + nil, + }, + { + "Alphabetic string with symbol", + "Isogram!", + 1, + false, + errors.New("Cannot contain numbers or symbols"), + }, + { + "Isogram string 1", + "Uncopyrightable", + 1, + true, + nil, + }, + { + "Second order isogram 1", + "Caucasus", + 2, + true, + nil, + }, + { + "Second order isogram 2", + "Couscous", + 2, + true, + nil, + }, + { + "Third order isogram 1", + "Deeded", + 3, + true, + nil, + }, + { + "Third order isogram 2", + "Sestettes", + 3, + true, + nil, + }, + { + "Not an isogram", + "Pneumonoultramicroscopicsilicovolcanoconiosis", + 1, + false, + nil, + }, + { + "Not an isogram", + "Randomstring", + 4, + false, + errors.New("Invalid isogram order provided"), + }, + { + "Third order isogram checked as first order", + "Deeded", + 1, + false, + nil, + }, +} + +func TestIsIsogram(t *testing.T) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + actualVal, actualErr := strings.IsIsogram(test.input, test.order) + + if actualErr != nil && test.expectedErr.Error() != actualErr.Error() { + t.Errorf("Expected to be '%v' for string %s but was '%v'.", test.expectedErr, test.input, actualErr) + } + + if test.expectedVal != actualVal { + t.Errorf("Expected to be '%v' for string %s but was '%v'.", test.expectedVal, test.input, actualVal) + } + }) + } +} From 54f082bf028e5d6dc09f63167ed837e5d4501759 Mon Sep 17 00:00:00 2001 From: Michele Caci Date: Mon, 21 Nov 2022 12:20:16 +0100 Subject: [PATCH 105/202] feat(cipher/transposition): add fuzz test to transposition cipher #600 (#601) --- cipher/transposition/transposition.go | 43 ++++++----- cipher/transposition/transposition_test.go | 84 +++++++++++++++------- 2 files changed, 78 insertions(+), 49 deletions(-) diff --git a/cipher/transposition/transposition.go b/cipher/transposition/transposition.go index e27020b43..6365ffa4a 100644 --- a/cipher/transposition/transposition.go +++ b/cipher/transposition/transposition.go @@ -8,19 +8,16 @@ package transposition import ( + "errors" + "fmt" "sort" "strings" ) -type NoTextToEncryptError struct{} -type KeyMissingError struct{} +var ErrNoTextToEncrypt = errors.New("no text to encrypt") +var ErrKeyMissing = errors.New("missing Key") -func (n *NoTextToEncryptError) Error() string { - return "No text to encrypt" -} -func (n *KeyMissingError) Error() string { - return "Missing Key" -} +const placeholder = ' ' func getKey(keyWord string) []int { keyWord = strings.ToLower(keyWord) @@ -51,56 +48,58 @@ func getIndex(wordSet []rune, subString rune) int { return 0 } -func Encrypt(text []rune, keyWord string) (string, error) { +func Encrypt(text []rune, keyWord string) ([]rune, error) { key := getKey(keyWord) - space := ' ' keyLength := len(key) textLength := len(text) if keyLength <= 0 { - return "", &KeyMissingError{} + return nil, ErrKeyMissing } if textLength <= 0 { - return "", &NoTextToEncryptError{} + return nil, ErrNoTextToEncrypt + } + if text[len(text)-1] == placeholder { + return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder) } n := textLength % keyLength for i := 0; i < keyLength-n; i++ { - text = append(text, space) + text = append(text, placeholder) } textLength = len(text) - result := "" + var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[key[j]-1] = text[i+j] } - result += string(transposition) + result = append(result, transposition...) } return result, nil } -func Decrypt(text []rune, keyWord string) (string, error) { +func Decrypt(text []rune, keyWord string) ([]rune, error) { key := getKey(keyWord) textLength := len(text) if textLength <= 0 { - return "", &NoTextToEncryptError{} + return nil, ErrNoTextToEncrypt } keyLength := len(key) if keyLength <= 0 { - return "", &KeyMissingError{} + return nil, ErrKeyMissing } - space := ' ' n := textLength % keyLength for i := 0; i < keyLength-n; i++ { - text = append(text, space) + text = append(text, placeholder) } - result := "" + var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[j] = text[i+key[j]-1] } - result += string(transposition) + result = append(result, transposition...) } + result = []rune(strings.TrimRight(string(result), string(placeholder))) return result, nil } diff --git a/cipher/transposition/transposition_test.go b/cipher/transposition/transposition_test.go index f2f155a15..250f43832 100644 --- a/cipher/transposition/transposition_test.go +++ b/cipher/transposition/transposition_test.go @@ -8,20 +8,18 @@ package transposition import ( "errors" "math/rand" - "strings" + "reflect" "testing" ) -const enAlphabet = "abcdefghijklmnopqrstuvwxyz " +const enAlphabet = "abcdefghijklmnopqrstuvwxyz" -func getTexts() []string { - return []string{ - "Ilya Sokolov", - "A slice literal is declared just like an array literal, except you leave out the element count", - "Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.", - "Go’s treatment of errors as values has served us well over the last decade. Although the standard library’s support for errors has been minimal—just the errors.New and fmt.Errorf functions, which produce errors that contain only a message—the built-in error interface allows Go programmers to add whatever information they desire. All it requires is a type that implements an Error method:", - "А тут для примера русский текст", - } +var texts = []string{ + "Ilya Sokolov", + "A slice literal is declared just like an array literal, except you leave out the element count", + "Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.", + "Go’s treatment of errors as values has served us well over the last decade. Although the standard library’s support for errors has been minimal—just the errors.New and fmt.Errorf functions, which produce errors that contain only a message—the built-in error interface allows Go programmers to add whatever information they desire. All it requires is a type that implements an Error method:", + "А тут для примера русский текст", } func getRandomString() string { @@ -36,12 +34,12 @@ func getRandomString() string { func TestEncrypt(t *testing.T) { fn := func(text string, keyWord string) (bool, error) { encrypt, err := Encrypt([]rune(text), keyWord) - if err != nil && !errors.Is(err, &NoTextToEncryptError{}) && !errors.Is(err, &KeyMissingError{}) { + if err != nil && !errors.Is(err, ErrNoTextToEncrypt) && !errors.Is(err, ErrKeyMissing) { t.Error("Unexpected error ", err) } - return text == encrypt, err + return text == string(encrypt), err } - for _, s := range getTexts() { + for _, s := range texts { if check, err := fn(s, getRandomString()); check || err != nil { t.Error("String ", s, " not encrypted") } @@ -52,12 +50,12 @@ func TestEncrypt(t *testing.T) { } func TestDecrypt(t *testing.T) { - for _, s := range getTexts() { + for _, s := range texts { keyWord := getRandomString() encrypt, errEncrypt := Encrypt([]rune(s), keyWord) if errEncrypt != nil && - !errors.Is(errEncrypt, &NoTextToEncryptError{}) && - !errors.Is(errEncrypt, &KeyMissingError{}) { + !errors.Is(errEncrypt, ErrNoTextToEncrypt) && + !errors.Is(errEncrypt, ErrKeyMissing) { t.Error("Unexpected error ", errEncrypt) } if errEncrypt != nil { @@ -65,39 +63,71 @@ func TestDecrypt(t *testing.T) { } decrypt, errDecrypt := Decrypt([]rune(encrypt), keyWord) if errDecrypt != nil && - !errors.Is(errDecrypt, &NoTextToEncryptError{}) && - !errors.Is(errDecrypt, &KeyMissingError{}) { + !errors.Is(errDecrypt, ErrNoTextToEncrypt) && + !errors.Is(errDecrypt, ErrKeyMissing) { t.Error("Unexpected error ", errDecrypt) } if errDecrypt != nil { t.Error(errDecrypt) } - if encrypt == decrypt { + if reflect.DeepEqual(encrypt, decrypt) { t.Error("String ", s, " not encrypted") } - if encrypt == s { + if reflect.DeepEqual(encrypt, s) { t.Error("String ", s, " not encrypted") } } } func TestEncryptDecrypt(t *testing.T) { - text := "Test text for checking the algorithm" + text := []rune("Test text for checking the algorithm") key1 := "testKey" key2 := "Test Key2" - encrypt, errEncrypt := Encrypt([]rune(text), key1) + encrypt, errEncrypt := Encrypt(text, key1) if errEncrypt != nil { t.Error(errEncrypt) } - decrypt, errDecrypt := Decrypt([]rune(encrypt), key1) + decrypt, errDecrypt := Decrypt(encrypt, key1) if errDecrypt != nil { t.Error(errDecrypt) } - if strings.Contains(decrypt, text) == false { - t.Error("The string was not decrypted correctly") + if !reflect.DeepEqual(decrypt, text) { + t.Errorf("The string was not decrypted correctly %q %q", decrypt, text) } decrypt, _ = Decrypt([]rune(encrypt), key2) - if strings.Contains(decrypt, text) == true { - t.Error("The string was decrypted with a different key") + if reflect.DeepEqual(decrypt, text) { + t.Errorf("The string was decrypted with a different key: %q %q", decrypt, text) + } +} + +func FuzzTransposition(f *testing.F) { + for _, transpositionTestInput := range texts { + f.Add(transpositionTestInput) } + f.Fuzz(func(t *testing.T, input string) { + keyword := getRandomString() + message := []rune(input) + encrypted, err := Encrypt(message, keyword) + switch { + case err == nil: + case errors.Is(err, ErrKeyMissing), + errors.Is(err, ErrNoTextToEncrypt): + return + default: + t.Fatalf("unexpected error when encrypting string %q: %v", input, err) + } + decrypted, err := Decrypt([]rune(encrypted), keyword) + switch { + case err == nil: + case errors.Is(err, ErrKeyMissing), + errors.Is(err, ErrNoTextToEncrypt): + return + default: + t.Fatalf("unexpected error when decrypting string %q: %v", encrypted, err) + } + + if !reflect.DeepEqual(message, decrypted) { + t.Fatalf("expected: %+v, got: %+v", message, []rune(decrypted)) + } + }) } From d21128ee8cc06147246d3cf872ab45023962369e Mon Sep 17 00:00:00 2001 From: tabosuke <45633620+tabo-syu@users.noreply.github.com> Date: Tue, 22 Nov 2022 02:12:53 +0900 Subject: [PATCH 106/202] fix: Fix file name of constraints package (#608) --- constraints/{contraints.go => constraints.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename constraints/{contraints.go => constraints.go} (100%) diff --git a/constraints/contraints.go b/constraints/constraints.go similarity index 100% rename from constraints/contraints.go rename to constraints/constraints.go From c027418e6c6529b86232dc3999a43b918cf5c874 Mon Sep 17 00:00:00 2001 From: hypntc <88018994+hypntc@users.noreply.github.com> Date: Sat, 26 Nov 2022 19:41:57 +0100 Subject: [PATCH 107/202] algorithm: bucketsort and pancakesort (#606) --- README.md | 38 +++++++++++++++++++------------------ sort/bucketsort.go | 46 +++++++++++++++++++++++++++++++++++++++++++++ sort/pancakesort.go | 44 +++++++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 16 ++++++++++++++++ 4 files changed, 126 insertions(+), 18 deletions(-) create mode 100644 sort/bucketsort.go create mode 100644 sort/pancakesort.go diff --git a/README.md b/README.md index 06be382be..931f1af5c 100644 --- a/README.md +++ b/README.md @@ -867,24 +867,26 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. -2. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. -3. [`Count`](./sort/countingsort.go#L11): No description provided. -4. [`Exchange`](./sort/exchangesort.go#L8): No description provided. -5. [`HeapSort`](./sort/heapsort.go#L116): No description provided. -6. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort -7. [`Insertion`](./sort/insertionsort.go#L5): No description provided. -8. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice -9. [`MergeIter`](./sort/mergesort.go#L55): No description provided. -10. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines -11. [`Partition`](./sort/quicksort.go#L12): No description provided. -12. [`Patience`](./sort/patiencesort.go#L13): No description provided. -13. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. -14. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array -15. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array -16. [`RadixSort`](./sort/radixsort.go#L43): No description provided. -17. [`Selection`](./sort/selectionsort.go#L5): No description provided. -18. [`Shell`](./sort/shellsort.go#L5): No description provided. -19. [`Simple`](./sort/simplesort.go#L13): No description provided. +2. [`Bucket Sort`](./sort/bucketsort.go#L5): Bucket Sort works with the idea of distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. +3. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. +4. [`Count`](./sort/countingsort.go#L11): No description provided. +5. [`Exchange`](./sort/exchangesort.go#L8): No description provided. +6. [`HeapSort`](./sort/heapsort.go#L116): No description provided. +7. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +8. [`Insertion`](./sort/insertionsort.go#L5): No description provided. +9. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice +10. [`MergeIter`](./sort/mergesort.go#L55): No description provided. +11. [`Pancake Sort`](./sort/pancakesort.go#L7): Pancake Sort is a sorting algorithm that is similar to selection sort that reverses elements of an array. The Pancake Sort uses the flip operation to sort the array. +12. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines +13. [`Partition`](./sort/quicksort.go#L12): No description provided. +14. [`Patience`](./sort/patiencesort.go#L13): No description provided. +15. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. +16. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +17. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +18. [`RadixSort`](./sort/radixsort.go#L43): No description provided. +19. [`Selection`](./sort/selectionsort.go#L5): No description provided. +20. [`Shell`](./sort/shellsort.go#L5): No description provided. +21. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types diff --git a/sort/bucketsort.go b/sort/bucketsort.go new file mode 100644 index 000000000..3f05a41a4 --- /dev/null +++ b/sort/bucketsort.go @@ -0,0 +1,46 @@ +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// Bucket sorts a slice. It is mainly useful +// when input is uniformly distributed over a range. +func Bucket[T constraints.Number](arr []T) []T { + // early return if the array too small + if len(arr) <= 1 { + return arr + } + + // find the maximum and minimum elements in arr + max := arr[0] + min := arr[0] + for _, v := range arr { + if v > max { + max = v + } + if v < min { + min = v + } + } + + // create an empty bucket for each element in arr + bucket := make([][]T, len(arr)) + + // put each element in the appropriate bucket + for _, v := range arr { + bucketIndex := int((v - min) / (max - min) * T(len(arr)-1)) + bucket[bucketIndex] = append(bucket[bucketIndex], v) + } + + // use insertion sort to sort each bucket + for i := range bucket { + bucket[i] = Insertion(bucket[i]) + } + + // concatenate the sorted buckets + sorted := make([]T, 0, len(arr)) + for _, v := range bucket { + sorted = append(sorted, v...) + } + + return sorted +} diff --git a/sort/pancakesort.go b/sort/pancakesort.go new file mode 100644 index 000000000..a809ba1c4 --- /dev/null +++ b/sort/pancakesort.go @@ -0,0 +1,44 @@ +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// Pancake sorts a slice using flip operations, +// where flip refers to the idea of reversing the +// slice from index `0` to `i`. +func Pancake[T constraints.Ordered](arr []T) []T { + // early return if the array too small + if len(arr) <= 1 { + return arr + } + + // start from the end of the array + for i := len(arr) - 1; i > 0; i-- { + // find the index of the maximum element in arr + max := 0 + for j := 1; j <= i; j++ { + if arr[j] > arr[max] { + max = j + } + } + + // if the maximum element is not at the end of the array + if max != i { + // flip the maximum element to the beginning of the array + arr = flip(arr, max) + + // flip the maximum element to the end of the array by flipping the whole array + arr = flip(arr, i) + } + } + + return arr +} + +// flip reverses the input slice from `0` to `i`. +func flip[T constraints.Ordered](arr []T, i int) []T { + for j := 0; j < i; j++ { + arr[j], arr[i] = arr[i], arr[j] + i-- + } + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index ecee3d33c..9f34a23cb 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -81,6 +81,10 @@ func TestBubble(t *testing.T) { testFramework(t, sort.Bubble[int]) } +func TestBucketSort(t *testing.T) { + testFramework(t, sort.Bucket[int]) +} + func TestExchange(t *testing.T) { testFramework(t, sort.Exchange[int]) } @@ -153,6 +157,10 @@ func TestComb(t *testing.T) { testFramework(t, sort.Comb[int]) } +func TestPancakeSort(t *testing.T) { + testFramework(t, sort.Pancake[int]) +} + func TestPigeonhole(t *testing.T) { testFramework(t, sort.Pigeonhole[int]) } @@ -206,6 +214,10 @@ func BenchmarkBubble(b *testing.B) { benchmarkFramework(b, sort.Bubble[int]) } +func BenchmarkBucketSort(b *testing.B) { + benchmarkFramework(b, sort.Bucket[int]) +} + func BenchmarkExchange(b *testing.B) { benchmarkFramework(b, sort.Exchange[int]) } @@ -263,6 +275,10 @@ func BenchmarkComb(b *testing.B) { benchmarkFramework(b, sort.Comb[int]) } +func BenchmarkPancakeSort(b *testing.B) { + benchmarkFramework(b, sort.Pancake[int]) +} + func BenchmarkPigeonhole(b *testing.B) { benchmarkFramework(b, sort.Pigeonhole[int]) } From 41fa294871a58f0da65500a01c413e287fdbf0b4 Mon Sep 17 00:00:00 2001 From: Reo Uehara <47747828+uh-zz@users.noreply.github.com> Date: Sun, 4 Dec 2022 23:29:58 +0900 Subject: [PATCH 108/202] Add: kmp(Knuth-Morris-Pratt) algorithm (#586) --- README.md | 8 +-- strings/kmp/kmp.go | 132 ++++++++++------------------------------ strings/kmp/kmp_test.go | 87 ++++++++++++++------------ 3 files changed, 81 insertions(+), 146 deletions(-) diff --git a/README.md b/README.md index 931f1af5c..f672ba088 100644 --- a/README.md +++ b/README.md @@ -435,13 +435,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Kmp`](./strings/kmp/kmp.go#L70): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. Prints whether the word/pattern was found and on what position in the text or not. m - current match in text, i - current character in w, c - amount of comparisons. - ---- -##### Types - -1. [`Result`](./strings/kmp/kmp.go#L15): No description provided. - +1. [`Kmp`](./strings/kmp/kmp.go#L4): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. ---
diff --git a/strings/kmp/kmp.go b/strings/kmp/kmp.go index a0f138724..cef57d7d1 100644 --- a/strings/kmp/kmp.go +++ b/strings/kmp/kmp.go @@ -1,117 +1,49 @@ package kmp -import ( - "fmt" -) - -// User defined. -// Set to true to read input from two command line arguments -// Set to false to read input from two files "pattern.txt" and "text.txt" - -// const isTakingInputFromCommandLine bool = true - -const notFoundPosition int = -1 - -type Result struct { - resultPosition int - numberOfComparison int -} - -// Implementation of Knuth-Morris-Pratt algorithm (Prefix based approach). -// Requires either a two command line arguments separated by a single space, -// or two files in the same folder: "pattern.txt" containing the string to -// be searched for, "text.txt" containing the text to be searched in. -// func main() { -// var text string -// var word string - -// if isTakingInputFromCommandLine { // case of command line input -// args := os.Args -// if len(args) <= 2 { -// log.Fatal("Not enough arguments. Two string arguments separated by spaces are required!") -// } -// word = args[1] -// text = args[2] -// for i := 3; i < len(args); i++ { -// text = text + " " + args[i] -// } -// } else { // case of file input -// patFile, err := ioutil.ReadFile("../pattern.txt") -// if err != nil { -// log.Fatal(err) -// } -// textFile, err := ioutil.ReadFile("../text.txt") -// if err != nil { -// log.Fatal(err) -// } -// text = string(textFile) -// word = string(patFile) -// } +// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. +func Kmp(word, text string, patternTable []int) []int { + if len(word) > len(text) { + return nil + } -// if len(word) > len(text) { -// log.Fatal("Pattern is longer than text!") -// } -// fmt.Printf("\nRunning: Knuth-Morris-Pratt algorithm.\n\n") -// fmt.Printf("Search word (%d chars long): %q.\n", len(word), word) -// fmt.Printf("Text (%d chars long): %q.\n\n", len(text), text) + var ( + i, j int + matches []int + ) + for i+j < len(text) { -// r := kmp(text, word) -// if r.resultPosition == notFoundPosition { -// fmt.Printf("\n\nWord was not found.\n%d comparisons were done.", r.numberOfComparison) -// } else { -// fmt.Printf("\n\nWord %q was found at position %d in %q. \n%d comparisons were done.", word, -// r.resultPosition, text, r.numberOfComparison) -// } -// } + if word[j] == text[i+j] { + j++ + if j == len(word) { + matches = append(matches, i) -// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. -// Prints whether the word/pattern was found and on what position in the text or not. -// m - current match in text, i - current character in w, c - amount of comparisons. -func Kmp(text string, word string) Result { - m, i, c := 0, 0, 0 - t := kmpTable(word) - for m+i < len(text) { - fmt.Printf("\n comparing characters %c %c at positions %d %d", text[m+i], word[i], m+i, i) - c++ - if word[i] == text[m+i] { - fmt.Printf(" - match") - if i == len(word)-1 { - return Result{ - m, c, - } + i = i + j + j = 0 } - i++ } else { - m = m + i - t[i] - if t[i] > -1 { - i = t[i] + i = i + j - patternTable[j] + if patternTable[j] > -1 { + j = patternTable[j] } else { - i = 0 + j = 0 } } } - return Result{notFoundPosition, - c, - } + return matches } -// Table building algorithm. -// Takes word to be analyzed and table to be filled. -func kmpTable(word string) (t []int) { - t = make([]int, len(word)) - pos, cnd := 2, 0 - t[0], t[1] = -1, 0 - for pos < len(word) { - if word[pos-1] == word[cnd] { - cnd++ - t[pos] = cnd - pos++ - } else if cnd > 0 { - cnd = t[cnd] - } else { - t[pos] = 0 - pos++ +// table building for kmp algorithm. +func table(w string) []int { + var ( + t []int = []int{-1} + k int + ) + for j := 1; j < len(w); j++ { + k = j - 1 + for w[0:k] != w[j-k:j] && k > 0 { + k-- } + t = append(t, k) } return t } diff --git a/strings/kmp/kmp_test.go b/strings/kmp/kmp_test.go index f25c68a07..4d012986a 100644 --- a/strings/kmp/kmp_test.go +++ b/strings/kmp/kmp_test.go @@ -5,48 +5,57 @@ import ( "testing" ) -var testCases = []struct { - name string - word string - text string - expected Result -}{ - { - "String comparison on single pattern match", - "announce", - "CPM_annual_conference_announce", - Result{ - 22, - 32, - }, - }, - { - "String comparison on multiple pattern match", - "AABA", - "AABAACAADAABAABA", - Result{ - 0, - 4, - }, - }, - { - "String comparison with not found pattern", - "AABC", - "AABAACAADAABAABA", - Result{ - -1, - 23, +func TestKmp(t *testing.T) { + type args struct { + word string + text string + patternTable []int + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "test1", + args: args{ + word: "ab", + text: "ababacaab", + patternTable: table("ababacaab"), + }, + want: []int{0, 2, 7}, }, - }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Kmp(tt.args.word, tt.args.text, tt.args.patternTable); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Kmp() = %v, want %v", got, tt.want) + } + }) + } } -func TestKMP(t *testing.T) { - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - actual := Kmp(tc.text, tc.word) - if !reflect.DeepEqual(actual, tc.expected) { - t.Errorf("Expected matches for pattern '%s' for string '%s' are: %v steps at position %v, but actual matches are: %v steps at position %v", - tc.word, tc.text, tc.expected.numberOfComparison, tc.expected.resultPosition, actual.numberOfComparison, actual.resultPosition) +func TestTable(t *testing.T) { + type args struct { + w string + } + tests := []struct { + name string + args args + want []int + }{ + { + name: "test1", + args: args{ + w: "ababacaab", + }, + want: []int{-1, 0, 0, 1, 2, 3, 0, 1, 1}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := table(tt.args.w); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Table() = %v, want %v", got, tt.want) } }) } From 1be70bd84835778d9538bd20c0db296e00ea91c3 Mon Sep 17 00:00:00 2001 From: Rangding Zhang Date: Thu, 8 Dec 2022 20:13:34 +0800 Subject: [PATCH 109/202] rename LRU field capacity->size, maxCapacity->capacity (#612) --- cache/lru.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/cache/lru.go b/cache/lru.go index d937118f9..c6b8c734e 100644 --- a/cache/lru.go +++ b/cache/lru.go @@ -10,19 +10,19 @@ type item struct { } type LRU struct { - dl *linkedlist.Doubly[any] - capacity int - maxCapacity int - storage map[string]*linkedlist.Node[any] + dl *linkedlist.Doubly[any] + size int + capacity int + storage map[string]*linkedlist.Node[any] } // NewLRU represent initiate lru cache with capacity func NewLRU(capacity int) LRU { return LRU{ - dl: linkedlist.NewDoubly[any](), - storage: make(map[string]*linkedlist.Node[any], capacity), - capacity: 0, - maxCapacity: capacity, + dl: linkedlist.NewDoubly[any](), + storage: make(map[string]*linkedlist.Node[any], capacity), + size: 0, + capacity: capacity, } } @@ -49,17 +49,17 @@ func (c *LRU) Put(key string, value any) { return } - if c.capacity >= c.maxCapacity { + if c.size >= c.capacity { e := c.dl.Front() dk := e.Val.(item).key c.dl.Remove(e) delete(c.storage, dk) - c.capacity-- + c.size-- } n := item{key: key, value: value} c.dl.AddAtEnd(n) ne := c.dl.Back() c.storage[key] = ne - c.capacity++ + c.size++ } From 83cff67238da18d5a94c917ae713f5697b98a383 Mon Sep 17 00:00:00 2001 From: Tan <118096187+qizhaoTan@users.noreply.github.com> Date: Thu, 8 Dec 2022 21:30:23 +0800 Subject: [PATCH 110/202] feat: add heap implementation using generic. (#607) --- structure/heap/heap.go | 98 +++++++++++++++++++++++ structure/heap/heap_test.go | 150 ++++++++++++++++++++++++++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 structure/heap/heap.go create mode 100644 structure/heap/heap_test.go diff --git a/structure/heap/heap.go b/structure/heap/heap.go new file mode 100644 index 000000000..693f1ab88 --- /dev/null +++ b/structure/heap/heap.go @@ -0,0 +1,98 @@ +package heap + +import ( + "errors" + "github.com/TheAlgorithms/Go/constraints" +) + +// Heap heap implementation using generic. +type Heap[T any] struct { + heaps []T + lessFunc func(a, b T) bool +} + +// New gives a new heap object. +func New[T constraints.Ordered]() *Heap[T] { + less := func(a, b T) bool { + return a < b + } + h, _ := NewAny[T](less) + return h +} + +// NewAny gives a new heap object. element can be anything, but must provide less function. +func NewAny[T any](less func(a, b T) bool) (*Heap[T], error) { + if less == nil { + return nil, errors.New("less func is necessary") + } + return &Heap[T]{ + lessFunc: less, + }, nil +} + +// Push pushes the element t onto the heap. +// The complexity is O(log n) where n = h.Len(). +func (h *Heap[T]) Push(t T) { + h.heaps = append(h.heaps, t) + h.up(len(h.heaps) - 1) +} + +// Top returns the minimum element (according to Less) from the heap. +// Top panics if the heap is empty. +func (h *Heap[T]) Top() T { + return h.heaps[0] +} + +// Pop removes the minimum element (according to Less) from the heap. +// The complexity is O(log n) where n = h.Len(). +func (h *Heap[T]) Pop() { + if len(h.heaps) <= 1 { + h.heaps = nil + return + } + h.swap(0, len(h.heaps)-1) + h.heaps = h.heaps[:len(h.heaps)-1] + h.down(0) +} + +// Empty returns the heap is empty or not. +func (h *Heap[T]) Empty() bool { + return len(h.heaps) == 0 +} + +// Size returns the size of the heap +func (h *Heap[T]) Size() int { + return len(h.heaps) +} + +func (h *Heap[T]) swap(i, j int) { + h.heaps[i], h.heaps[j] = h.heaps[j], h.heaps[i] +} + +func (h *Heap[T]) up(child int) { + if child <= 0 { + return + } + parent := (child - 1) >> 1 + if !h.lessFunc(h.heaps[child], h.heaps[parent]) { + return + } + h.swap(child, parent) + h.up(parent) +} + +func (h *Heap[T]) down(parent int) { + lessIdx := parent + lChild, rChild := (parent<<1)+1, (parent<<1)+2 + if lChild < len(h.heaps) && h.lessFunc(h.heaps[lChild], h.heaps[lessIdx]) { + lessIdx = lChild + } + if rChild < len(h.heaps) && h.lessFunc(h.heaps[rChild], h.heaps[lessIdx]) { + lessIdx = rChild + } + if lessIdx == parent { + return + } + h.swap(lessIdx, parent) + h.down(lessIdx) +} diff --git a/structure/heap/heap_test.go b/structure/heap/heap_test.go new file mode 100644 index 000000000..00ba54d7e --- /dev/null +++ b/structure/heap/heap_test.go @@ -0,0 +1,150 @@ +package heap_test + +import ( + "github.com/TheAlgorithms/Go/structure/heap" + "reflect" + "testing" +) + +type testInt int + +func (u testInt) Less(o testInt) bool { + return u < o +} + +type testStudent struct { + Name string + Score int64 +} + +func (u testStudent) Less(o testStudent) bool { + if u.Score == o.Score { + return u.Name < o.Name + } + return u.Score > o.Score +} + +func TestHeap_Empty(t *testing.T) { + tests := []struct { + name string + want bool + }{ + {name: "empty", want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h := heap.New[testInt]() + if got := h.Empty(); got != tt.want { + t.Errorf("Empty() = %v, want %v", got, tt.want) + } + }) + } +} + +type testOpType int + +const ( + testPush = 1 + testPop = 2 + testTop = 3 + testEmpty = 4 +) + +type testOp[T any] struct { + typ testOpType + x T + isEmpty bool +} + +type testStruct[T any] struct { + name string + ops []testOp[T] +} + +func TestHeapExample1(t *testing.T) { + tests1 := []testStruct[testInt]{ + { + name: "example 1", + ops: []testOp[testInt]{ + {typ: testEmpty, isEmpty: true}, + {typ: testPush, x: 10}, + {typ: testEmpty, isEmpty: false}, + {typ: testTop, x: 10}, + {typ: testPop}, + {typ: testEmpty, isEmpty: true}, + {typ: testPush, x: 9}, + {typ: testPush, x: 8}, + {typ: testPop}, + {typ: testPush, x: 3}, + {typ: testTop, x: 3}, + {typ: testPush, x: 2}, + {typ: testTop, x: 2}, + {typ: testPush, x: 4}, + {typ: testPush, x: 6}, + {typ: testPush, x: 5}, + {typ: testTop, x: 2}, + {typ: testPop}, + {typ: testTop, x: 3}, + {typ: testPop}, + {typ: testPop}, + {typ: testTop, x: 5}, + {typ: testEmpty, isEmpty: false}, + }, + }, + } + testFunc(t, tests1, testInt.Less) +} + +func TestHeapExample2(t *testing.T) { + tests1 := []testStruct[testStudent]{ + { + name: "example 2", + ops: []testOp[testStudent]{ + {typ: testPush, x: testStudent{Name: "Alan", Score: 87}}, + {typ: testPush, x: testStudent{Name: "Bob", Score: 98}}, + {typ: testTop, x: testStudent{Name: "Bob", Score: 98}}, + {typ: testPop}, + {typ: testPush, x: testStudent{Name: "Carl", Score: 70}}, + {typ: testTop, x: testStudent{Name: "Alan", Score: 87}}, + }, + }, + } + testFunc(t, tests1, testStudent.Less) +} + +func testFunc[T any](t *testing.T, tests []testStruct[T], less func(a, b T) bool) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h, err := heap.NewAny[T](less) + if err != nil { + t.Errorf("New Heap err %v", err) + } + for i, op := range tt.ops { + switch op.typ { + case testPush: + oldSize := h.Size() + h.Push(op.x) + newSize := h.Size() + if oldSize+1 != newSize { + t.Errorf("op %d testPush %v failed", i, op.x) + } + case testPop: + oldSize := h.Size() + h.Pop() + newSize := h.Size() + if oldSize-1 != newSize { + t.Errorf("op %d testPop %v failed", i, op.x) + } + case testTop: + if got := h.Top(); !reflect.DeepEqual(got, op.x) { + t.Errorf("op %d testTop %v, want %v", i, got, op.x) + } + case testEmpty: + if got := h.Empty(); got != op.isEmpty { + t.Errorf("op %d Empty() = %v, want %v", i, got, op.isEmpty) + } + } + } + }) + } +} From e5658c3df734e87874ec5e7a508b4b1fc3a2d770 Mon Sep 17 00:00:00 2001 From: Paulden Date: Sun, 15 Jan 2023 22:34:30 +0800 Subject: [PATCH 111/202] fix: Tree package bug (#589) * add Parent to binary search tree * refactor NIL in all trees * add Successor and Predecessor to * fix: tree package bug * remove dummy variable leaf * Refactoring: remove method; make NIL a sentinel value for 3 trees, and eliminate nil in those implementations. * change the method isRBTree to isRB * fix:remove base struct, separate Node to three different nodes that complete Node Interface; still save NIL, but make it unexported * Add more comments; Move Tree interface to tree_test package for future development. * code tidy * fix typo in comments --- structure/tree/avl.go | 309 ++++++++++++++++----- structure/tree/avl_test.go | 164 ++++++++---- structure/tree/bstree.go | 228 +++++++++++++--- structure/tree/bstree_test.go | 71 ++++- structure/tree/example_test.go | 167 ++++++++++++ structure/tree/rbtree.go | 477 +++++++++++++++++++-------------- structure/tree/rbtree_test.go | 91 ++----- structure/tree/tree.go | 262 ++++++------------ structure/tree/tree_test.go | 227 ++++++++-------- 9 files changed, 1252 insertions(+), 744 deletions(-) create mode 100644 structure/tree/example_test.go diff --git a/structure/tree/avl.go b/structure/tree/avl.go index 7cb62d885..4b0aee7c4 100644 --- a/structure/tree/avl.go +++ b/structure/tree/avl.go @@ -1,3 +1,9 @@ +// AVL tree is a self-balancing binary search tree. +// +// For more details check out those link below here: +// Wikipedia article: https://en.wikipedia.org/wiki/AVL_tree +// see avl.go + package tree import ( @@ -5,20 +11,58 @@ import ( "github.com/TheAlgorithms/Go/math/max" ) +// Verify Interface Compliance +var _ Node[int] = &AVLNode[int]{} + +// AVLNode represents a single node in the AVL. +type AVLNode[T constraints.Ordered] struct { + key T + parent *AVLNode[T] + left *AVLNode[T] + right *AVLNode[T] + height int +} + +func (n *AVLNode[T]) Key() T { + return n.key +} + +func (n *AVLNode[T]) Parent() Node[T] { + return n.parent +} + +func (n *AVLNode[T]) Left() Node[T] { + return n.left +} + +func (n *AVLNode[T]) Right() Node[T] { + return n.right +} + +func (n *AVLNode[T]) Height() int { + return n.height +} + +// AVL represents a AVL tree. +// By default, _NIL = nil. type AVL[T constraints.Ordered] struct { - *binaryTree[T] + Root *AVLNode[T] + _NIL *AVLNode[T] // a sentinel value for nil } -// NewAVL create a novel AVL tree +// NewAVL creates a novel AVL tree func NewAVL[T constraints.Ordered]() *AVL[T] { return &AVL[T]{ - binaryTree: &binaryTree[T]{ - Root: nil, - NIL: nil, - }, + Root: nil, + _NIL: nil, } } +// Empty determines the AVL tree is empty +func (avl *AVL[T]) Empty() bool { + return avl.Root == avl._NIL +} + // Push a chain of Node's into the AVL Tree func (avl *AVL[T]) Push(keys ...T) { for _, k := range keys { @@ -36,42 +80,140 @@ func (avl *AVL[T]) Delete(key T) bool { return true } -func (avl *AVL[T]) pushHelper(root *Node[T], key T) *Node[T] { - if root == nil { - return &Node[T]{ - Key: key, - Height: 1, +// Get a Node from the AVL Tree +func (avl *AVL[T]) Get(key T) (Node[T], bool) { + return searchTreeHelper[T](avl.Root, avl._NIL, key) +} + +// Has Determines the tree has the node of Key +func (avl *AVL[T]) Has(key T) bool { + _, ok := searchTreeHelper[T](avl.Root, avl._NIL, key) + return ok +} + +// PreOrder Traverses the tree in the following order Root --> Left --> Right +func (avl *AVL[T]) PreOrder() []T { + traversal := make([]T, 0) + preOrderRecursive[T](avl.Root, avl._NIL, &traversal) + return traversal +} + +// InOrder Traverses the tree in the following order Left --> Root --> Right +func (avl *AVL[T]) InOrder() []T { + return inOrderHelper[T](avl.Root, avl._NIL) +} + +// PostOrder traverses the tree in the following order Left --> Right --> Root +func (avl *AVL[T]) PostOrder() []T { + traversal := make([]T, 0) + postOrderRecursive[T](avl.Root, avl._NIL, &traversal) + return traversal +} + +// LevelOrder returns the level order traversal of the tree +func (avl *AVL[T]) LevelOrder() []T { + traversal := make([]T, 0) + levelOrderHelper[T](avl.Root, avl._NIL, &traversal) + return traversal +} + +// AccessNodesByLayer accesses nodes layer by layer (2-D array), instead of printing the results as 1-D array. +func (avl *AVL[T]) AccessNodesByLayer() [][]T { + return accessNodeByLayerHelper[T](avl.Root, avl._NIL) +} + +// Depth returns the calculated depth of the AVL tree +func (avl *AVL[T]) Depth() int { + return calculateDepth[T](avl.Root, avl._NIL, 0) +} + +// Max returns the Max value of the tree +func (avl *AVL[T]) Max() (T, bool) { + ret := maximum[T](avl.Root, avl._NIL) + if ret == avl._NIL { + var dft T + return dft, false + } + return ret.Key(), true +} + +// Min returns the Min value of the tree +func (avl *AVL[T]) Min() (T, bool) { + ret := minimum[T](avl.Root, avl._NIL) + if ret == avl._NIL { + var dft T + return dft, false + } + return ret.Key(), true +} + +// Predecessor returns the Predecessor of the node of Key +// if there is no predecessor, return default value of type T and false +// otherwise return the Key of predecessor and true +func (avl *AVL[T]) Predecessor(key T) (T, bool) { + node, ok := searchTreeHelper[T](avl.Root, avl._NIL, key) + if !ok { + var dft T + return dft, ok + } + return predecessorHelper[T](node, avl._NIL) +} + +// Successor returns the Successor of the node of Key +// if there is no successor, return default value of type T and false +// otherwise return the Key of successor and true +func (avl *AVL[T]) Successor(key T) (T, bool) { + node, ok := searchTreeHelper[T](avl.Root, avl._NIL, key) + if !ok { + var dft T + return dft, ok + } + return successorHelper[T](node, avl._NIL) +} + +func (avl *AVL[T]) pushHelper(root *AVLNode[T], key T) *AVLNode[T] { + if root == avl._NIL { + return &AVLNode[T]{ + key: key, + left: avl._NIL, + right: avl._NIL, + parent: avl._NIL, + height: 1, } } switch { - case key < root.Key: - root.Left = avl.pushHelper(root.Left, key) - case key > root.Key: - root.Right = avl.pushHelper(root.Right, key) + case key < root.key: + tmp := avl.pushHelper(root.left, key) + tmp.parent = root + root.left = tmp + case key > root.key: + tmp := avl.pushHelper(root.right, key) + tmp.parent = root + root.right = tmp default: return root } // balance the tree - root.Height = avl.height(root) + root.height = avl.height(root) bFactor := avl.balanceFactor(root) if bFactor > 1 { switch { - case key < root.Left.Key: + case key < root.left.key: return avl.rightRotate(root) - case key > root.Left.Key: - root.Left = avl.leftRotate(root.Left) + case key > root.left.key: + root.left = avl.leftRotate(root.left) return avl.rightRotate(root) } } if bFactor < -1 { switch { - case key > root.Right.Key: + case key > root.right.key: return avl.leftRotate(root) - case key < root.Right.Key: - root.Right = avl.rightRotate(root.Right) + case key < root.right.key: + root.right = avl.rightRotate(root.right) return avl.leftRotate(root) } } @@ -79,57 +221,70 @@ func (avl *AVL[T]) pushHelper(root *Node[T], key T) *Node[T] { return root } -func (avl *AVL[T]) deleteHelper(root *Node[T], key T) *Node[T] { - if root == nil { +func (avl *AVL[T]) deleteHelper(root *AVLNode[T], key T) *AVLNode[T] { + if root == avl._NIL { return root } switch { - case key < root.Key: - root.Left = avl.deleteHelper(root.Left, key) - case key > root.Key: - root.Right = avl.deleteHelper(root.Right, key) + case key < root.key: + tmp := avl.deleteHelper(root.left, key) + root.left = tmp + if tmp != avl._NIL { + tmp.parent = root + } + case key > root.key: + tmp := avl.deleteHelper(root.right, key) + root.right = tmp + if tmp != avl._NIL { + tmp.parent = root + } default: - if root.Left == nil || root.Right == nil { - tmp := root.Left - if root.Left != nil { - tmp = root.Right + if root.left == avl._NIL || root.right == avl._NIL { + tmp := root.left + if root.right != avl._NIL { + tmp = root.right } - if tmp == nil { - root = nil + if tmp == avl._NIL { + root = avl._NIL } else { - *root = *tmp + tmp.parent = root.parent + root = tmp } } else { - tmp := avl.minimum(root.Right) - root.Key = tmp.Key - root.Right = avl.deleteHelper(root.Right, tmp.Key) + tmp := minimum[T](root.right, avl._NIL).(*AVLNode[T]) + root.key = tmp.key + del := avl.deleteHelper(root.right, tmp.key) + root.right = del + if del != avl._NIL { + del.parent = root + } } } - if root == nil { + if root == avl._NIL { return root } // balance the tree - root.Height = avl.height(root) + root.height = avl.height(root) bFactor := avl.balanceFactor(root) switch { case bFactor > 1: switch { - case avl.balanceFactor(root.Left) >= 0: + case avl.balanceFactor(root.left) >= 0: return avl.rightRotate(root) default: - root.Left = avl.leftRotate(root.Left) + root.left = avl.leftRotate(root.left) return avl.rightRotate(root) } case bFactor < -1: switch { - case avl.balanceFactor(root.Right) <= 0: + case avl.balanceFactor(root.right) <= 0: return avl.leftRotate(root) default: - root.Right = avl.rightRotate(root.Right) + root.right = avl.rightRotate(root.right) return avl.leftRotate(root) } } @@ -137,52 +292,66 @@ func (avl *AVL[T]) deleteHelper(root *Node[T], key T) *Node[T] { return root } -func (avl *AVL[T]) height(root *Node[T]) int { - if root == nil { - return 0 +func (avl *AVL[T]) height(root *AVLNode[T]) int { + if root == avl._NIL { + return 1 } var leftHeight, rightHeight int - if root.Left != nil { - leftHeight = root.Left.Height + if root.left != avl._NIL { + leftHeight = root.left.height } - if root.Right != nil { - rightHeight = root.Right.Height + if root.right != avl._NIL { + rightHeight = root.right.height } return 1 + max.Int(leftHeight, rightHeight) } // balanceFactor : negative balance factor means subtree Root is heavy toward Left // and positive balance factor means subtree Root is heavy toward Right side -func (avl *AVL[T]) balanceFactor(root *Node[T]) int { +func (avl *AVL[T]) balanceFactor(root *AVLNode[T]) int { var leftHeight, rightHeight int - if root.Left != nil { - leftHeight = root.Left.Height + if root.left != avl._NIL { + leftHeight = root.left.height } - if root.Right != nil { - rightHeight = root.Right.Height + if root.right != avl._NIL { + rightHeight = root.right.height } return leftHeight - rightHeight } -func (avl *AVL[T]) leftRotate(root *Node[T]) *Node[T] { - y := root.Right - yl := y.Left - y.Left = root - root.Right = yl +func (avl *AVL[T]) leftRotate(x *AVLNode[T]) *AVLNode[T] { + y := x.right + yl := y.left + y.left = x + x.right = yl - root.Height = avl.height(root) - y.Height = avl.height(y) + if yl != avl._NIL { + yl.parent = x + } + + y.parent = x.parent + x.parent = y + + x.height = avl.height(x) + y.height = avl.height(y) return y } -func (avl *AVL[T]) rightRotate(root *Node[T]) *Node[T] { - y := root.Left - yr := y.Right - y.Right = root - root.Left = yr +func (avl *AVL[T]) rightRotate(x *AVLNode[T]) *AVLNode[T] { + y := x.left + yr := y.right + y.right = x + x.left = yr + + if yr != avl._NIL { + yr.parent = x + } + + y.parent = x.parent + x.parent = y - root.Height = avl.height(root) - y.Height = avl.height(y) + x.height = avl.height(x) + y.height = avl.height(y) return y } diff --git a/structure/tree/avl_test.go b/structure/tree/avl_test.go index cbbc3581e..14a7ab570 100644 --- a/structure/tree/avl_test.go +++ b/structure/tree/avl_test.go @@ -1,9 +1,11 @@ package tree_test import ( - "testing" - bt "github.com/TheAlgorithms/Go/structure/tree" + "math/rand" + "sort" + "testing" + "time" ) func TestAVLPush(t *testing.T) { @@ -12,51 +14,51 @@ func TestAVLPush(t *testing.T) { tree.Push(5, 4, 3) root := tree.Root - if root.Key != 4 { - t.Errorf("Root should have value = 4, not %v", root.Key) + if root.Key() != 4 { + t.Errorf("Root should have value = 4, not %v", root.Key()) } - if root.Height != 2 { - t.Errorf("Height of Root should be = 2, not %d", root.Height) + if root.Height() != 2 { + t.Errorf("Height of Root should be = 2, not %d", root.Height()) } - if root.Left.Key != 3 { + if root.Left().Key() != 3 { t.Errorf("Left child should have value = 3") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 5 { + if root.Right().Key() != 5 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } - }) + t.Run("LRRotation-Test", func(t *testing.T) { tree := bt.NewAVL[int]() tree.Push(5, 3, 4) root := tree.Root - if root.Key != 4 { - t.Errorf("Root should have value = 4") + if root.Key() != 4 { + t.Errorf("Root should have value = 4, not %v", root.Key()) } - if root.Height != 2 { - t.Errorf("Height of Root should be = 2") + if root.Height() != 2 { + t.Errorf("Height of Root should be = 2, not %d", root.Height()) } - if root.Left.Key != 3 { + if root.Left().Key() != 3 { t.Errorf("Left child should have value = 3") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 5 { + if root.Right().Key() != 5 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) @@ -68,52 +70,52 @@ func TestAVLPush(t *testing.T) { tree.Push(5) root := tree.Root - if root.Key != 4 { - t.Errorf("Root should have value = 4") + if root.Key() != 4 { + t.Errorf("Root should have value = 4, not %v", root.Key()) } - if root.Height != 2 { - t.Errorf("Height of Root should be = 2") + if root.Height() != 2 { + t.Errorf("Height of Root should be = 2, not %d", root.Height()) } - if root.Left.Key != 3 { + if root.Left().Key() != 3 { t.Errorf("Left child should have value = 3") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 5 { + if root.Right().Key() != 5 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) - t.Run("RLRotaion-Test", func(t *testing.T) { + t.Run("RLRotation-Test", func(t *testing.T) { tree := bt.NewAVL[int]() tree.Push(3) tree.Push(5) tree.Push(4) root := tree.Root - if root.Key != 4 { + if root.Key() != 4 { t.Errorf("Root should have value = 4") } - if root.Height != 2 { + if root.Height() != 2 { t.Errorf("Height of Root should be = 2") } - if root.Left.Key != 3 { + if root.Left().Key() != 3 { t.Errorf("Left child should have value = 3") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 5 { + if root.Right().Key() != 5 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) @@ -122,6 +124,9 @@ func TestAVLPush(t *testing.T) { func TestAVLDelete(t *testing.T) { t.Run("LLRotation-Test", func(t *testing.T) { tree := bt.NewAVL[int]() + if tree.Delete(5) { + t.Errorf("There is no node, whose value is 5") + } tree.Push(5) tree.Push(4) @@ -137,24 +142,24 @@ func TestAVLDelete(t *testing.T) { } root := tree.Root - if root.Key != 3 { + if root.Key() != 3 { t.Errorf("Root should have value = 3") } - if root.Height != 2 { + if root.Height() != 2 { t.Errorf("Height of Root should be = 2") } - if root.Left.Key != 2 { + if root.Left().Key() != 2 { t.Errorf("Left child should have value = 2") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 4 { + if root.Right().Key() != 4 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) @@ -164,6 +169,7 @@ func TestAVLDelete(t *testing.T) { tree.Push(10) tree.Push(8) + tree.Push(8) tree.Push(6) tree.Push(7) @@ -176,24 +182,24 @@ func TestAVLDelete(t *testing.T) { } root := tree.Root - if root.Key != 7 { + if root.Key() != 7 { t.Errorf("Root should have value = 7") } - if root.Height != 2 { + if root.Height() != 2 { t.Errorf("Height of Root should be = 2") } - if root.Left.Key != 6 { + if root.Left().Key() != 6 { t.Errorf("Left child should have value = 6") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 8 { + if root.Right().Key() != 8 { t.Errorf("Right child should have value = 8") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } @@ -204,6 +210,7 @@ func TestAVLDelete(t *testing.T) { tree.Push(2) tree.Push(3) + tree.Push(3) tree.Push(4) tree.Push(5) @@ -216,60 +223,99 @@ func TestAVLDelete(t *testing.T) { } root := tree.Root - if root.Key != 4 { + if root.Key() != 4 { t.Errorf("Root should have value = 4") } - if root.Height != 2 { + if root.Height() != 2 { t.Errorf("Height of Root should be = 2") } - if root.Left.Key != 3 { + if root.Left().Key() != 3 { t.Errorf("Left child should have value = 3") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 5 { + if root.Right().Key() != 5 { t.Errorf("Right child should have value = 5") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) - t.Run("RLRotaion-Test", func(t *testing.T) { + t.Run("RLRotation-Test", func(t *testing.T) { tree := bt.NewAVL[int]() tree.Push(7) tree.Push(6) + tree.Push(6) tree.Push(9) tree.Push(8) tree.Delete(6) root := tree.Root - if root.Key != 8 { + if root.Key() != 8 { t.Errorf("Root should have value = 8") } - if root.Height != 2 { + if root.Height() != 2 { t.Errorf("Height of Root should be = 2") } - if root.Left.Key != 7 { + if root.Left().Key() != 7 { t.Errorf("Left child should have value = 7") } - if root.Left.Height != 1 { + if root.Left().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Left child should be 1") } - if root.Right.Key != 9 { + if root.Right().Key() != 9 { t.Errorf("Right child should have value = 9") } - if root.Right.Height != 1 { + if root.Right().(*bt.AVLNode[int]).Height() != 1 { t.Errorf("Height of Right should be 1") } }) + + t.Run("Random Test", func(t *testing.T) { + nums := []int{100, 500, 1000, 10_000} + for _, n := range nums { + rand.Seed(time.Now().Unix()) + tree := bt.NewAVL[int]() + nums := rand.Perm(n) + tree.Push(nums...) + + rets := tree.InOrder() + if !sort.IntsAreSorted(rets) { + t.Error("Error with Push") + } + + if res, ok := tree.Min(); !ok || res != rets[0] { + t.Errorf("Error with Min, get %d, want: %d", res, rets[0]) + } + + if res, ok := tree.Max(); !ok || res != rets[n-1] { + t.Errorf("Error with Max, get %d, want: %d", res, rets[n-1]) + } + + for i := 0; i < n-1; i++ { + if ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok { + t.Error("Error with Successor") + } + if ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok { + t.Error("Error with Predecessor") + } + + ok := tree.Delete(nums[i]) + rets = tree.InOrder() + if !ok || !sort.IntsAreSorted(rets) { + t.Errorf("Error With Delete") + } + } + } + }) } diff --git a/structure/tree/bstree.go b/structure/tree/bstree.go index 72c0e4da2..b4f6a0a7c 100644 --- a/structure/tree/bstree.go +++ b/structure/tree/bstree.go @@ -6,73 +6,223 @@ package tree -import ( - "github.com/TheAlgorithms/Go/constraints" -) +import "github.com/TheAlgorithms/Go/constraints" +// Verify Interface Compliance +var _ Node[int] = &BSNode[int]{} + +// BSNode represents a single node in the BinarySearch. +type BSNode[T constraints.Ordered] struct { + key T + parent *BSNode[T] + left *BSNode[T] + right *BSNode[T] +} + +func (n *BSNode[T]) Key() T { + return n.key +} + +func (n *BSNode[T]) Parent() Node[T] { + return n.parent +} + +func (n *BSNode[T]) Left() Node[T] { + return n.left +} + +func (n *BSNode[T]) Right() Node[T] { + return n.right +} + +// BinarySearch represents a Binary-Search tree. +// By default, _NIL = nil. type BinarySearch[T constraints.Ordered] struct { - *binaryTree[T] + Root *BSNode[T] + _NIL *BSNode[T] // a sentinel value for nil } -// NewBinarySearch create a novel Binary-Search tree +// NewBinarySearch creates a novel Binary-Search tree func NewBinarySearch[T constraints.Ordered]() *BinarySearch[T] { return &BinarySearch[T]{ - binaryTree: &binaryTree[T]{ - Root: nil, - NIL: nil, - }, + Root: nil, + _NIL: nil, } } +// Empty determines the Binary-Search tree is empty +func (t *BinarySearch[T]) Empty() bool { + return t.Root == t._NIL +} + // Push a chain of Node's into the BinarySearch func (t *BinarySearch[T]) Push(keys ...T) { for _, key := range keys { - t.Root = t.pushHelper(t.Root, key) + t.pushHelper(t.Root, key) } } // Delete removes the node of val func (t *BinarySearch[T]) Delete(val T) bool { - if !t.Has(val) { + node, ok := t.Get(val) + if !ok { return false } - t.deleteHelper(t.Root, val) + t.deleteHelper(node.(*BSNode[T])) return true } -func (t *BinarySearch[T]) pushHelper(root *Node[T], val T) *Node[T] { - if root == nil { - return &Node[T]{Key: val, Left: nil, Right: nil} +// Get a Node from the Binary-Search Tree +func (t *BinarySearch[T]) Get(key T) (Node[T], bool) { + return searchTreeHelper[T](t.Root, t._NIL, key) +} + +// Has Determines the tree has the node of Key +func (t *BinarySearch[T]) Has(key T) bool { + _, ok := searchTreeHelper[T](t.Root, t._NIL, key) + return ok +} + +// PreOrder Traverses the tree in the following order Root --> Left --> Right +func (t *BinarySearch[T]) PreOrder() []T { + traversal := make([]T, 0) + preOrderRecursive[T](t.Root, t._NIL, &traversal) + return traversal +} + +// InOrder Traverses the tree in the following order Left --> Root --> Right +func (t *BinarySearch[T]) InOrder() []T { + return inOrderHelper[T](t.Root, t._NIL) +} + +// PostOrder traverses the tree in the following order Left --> Right --> Root +func (t *BinarySearch[T]) PostOrder() []T { + traversal := make([]T, 0) + postOrderRecursive[T](t.Root, t._NIL, &traversal) + return traversal +} + +// LevelOrder returns the level order traversal of the tree +func (t *BinarySearch[T]) LevelOrder() []T { + traversal := make([]T, 0) + levelOrderHelper[T](t.Root, t._NIL, &traversal) + return traversal +} + +// AccessNodesByLayer accesses nodes layer by layer (2-D array), instead of printing the results as 1-D array. +func (t *BinarySearch[T]) AccessNodesByLayer() [][]T { + return accessNodeByLayerHelper[T](t.Root, t._NIL) +} + +// Depth returns the calculated depth of a binary search tree +func (t *BinarySearch[T]) Depth() int { + return calculateDepth[T](t.Root, t._NIL, 0) +} + +// Max returns the Max value of the tree +func (t *BinarySearch[T]) Max() (T, bool) { + ret := maximum[T](t.Root, t._NIL) + if ret == t._NIL { + var dft T + return dft, false } - if val < root.Key { - root.Left = t.pushHelper(root.Left, val) - } else { - root.Right = t.pushHelper(root.Right, val) + return ret.Key(), true +} + +// Min returns the Min value of the tree +func (t *BinarySearch[T]) Min() (T, bool) { + ret := minimum[T](t.Root, t._NIL) + if ret == t._NIL { + var dft T + return dft, false } - return root + return ret.Key(), true } -func (t *BinarySearch[T]) deleteHelper(root *Node[T], val T) *Node[T] { - if root == nil { - return nil +// Predecessor returns the Predecessor of the node of Key +// if there is no predecessor, return default value of type T and false +// otherwise return the Key of predecessor and true +func (t *BinarySearch[T]) Predecessor(key T) (T, bool) { + node, ok := searchTreeHelper[T](t.Root, t._NIL, key) + if !ok { + var dft T + return dft, ok } - if val < root.Key { - root.Left = t.deleteHelper(root.Left, val) - } else if val > root.Key { - root.Right = t.deleteHelper(root.Right, val) + return predecessorHelper[T](node, t._NIL) +} + +// Successor returns the Successor of the node of Key +// if there is no successor, return default value of type T and false +// otherwise return the Key of successor and true +func (t *BinarySearch[T]) Successor(key T) (T, bool) { + node, ok := searchTreeHelper[T](t.Root, t._NIL, key) + if !ok { + var dft T + return dft, ok + } + return successorHelper[T](node, t._NIL) +} + +func (t *BinarySearch[T]) pushHelper(x *BSNode[T], val T) { + y := t._NIL + for x != t._NIL { + y = x + switch { + case val < x.Key(): + x = x.left + case val > x.Key(): + x = x.right + default: + return + } + } + + z := &BSNode[T]{ + key: val, + left: t._NIL, + right: t._NIL, + parent: y, + } + if y == t._NIL { + t.Root = z + } else if val < y.key { + y.left = z } else { - // this is the node to delete - // node with one child - if root.Left == nil { - return root.Right - } else if root.Right == nil { - return root.Left - } else { - n := root.Right - d := t.minimum(n) - d.Left = root.Left - return root.Right + y.right = z + } +} + +func (t *BinarySearch[T]) deleteHelper(z *BSNode[T]) { + switch { + case z.left == t._NIL: + t.transplant(z, z.right) + case z.right == t._NIL: + t.transplant(z, z.left) + default: + y := minimum[T](z.right, t._NIL).(*BSNode[T]) + if y.parent != z { + t.transplant(y, y.right) + y.right = z.right + y.right.parent = y } + + t.transplant(z, y) + y.left = z.left + y.left.parent = y + } +} + +func (t *BinarySearch[T]) transplant(u, v *BSNode[T]) { + switch { + case u.parent == t._NIL: + t.Root = v + case u == u.parent.left: + u.parent.left = v + default: + u.parent.right = v + } + + if v != t._NIL { + v.parent = u.parent } - return root } diff --git a/structure/tree/bstree_test.go b/structure/tree/bstree_test.go index 094406487..abbf8bfea 100644 --- a/structure/tree/bstree_test.go +++ b/structure/tree/bstree_test.go @@ -1,7 +1,10 @@ package tree_test import ( + "math/rand" + "sort" "testing" + "time" bt "github.com/TheAlgorithms/Go/structure/tree" ) @@ -13,15 +16,15 @@ func TestPush(t *testing.T) { bst.Push(80) bst.Push(100) - if bst.Root.Key != 90 { + if bst.Root.Key() != 90 { t.Errorf("Root should have value = 90") } - if bst.Root.Left.Key != 80 { + if bst.Root.Left().Key() != 80 { t.Errorf("Left child should have value = 80") } - if bst.Root.Right.Key != 100 { + if bst.Root.Right().Key() != 100 { t.Errorf("Right child should have value = 100") } @@ -36,6 +39,7 @@ func TestDelete(t *testing.T) { bst.Push(90) bst.Push(80) + bst.Push(80) bst.Push(100) if !bst.Delete(100) { @@ -47,15 +51,15 @@ func TestDelete(t *testing.T) { } root := bst.Root - if root.Key != 90 { + if root.Key() != 90 { t.Errorf("Root should have value = 90") } - if root.Left.Key != 80 { + if root.Left().Key() != 80 { t.Errorf("Left child should have value = 80") } - if root.Right != nil { + if root.Right().(*bt.BSNode[int]) != nil { t.Errorf("Right child should have value = nil") } @@ -65,11 +69,11 @@ func TestDelete(t *testing.T) { bst.Delete(80) - if root.Key != 90 { + if root.Key() != 90 { t.Errorf("Root should have value = 90") } - if root.Left != nil { + if root.Left().(*bt.BSNode[int]) != nil { t.Errorf("Left child should have value = nil") } @@ -95,15 +99,15 @@ func TestDelete(t *testing.T) { } root := bst.Root - if root.Key != 90 { + if root.Key() != 90 { t.Errorf("Root should have value = 90") } - if root.Right.Key != 100 { + if root.Right().Key() != 100 { t.Errorf("Right child should have value = 100") } - if root.Left.Key != 70 { + if root.Left().Key() != 70 { t.Errorf("Left child should have value = 70") } @@ -130,15 +134,15 @@ func TestDelete(t *testing.T) { } root := bst.Root - if root.Key != 90 { + if root.Key() != 90 { t.Errorf("Root should have value = 90") } - if root.Left.Key != 85 { + if root.Left().Key() != 85 { t.Errorf("Left child should have value = 85") } - if root.Right.Key != 100 { + if root.Right().Key() != 100 { t.Errorf("Right child should have value = 100") } @@ -146,4 +150,43 @@ func TestDelete(t *testing.T) { t.Errorf("Depth should have value = 3") } }) + + t.Run("Random Test", func(t *testing.T) { + tests := []int{100, 500, 1000, 10_000} + for _, n := range tests { + rand.Seed(time.Now().Unix()) + tree := bt.NewBinarySearch[int]() + nums := rand.Perm(n) + tree.Push(nums...) + + rets := tree.InOrder() + if !sort.IntsAreSorted(rets) { + t.Error("Error with Push") + } + + if res, ok := tree.Min(); !ok || res != rets[0] { + t.Errorf("Error with Min, get %d, want: %d", res, rets[0]) + } + + if res, ok := tree.Max(); !ok || res != rets[n-1] { + t.Errorf("Error with Max, get %d, want: %d", res, rets[n-1]) + } + + for i := 0; i < n-1; i++ { + if ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok { + t.Error("Error with Successor") + } + + if ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok { + t.Error("Error with Predecessor") + } + + ok := tree.Delete(nums[i]) + rets = tree.InOrder() + if !ok || !sort.IntsAreSorted(rets) { + t.Errorf("Error With Delete") + } + } + } + }) } diff --git a/structure/tree/example_test.go b/structure/tree/example_test.go new file mode 100644 index 000000000..2d3c384c8 --- /dev/null +++ b/structure/tree/example_test.go @@ -0,0 +1,167 @@ +package tree_test + +import ( + "fmt" + "github.com/TheAlgorithms/Go/constraints" + "testing" + + bt "github.com/TheAlgorithms/Go/structure/tree" +) + +type TestTree[T constraints.Ordered] interface { + Push(...T) + Delete(T) bool + Get(T) (bt.Node[T], bool) + Empty() bool + Has(T) bool + Depth() int + Max() (T, bool) + Min() (T, bool) + Predecessor(T) (T, bool) + Successor(T) (T, bool) + PreOrder() []T + InOrder() []T + PostOrder() []T + LevelOrder() []T + AccessNodesByLayer() [][]T +} + +// BinarySearch, AVL and RB have completed the `TestTree` interface. +var ( + _ TestTree[int] = (*bt.BinarySearch[int])(nil) + _ TestTree[int] = (*bt.AVL[int])(nil) + _ TestTree[int] = (*bt.RB[int])(nil) +) + +var tree TestTree[int] + +func TestBinarySearch(t *testing.T) { + tree = bt.NewBinarySearch[int]() + + if tree.Empty() { + t.Log("Binary Search Tree is empty now.") + } + + tree.Push(1, 4, 10) + tree.Push(-8) + nums := []int{87, 18, 10, -34} + tree.Push(nums...) + tree.Push(4) // duplicate key, dismiss it + + if tree.Has(4) { + t.Logf("There is a node of 4") + } + + if n, ok := tree.Get(10); ok { + t.Logf("node of 10: %T", n) + } + + if ret, ok := tree.Min(); ok { + t.Logf("tree.Min() = %v", ret) + } + + if ret, ok := tree.Max(); ok { + t.Logf("tree.Max() = %v", ret) + } + + if ret, ok := tree.Predecessor(1); ok { + t.Logf("tree.Preducessor(1) = %v", ret) + } + + if ret, ok := tree.Successor(18); ok { + t.Logf("tree.Successor(18) = %v", ret) + } + + fmt.Println(tree.InOrder()) + fmt.Println(tree.AccessNodesByLayer()) + + tree.Delete(18) + fmt.Println("Delete 18") + fmt.Println(tree.InOrder()) +} + +func TestAVL(t *testing.T) { + tree = bt.NewAVL[int]() + + if tree.Empty() { + t.Log("AVL Tree is empty now.") + } + + tree.Push(1, 4, 10) + tree.Push(-8) + nums := []int{87, 18, 10, -34} + tree.Push(nums...) + tree.Push(4) // duplicate key, dismiss it + + if tree.Has(4) { + t.Logf("There is a node of 4") + } + + if n, ok := tree.Get(10); ok { + t.Logf("node of 10: %T", n) + } + + if ret, ok := tree.Min(); ok { + t.Logf("tree.Min() = %v", ret) + } + + if ret, ok := tree.Max(); ok { + t.Logf("tree.Max() = %v", ret) + } + + if ret, ok := tree.Predecessor(1); ok { + t.Logf("tree.Preducessor(1) = %v", ret) + } + + if ret, ok := tree.Successor(18); ok { + t.Logf("tree.Successor(18) = %v", ret) + } + + fmt.Println(tree.InOrder()) + fmt.Println(tree.AccessNodesByLayer()) + + tree.Delete(18) + fmt.Println("Delete 18") + fmt.Println(tree.InOrder()) +} + +func TestRB(t *testing.T) { + tree = bt.NewRB[int]() + + if tree.Empty() { + t.Log("RB Tree is empty now.") + } + + tree.Push(1, 4, 10) + tree.Push(-8) + nums := []int{87, 18, 10, -34} + tree.Push(nums...) + tree.Push(4) // duplicate key, dismiss it + + if tree.Has(4) { + t.Logf("There is a node of 4") + } + + if n, ok := tree.Get(10); ok { + t.Logf("node of 10: %T", n) + } + + if ret, ok := tree.Min(); ok { + t.Logf("tree.Min() = %v", ret) + } + + if ret, ok := tree.Max(); ok { + t.Logf("tree.Max() = %v", ret) + } + + if ret, ok := tree.Predecessor(1); ok { + t.Logf("tree.Preducessor(1) = %v", ret) + } + + if ret, ok := tree.Successor(18); ok { + t.Logf("tree.Successor(18) = %v", ret) + } + + fmt.Println(tree.InOrder()) + fmt.Println(tree.AccessNodesByLayer()) +} diff --git a/structure/tree/rbtree.go b/structure/tree/rbtree.go index 252c99930..de6f2ed6d 100644 --- a/structure/tree/rbtree.go +++ b/structure/tree/rbtree.go @@ -1,5 +1,5 @@ // Red-Black Tree is a kind of self-balancing binary search tree. -// Each node stores "Color" ("red" or "black"), used to ensure that the tree remains balanced during insertions and deletions. +// Each node stores "color" ("red" or "black"), used to ensure that the tree remains balanced during insertions and deletions. // // For more details check out those links below here: // Programiz article : https://www.programiz.com/dsa/red-black-tree @@ -9,27 +9,65 @@ package tree -import ( - "fmt" +import "github.com/TheAlgorithms/Go/constraints" - "github.com/TheAlgorithms/Go/constraints" +type Color byte + +const ( + Red Color = iota + Black ) +// Verify Interface Compliance +var _ Node[int] = &RBNode[int]{} + +// RBNode represents a single node in the RB. +type RBNode[T constraints.Ordered] struct { + key T + parent *RBNode[T] + left *RBNode[T] + right *RBNode[T] + color Color +} + +func (n *RBNode[T]) Key() T { + return n.key +} + +func (n *RBNode[T]) Parent() Node[T] { + return n.parent +} + +func (n *RBNode[T]) Left() Node[T] { + return n.left +} + +func (n *RBNode[T]) Right() Node[T] { + return n.right +} + +// RB represents a Red-Black tree. +// By default, _NIL = leaf, a dummy variable. type RB[T constraints.Ordered] struct { - *binaryTree[T] + Root *RBNode[T] + _NIL *RBNode[T] // a sentinel value for nil } -// Create a new Red-Black Tree +// NewRB creates a new Red-Black Tree func NewRB[T constraints.Ordered]() *RB[T] { - leaf := &Node[T]{Color: Black, Left: nil, Right: nil} + leaf := &RBNode[T]{color: Black, left: nil, right: nil} + leaf.parent = leaf return &RB[T]{ - binaryTree: &binaryTree[T]{ - Root: leaf, - NIL: leaf, - }, + Root: leaf, + _NIL: leaf, } } +// Empty determines the Red-Black tree is empty +func (t *RB[T]) Empty() bool { + return t.Root == t._NIL +} + // Push a chain of Node's into the Red-Black Tree func (t *RB[T]) Push(keys ...T) { for _, key := range keys { @@ -43,145 +81,212 @@ func (t *RB[T]) Delete(data T) bool { return t.deleteHelper(t.Root, data) } -// Return the Predecessor of the node of Key +// Get a Node from the Red-Black Tree +func (t *RB[T]) Get(key T) (Node[T], bool) { + return searchTreeHelper[T](t.Root, t._NIL, key) +} + +// Has Determines the tree has the node of Key +func (t *RB[T]) Has(key T) bool { + _, ok := searchTreeHelper[T](t.Root, t._NIL, key) + return ok +} + +// PreOrder Traverses the tree in the following order Root --> Left --> Right +func (t *RB[T]) PreOrder() []T { + traversal := make([]T, 0) + preOrderRecursive[T](t.Root, t._NIL, &traversal) + return traversal +} + +// InOrder Traverses the tree in the following order Left --> Root --> Right +func (t *RB[T]) InOrder() []T { + return inOrderHelper[T](t.Root, t._NIL) +} + +// PostOrder traverses the tree in the following order Left --> Right --> Root +func (t *RB[T]) PostOrder() []T { + traversal := make([]T, 0) + postOrderRecursive[T](t.Root, t._NIL, &traversal) + return traversal +} + +// LevelOrder returns the level order traversal of the tree +func (t *RB[T]) LevelOrder() []T { + traversal := make([]T, 0) + levelOrderHelper[T](t.Root, t._NIL, &traversal) + return traversal +} + +// AccessNodesByLayer accesses nodes layer by layer (2-D array), instead of printing the results as 1-D array. +func (t *RB[T]) AccessNodesByLayer() [][]T { + return accessNodeByLayerHelper[T](t.Root, t._NIL) +} + +// Depth returns the calculated depth of a Red-Black tree +func (t *RB[T]) Depth() int { + return calculateDepth[T](t.Root, t._NIL, 0) +} + +// Max returns the Max value of the tree +func (t *RB[T]) Max() (T, bool) { + ret := maximum[T](t.Root, t._NIL) + if ret == t._NIL { + var dft T + return dft, false + } + return ret.Key(), true +} + +// Min returns the Min value of the tree +func (t *RB[T]) Min() (T, bool) { + ret := minimum[T](t.Root, t._NIL) + if ret == t._NIL { + var dft T + return dft, false + } + return ret.Key(), true +} + +// Predecessor returns the Predecessor of the node of Key // if there is no predecessor, return default value of type T and false // otherwise return the Key of predecessor and true func (t *RB[T]) Predecessor(key T) (T, bool) { - node, ok := t.searchTreeHelper(t.Root, key) + node, ok := searchTreeHelper[T](t.Root, t._NIL, key) if !ok { - return t.NIL.Key, ok + var dft T + return dft, ok } - return t.predecessorHelper(node) + return predecessorHelper[T](node, t._NIL) } -// Return the Successor of the node of Key +// Successor returns the Successor of the node of Key // if there is no successor, return default value of type T and false // otherwise return the Key of successor and true func (t *RB[T]) Successor(key T) (T, bool) { - node, ok := t.searchTreeHelper(t.Root, key) + node, ok := searchTreeHelper[T](t.Root, t._NIL, key) if !ok { - return t.NIL.Key, ok + var dft T + return dft, ok } - - return t.successorHelper(node) + return successorHelper[T](node, t._NIL) } -func (t *RB[T]) pushHelper(x *Node[T], key T) { - node := &Node[T]{ - Key: key, - Left: t.NIL, - Right: t.NIL, - Parent: nil, - Color: Red, - } - - var y *Node[T] - for !t.isNil(x) { +func (t *RB[T]) pushHelper(x *RBNode[T], key T) { + y := t._NIL + for x != t._NIL { y = x - if node.Key < x.Key { - x = x.Left - } else { - x = x.Right + switch { + case key < x.Key(): + x = x.left + case key > x.Key(): + x = x.right + default: + return } - } - node.Parent = y - if y == nil { + node := &RBNode[T]{ + key: key, + left: t._NIL, + right: t._NIL, + parent: y, + color: Red, + } + if y == t._NIL { t.Root = node - } else if node.Key < y.Key { - y.Left = node + } else if node.key < y.key { + y.left = node } else { - y.Right = node + y.right = node } - if node.Parent == nil { - node.Color = Black + if node.parent == t._NIL { + node.color = Black return } - if node.Parent.Parent == nil { + if node.parent.parent == t._NIL { return } t.pushFix(node) } -func (t *RB[T]) leftRotate(x *Node[T]) { - y := x.Right - x.Right = y.Left +func (t *RB[T]) leftRotate(x *RBNode[T]) { + y := x.right + x.right = y.left - if !t.isNil(y.Left) { - y.Left.Parent = x + if y.left != t._NIL { + y.left.parent = x } - y.Parent = x.Parent - if x.Parent == nil { + y.parent = x.parent + if x.parent == t._NIL { t.Root = y - } else if x == x.Parent.Left { - x.Parent.Left = y + } else if x == x.parent.left { + x.parent.left = y } else { - x.Parent.Right = y + x.parent.right = y } - y.Left = x - x.Parent = y + y.left = x + x.parent = y } -func (t *RB[T]) rightRotate(x *Node[T]) { - y := x.Left - x.Left = y.Right - if !t.isNil(y.Right) { - y.Right.Parent = x +func (t *RB[T]) rightRotate(x *RBNode[T]) { + y := x.left + x.left = y.right + if y.right != t._NIL { + y.right.parent = x } - y.Parent = x.Parent - if x.Parent == nil { + y.parent = x.parent + if x.parent == t._NIL { t.Root = y - } else if x == y.Parent.Right { - y.Parent.Right = y + } else if x == y.parent.right { + y.parent.right = y } else { - y.Parent.Left = y + y.parent.left = y } - y.Right = x - x.Parent = y + y.right = x + x.parent = y } -func (t *RB[T]) pushFix(k *Node[T]) { - var u *Node[T] - for k.Parent.Color == Red { - if k.Parent == k.Parent.Parent.Right { - u = k.Parent.Parent.Left - if u != nil && u.Color == Red { - u.Color = Black - k.Parent.Color = Black - k.Parent.Parent.Color = Red - k = k.Parent.Parent +func (t *RB[T]) pushFix(k *RBNode[T]) { + for k.parent.color == Red { + if k.parent == k.parent.parent.right { + u := k.parent.parent.left + if u.color == Red { + u.color = Black + k.parent.color = Black + k.parent.parent.color = Red + k = k.parent.parent } else { - if k == k.Parent.Left { - k = k.Parent + if k == k.parent.left { + k = k.parent t.rightRotate(k) } - k.Parent.Color = Black - k.Parent.Parent.Color = Red - t.leftRotate(k.Parent.Parent) + k.parent.color = Black + k.parent.parent.color = Red + t.leftRotate(k.parent.parent) } } else { - u = k.Parent.Parent.Right - if u != nil && u.Color == Red { - u.Color = Black - k.Parent.Color = Black - k.Parent.Parent.Color = Red - k = k.Parent.Parent + u := k.parent.parent.right + if u.color == Red { + u.color = Black + k.parent.color = Black + k.parent.parent.color = Red + k = k.parent.parent } else { - if k == k.Parent.Right { - k = k.Parent + if k == k.parent.right { + k = k.parent t.leftRotate(k) } - k.Parent.Color = Black - k.Parent.Parent.Color = Red - t.rightRotate(k.Parent.Parent) + k.parent.color = Black + k.parent.parent.color = Red + t.rightRotate(k.parent.parent) } } if k == t.Root { @@ -189,53 +294,52 @@ func (t *RB[T]) pushFix(k *Node[T]) { } } - t.Root.Color = Black + t.Root.color = Black } -func (t *RB[T]) deleteHelper(node *Node[T], key T) bool { - z := t.NIL - for !t.isNil(node) { +func (t *RB[T]) deleteHelper(node *RBNode[T], key T) bool { + z := t._NIL + for node != t._NIL { switch { - case node.Key == key: + case node.key == key: z = node fallthrough - case node.Key <= key: - node = node.Right - case node.Key > key: - node = node.Left + case node.key <= key: + node = node.right + case node.key > key: + node = node.left } } - if t.isNil(z) { - fmt.Println("Key not found in the tree") + if z == t._NIL { return false } - var x *Node[T] + var x *RBNode[T] y := z - yOriginColor := y.Color - if t.isNil(z.Left) { - x = z.Right - t.rbTransplant(z, z.Right) - } else if t.isNil(z.Right) { - x = z.Left - t.rbTransplant(z, z.Left) + yOriginColor := y.color + if z.left == t._NIL { + x = z.right + t.transplant(z, z.right) + } else if z.right == t._NIL { + x = z.left + t.transplant(z, z.left) } else { - y = t.minimum(z.Right) - yOriginColor = y.Color - x = y.Right - if y.Parent == z { - x.Parent = y + y = minimum[T](z.right, t._NIL).(*RBNode[T]) + yOriginColor = y.color + x = y.right + if y.parent == z { + x.parent = y } else { - t.rbTransplant(y, y.Right) - y.Right = z.Right - y.Right.Parent = y + t.transplant(y, y.right) + y.right = z.right + y.right.parent = y } - t.rbTransplant(z, y) - y.Left = z.Left - y.Left.Parent = y - y.Color = z.Color + t.transplant(z, y) + y.left = z.left + y.left.parent = y + y.color = z.color } if yOriginColor == Black { @@ -245,109 +349,76 @@ func (t *RB[T]) deleteHelper(node *Node[T], key T) bool { return true } -func (t *RB[T]) deleteFix(x *Node[T]) { - var s *Node[T] - for x != t.Root && x.Color == Black { - if x == x.Parent.Left { - s = x.Parent.Right - if s.Color == Red { - s.Color = Black - x.Parent.Color = Red - t.leftRotate(x.Parent) - s = x.Parent.Right +func (t *RB[T]) deleteFix(x *RBNode[T]) { + var s *RBNode[T] + for x != t.Root && x.color == Black { + if x == x.parent.left { + s = x.parent.right + if s.color == Red { + s.color = Black + x.parent.color = Red + t.leftRotate(x.parent) + s = x.parent.right } - if s.Left.Color == Black && s.Right.Color == Black { - s.Color = Red - x = x.Parent + if s.left.color == Black && s.right.color == Black { + s.color = Red + x = x.parent } else { - if s.Right.Color == Black { - s.Left.Color = Black - s.Color = Red + if s.right.color == Black { + s.left.color = Black + s.color = Red t.rightRotate(s) - s = x.Parent.Right + s = x.parent.right } - s.Color = x.Parent.Color - x.Parent.Color = Black - s.Right.Color = Black - t.leftRotate(x.Parent) + s.color = x.parent.color + x.parent.color = Black + s.right.color = Black + t.leftRotate(x.parent) x = t.Root } } else { - s = x.Parent.Left - if s.Color == Red { - s.Color = Black - x.Parent.Color = Red - t.rightRotate(x.Parent) - s = x.Parent.Left + s = x.parent.left + if s.color == Red { + s.color = Black + x.parent.color = Red + t.rightRotate(x.parent) + s = x.parent.left } - if s.Right.Color == Black && s.Left.Color == Black { - s.Color = Red - x = x.Parent + if s.right.color == Black && s.left.color == Black { + s.color = Red + x = x.parent } else { - if s.Left.Color == Black { - s.Right.Color = Black - s.Color = Red + if s.left.color == Black { + s.right.color = Black + s.color = Red t.leftRotate(s) - s = x.Parent.Left + s = x.parent.left } - s.Color = x.Parent.Color - x.Parent.Color = Black - s.Left.Color = Black - t.rightRotate(x.Parent) + s.color = x.parent.color + x.parent.color = Black + s.left.color = Black + t.rightRotate(x.parent) x = t.Root } } } - x.Color = Black + x.color = Black } -func (t *RB[T]) rbTransplant(u, v *Node[T]) { +func (t *RB[T]) transplant(u, v *RBNode[T]) { switch { - case u.Parent == nil: + case u.parent == t._NIL: t.Root = v - case u == u.Parent.Left: - u.Parent.Left = v + case u == u.parent.left: + u.parent.left = v default: - u.Parent.Right = v - } - v.Parent = u.Parent -} - -func (t *RB[T]) predecessorHelper(node *Node[T]) (T, bool) { - if !t.isNil(node.Left) { - return t.maximum(node.Left).Key, true - } - - p := node.Parent - for p != nil && !t.isNil(p) && node == p.Left { - node = p - p = p.Parent - } - - if p == nil { - return t.NIL.Key, false - } - return p.Key, true -} - -func (t *RB[T]) successorHelper(node *Node[T]) (T, bool) { - if !t.isNil(node.Right) { - return t.minimum(node.Right).Key, true + u.parent.right = v } - p := node.Parent - for p != nil && !t.isNil(p) && node == p.Right { - node = p - p = p.Parent - } - - if p == nil { - return t.NIL.Key, false - } - return p.Key, true + v.parent = u.parent } diff --git a/structure/tree/rbtree_test.go b/structure/tree/rbtree_test.go index 25a8c37e1..a609aa7d2 100644 --- a/structure/tree/rbtree_test.go +++ b/structure/tree/rbtree_test.go @@ -26,13 +26,13 @@ func TestRBTreePush(t *testing.T) { t.Errorf("Error with Max: %v", r) } - nums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 88, 1 << 32} + nums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 1 << 32} tree.Push(nums...) ret = tree.InOrder() - if !sort.IntsAreSorted(ret) || len(ret) != len(nums) { + if !sort.IntsAreSorted(ret) { t.Errorf("Error with Push: %v", ret) } @@ -54,27 +54,22 @@ func TestRBTreeDelete(t *testing.T) { ok = tree.Delete(188) - if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-1 { + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) { t.Errorf("Error with Delete: %v", ret) } ok = tree.Delete(188) - if ret := tree.InOrder(); ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-1 { + if ret := tree.InOrder(); ok || !sort.IntsAreSorted(ret) { t.Errorf("Error with Delete: %v", ret) } ok = tree.Delete(1<<63 - 1) - if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-2 { - t.Errorf("Error with Delete: %v", ret) - } - - ok = tree.Delete(4) - if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-3 { + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) { t.Errorf("Error with Delete: %v", ret) } ok = tree.Delete(4) - if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) || len(ret) != len(nums)-4 { + if ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) { t.Errorf("Error with Delete: %v", ret) } @@ -87,16 +82,12 @@ func TestRBTreeDelete(t *testing.T) { } } -func FuzzRBTree(f *testing.F) { +func TestRBTree(t *testing.T) { testcases := []int{100, 200, 1000, 10000} - for _, tc := range testcases { - f.Add(tc) - } - - f.Fuzz(func(t *testing.T, a int) { + for _, n := range testcases { rand.Seed(time.Now().Unix()) tree := bt.NewRB[int]() - nums := rand.Perm(a) + nums := rand.Perm(n) tree.Push(nums...) rets := tree.InOrder() @@ -108,68 +99,24 @@ func FuzzRBTree(f *testing.F) { t.Errorf("Error with Min, get %d, want: %d", res, rets[0]) } - if res, ok := tree.Max(); !ok || res != rets[a-1] { - t.Errorf("Error with Max, get %d, want: %d", res, rets[a-1]) + if res, ok := tree.Max(); !ok || res != rets[n-1] { + t.Errorf("Error with Max, get %d, want: %d", res, rets[n-1]) } - for i := 0; i < a-1; i++ { + for i := 0; i < n-1; i++ { + if ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok { + t.Error("Error with Successor") + } + if ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok { + t.Error("Error with Predecessor") + } + ok := tree.Delete(nums[i]) rets = tree.InOrder() if !ok || !sort.IntsAreSorted(rets) { t.Errorf("Error With Delete") } } - }) -} - -func TestRBTreePredecessorAndSuccessor(t *testing.T) { - tree := bt.NewRB[int]() - - nums := []int{10, 8, 88, 888, 4, -1, 100} - tree.Push(nums...) - - if ret, ok := tree.Predecessor(100); !ok && ret == 88 { - t.Errorf("Error with Predecessor") - } - - if _, ok := tree.Predecessor(-1); ok { - t.Errorf("Error with Predecessor") - } - - if _, ok := tree.Predecessor(-12); ok { - t.Errorf("Error with Predecessor") - } - - if ret, ok := tree.Predecessor(4); !ok && ret == -1 { - t.Errorf("Error with Predecessor") - } - - if ret, ok := tree.Successor(4); !ok && ret == 8 { - t.Errorf("Error with Successor") - } - - if ret, ok := tree.Successor(8); !ok && ret == 88 { - t.Errorf("Error with Successor") - } - - if ret, ok := tree.Successor(88); !ok && ret == 100 { - t.Errorf("Error with Successor") - } - - if ret, ok := tree.Successor(100); !ok && ret == 888 { - t.Errorf("Error with Successor") - } - - if ret, ok := tree.Successor(-1); !ok && ret == 4 { - t.Errorf("Error with Successor") - } - - if _, ok := tree.Successor(888); ok { - t.Errorf("Error with Successor") - } - - if _, ok := tree.Successor(188); ok { - t.Errorf("Error with Successor") } } diff --git a/structure/tree/tree.go b/structure/tree/tree.go index b7ec06fc8..53f89ec74 100644 --- a/structure/tree/tree.go +++ b/structure/tree/tree.go @@ -8,106 +8,25 @@ package tree import ( - "fmt" - "github.com/TheAlgorithms/Go/constraints" "github.com/TheAlgorithms/Go/math/max" ) -type Color byte - -const ( - Red Color = iota - Black -) - -// Node of a binary tree -type Node[T constraints.Ordered] struct { - Key T - Parent *Node[T] // for Red-Black Tree - Left *Node[T] - Right *Node[T] - Color Color // for Red-Black Tree - Height int // for AVL Tree -} - -// binaryTree is a base-struct for BinarySearch, AVL, RB, etc. -// Note: to avoid instantiation, we make the base struct un-exported. -type binaryTree[T constraints.Ordered] struct { - Root *Node[T] - NIL *Node[T] // NIL denotes the leaf node of Red-Black Tree -} - -// Get a Node from the binary-search Tree -func (t *binaryTree[T]) Get(key T) (*Node[T], bool) { - return t.searchTreeHelper(t.Root, key) -} - -// Determines the tree has the node of Key -func (t *binaryTree[T]) Has(key T) bool { - _, ok := t.searchTreeHelper(t.Root, key) - return ok -} - -// Traverses the tree in the following order Root --> Left --> Right -func (t *binaryTree[T]) PreOrder() []T { - traversal := make([]T, 0) - t.preOrderRecursive(t.Root, &traversal) - return traversal -} - -// Traverses the tree in the following order Left --> Root --> Right -func (t *binaryTree[T]) InOrder() []T { - return t.inOrderHelper(t.Root) -} - -// Traverses the tree in the following order Left --> Right --> Root -func (t *binaryTree[T]) PostOrder() []T { - traversal := make([]T, 0) - t.postOrderRecursive(t.Root, &traversal) - return traversal -} - -// Depth returns the calculated depth of a binary search tree -func (t *binaryTree[T]) Depth() int { - return t.calculateDepth(t.Root, 0) -} - -// Returns the Max value of the tree -func (t *binaryTree[T]) Max() (T, bool) { - ret := t.maximum(t.Root) - if t.isNil(ret) { - return t.NIL.Key, false - } - - return ret.Key, true -} - -// Return the Min value of the tree -func (t *binaryTree[T]) Min() (T, bool) { - ret := t.minimum(t.Root) - if t.isNil(ret) { - return t.NIL.Key, false - } - - return ret.Key, true +type Node[T constraints.Ordered] interface { + Key() T + Parent() Node[T] + Left() Node[T] + Right() Node[T] } -// LevelOrder returns the level order traversal of the tree -func (t *binaryTree[T]) LevelOrder() []T { - traversal := make([]T, 0) - t.levelOrderHelper(t.Root, &traversal) - return traversal -} +// The following is a collection of helper functions for BinarySearch, AVL and RB. -// AccessNodesByLayer accesses nodes layer by layer (2-D array), instead of printing the results as 1-D array. -func (t *binaryTree[T]) AccessNodesByLayer() [][]T { - root := t.Root - if t.isNil(root) { +func accessNodeByLayerHelper[T constraints.Ordered](root, nilNode Node[T]) [][]T { + if root == nilNode { return [][]T{} } - var q []*Node[T] - var n *Node[T] + var q []Node[T] + var n Node[T] var idx = 0 q = append(q, root) var res [][]T @@ -117,12 +36,12 @@ func (t *binaryTree[T]) AccessNodesByLayer() [][]T { qLen := len(q) for i := 0; i < qLen; i++ { n, q = q[0], q[1:] - res[idx] = append(res[idx], n.Key) - if !t.isNil(n.Left) { - q = append(q, n.Left) + res[idx] = append(res[idx], n.Key()) + if n.Left() != nilNode { + q = append(q, n.Left()) } - if !t.isNil(n.Right) { - q = append(q, n.Right) + if n.Right() != nilNode { + q = append(q, n.Right()) } } idx++ @@ -130,154 +49,141 @@ func (t *binaryTree[T]) AccessNodesByLayer() [][]T { return res } -// Print the tree horizontally -func (t *binaryTree[T]) Print() { - t.printHelper(t.Root, "", false) -} - -// Determines node is a leaf node -func (t *binaryTree[T]) isNil(node *Node[T]) bool { - return node == t.NIL -} - -func (t *binaryTree[T]) searchTreeHelper(node *Node[T], key T) (*Node[T], bool) { - if node == nil || t.isNil(node) { +func searchTreeHelper[T constraints.Ordered](node, nilNode Node[T], key T) (Node[T], bool) { + if node == nilNode { return node, false } - if key == node.Key { + if key == node.Key() { return node, true } - - if key < node.Key { - return t.searchTreeHelper(node.Left, key) + if key < node.Key() { + return searchTreeHelper(node.Left(), nilNode, key) } - return t.searchTreeHelper(node.Right, key) + return searchTreeHelper(node.Right(), nilNode, key) } -// The iterative inorder; -// The recursive way is similar to the preOrderRecursive -func (t *binaryTree[T]) inOrderHelper(node *Node[T]) []T { - var stack []*Node[T] +func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T { + var stack []Node[T] var ret []T - for !t.isNil(node) || len(stack) > 0 { - for !t.isNil(node) { + for node != nilNode || len(stack) > 0 { + for node != nilNode { stack = append(stack, node) - node = node.Left + node = node.Left() } node = stack[len(stack)-1] stack = stack[:len(stack)-1] - ret = append(ret, node.Key) - node = node.Right + ret = append(ret, node.Key()) + node = node.Right() } return ret } -func (t *binaryTree[T]) preOrderRecursive(n *Node[T], traversal *[]T) { - if t.isNil(n) { +func preOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) { + if n == nilNode { return } - *traversal = append(*traversal, n.Key) - t.preOrderRecursive(n.Left, traversal) - t.preOrderRecursive(n.Right, traversal) + *traversal = append(*traversal, n.Key()) + preOrderRecursive(n.Left(), nilNode, traversal) + preOrderRecursive(n.Right(), nilNode, traversal) + } -func (t *binaryTree[T]) postOrderRecursive(n *Node[T], traversal *[]T) { - if t.isNil(n) { +func postOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) { + if n == nilNode { return } - t.postOrderRecursive(n.Left, traversal) - t.postOrderRecursive(n.Right, traversal) - *traversal = append(*traversal, n.Key) + postOrderRecursive(n.Left(), nilNode, traversal) + postOrderRecursive(n.Right(), nilNode, traversal) + *traversal = append(*traversal, n.Key()) } -func (t *binaryTree[T]) calculateDepth(n *Node[T], depth int) int { - if t.isNil(n) { +func calculateDepth[T constraints.Ordered](n, nilNode Node[T], depth int) int { + if n == nilNode { return depth } - return max.Int(t.calculateDepth(n.Left, depth+1), t.calculateDepth(n.Right, depth+1)) + return max.Int(calculateDepth(n.Left(), nilNode, depth+1), calculateDepth(n.Right(), nilNode, depth+1)) } -// Returns the minimum value of node of the tree -func (t *binaryTree[T]) minimum(node *Node[T]) *Node[T] { - if t.isNil(node) { +func minimum[T constraints.Ordered](node, nilNode Node[T]) Node[T] { + if node == nilNode { return node } - for !t.isNil(node.Left) { - node = node.Left + for node.Left() != nilNode { + node = node.Left() } return node } -// Returns the maximum value of node of the tree -func (t *binaryTree[T]) maximum(node *Node[T]) *Node[T] { - if t.isNil(node) { +func maximum[T constraints.Ordered](node, nilNode Node[T]) Node[T] { + if node == nilNode { return node } - for !t.isNil(node.Right) { - node = node.Right + for node.Right() != nilNode { + node = node.Right() } return node } -func (t *binaryTree[T]) levelOrderHelper(root *Node[T], traversal *[]T) { - var q []*Node[T] // queue - var tmp *Node[T] +func levelOrderHelper[T constraints.Ordered](root, nilNode Node[T], traversal *[]T) { + var q []Node[T] // queue + var tmp Node[T] q = append(q, root) for len(q) != 0 { tmp, q = q[0], q[1:] - *traversal = append(*traversal, tmp.Key) - if !t.isNil(tmp.Left) { - q = append(q, tmp.Left) + *traversal = append(*traversal, tmp.Key()) + if tmp.Left() != nilNode { + q = append(q, tmp.Left()) } - if !t.isNil(tmp.Right) { - q = append(q, tmp.Right) + if tmp.Right() != nilNode { + q = append(q, tmp.Right()) } } } -// Reference: https://stackoverflow.com/a/51730733/15437172 -func (t *binaryTree[T]) printHelper(root *Node[T], indent string, isLeft bool) { - if t.isNil(root) { - return +func predecessorHelper[T constraints.Ordered](node, nilNode Node[T]) (T, bool) { + if node.Left() != nilNode { + return maximum(node.Left(), nilNode).Key(), true } - fmt.Print(indent) - if isLeft { - fmt.Print("├──") - indent += "│ " - } else { - fmt.Print("└──") - indent += " " + p := node.Parent() + for p != nilNode && node == p.Left() { + node = p + p = p.Parent() } - if t.isRBTree() { - color := "Black" - if root.Color == Red { - color = "Red" - } + if p == nilNode { + var dft T + return dft, false + } + return p.Key(), true +} - fmt.Println(root.Key, "(", color, ")") - } else { - fmt.Println(root.Key) +func successorHelper[T constraints.Ordered](node, nilNode Node[T]) (T, bool) { + if node.Right() != nilNode { + return minimum(node.Right(), nilNode).Key(), true } - t.printHelper(root.Left, indent, true) - t.printHelper(root.Right, indent, false) -} + p := node.Parent() + for p != nilNode && node == p.Right() { + node = p + p = p.Parent() + } -// Determines the tree is RB -func (t *binaryTree[T]) isRBTree() bool { - return t.NIL != nil + if p == nilNode { + var dft T + return dft, false + } + return p.Key(), true } diff --git a/structure/tree/tree_test.go b/structure/tree/tree_test.go index 2426e57e6..3653f7355 100644 --- a/structure/tree/tree_test.go +++ b/structure/tree/tree_test.go @@ -10,47 +10,42 @@ import ( ) func TestTreeGetOrHas(t *testing.T) { + helper := func(tree TestTree[int], nums []int) { + tree.Push(nums...) + for _, num := range nums { + if !tree.Has(num) { + t.Errorf("Error with Has or Push method") + } + } + + min, _ := tree.Min() + max, _ := tree.Max() + + if _, ok := tree.Get(min - 1); ok { + t.Errorf("Error with Get method") + } + + if _, ok := tree.Get(max + 1); ok { + t.Errorf("Error with Get method") + } + } + lens := []int{100, 1_000, 10_000, 100_000} for _, ll := range lens { nums := rand.Perm(ll) t.Run("Test Binary Search Tree", func(t *testing.T) { bsTree := bt.NewBinarySearch[int]() - bsTree.Push(nums...) - for _, num := range nums { - if !bsTree.Has(num) { - t.Errorf("Error with Has or Push method") - } - } - min, _ := bsTree.Min() - max, _ := bsTree.Max() - - if _, ok := bsTree.Get(min - 1); ok { - t.Errorf("Error with Get method") - } - - if _, ok := bsTree.Get(max + 1); ok { - t.Errorf("Error with Get method") - } + helper(bsTree, nums) }) t.Run("Test Red-Black Tree", func(t *testing.T) { rbTree := bt.NewRB[int]() - rbTree.Push(nums...) - for _, num := range nums { - if !rbTree.Has(num) { - t.Errorf("Error with Has or Push method") - } - } + helper(rbTree, nums) }) t.Run("Test AVL Tree", func(t *testing.T) { avlTree := bt.NewAVL[int]() - avlTree.Push(nums...) - for _, num := range nums { - if !avlTree.Has(num) { - t.Errorf("Error with Has or Push method") - } - } + helper(avlTree, nums) }) } } @@ -261,43 +256,38 @@ func TestTreeLevelOrder(t *testing.T) { } func TestTreeMinAndMax(t *testing.T) { + helper := func(tree TestTree[int], nums []int) { + ll := len(nums) + if _, ok := tree.Min(); ok { + t.Errorf("Error with Min method.") + } + if _, ok := tree.Max(); ok { + t.Errorf("Error with Max method.") + } + tree.Push(nums...) + if min, ok := tree.Min(); !ok || min != nums[0] { + t.Errorf("Error with Min method.") + } + if max, ok := tree.Max(); !ok || max != nums[ll-1] { + t.Errorf("Error with Max method.") + } + } + lens := []int{500, 1_000, 10_000} for _, ll := range lens { nums := rand.Perm(ll) sort.Ints(nums) t.Run("Test Binary Search Tree", func(t *testing.T) { - bsTree := bt.NewBinarySearch[int]() - bsTree.Push(nums...) - if min, ok := bsTree.Min(); !ok || min != nums[0] { - t.Errorf("Error with Min method.") - } - if max, ok := bsTree.Max(); !ok || max != nums[ll-1] { - t.Errorf("Error with Max method.") - } + helper(bt.NewBinarySearch[int](), nums) }) t.Run("Test Red-Black Tree", func(t *testing.T) { - rbTree := bt.NewRB[int]() - rbTree.Push(nums...) - if min, ok := rbTree.Min(); !ok || min != nums[0] { - t.Errorf("Error with Min method.") - } - if max, ok := rbTree.Max(); !ok || max != nums[ll-1] { - t.Errorf("Error with Max method.") - } + helper(bt.NewRB[int](), nums) }) t.Run("Test AVL Tree", func(t *testing.T) { - avlTree := bt.NewAVL[int]() - avlTree.Push(nums...) - if min, ok := avlTree.Min(); !ok || min != nums[0] { - t.Errorf("Error with Min method.") - } - - if max, ok := avlTree.Max(); !ok || max != nums[ll-1] { - t.Errorf("Error with Max method.") - } + helper(bt.NewAVL[int](), nums) }) } } @@ -361,62 +351,6 @@ func TestTreeDepth(t *testing.T) { }) } -func TestTreePrint(t *testing.T) { - t.Run("Test for Binary-Search Tree", func(t *testing.T) { - tests := []struct { - input []int - want []int - }{ - {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, - {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, - []int{61, 51, 41, 31, 21, 1, 71, 70, 85, 80, 95, 105, 100, 90}}, - {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}, - } - for _, tt := range tests { - tree := bt.NewBinarySearch[int]() - t.Log(reflect.TypeOf(tree).String()) - tree.Push(tt.input...) - tree.Print() - } - }) - - t.Run("Test for AVL Tree", func(t *testing.T) { - tests := []struct { - input []int - want []int - }{ - {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, - {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, - []int{1, 31, 21, 61, 51, 41, 71, 85, 80, 95, 105, 100, 90, 70}}, - {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 6, 5, 3, 8, 10, 9, 7}}, - } - for _, tt := range tests { - tree := bt.NewAVL[int]() - t.Log(reflect.TypeOf(tree).String()) - tree.Push(tt.input...) - tree.Print() - } - }) - - t.Run("Test for Red-Black Tree", func(t *testing.T) { - tests := []struct { - input []int - want []int - }{ - {[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}}, - {[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, - []int{1, 31, 21, 51, 71, 70, 61, 41, 85, 95, 105, 100, 90, 80}}, - {[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 3, 6, 5, 8, 10, 9, 7}}, - } - for _, tt := range tests { - tree := bt.NewRB[int]() - t.Log(reflect.TypeOf(tree).String() == "*tree.RB[int]") - tree.Push(tt.input...) - tree.Print() - } - }) -} - func TestTreeAccessNodesByLayer(t *testing.T) { t.Run("Test for Binary-Search Tree", func(t *testing.T) { tests := []struct { @@ -480,6 +414,81 @@ func TestTreeAccessNodesByLayer(t *testing.T) { }) } +func TestTreePredecessorAndSuccessor(t *testing.T) { + helper := func(tree TestTree[int]) { + nums := []int{10, 8, 88, 888, 4, -1, 100} + tree.Push(nums...) + if ret, ok := tree.Predecessor(100); !ok || ret != 88 { + t.Error("Error with Predecessor") + } + + if _, ok := tree.Predecessor(-1); ok { + t.Error("Error with Predecessor") + } + + tree.Push(-100) + if ret, ok := tree.Predecessor(-1); !ok || ret != -100 { + t.Error("Error with Predecessor") + } + + if _, ok := tree.Predecessor(-12); ok { + t.Error("Error with Predecessor") + } + + if ret, ok := tree.Predecessor(4); !ok || ret != -1 { + t.Error("Error with Predecessor") + } + + if ret, ok := tree.Successor(4); !ok || ret != 8 { + t.Error("Error with Successor") + } + + if ret, ok := tree.Successor(8); !ok || ret != 10 { + t.Error("Error with Successor") + } + + if ret, ok := tree.Successor(88); !ok || ret != 100 { + t.Error("Error with Successor") + } + + if ret, ok := tree.Successor(100); !ok || ret != 888 { + t.Error("Error with Successor") + } + + tree.Delete(888) + if _, ok := tree.Successor(100); ok { + t.Error("Error with Successor") + } + + if ret, ok := tree.Successor(-1); !ok || ret != 4 { + t.Error("Error with Successor") + } + + if _, ok := tree.Successor(888); ok { + t.Error("Error with Successor") + } + + if _, ok := tree.Successor(188); ok { + t.Error("Error with Successor") + } + } + + t.Run("Test for Binary Search Tree", func(t *testing.T) { + tree := bt.NewBinarySearch[int]() + helper(tree) + }) + + t.Run("Test for Red-Black Tree", func(t *testing.T) { + tree := bt.NewRB[int]() + helper(tree) + }) + + t.Run("Test for AVL Tree", func(t *testing.T) { + tree := bt.NewAVL[int]() + helper(tree) + }) +} + // Benchmark the comparisons between BST, AVL and RB Tree const testNum = 10_000 From bc2ae780e22b212766014967b27f6a4078d3bdc3 Mon Sep 17 00:00:00 2001 From: Yury <72691412+cheatsnake@users.noreply.github.com> Date: Thu, 19 Jan 2023 20:35:14 +0300 Subject: [PATCH 112/202] feat: add GUID algorithm (#614) --- strings/guid/guid.go | 48 +++++++++++++++++++++++++++ strings/guid/guid_test.go | 68 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 strings/guid/guid.go create mode 100644 strings/guid/guid_test.go diff --git a/strings/guid/guid.go b/strings/guid/guid.go new file mode 100644 index 000000000..36cc906a7 --- /dev/null +++ b/strings/guid/guid.go @@ -0,0 +1,48 @@ +// guid.go +// description: Generate random globally unique identifiers (GUIDs). +// details: +// A GUID (globally unique identifier) is a 128-bit text string that +// represents an identification (ID). Organizations generate GUIDs when +// a unique reference number is needed to identify information on +// a computer or network. A GUID can be used to ID hardware, software, +// accounts, documents and other items. The term is also often used in +// software created by Microsoft. +// See more information on: https://en.wikipedia.org/wiki/Universally_unique_identifier +// author(s) [cheatsnake](https://github.com/cheatsnake) +// see guid_test.go + +// Package guid provides facilities for generating random globally unique identifiers. +package guid + +import ( + "crypto/rand" + "fmt" + "math/big" + "strings" +) + +const pattern string = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx" +const versionIndex int = 14 + +// New returns a randomly generated global unique identifier. +func New() (string, error) { + var guid strings.Builder + + for i, ch := range pattern { + if i == versionIndex { + guid.WriteRune(ch) + continue + } + if ch == '-' { + guid.WriteRune(ch) + continue + } + random, err := rand.Int(rand.Reader, big.NewInt(16)) + if err != nil { + return "", err + } + guid.WriteString(fmt.Sprintf("%x", random.Int64())) + } + + return guid.String(), nil +} diff --git a/strings/guid/guid_test.go b/strings/guid/guid_test.go new file mode 100644 index 000000000..a9e66c95e --- /dev/null +++ b/strings/guid/guid_test.go @@ -0,0 +1,68 @@ +package guid + +import ( + "strings" + "testing" +) + +func TestNew(t *testing.T) { + t.Run("check for allowed characters", func(t *testing.T) { + allowedChars := "0123456789abcdef-" + guid, err := New() + if err != nil { + t.Errorf(`the test failed, an error occurred: %s`, err.Error()) + } + + for _, char := range guid { + if !strings.Contains(allowedChars, string(char)) { + t.Errorf(`allowed only "%s" characters, but got %v`, allowedChars, char) + } + } + }) + + t.Run("check string length", func(t *testing.T) { + guid, err := New() + if err != nil { + t.Errorf(`the test failed, an error occurred: %s`, err.Error()) + } + + if len(guid) != len(pattern) { + t.Errorf(`the length of the string should be "%d", but got %d`, len(pattern), len(guid)) + } + }) + + t.Run("check for version index", func(t *testing.T) { + expected := "4" + versionIndex := strings.Index(pattern, expected) + guid, err := New() + if err != nil { + t.Errorf(`the test failed, an error occurred: %s`, err.Error()) + } + + result := string(guid[versionIndex]) + + if expected != result { + t.Errorf(`at the index %d should be %s, but got %s`, versionIndex, expected, result) + } + }) + + t.Run("check the number of dashes", func(t *testing.T) { + expected := strings.Count(pattern, "-") + guid, err := New() + if err != nil { + t.Errorf(`the test failed, an error occurred: %s`, err.Error()) + } + + result := strings.Count(guid, "-") + + if expected != result { + t.Errorf(`the length of the string should be "%d", but got %d`, len(pattern), len(guid)) + } + }) +} + +func BenchmarkNew(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = New() + } +} From 771209819da96ee02230fbe2013dcc702d446e78 Mon Sep 17 00:00:00 2001 From: Alexander John Lee <77119221+partylikeits1983@users.noreply.github.com> Date: Tue, 31 Jan 2023 19:34:55 +0300 Subject: [PATCH 113/202] fix: misspelled variable (#618) * fix: misspelled variable * fix: refactor math/binary/sqrt.go --- math/binary/sqrt.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/math/binary/sqrt.go b/math/binary/sqrt.go index 4d352ed49..111dd94a9 100644 --- a/math/binary/sqrt.go +++ b/math/binary/sqrt.go @@ -13,12 +13,12 @@ import ( const threeHalves = 1.5 -func Sqrt(number float32) float32 { - var halfHumber, y float32 - halfHumber = number * 0.5 - z := math.Float32bits(number) +func Sqrt(n float32) float32 { + var half, y float32 + half = n * 0.5 + z := math.Float32bits(n) z = 0x5f3759df - (z >> 1) // floating point bit level hacking y = math.Float32frombits(z) - y = y * (threeHalves - (halfHumber * y * y)) // Newton's approximation + y = y * (threeHalves - (half * y * y)) // Newton's approximation return 1 / y } From 68eb0fbf787d963d5f3bee9a072cfe32114eff6f Mon Sep 17 00:00:00 2001 From: Neha G <113783174+nehag0x1@users.noreply.github.com> Date: Wed, 1 Feb 2023 16:35:55 +0530 Subject: [PATCH 114/202] fix: range condition in IsPowerOfTwoLeftShift (#619) Remove redundant condition --- math/binary/checkisnumberpoweroftwo.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/math/binary/checkisnumberpoweroftwo.go b/math/binary/checkisnumberpoweroftwo.go index 63ecc6e3b..29c023e5a 100644 --- a/math/binary/checkisnumberpoweroftwo.go +++ b/math/binary/checkisnumberpoweroftwo.go @@ -26,10 +26,7 @@ func IsPowerOfTwo(x int) bool { // by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, // which in decimal system is 8 or = 2 * 2 * 2 func IsPowerOfTwoLeftShift(number uint) bool { - if number == 0 { - return false - } - for p := uint(1); p > 0; p = p << 1 { + for p := uint(1); p <= number; p = p << 1 { if number == p { return true } From 97d4a1451082a4fa0b7f269a3b1257cd064ce7ef Mon Sep 17 00:00:00 2001 From: Pedro Rocha Date: Sat, 11 Feb 2023 16:40:09 +0000 Subject: [PATCH 115/202] test: Add benchmark for prime sieve (#621) --- math/prime/sieve_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/math/prime/sieve_test.go b/math/prime/sieve_test.go index 82cc63017..36a1c5811 100644 --- a/math/prime/sieve_test.go +++ b/math/prime/sieve_test.go @@ -44,3 +44,9 @@ func TestGeneratePrimes(t *testing.T) { } }) } + +func BenchmarkSieve10(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Generate(10) + } +} From 27c627e06107f8a4fa472bc1daeede6b60951f6f Mon Sep 17 00:00:00 2001 From: Hidenari-Yuda <106872451+hidenari-yuda@users.noreply.github.com> Date: Tue, 14 Feb 2023 19:48:02 +0900 Subject: [PATCH 116/202] fix: rand.Seed() deparcated (#624) * fix rand.Seed fix rand.Seed * fix rand.Seed fix rand.Seed fix unexpected format change fix unexpected format change * fix unexpected format change --------- Co-authored-by: Andrii Siriak --- cipher/caesar/caesar_test.go | 4 ++-- graph/lowestcommonancestor_test.go | 14 +++++++------- sort/sorts_test.go | 4 ++-- strings/genetic/genetic.go | 16 ++++++++-------- structure/tree/avl_test.go | 4 ++-- structure/tree/bstree_test.go | 4 ++-- structure/tree/rbtree_test.go | 4 ++-- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/cipher/caesar/caesar_test.go b/cipher/caesar/caesar_test.go index 4d03ea3ec..1e22a8c34 100644 --- a/cipher/caesar/caesar_test.go +++ b/cipher/caesar/caesar_test.go @@ -156,10 +156,10 @@ func Example() { } func FuzzCaesar(f *testing.F) { - rand.Seed(time.Now().Unix()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) f.Add("The Quick Brown Fox Jumps over the Lazy Dog.") f.Fuzz(func(t *testing.T, input string) { - key := rand.Intn(26) + key := rnd.Intn(26) if result := Decrypt(Encrypt(input, key), key); result != input { t.Fatalf("With input: '%s' and key: %d\n\tExpected: '%s'\n\tGot: '%s'", input, key, input, result) } diff --git a/graph/lowestcommonancestor_test.go b/graph/lowestcommonancestor_test.go index c7149e46e..ab55219fb 100644 --- a/graph/lowestcommonancestor_test.go +++ b/graph/lowestcommonancestor_test.go @@ -147,11 +147,11 @@ func TestLCA(t *testing.T) { } func generateTree() *Tree { - rand.Seed(time.Now().UnixNano()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) const MAXVERTEX int = 2000 - var numbersVertex int = rand.Intn(MAXVERTEX) + 1 - var root int = rand.Intn(numbersVertex) + var numbersVertex int = rnd.Intn(MAXVERTEX) + 1 + var root int = rnd.Intn(numbersVertex) var edges []TreeEdge var fullGraph []TreeEdge @@ -163,7 +163,7 @@ func generateTree() *Tree { }) } } - rand.Shuffle(len(fullGraph), func(i, j int) { + rnd.Shuffle(len(fullGraph), func(i, j int) { fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i] }) @@ -201,7 +201,7 @@ func generateTree() *Tree { } func generateQuery(tree *Tree) []Query { - rand.Seed(time.Now().UnixNano()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) const MAXQUERY = 50 var queries []Query @@ -217,8 +217,8 @@ func generateQuery(tree *Tree) []Query { } for q := 1; q <= MAXQUERY; q++ { - u := rand.Intn(tree.numbersVertex) - v := rand.Intn(tree.numbersVertex) + u := rnd.Intn(tree.numbersVertex) + v := rnd.Intn(tree.numbersVertex) queries = append(queries, Query{ u: u, v: v, diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 9f34a23cb..7ff8b4363 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -106,11 +106,11 @@ func TestMergeParallel(t *testing.T) { // Test parallel merge sort with a large slice t.Run("ParallelMerge on large slice", func(t *testing.T) { - rand.Seed(time.Now().UnixNano()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) size := 100000 randomLargeSlice := make([]int, size) for i := range randomLargeSlice { - randomLargeSlice[i] = rand.Intn(size) + randomLargeSlice[i] = rnd.Intn(size) } sortedSlice := sort.ParallelMerge[int](randomLargeSlice) for i := 0; i < len(sortedSlice)-1; i++ { diff --git a/strings/genetic/genetic.go b/strings/genetic/genetic.go index 95fc05fa6..384ecf940 100644 --- a/strings/genetic/genetic.go +++ b/strings/genetic/genetic.go @@ -92,7 +92,7 @@ func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) { debug := conf.Debug // Just a seed to improve randomness required by the algorithm - rand.Seed(time.Now().UnixNano()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) // Verify that the target contains no genes besides the ones inside genes variable. for position, r := range target { @@ -113,7 +113,7 @@ func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) { for i := 0; i < populationNum; i++ { key := "" for x := 0; x < utf8.RuneCountInString(target); x++ { - choice := rand.Intn(len(charmap)) + choice := rnd.Intn(len(charmap)) key += string(charmap[choice]) } pop[i] = PopulationItem{key, 0} @@ -165,18 +165,18 @@ func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) { nChild = 10 } for x := 0.0; x < nChild; x++ { - parent2 := pop[rand.Intn(selectionNum)] + parent2 := pop[rnd.Intn(selectionNum)] // Crossover - split := rand.Intn(utf8.RuneCountInString(target)) + split := rnd.Intn(utf8.RuneCountInString(target)) child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...) child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...) // Clean fitness value // Mutate - if rand.Float64() < mutationProb { - child1[rand.Intn(len(child1))] = charmap[rand.Intn(len(charmap))] + if rnd.Float64() < mutationProb { + child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))] } - if rand.Float64() < mutationProb { - child2[rand.Intn(len(child2))] = charmap[rand.Intn(len(charmap))] + if rnd.Float64() < mutationProb { + child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))] } // Push into 'popChildren' popChildren = append(popChildren, PopulationItem{string(child1), 0}) diff --git a/structure/tree/avl_test.go b/structure/tree/avl_test.go index 14a7ab570..70913499a 100644 --- a/structure/tree/avl_test.go +++ b/structure/tree/avl_test.go @@ -284,9 +284,9 @@ func TestAVLDelete(t *testing.T) { t.Run("Random Test", func(t *testing.T) { nums := []int{100, 500, 1000, 10_000} for _, n := range nums { - rand.Seed(time.Now().Unix()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) tree := bt.NewAVL[int]() - nums := rand.Perm(n) + nums := rnd.Perm(n) tree.Push(nums...) rets := tree.InOrder() diff --git a/structure/tree/bstree_test.go b/structure/tree/bstree_test.go index abbf8bfea..211daa28a 100644 --- a/structure/tree/bstree_test.go +++ b/structure/tree/bstree_test.go @@ -154,9 +154,9 @@ func TestDelete(t *testing.T) { t.Run("Random Test", func(t *testing.T) { tests := []int{100, 500, 1000, 10_000} for _, n := range tests { - rand.Seed(time.Now().Unix()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) tree := bt.NewBinarySearch[int]() - nums := rand.Perm(n) + nums := rnd.Perm(n) tree.Push(nums...) rets := tree.InOrder() diff --git a/structure/tree/rbtree_test.go b/structure/tree/rbtree_test.go index a609aa7d2..1b6b38265 100644 --- a/structure/tree/rbtree_test.go +++ b/structure/tree/rbtree_test.go @@ -85,9 +85,9 @@ func TestRBTreeDelete(t *testing.T) { func TestRBTree(t *testing.T) { testcases := []int{100, 200, 1000, 10000} for _, n := range testcases { - rand.Seed(time.Now().Unix()) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) tree := bt.NewRB[int]() - nums := rand.Perm(n) + nums := rnd.Perm(n) tree.Push(nums...) rets := tree.InOrder() From 4f43cc154fccf98cccd49c1b1fdba21cba8e4a5f Mon Sep 17 00:00:00 2001 From: Rahul <122198550+GooMonk@users.noreply.github.com> Date: Mon, 6 Mar 2023 12:15:56 +0530 Subject: [PATCH 117/202] Add Krishnamurthy number (#620) Co-authored-by: rahul291999 --- math/krishnamurthy.go | 32 ++++++++++++++++++++++++ math/krishnamurthy_test.go | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 math/krishnamurthy.go create mode 100644 math/krishnamurthy_test.go diff --git a/math/krishnamurthy.go b/math/krishnamurthy.go new file mode 100644 index 000000000..641dfbf92 --- /dev/null +++ b/math/krishnamurthy.go @@ -0,0 +1,32 @@ +// filename : krishnamurthy.go +// description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. +// details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. +// Ex: 1! = 1, 145 = 1! + 4! + 5! +// author(s): [GooMonk](https://github.com/GooMonk) +// see krishnamurthy_test.go +package math + +import "github.com/TheAlgorithms/Go/constraints" + +// IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not. +func IsKrishnamurthyNumber[T constraints.Integer](n T) bool { + if n <= 0 { + return false + } + + // Preprocessing: Using a slice to store the digit Factorials + digitFact := make([]T, 10) + digitFact[0] = 1 // 0! = 1 + + for i := 1; i < 10; i++ { + digitFact[i] = digitFact[i-1] * T(i) + } + + // Subtract the digit Facotorial from the number + nTemp := n + for n > 0 { + nTemp -= digitFact[n%10] + n /= 10 + } + return nTemp == 0 +} diff --git a/math/krishnamurthy_test.go b/math/krishnamurthy_test.go new file mode 100644 index 000000000..c4fc81895 --- /dev/null +++ b/math/krishnamurthy_test.go @@ -0,0 +1,51 @@ +package math + +import ( + "fmt" + "testing" +) + +func retCases() []struct { + input int64 + output bool + outputString string +} { + return []struct { + input int64 + output bool + outputString string + }{ + {-3112312321, false, "is not"}, + {0, false, "is not"}, + {1, true, "is"}, + {2, true, "is"}, + {109, false, "is not"}, + {145, true, "is"}, + {943, false, "is not"}, + {6327, false, "is not"}, + {40585, true, "is"}, + {9743821, false, "is not"}, + {3421488712, false, "is not"}, + } +} + +func TestIsKrishnamurthyNumber(t *testing.T) { + for _, test := range retCases() { + t.Run(fmt.Sprintf("%d %s a Krishnamurthy Number", test.input, test.outputString), func(t *testing.T) { + res := IsKrishnamurthyNumber(test.input) + if res != test.output { + t.Errorf("for input %d, expected: %t, found: %t", test.input, test.output, res) + } + }) + } +} + +func BenchmarkIsKrishnamurthyNumber(b *testing.B) { + for _, test := range retCases() { + b.Run(fmt.Sprintf("%d %s a Krishnamurthy Number", test.input, test.outputString), func(b *testing.B) { + for i := 0; i < b.N; i++ { + IsKrishnamurthyNumber(test.input) + } + }) + } +} From abeec331273c92d9e70921bd30d043164e9149bc Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 15 Mar 2023 19:34:02 +0100 Subject: [PATCH 118/202] Upgrade GitHub Actions (#627) --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40ebab4a1..29615bbe0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,13 +15,13 @@ jobs: strategy: fail-fast: false steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Setup Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: '^1.18' - name: Run Golang CI Lint - uses: golangci/golangci-lint-action@v2 + uses: golangci/golangci-lint-action@v3 with: version: latest args: -E gofmt @@ -31,7 +31,7 @@ jobs: name: Check for spelling errors runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: codespell-project/actions-codespell@master with: ignore_words_list: "actualy,nwe" From 1a0e193780d3ba6a2cb97289e3797db3f339ffa6 Mon Sep 17 00:00:00 2001 From: Rak Laptudirm Date: Thu, 16 Mar 2023 01:07:03 +0530 Subject: [PATCH 119/202] Add Style guide (#493) * chore: basic style suggestions * chore: add commenting and naming guidelines * Update STYLE.md * chore: grammer update Co-authored-by: Taj * chore: clarify the use of the workflows Co-authored-by: Taj * chore: grammer update Co-authored-by: Taj * chore: update package naming guidelines Co-authored-by: Taj * chore: finish sentence fragment Co-authored-by: Taj * chore: use the term UpperCamelCase instead of PascalCase Co-authored-by: Taj * chore: fix typo --------- Co-authored-by: Yang Libin Co-authored-by: Taj --- STYLE.md | 188 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 STYLE.md diff --git a/STYLE.md b/STYLE.md new file mode 100644 index 000000000..2027f05e9 --- /dev/null +++ b/STYLE.md @@ -0,0 +1,188 @@ +# The Algorithms Go Repository Style Guide + +This guide contains a set of go idioms and best practices which should be followed while writing +code whenever they are applicable. The instructions in this document should be given precedence +if there is a conflict between this document and [contribution guidelines](./CONTRIBUTING.md). If you find any issue or ambiguity in +this document, the maintainers of this repository should be consulted. + +## Table of Contents + +- [Formatting](#formatting) +- [Commenting](#commenting) + - [Package Comments](#package-comments) + - [Documentation Comments](#documentation-comments) + - [Author Comments](#author-comments) +- [Naming](#naming) + - [Package Naming](#package-naming) + - [Symbol Naming](#symbol-naming) + - [Function Naming](#function-naming) + - [Constructor Naming](#constructor-naming) + - [Getter Naming](#getter-naming) + - [Setter Naming](#setter-naming) + - [Interface Naming](#interface-naming) + +## Formatting + +All go code should be formatted with the official formatting tool `gofmt`. This requirement is +verified by the repository workflows. + +## Commenting + +All exported symbols should be commented with documentation, so that their motivation and use is +clear. All documentation should record any nuances of the symbol so that users are well aware of +them. + +C++ style line comments should be preferred over C-style block comments. + + + + + +
BadGood
+ +```go +/* + Unmarshal converts a JSON string into a go interface + ... +*/ +``` + + + +```go +// Unmarshal converts a JSON string into a go interface +// ... +``` + +
+ +### Package Comments + +Package comments should start with the word "Package" followed by the package name. For packages +spanning multiple files or with a need for a large documentation, use a separate `doc.go` file for package level documentation comment. + + + + + +
BadGood
+ +```go +// sort is a package which implements sorting functions. +``` + + + +```go +// Package sort implements sorting functions. +``` + +
+ +### Documentation Comments + +All doc comments for symbols should start with the symbol name. + + + + + +
BadGood
+ +```go +// Function Quick is an implementation +// of the Quicksort algorithm. +``` + + + +```go +// Quick is an implementation +// of the Quicksort algorithm. +``` + +
+ +### Author Comments + +A comment recording the author of a particular file may also be added. This comment should be +written at the top of the file and it should not be a part of the package documentation. + + + + + +
BadGood
+ +```go +// author: Rak Laptudirm (@raklaptudirm) +package sort +``` +Comment is a part of the package documentation. + + + +```go +// author: Rak Laptudirm (@raklaptudirm) + +package sort +``` +Comment is not a part of the package documentation. + +
+ +## Naming + +### Package Naming + +Package names should be short and to the point. Keep in mind that this identifier will be used to +refer to your package, so make it easy to remember. It should be only composed of lower case +letters. Prefer `json` to `JSON` or `Json`. If your package name has two words, merge them +together. Prefer `jsonencoding` to `jsonEncoding` or `json_encoding`. Although, there is almost always a word to succinctly describe the package with an appropriate name. So if you have a name that describes the package nicely, please use that. + +Add the `_test` suffix to your package name to implement black-box testing for your package in the test files. + +### Symbol Naming + +Go symbols should be named in the `camelCase` or `PascalCase`, depending of whether the symbol +is exported or not. The case when using acronymns in names should be consistent. Use `json` or +`JSON` instead of `Json`. + +For exported symbols, use the package name to your advantage to write concise symbol names. For +example, if you have a package `png`, instead of defining a `png.PNGFile`, define a `png.File`. +It is much clearer and avoids repetition. + +### Function Naming + +#### Constructor Naming + +Constructors should use the naming format `New()` for constructors which return pointers and +`Make()` for constructors which return values in accordance with the Go Programming Language's +`new` and `make` functions. If the package only exports a single constructor, use the name `New()`. +Some valid names are `reader.New()`, `metainfo.NewFile()`. + +#### Getter Naming + +Usage of Getters and Setters are discouraged. Use exported variables instead. + +Getters should use the name of the field that is being fetched. For example, prefer a getter +name like `user.Name()` to `user.GetName()`. + +#### Setter Naming + +Setters should use names in the format `Set`. For example, `user.SetName()`. + +### Interface Naming + +Interfaces should use names in the format of `er` or ``. For example, some +valid interface names are: + +```go +type Node interface { + Node() +} + +type Writer interface { + Write() +} +``` From 0bf1025ea7d7f080dc7df0082c18a6705f3d6254 Mon Sep 17 00:00:00 2001 From: Pedro Rocha Date: Thu, 23 Mar 2023 03:36:20 +0000 Subject: [PATCH 120/202] feat: adds Huffman coding algorithm (#625) * feat: add Huffman coding algorithm * add struct SymbolFreq to explicitly represent a pair of a symbol and its frequency * adds panic call to BuildTree method * docs: add documentation * test: add basic test for huffman coding algorithm * makes list of symbol-frequency pairs explicitly ordered by frequency * test: Make test cases dependent only on input string by computing sorted symbol-frequency list * doc: add dome doc comments and remove logs * fix some typos * add minor refactoring of if-else statement Co-authored-by: Taj * add minor refactoring of if-else statement Co-authored-by: Taj * add minor refactoring of if-else statement * replace panic call by returning an error * add minor refactoring of if-else statement Co-authored-by: Taj * replace BuildDict by GetEncoding * replace 'dict' with 'codes' * move sort interface instantation to test * move huffman coding to compression folder * rename package 'huffmancodin' to 'compression' * Update compression/huffmancoding_test.go Co-authored-by: Taj * rename functions from huffmancoding * use sort.Slice instead of sort.Sort in SymbolCountOrd --------- Co-authored-by: Taj --- compression/huffmancoding.go | 116 ++++++++++++++++++++++++++++++ compression/huffmancoding_test.go | 55 ++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 compression/huffmancoding.go create mode 100644 compression/huffmancoding_test.go diff --git a/compression/huffmancoding.go b/compression/huffmancoding.go new file mode 100644 index 000000000..f6515872e --- /dev/null +++ b/compression/huffmancoding.go @@ -0,0 +1,116 @@ +// huffman.go +// description: Implements Huffman compression, encoding and decoding +// details: +// We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding. +// It assumes that the list of symbol-frequencies is sorted. +// author(s) [pedromsrocha](https://github.com/pedromsrocha) +// see also huffmancoding_test.go + +package compression + +import "fmt" + +// A Node of an Huffman tree, which can either be a leaf or an internal node. +// Each node has a weight. +// A leaf node has an associated symbol, but no children (i.e., left == right == nil). +// A parent node has a left and right child and no symbol (i.e., symbol == -1). +type Node struct { + left *Node + right *Node + symbol rune + weight int +} + +// A SymbolFreq is a pair of a symbol and its associated frequency. +type SymbolFreq struct { + Symbol rune + Freq int +} + +// HuffTree returns the root Node of the Huffman tree by compressing listfreq. +// The compression produces the most optimal code lengths, provided listfreq is ordered, +// i.e.: listfreq[i] <= listfreq[j], whenever i < j. +func HuffTree(listfreq []SymbolFreq) (*Node, error) { + if len(listfreq) < 1 { + return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs") + } + q1 := make([]Node, len(listfreq)) + q2 := make([]Node, 0, len(listfreq)) + for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq + q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq} + } + //loop invariant: q1, q2 are ordered by increasing weights + for len(q1)+len(q2) > 1 { + var node1, node2 Node + node1, q1, q2 = least(q1, q2) + node2, q1, q2 = least(q1, q2) + node := Node{left: &node1, right: &node2, + symbol: -1, weight: node1.weight + node2.weight} + q2 = append(q2, node) + } + if len(q1) == 1 { // returns the remaining node in q1, q2 + return &q1[0], nil + } + return &q2[0], nil +} + +// least removes the node with lowest weight from q1, q2. +// It returns the node with lowest weight and the slices q1, q2 after the update. +func least(q1 []Node, q2 []Node) (Node, []Node, []Node) { + if len(q1) == 0 { + return q2[0], q1, q2[1:] + } + if len(q2) == 0 { + return q1[0], q1[1:], q2 + } + if q1[0].weight <= q2[0].weight { + return q1[0], q1[1:], q2 + } + return q2[0], q1, q2[1:] +} + +// HuffEncoding recursively traverses the Huffman tree pointed by node to obtain +// the map codes, that associates a rune with a slice of booleans. +// Each code is prefixed by prefix and left and right children are labelled with +// the booleans false and true, respectively. +func HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) { + if node.symbol != -1 { //base case + codes[node.symbol] = prefix + return + } + // inductive step + prefixLeft := make([]bool, len(prefix)) + copy(prefixLeft, prefix) + prefixLeft = append(prefixLeft, false) + HuffEncoding(node.left, prefixLeft, codes) + prefixRight := make([]bool, len(prefix)) + copy(prefixRight, prefix) + prefixRight = append(prefixRight, true) + HuffEncoding(node.right, prefixRight, codes) +} + +// HuffEncode encodes the string in by applying the mapping defined by codes. +func HuffEncode(codes map[rune][]bool, in string) []bool { + out := make([]bool, 0) + for _, s := range in { + out = append(out, codes[s]...) + } + return out +} + +// HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root. +// current stores the current node of the traversing algorithm. +// out stores the current decoded string. +func HuffDecode(root, current *Node, in []bool, out string) string { + if current.symbol != -1 { + out += string(current.symbol) + return HuffDecode(root, root, in, out) + } + if len(in) == 0 { + return out + } + if in[0] { + return HuffDecode(root, current.right, in[1:], out) + } + return HuffDecode(root, current.left, in[1:], out) +} diff --git a/compression/huffmancoding_test.go b/compression/huffmancoding_test.go new file mode 100644 index 000000000..8c0434d85 --- /dev/null +++ b/compression/huffmancoding_test.go @@ -0,0 +1,55 @@ +// huffmancoding_test.go +// description: Tests the compression, encoding and decoding algorithms of huffmancoding.go. +// author(s) [pedromsrocha](https://github.com/pedromsrocha) +// see huffmancoding.go + +package compression_test + +import ( + "sort" + "testing" + + "github.com/TheAlgorithms/Go/compression" +) + +// SymbolCountOrd computes sorted symbol-frequency list of input message +func SymbolCountOrd(message string) []compression.SymbolFreq { + runeCount := make(map[rune]int) + for _, s := range message { + runeCount[s]++ + } + listfreq := make([]compression.SymbolFreq, len(runeCount)) + i := 0 + for s, n := range runeCount { + listfreq[i] = compression.SymbolFreq{Symbol: s, Freq: n} + i++ + } + sort.Slice(listfreq, func(i, j int) bool { return listfreq[i].Freq < listfreq[j].Freq }) + return listfreq +} + +func TestHuffman(t *testing.T) { + messages := []string{ + "hello world \U0001F600", + "colorless green ideas sleep furiously", + "the quick brown fox jumps over the lazy dog", + `Lorem ipsum dolor sit amet, consectetur adipiscing elit, + sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. + Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut + aliquip ex ea commodo consequat.`, + } + + for _, message := range messages { + t.Run("huffman: "+message, func(t *testing.T) { + tree, _ := compression.HuffTree(SymbolCountOrd(message)) + codes := make(map[rune][]bool) + compression.HuffEncoding(tree, nil, codes) + messageCoded := compression.HuffEncode(codes, message) + messageHuffDecoded := compression.HuffDecode(tree, tree, messageCoded, "") + if messageHuffDecoded != message { + t.Errorf("got: %q\nbut expected: %q", messageHuffDecoded, message) + + } + }) + } +} From 51028c442fce0c208469fe594d807384266926ad Mon Sep 17 00:00:00 2001 From: Jahnab Dutta <76475829+JahnabDutta@users.noreply.github.com> Date: Mon, 27 Mar 2023 02:25:30 +0530 Subject: [PATCH 121/202] Fix typo in CONTRIBUTING.md (#630) --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0eb6982c1..bc45ed171 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ Being a contributor at The Algorithms, we request you to follow the points menti - Please use the directory structure of the repository. - Make sure the file extensions should be `*.go`. -- Use meaning variable names. +- Use meaningful variable names. - Use standard library inside your code and avoid to import packages from other repositories - If an implementation of the algorithm already exists, please refer to the [filename section below](#new-file-name-guidelines). - You can suggest reasonable changes to existing algorithms. From 434ab6f90b6061ee544e555c3f33e20e80b84db0 Mon Sep 17 00:00:00 2001 From: yan-aint-nickname <50468068+yan-aint-nickname@users.noreply.github.com> Date: Wed, 12 Apr 2023 18:08:58 +0300 Subject: [PATCH 122/202] Fix typos in function and variable names (#632) --- README.md | 2 +- STYLE.md | 2 +- dynamic/longestincreasingsubsequencegreedy.go | 14 +++++++------- math/modular/exponentiation_test.go | 2 +- search/binary_test.go | 2 +- search/testcases.go | 2 +- strings/genetic/genetic.go | 2 +- structure/trie/trie_bench_test.go | 4 ++-- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f672ba088..6d85ad640 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`GeneticString`](./strings/genetic/genetic.go#L71): GeneticString generates PopultaionItem based on the imputed target string, and a set of possible runes to build a string with. In order to optimise string generation additional configurations can be provided with Conf instance. Empty instance of Conf (&Conf{}) can be provided, then default values would be set. Link to the same algorithm implemented in python: https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py +1. [`GeneticString`](./strings/genetic/genetic.go#L71): GeneticString generates PopulationItem based on the imputed target string, and a set of possible runes to build a string with. In order to optimise string generation additional configurations can be provided with Conf instance. Empty instance of Conf (&Conf{}) can be provided, then default values would be set. Link to the same algorithm implemented in python: https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py --- ##### Types diff --git a/STYLE.md b/STYLE.md index 2027f05e9..e72214bc8 100644 --- a/STYLE.md +++ b/STYLE.md @@ -145,7 +145,7 @@ Add the `_test` suffix to your package name to implement black-box testing for y ### Symbol Naming Go symbols should be named in the `camelCase` or `PascalCase`, depending of whether the symbol -is exported or not. The case when using acronymns in names should be consistent. Use `json` or +is exported or not. The case when using acronyms in names should be consistent. Use `json` or `JSON` instead of `Json`. For exported symbols, use the package name to your advantage to write concise symbol names. For diff --git a/dynamic/longestincreasingsubsequencegreedy.go b/dynamic/longestincreasingsubsequencegreedy.go index 438836527..bb039468a 100644 --- a/dynamic/longestincreasingsubsequencegreedy.go +++ b/dynamic/longestincreasingsubsequencegreedy.go @@ -7,20 +7,20 @@ package dynamic // Auxiliary Space: O(n), where n is the length of the array(slice). // Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/ func LongestIncreasingSubsequenceGreedy(nums []int) int { - longestIncreasingSubsequnce := make([]int, 0) + longestIncreasingSubsequence := make([]int, 0) for _, num := range nums { - // find the leftmost index in longestIncreasingSubsequnce with value >= num - leftmostIndex := lowerBound(longestIncreasingSubsequnce, num) + // find the leftmost index in longestIncreasingSubsequence with value >= num + leftmostIndex := lowerBound(longestIncreasingSubsequence, num) - if leftmostIndex == len(longestIncreasingSubsequnce) { - longestIncreasingSubsequnce = append(longestIncreasingSubsequnce, num) + if leftmostIndex == len(longestIncreasingSubsequence) { + longestIncreasingSubsequence = append(longestIncreasingSubsequence, num) } else { - longestIncreasingSubsequnce[leftmostIndex] = num + longestIncreasingSubsequence[leftmostIndex] = num } } - return len(longestIncreasingSubsequnce) + return len(longestIncreasingSubsequence) } // Function to find the leftmost index in arr with value >= val, mimicking the inbuild lower_bound function in C++ diff --git a/math/modular/exponentiation_test.go b/math/modular/exponentiation_test.go index b5c8d4eb9..2c25ac22b 100644 --- a/math/modular/exponentiation_test.go +++ b/math/modular/exponentiation_test.go @@ -1,5 +1,5 @@ // exponentiation_test.go -// description: Test for ModularExponentation +// description: Test for ModularExponentiation // author(s) [Taj](https://github.com/tjgurwara99) // see exponentiation.go diff --git a/search/binary_test.go b/search/binary_test.go index ea77bf817..24e2a0c41 100644 --- a/search/binary_test.go +++ b/search/binary_test.go @@ -39,7 +39,7 @@ func TestLowerBound(t *testing.T) { } func TestUpperBound(t *testing.T) { - for _, test := range uppperBoundTests { + for _, test := range upperBoundTests { actualValue, actualError := UpperBound(test.data, test.key) if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) diff --git a/search/testcases.go b/search/testcases.go index 7e02bc5c8..0ef2f5cb3 100644 --- a/search/testcases.go +++ b/search/testcases.go @@ -43,7 +43,7 @@ var lowerBoundTests = []searchTest{ {[]int{}, 2, -1, ErrNotFound, "Empty"}, } -var uppperBoundTests = []searchTest{ +var upperBoundTests = []searchTest{ //Sanity {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, -25, 0, nil, "Sanity"}, {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 1, nil, "Sanity"}, diff --git a/strings/genetic/genetic.go b/strings/genetic/genetic.go index 384ecf940..b385ad867 100644 --- a/strings/genetic/genetic.go +++ b/strings/genetic/genetic.go @@ -60,7 +60,7 @@ type Result struct { Best PopulationItem } -// GeneticString generates PopultaionItem based on the imputed target +// GeneticString generates PopulationItem based on the imputed target // string, and a set of possible runes to build a string with. In order // to optimise string generation additional configurations can be provided // with Conf instance. Empty instance of Conf (&Conf{}) can be provided, diff --git a/structure/trie/trie_bench_test.go b/structure/trie/trie_bench_test.go index be59496ee..7243a1bd9 100644 --- a/structure/trie/trie_bench_test.go +++ b/structure/trie/trie_bench_test.go @@ -22,7 +22,7 @@ func BenchmarkTrie_Insert(b *testing.B) { } } -func BenchmarkTrie_Find_non_existant(b *testing.B) { +func BenchmarkTrie_Find_non_existent(b *testing.B) { insert := make([]string, 3000) for i := 0; i < len(insert); i++ { @@ -37,7 +37,7 @@ func BenchmarkTrie_Find_non_existant(b *testing.B) { } } -func BenchmarkTrie_Find_existant(b *testing.B) { +func BenchmarkTrie_Find_existent(b *testing.B) { insert := make([]string, 3000) for i := 0; i < len(insert); i++ { insert[i] = fmt.Sprintf("%f", rand.Float64()) From a0bc6d60cedef86ca34e319a592ed208b38a139d Mon Sep 17 00:00:00 2001 From: David Leal Date: Sun, 23 Apr 2023 05:32:49 -0600 Subject: [PATCH 123/202] chore: fix CI badge (#633) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d85ad640..5fd73e573 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # The Algorithms - Go [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Go)  -![golangci-lint](https://github.com/TheAlgorithms/Go/workflows/golangci-lint/badge.svg) +[![Continuous Integration](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml/badge.svg)](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml) ![godocmd](https://github.com/tjgurwara99/Go/workflows/godocmd/badge.svg) ![](https://img.shields.io/github/repo-size/TheAlgorithms/Go.svg?label=Repo%20size&style=flat-square)  ![update_directory_md](https://github.com/TheAlgorithms/Go/workflows/update_directory_md/badge.svg) From 0de898fed2f753dc6b13614733b84731f6961139 Mon Sep 17 00:00:00 2001 From: Aditya Pal Date: Mon, 1 May 2023 12:05:55 +0530 Subject: [PATCH 124/202] feat: add cycle sort algorithm (#634) * feat: add cycle sort algorithm * feat: add cycle sort algorithm * feat: address code review comments * feat: address code review comments * Remove unnecessary newline --------- Co-authored-by: Taj --- sort/cyclesort.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 8 +++++++ 2 files changed, 66 insertions(+) create mode 100644 sort/cyclesort.go diff --git a/sort/cyclesort.go b/sort/cyclesort.go new file mode 100644 index 000000000..611fe27c2 --- /dev/null +++ b/sort/cyclesort.go @@ -0,0 +1,58 @@ +package sort + +import ( + "github.com/TheAlgorithms/Go/constraints" +) + +// Cycle sort is an in-place, unstable sorting algorithm that is particularly useful +// when sorting arrays containing elements with a small range of values. It is theoretically +// optimal in terms of the total number of writes to the original array. +func Cycle[T constraints.Number](arr []T) []T { + counter, cycle, len := 0, 0, len(arr) + // Early return if the array too small + if len <= 1 { + return arr + } + + for cycle = 0; cycle < len-1; cycle++ { + elem := arr[cycle] + // Find total smaller elements to right + pos := cycle + for counter = cycle + 1; counter < len; counter++ { + if arr[counter] < elem { + pos++ + } + } + // In case this element is already in correct position, let's skip processing + if pos == cycle { + continue + } + // In case we have same elements, we want to skip to the end of that list as well, ignoring order + // This makes the algorithm unstable for composite elements + for elem == arr[pos] { + pos++ + } + // Now let us put the item to it's right position + arr[pos], elem = elem, arr[pos] + + //We need to rotate the array till we have reached the start of the cycle again + for pos != cycle { + pos = cycle + // Find smaller elements to right again + for counter = cycle + 1; counter < len; counter++ { + if arr[counter] < elem { + pos++ + } + } + for elem == arr[pos] { + pos++ + } + //We can do this unconditionally, but the check helps prevent redundant writes to the array + if elem != arr[pos] { + arr[pos], elem = elem, arr[pos] + } + } + } + + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 7ff8b4363..aeb90c04e 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -169,6 +169,10 @@ func TestPatience(t *testing.T) { testFramework(t, sort.Patience[int]) } +func TestCycle(t *testing.T) { + testFramework(t, sort.Cycle[int]) +} + //END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -286,3 +290,7 @@ func BenchmarkPigeonhole(b *testing.B) { func BenchmarkPatience(b *testing.B) { benchmarkFramework(b, sort.Patience[int]) } + +func BenchmarkCycle(b *testing.B) { + benchmarkFramework(b, sort.Cycle[int]) +} From b8648fb231848af1a418cda6d8fa8b7b85e09694 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Wed, 24 May 2023 12:11:10 +0200 Subject: [PATCH 125/202] refactor: simplify logic in `AliquotSum` (#636) * test: add missing test case * refactor: simplify logic by removing one branch --- math/aliquot_test.go | 1 + math/aliquotsum.go | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/math/aliquot_test.go b/math/aliquot_test.go index 0c6abd956..efeda425c 100644 --- a/math/aliquot_test.go +++ b/math/aliquot_test.go @@ -20,6 +20,7 @@ func TestAliquotSum(t *testing.T) { }{ {"n = 10", 10, 8, nil}, {"n = 11", 11, 1, nil}, + {"n = 1", 1, 0, nil}, {"n = -1", -1, 0, math.ErrPosArgsOnly}, {"n = 0", 0, 0, math.ErrNonZeroArgsOnly}, } diff --git a/math/aliquotsum.go b/math/aliquotsum.go index 707b818a2..6e3af6cc0 100644 --- a/math/aliquotsum.go +++ b/math/aliquotsum.go @@ -17,8 +17,6 @@ func AliquotSum(n int) (int, error) { return 0, ErrPosArgsOnly case n == 0: return 0, ErrNonZeroArgsOnly - case n == 1: - return 0, nil default: var sum int for i := 1; i <= n/2; i++ { From 4b49179e8ace094c03fde0b652c5fc7eb1d79e4f Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sun, 28 May 2023 19:43:08 +0200 Subject: [PATCH 126/202] style: use consistent naming (#637) * style: use consistent naming * style: use Int instead of Integer --- .../{integertoroman.go => inttoroman.go} | 0 ...egertoroman_test.go => inttoroman_test.go} | 0 .../{romantointeger.go => romantoint.go} | 4 ++-- ...antointeger_test.go => romantoint_test.go} | 22 +++++++++---------- 4 files changed, 13 insertions(+), 13 deletions(-) rename conversion/{integertoroman.go => inttoroman.go} (100%) rename conversion/{integertoroman_test.go => inttoroman_test.go} (100%) rename conversion/{romantointeger.go => romantoint.go} (89%) rename conversion/{romantointeger_test.go => romantoint_test.go} (70%) diff --git a/conversion/integertoroman.go b/conversion/inttoroman.go similarity index 100% rename from conversion/integertoroman.go rename to conversion/inttoroman.go diff --git a/conversion/integertoroman_test.go b/conversion/inttoroman_test.go similarity index 100% rename from conversion/integertoroman_test.go rename to conversion/inttoroman_test.go diff --git a/conversion/romantointeger.go b/conversion/romantoint.go similarity index 89% rename from conversion/romantointeger.go rename to conversion/romantoint.go index e7a8eb594..dda0000f3 100644 --- a/conversion/romantointeger.go +++ b/conversion/romantoint.go @@ -34,10 +34,10 @@ var nums = []numeral{ {1, "I"}, } -// RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers +// RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers // outside the range 1 to 3,999 will return an error. Nil or empty string return 0 // with no error thrown. -func RomanToInteger(input string) (int, error) { +func RomanToInt(input string) (int, error) { if input == "" { return 0, nil } diff --git a/conversion/romantointeger_test.go b/conversion/romantoint_test.go similarity index 70% rename from conversion/romantointeger_test.go rename to conversion/romantoint_test.go index 2916c1981..0fd34b2c3 100644 --- a/conversion/romantointeger_test.go +++ b/conversion/romantoint_test.go @@ -21,33 +21,33 @@ var romanTestCases = map[string]int{ "MMCMXCIX": 2999, "MMM": 3000, "MMMCMLXXIX": 3979, "MMMCMXCIX": 3999, } -func TestRomanToInteger(t *testing.T) { +func TestRomanToInt(t *testing.T) { for input, expected := range romanTestCases { - out, err := RomanToInteger(input) + out, err := RomanToInt(input) if err != nil { - t.Errorf("RomanToInteger(%s) returned an error %s", input, err.Error()) + t.Errorf("RomanToInt(%s) returned an error %s", input, err.Error()) } if out != expected { - t.Errorf("RomanToInteger(%s) = %d; want %d", input, out, expected) + t.Errorf("RomanToInt(%s) = %d; want %d", input, out, expected) } } - _, err := RomanToInteger("IVCMXCIX") + _, err := RomanToInt("IVCMXCIX") if err == nil { - t.Error("RomanToInteger(IVCMXCIX) expected an error") + t.Error("RomanToInt(IVCMXCIX) expected an error") } - val, err := RomanToInteger("") + val, err := RomanToInt("") if val != 0 { - t.Errorf("RomanToInteger(\"\") = %d; want 0", val) + t.Errorf("RomanToInt(\"\") = %d; want 0", val) } if err != nil { - t.Errorf("RomanToInteger(\"\") returned an error %s", err.Error()) + t.Errorf("RomanToInt(\"\") returned an error %s", err.Error()) } } -func BenchmarkRomanToInteger(b *testing.B) { +func BenchmarkRomanToInt(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { - _, _ = RomanToInteger("MMMCMXCIX") + _, _ = RomanToInt("MMMCMXCIX") } } From c57461a314476a97474517d989dc70c3a145ceee Mon Sep 17 00:00:00 2001 From: Andrii Siriak Date: Mon, 29 May 2023 22:51:00 +0300 Subject: [PATCH 127/202] Check if godocmd runs (#638) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5fd73e573..8c7814432 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ The repository is a collection of open-source implementation of a variety of alg Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ## List of Algorithms + # Packages: From a3beedefdfff450ff1461a19c4ee8855de040780 Mon Sep 17 00:00:00 2001 From: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 29 May 2023 19:51:21 +0000 Subject: [PATCH 128/202] Updated Documentation in README.md --- README.md | 229 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 155 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 8c7814432..776a50f4b 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,37 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Combinations`](./strings/combination/combination.go#L7): No description provided. +--- +
+ compression + +--- + +##### Functions: + +1. [`HuffDecode`](./compression/huffmancoding.go#L104): HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root. current stores the current node of the traversing algorithm. out stores the current decoded string. +2. [`HuffEncode`](./compression/huffmancoding.go#L93): HuffEncode encodes the string in by applying the mapping defined by codes. +3. [`HuffEncoding`](./compression/huffmancoding.go#L76): HuffEncoding recursively traverses the Huffman tree pointed by node to obtain the map codes, that associates a rune with a slice of booleans. Each code is prefixed by prefix and left and right children are labelled with the booleans false and true, respectively. +4. [`HuffTree`](./compression/huffmancoding.go#L33): HuffTree returns the root Node of the Huffman tree by compressing listfreq. The compression produces the most optimal code lengths, provided listfreq is ordered, i.e.: listfreq[i] <= listfreq[j], whenever i < j. + +--- +##### Types + +1. [`Node`](./compression/huffmancoding.go#L17): No description provided. + +2. [`SymbolFreq`](./compression/huffmancoding.go#L25): No description provided. + + +--- +
+ compression_test + +--- + +##### Functions: + +1. [`SymbolCountOrd`](./compression/huffmancoding_test.go#L16): SymbolCountOrd computes sorted symbol-frequency list of input message + ---
conversion @@ -196,10 +227,10 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. 5. [`FuzzBase64Encode`](./conversion/base64_test.go#L113): No description provided. 6. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue -7. [`IntToRoman`](./conversion/integertoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. +7. [`IntToRoman`](./conversion/inttoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. 8. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex 9. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. -10. [`RomanToInteger`](./conversion/romantointeger.go#L40): RomanToInteger converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. +10. [`RomanToInt`](./conversion/romantoint.go#L40): RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. ---
@@ -343,25 +374,28 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package geometry contains geometric algorithms +##### Package geometry contains geometric algorithms Package geometry contains geometric algorithms --- ##### Functions: 1. [`Distance`](./math/geometry/straightlines.go#L18): Distance calculates the shortest distance between two points. -2. [`IsParallel`](./math/geometry/straightlines.go#L42): IsParallel checks if two lines are parallel or not. -3. [`IsPerpendicular`](./math/geometry/straightlines.go#L47): IsPerpendicular checks if two lines are perpendicular or not. -4. [`PointDistance`](./math/geometry/straightlines.go#L53): PointDistance calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. -5. [`Section`](./math/geometry/straightlines.go#L24): Section calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. -6. [`Slope`](./math/geometry/straightlines.go#L32): Slope calculates the slope (gradient) of a line. -7. [`YIntercept`](./math/geometry/straightlines.go#L37): YIntercept calculates the Y-Intercept of a line from a specific Point. +2. [`EuclideanDistance`](./math/geometry/distance.go#L20): EuclideanDistance returns the Euclidean distance between points in any `n` dimensional Euclidean space. +3. [`IsParallel`](./math/geometry/straightlines.go#L42): IsParallel checks if two lines are parallel or not. +4. [`IsPerpendicular`](./math/geometry/straightlines.go#L47): IsPerpendicular checks if two lines are perpendicular or not. +5. [`PointDistance`](./math/geometry/straightlines.go#L53): PointDistance calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order. +6. [`Section`](./math/geometry/straightlines.go#L24): Section calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n. +7. [`Slope`](./math/geometry/straightlines.go#L32): Slope calculates the slope (gradient) of a line. +8. [`YIntercept`](./math/geometry/straightlines.go#L37): YIntercept calculates the Y-Intercept of a line from a specific Point. --- ##### Types -1. [`Line`](./math/geometry/straightlines.go#L13): No description provided. +1. [`EuclideanPoint`](./math/geometry/distance.go#L14): No description provided. -2. [`Point`](./math/geometry/straightlines.go#L9): No description provided. +2. [`Line`](./math/geometry/straightlines.go#L13): No description provided. + +3. [`Point`](./math/geometry/straightlines.go#L9): No description provided. --- @@ -411,6 +445,19 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 9. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. +--- +
+ guid + +--- + +##### Package guid provides facilities for generating random globally unique identifiers. + +--- +##### Functions: + +1. [`New`](./strings/guid/guid.go#L28): New returns a randomly generated global unique identifier. + ---
hashmap @@ -428,6 +475,40 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`HashMap`](./structure/hashmap/hashmap.go#L17): No description provided. +--- +
+ heap + +--- + +##### Functions: + +1. [`New`](./structure/heap/heap.go#L15): New gives a new heap object. +2. [`NewAny`](./structure/heap/heap.go#L24): NewAny gives a new heap object. element can be anything, but must provide less function. + +--- +##### Types + +1. [`Heap`](./structure/heap/heap.go#L9): No description provided. + + +--- +
+ heap_test + +--- + +##### Types + +1. [`testInt`](#L0): + + Methods: + 1. [`Less`](./structure/heap/heap_test.go#L11): No description provided. +2. [`testStudent`](#L0): + + Methods: + 1. [`Less`](./structure/heap/heap_test.go#L20): No description provided. + ---
kmp @@ -436,7 +517,13 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Kmp`](./strings/kmp/kmp.go#L4): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. +1. [`Kmp`](./strings/kmp/kmp.go#L4): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. + +--- +##### Types + +1. [`args`](./strings/kmp/kmp_test.go#L39): No description provided. + ---
@@ -505,29 +592,32 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### Package math is a package that contains mathematical algorithms and its different implementations. +##### filename : krishnamurthy.go description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. Ex: 1! = 1, 145 = 1! + 4! + 5! author(s): [GooMonk](https://github.com/GooMonk) see krishnamurthy_test.go Package math is a package that contains mathematical algorithms and its different implementations. --- ##### Functions: 1. [`Abs`](./math/abs.go#L11): Abs returns absolute value -2. [`Combinations`](./math/binomialcoefficient.go#L20): C is Binomial Coefficient function This function returns C(n, k) for given n and k -3. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) -4. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n -5. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -6. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -7. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number -8. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -9. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1' -10. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number -11. [`Mean`](./math/mean.go#L7): No description provided. -12. [`Median`](./math/median.go#L12): No description provided. -13. [`Mode`](./math/mode.go#L19): No description provided. -14. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number -15. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. -16. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 -17. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) -18. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. +2. [`AliquotSum`](./math/aliquotsum.go#L14): This function returns s(n) for given number +3. [`Combinations`](./math/binomialcoefficient.go#L20): C is Binomial Coefficient function This function returns C(n, k) for given n and k +4. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx) +5. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n +6. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +7. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. +8. [`IsKrishnamurthyNumber`](./math/krishnamurthy.go#L12): IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not. +9. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number +10. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +11. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1' +12. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number +13. [`Mean`](./math/mean.go#L7): No description provided. +14. [`Median`](./math/median.go#L12): No description provided. +15. [`Mode`](./math/mode.go#L19): No description provided. +16. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number +17. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +18. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 +19. [`PronicNumber`](./math/pronicnumber.go#L15): PronicNumber returns true if argument passed to the function is pronic and false otherwise. +20. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +21. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. ---
@@ -690,7 +780,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`NewPolybius`](./cipher/polybius/polybius.go#L21): NewPolybius returns a pointer to object of Polybius. If the size of "chars" is longer than "size", "chars" are truncated to "size". +1. [`FuzzPolybius`](./cipher/polybius/polybius_test.go#L154): No description provided. +2. [`NewPolybius`](./cipher/polybius/polybius.go#L21): NewPolybius returns a pointer to object of Polybius. If the size of "chars" is longer than "size", "chars" are truncated to "size". --- ##### Types @@ -799,6 +890,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Decrypt`](./cipher/rsa/rsa.go#L43): Decrypt decrypts encrypted rune slice based on the RSA algorithm 2. [`Encrypt`](./cipher/rsa/rsa.go#L28): Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory +3. [`FuzzRsa`](./cipher/rsa/rsa_test.go#L79): No description provided. ---
@@ -862,26 +954,27 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. -2. [`Bucket Sort`](./sort/bucketsort.go#L5): Bucket Sort works with the idea of distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. +2. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range. 3. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. 4. [`Count`](./sort/countingsort.go#L11): No description provided. -5. [`Exchange`](./sort/exchangesort.go#L8): No description provided. -6. [`HeapSort`](./sort/heapsort.go#L116): No description provided. -7. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort -8. [`Insertion`](./sort/insertionsort.go#L5): No description provided. -9. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice -10. [`MergeIter`](./sort/mergesort.go#L55): No description provided. -11. [`Pancake Sort`](./sort/pancakesort.go#L7): Pancake Sort is a sorting algorithm that is similar to selection sort that reverses elements of an array. The Pancake Sort uses the flip operation to sort the array. -12. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines -13. [`Partition`](./sort/quicksort.go#L12): No description provided. -14. [`Patience`](./sort/patiencesort.go#L13): No description provided. -15. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. -16. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array -17. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array -18. [`RadixSort`](./sort/radixsort.go#L43): No description provided. -19. [`Selection`](./sort/selectionsort.go#L5): No description provided. -20. [`Shell`](./sort/shellsort.go#L5): No description provided. -21. [`Simple`](./sort/simplesort.go#L13): No description provided. +5. [`Cycle`](./sort/cyclesort.go#L10): Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It is theoretically optimal in terms of the total number of writes to the original array. +6. [`Exchange`](./sort/exchangesort.go#L8): No description provided. +7. [`HeapSort`](./sort/heapsort.go#L116): No description provided. +8. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +9. [`Insertion`](./sort/insertionsort.go#L5): No description provided. +10. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice +11. [`MergeIter`](./sort/mergesort.go#L55): No description provided. +12. [`Pancake`](./sort/pancakesort.go#L8): Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`. +13. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines +14. [`Partition`](./sort/quicksort.go#L12): No description provided. +15. [`Patience`](./sort/patiencesort.go#L13): No description provided. +16. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. +17. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +18. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +19. [`RadixSort`](./sort/radixsort.go#L43): No description provided. +20. [`Selection`](./sort/selectionsort.go#L5): No description provided. +21. [`Shell`](./sort/shellsort.go#L5): No description provided. +22. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types @@ -916,6 +1009,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`CountChars`](./strings/charoccurrence.go#L12): CountChars counts the number of a times a character has occurred in the provided string argument and returns a map with `rune` as keys and the count as value. +2. [`IsIsogram`](./strings/isisogram.go#L34): No description provided. ---
@@ -925,16 +1019,9 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Decrypt`](./cipher/transposition/transposition.go#L82): No description provided. -2. [`Encrypt`](./cipher/transposition/transposition.go#L54): No description provided. - ---- -##### Types - -1. [`KeyMissingError`](./cipher/transposition/transposition.go#L16): No description provided. - -2. [`NoTextToEncryptError`](./cipher/transposition/transposition.go#L15): No description provided. - +1. [`Decrypt`](./cipher/transposition/transposition.go#L81): No description provided. +2. [`Encrypt`](./cipher/transposition/transposition.go#L51): No description provided. +3. [`FuzzTransposition`](./cipher/transposition/transposition_test.go#L103): No description provided. ---
@@ -947,31 +1034,25 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`NewAVL`](./structure/tree/avl.go#L13): NewAVL create a novel AVL tree -2. [`NewBinarySearch`](./structure/tree/bstree.go#L18): NewBinarySearch create a novel Binary-Search tree -3. [`NewRB`](./structure/tree/rbtree.go#L23): Create a new Red-Black Tree +1. [`NewAVL`](./structure/tree/avl.go#L54): NewAVL creates a novel AVL tree +2. [`NewBinarySearch`](./structure/tree/bstree.go#L46): NewBinarySearch creates a novel Binary-Search tree +3. [`NewRB`](./structure/tree/rbtree.go#L57): NewRB creates a new Red-Black Tree --- ##### Types -1. [`AVL`](./structure/tree/avl.go#L8): No description provided. +1. [`AVL`](./structure/tree/avl.go#L48): No description provided. -2. [`BinarySearch`](./structure/tree/bstree.go#L13): No description provided. +2. [`AVLNode`](./structure/tree/avl.go#L18): No description provided. -3. [`Node`](./structure/tree/tree.go#L25): No description provided. +3. [`BSNode`](./structure/tree/bstree.go#L15): No description provided. -4. [`RB`](./structure/tree/rbtree.go#L18): No description provided. +4. [`BinarySearch`](./structure/tree/bstree.go#L40): No description provided. +5. [`RB`](./structure/tree/rbtree.go#L51): No description provided. ---- -
- tree_test - ---- - -##### Functions: +6. [`RBNode`](./structure/tree/rbtree.go#L25): No description provided. -1. [`FuzzRBTree`](./structure/tree/rbtree_test.go#L90): No description provided. ---
From 0b4b2de30187e0015395aca0bab25963d60c38ad Mon Sep 17 00:00:00 2001 From: Lorenzo Tinfena Date: Fri, 21 Jul 2023 06:09:17 +0000 Subject: [PATCH 129/202] Added sqrt decomposition (#613) * Create binary_heap.go * Update binary_heap.go * fix * Update binary_heap.go * Create sqrt_decomposition_simple.go * move files * bono * bono * fix style * fix style * . * some changes * . * . --- sqrt/sqrtdecomposition.go | 102 +++++++++++++++++++++++++++++++++ sqrt/sqrtdecomposition_test.go | 80 ++++++++++++++++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 sqrt/sqrtdecomposition.go create mode 100644 sqrt/sqrtdecomposition_test.go diff --git a/sqrt/sqrtdecomposition.go b/sqrt/sqrtdecomposition.go new file mode 100644 index 000000000..34e26fc4a --- /dev/null +++ b/sqrt/sqrtdecomposition.go @@ -0,0 +1,102 @@ +// Package sqrt contains algorithms and data structures that contains a √n in their complexity +package sqrt + +import "math" + +// Sqrt (or Square Root) Decomposition is a technique used for query an array and perform updates +// Inside this package is described its most simple data structure, you can find more at: https://cp-algorithms.com/data_structures/sqrt_decomposition.html +// +// Formally, You can use SqrtDecomposition only if: +// +// Given a function $Query:E_1,...,E_n\rightarrow Q$ +// +// if $\exist unionQ:Q,Q\rightarrow Q$ +// +// s.t. +// +// - $\forall n\in \N > 1, 1\le i 0, E_1,..., E_n\in E \\ query(E_1,...,E_{new},..., E_n)=updateQ(query(E_1,...,E_{old},...,E_n), indexof(E_{old}), E_{new})$ +type SqrtDecomposition[E any, Q any] struct { + querySingleElement func(element E) Q + unionQ func(q1 Q, q2 Q) Q + updateQ func(oldQ Q, oldE E, newE E) (newQ Q) + + elements []E + blocks []Q + blockSize uint64 +} + +// Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment +// Assumptions: +// - len(elements) > 0 +func NewSqrtDecomposition[E any, Q any]( + elements []E, + querySingleElement func(element E) Q, + unionQ func(q1 Q, q2 Q) Q, + updateQ func(oldQ Q, oldE E, newE E) (newQ Q), +) *SqrtDecomposition[E, Q] { + sqrtDec := &SqrtDecomposition[E, Q]{ + querySingleElement: querySingleElement, + unionQ: unionQ, + updateQ: updateQ, + elements: elements, + } + sqrt := math.Sqrt(float64(len(sqrtDec.elements))) + blockSize := uint64(sqrt) + numBlocks := uint64(math.Ceil(float64(len(elements)) / float64(blockSize))) + sqrtDec.blocks = make([]Q, numBlocks) + for i := uint64(0); i < uint64(len(elements)); i++ { + if i%blockSize == 0 { + sqrtDec.blocks[i/blockSize] = sqrtDec.querySingleElement(elements[i]) + } else { + sqrtDec.blocks[i/blockSize] = sqrtDec.unionQ(sqrtDec.blocks[i/blockSize], sqrtDec.querySingleElement(elements[i])) + } + } + sqrtDec.blockSize = blockSize + return sqrtDec +} + +// Performs a query from index start to index end (non included) +// Assumptions: +// - start < end +// - start and end are valid +func (s *SqrtDecomposition[E, Q]) Query(start uint64, end uint64) Q { + firstIndexNextBlock := ((start / s.blockSize) + 1) * s.blockSize + q := s.querySingleElement(s.elements[start]) + if firstIndexNextBlock > end { // if in same block + start++ + for start < end { + q = s.unionQ(q, s.querySingleElement(s.elements[start])) + start++ + } + } else { + // left side + start++ + for start < firstIndexNextBlock { + q = s.unionQ(q, s.querySingleElement(s.elements[start])) + start++ + } + + //middle part + endBlock := end / s.blockSize + for i := firstIndexNextBlock / s.blockSize; i < endBlock; i++ { + q = s.unionQ(q, s.blocks[i]) + } + + // right part + for i := endBlock * s.blockSize; i < end; i++ { + q = s.unionQ(q, s.querySingleElement(s.elements[i])) + } + } + return q +} + +// Assumptions: +// - index is valid +func (s *SqrtDecomposition[E, Q]) Update(index uint64, newElement E) { + i := index / s.blockSize + s.blocks[i] = s.updateQ(s.blocks[i], s.elements[index], newElement) + s.elements[index] = newElement +} diff --git a/sqrt/sqrtdecomposition_test.go b/sqrt/sqrtdecomposition_test.go new file mode 100644 index 000000000..7a293c802 --- /dev/null +++ b/sqrt/sqrtdecomposition_test.go @@ -0,0 +1,80 @@ +package sqrt_test + +import ( + "github.com/TheAlgorithms/Go/sqrt" + "testing" +) + +// Query interval +type query struct { + firstIndex uint64 + lastIndex uint64 +} + +type update struct { + index uint64 + value int +} + +func TestSqrtDecomposition(t *testing.T) { + var sqrtDecompositionTestData = []struct { + description string + array []int + updates []update + queries []query + expected []int + }{ + { + description: "test 1-sized array", + array: []int{1}, + queries: []query{{0, 1}}, + expected: []int{1}, + }, + { + description: "test array with size 5", + array: []int{1, 2, 3, 4, 5}, + queries: []query{{0, 5}, {0, 2}, {2, 4}}, + expected: []int{15, 3, 7}, + }, + { + description: "test array with size 5 and updates", + array: []int{1, 2, 3, 4, 5}, + updates: []update{{index: 1, value: 3}, + {index: 2, value: 4}}, + queries: []query{{0, 5}, {0, 2}, {2, 4}}, + expected: []int{17, 4, 8}, + }, + { + description: "test array with size 11 and updates", + array: []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, + updates: []update{{index: 2, value: 2}, + {index: 3, value: 3}, + {index: 6, value: 6}}, + queries: []query{{3, 5}, {7, 8}, {3, 7}, {0, 10}}, + expected: []int{4, 1, 11, 18}, + }, + } + for _, test := range sqrtDecompositionTestData { + t.Run(test.description, func(t *testing.T) { + s := sqrt.NewSqrtDecomposition(test.array, + func(e int) int { return e }, + func(q1, q2 int) int { return q1 + q2 }, + func(q, a, b int) int { return q - a + b }, + ) + + for i := 0; i < len(test.updates); i++ { + s.Update(test.updates[i].index, test.updates[i].value) + } + + for i := 0; i < len(test.queries); i++ { + result := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex) + + if result != test.expected[i] { + t.Logf("FAIL: %s", test.description) + t.Fatalf("Expected result: %d\nFound: %d\n", test.expected[i], result) + } + } + + }) + } +} From 6429dfdb87ad0b2ae462f42f5307b6c0bcaca5c4 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Tue, 25 Jul 2023 18:06:51 +0200 Subject: [PATCH 130/202] chore: add basic gitpod configuration (#643) * chore: add basic gitpod configuration * Apply suggestions from code review Co-authored-by: Taj --------- Co-authored-by: Taj --- .gitpod.dockerfile | 1 + .gitpod.yml | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 .gitpod.dockerfile create mode 100644 .gitpod.yml diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile new file mode 100644 index 000000000..84fa1774b --- /dev/null +++ b/.gitpod.dockerfile @@ -0,0 +1 @@ +FROM gitpod/workspace-go diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 000000000..f9199716f --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,7 @@ +--- +image: + file: .gitpod.dockerfile + +tasks: + - init: | + echo "Welcome to TheAlgorithms/Go" From f7ca03bce44b23802e8ca5d7edfa3479ea491a5c Mon Sep 17 00:00:00 2001 From: yan-aint-nickname <50468068+yan-aint-nickname@users.noreply.github.com> Date: Fri, 1 Sep 2023 20:14:21 +0300 Subject: [PATCH 131/202] Add fast inverse square root algorithm (#647) * Add fast inverse square root algorithm * PR improvements see comments in https://github.com/TheAlgorithms/Go/pull/647 * Update math/binary/fast_inverse_sqrt.go file docstring Co-authored-by: Taj * Update math/binary/fast_inverse_sqrt.go function documentation Co-authored-by: Taj * Fix function documentation grammar Co-authored-by: Taj --------- Co-authored-by: Taj --- math/binary/fast_inverse_sqrt.go | 29 +++++++++++++++++++++++++++++ math/binary/sqrt.go | 16 +--------------- math/binary/sqrt_test.go | 2 +- 3 files changed, 31 insertions(+), 16 deletions(-) create mode 100644 math/binary/fast_inverse_sqrt.go diff --git a/math/binary/fast_inverse_sqrt.go b/math/binary/fast_inverse_sqrt.go new file mode 100644 index 000000000..24ee41a82 --- /dev/null +++ b/math/binary/fast_inverse_sqrt.go @@ -0,0 +1,29 @@ +// Calculating the inverse square root +// [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root) + +package binary + +import ( + "math" +) + +// FastInverseSqrt assumes that argument is always positive, +// and it does not deal with negative numbers. +// The "magic" number 0x5f3759df is hex for 1597463007 in decimals. +// The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) +// and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)). +func FastInverseSqrt(number float32) float32 { + var i uint32 + var y, x2 float32 + const threehalfs float32 = 1.5 + + x2 = number * float32(0.5) + y = number + i = math.Float32bits(y) // evil floating point bit level hacking + i = 0x5f3759df - (i >> 1) // magic number and bitshift hacking + y = math.Float32frombits(i) + + y = y * (threehalfs - (x2 * y * y)) // 1st iteration of Newton's method + y = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed + return y +} diff --git a/math/binary/sqrt.go b/math/binary/sqrt.go index 111dd94a9..520338eb6 100644 --- a/math/binary/sqrt.go +++ b/math/binary/sqrt.go @@ -7,18 +7,4 @@ package binary -import ( - "math" -) - -const threeHalves = 1.5 - -func Sqrt(n float32) float32 { - var half, y float32 - half = n * 0.5 - z := math.Float32bits(n) - z = 0x5f3759df - (z >> 1) // floating point bit level hacking - y = math.Float32frombits(z) - y = y * (threeHalves - (half * y * y)) // Newton's approximation - return 1 / y -} +func Sqrt(n float32) float32 { return 1 / FastInverseSqrt(n) } diff --git a/math/binary/sqrt_test.go b/math/binary/sqrt_test.go index 426794fd2..fe31aefac 100644 --- a/math/binary/sqrt_test.go +++ b/math/binary/sqrt_test.go @@ -10,7 +10,7 @@ import ( "testing" ) -const epsilon = 0.2 +const epsilon = 0.001 func TestSquareRootCalculation(t *testing.T) { tests := []struct { From ae9e760be410c082e3d56fa761305de974de74fe Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Tue, 5 Sep 2023 22:15:39 +0200 Subject: [PATCH 132/202] Update `actions/checkout` to `v4` (#650) --- .github/workflows/ci.yml | 4 ++-- .github/workflows/godocmd.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29615bbe0..9d18a4464 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup Go uses: actions/setup-go@v3 with: @@ -31,7 +31,7 @@ jobs: name: Check for spelling errors runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: codespell-project/actions-codespell@master with: ignore_words_list: "actualy,nwe" diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index 2ed6aec61..cac77e1a2 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -1,5 +1,5 @@ name: Generate Documentation -on: +on: push: branches: - master @@ -9,7 +9,7 @@ jobs: name: Markdown Generation runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/setup-go@v2 From 1e62d2126267ce62ff22bc6238aba03a6fe207eb Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 7 Sep 2023 14:44:47 +0200 Subject: [PATCH 133/202] Update `actions/setup-go` to `v4` (#653) --- .github/workflows/ci.yml | 2 +- .github/workflows/godocmd.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d18a4464..e7bc96e6c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Setup Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v4 with: go-version: '^1.18' - name: Run Golang CI Lint diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index cac77e1a2..454f1a632 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-go@v2 + - uses: actions/setup-go@v4 with: go-version: '^1.18' - name: Install GoDocMD From 58bb31e80f8347c91db049a09d32a4989c06b485 Mon Sep 17 00:00:00 2001 From: Andrii Siriak Date: Wed, 27 Sep 2023 10:09:14 +0300 Subject: [PATCH 134/202] Remove @siriak from CODEOWNERS --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index fd1f63e16..d709eff88 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -7,4 +7,4 @@ # Order is important. The last matching pattern has the most precedence. -* @siriak @raklaptudirm @tjgurwara99 @yanglbme +* @raklaptudirm @tjgurwara99 @yanglbme From 30392a3da977d3c3ebb94156489f3bd28d72c89d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0=20=D0=A5=D1=80=D0=BE?= =?UTF-8?q?=D0=BC=D0=BE=D0=B2?= Date: Mon, 2 Oct 2023 10:41:04 +0300 Subject: [PATCH 135/202] feat: add set implementation using generic (#656) * feat: add set implementation using generic * some refact * use gofmt --------- Co-authored-by: Rak Laptudirm --- README.md | 2 +- structure/set/set.go | 78 +++++++++++++++++++-------------------- structure/set/set_test.go | 30 +++++++-------- 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 776a50f4b..40ec68ed7 100644 --- a/README.md +++ b/README.md @@ -925,7 +925,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### package set implements a Set using a golang map. This implies that only the types that are accepted as valid map keys can be used as set elements. For instance, do not try to Add a slice, or the program will panic. +##### package set implements a Set using generics and a golang map with comparable interface key. This implies that only the types that are accepted as valid map keys can be used as set elements --- ##### Functions: diff --git a/structure/set/set.go b/structure/set/set.go index 811ec717e..b8c7b51e1 100644 --- a/structure/set/set.go +++ b/structure/set/set.go @@ -4,9 +4,9 @@ package set // New gives new set. -func New(items ...any) Set { - st := set{ - elements: make(map[any]bool), +func New[T comparable](items ...T) Set[T] { + st := set[T]{ + elements: make(map[T]bool), } for _, item := range items { st.Add(item) @@ -15,73 +15,73 @@ func New(items ...any) Set { } // Set is an interface of possible methods on 'set'. -type Set interface { +type Set[T comparable] interface { // Add: adds new element to the set - Add(item any) + Add(item T) // Delete: deletes the passed element from the set if present - Delete(item any) + Delete(item T) // Len: gives the length of the set (total no. of elements in set) Len() int - // GetItems: gives the array( []any ) of elements of the set. - GetItems() []any + // GetItems: gives the array( []T ) of elements of the set. + GetItems() []T // In: checks whether item is present in set or not. - In(item any) bool + In(item T) bool // IsSubsetOf: checks whether set is subset of set2 or not. - IsSubsetOf(set2 Set) bool + IsSubsetOf(set2 Set[T]) bool // IsProperSubsetOf: checks whether set is proper subset of set2 or not. // ex: [1,2,3] proper subset of [1,2,3,4] -> true - IsProperSubsetOf(set2 Set) bool + IsProperSubsetOf(set2 Set[T]) bool // IsSupersetOf: checks whether set is superset of set2 or not. - IsSupersetOf(set2 Set) bool + IsSupersetOf(set2 Set[T]) bool // IsProperSupersetOf: checks whether set is proper superset of set2 or not. // ex: [1,2,3,4] proper superset of [1,2,3] -> true - IsProperSupersetOf(set2 Set) bool + IsProperSupersetOf(set2 Set[T]) bool // Union: gives new union set of both sets. // ex: [1,2,3] union [3,4,5] -> [1,2,3,4,5] - Union(set2 Set) Set + Union(set2 Set[T]) Set[T] // Intersection: gives new intersection set of both sets. // ex: [1,2,3] Intersection [3,4,5] -> [3] - Intersection(set2 Set) Set + Intersection(set2 Set[T]) Set[T] // Difference: gives new difference set of both sets. // ex: [1,2,3] Difference [3,4,5] -> [1,2] - Difference(set2 Set) Set + Difference(set2 Set[T]) Set[T] // SymmetricDifference: gives new symmetric difference set of both sets. // ex: [1,2,3] SymmetricDifference [3,4,5] -> [1,2,4,5] - SymmetricDifference(set2 Set) Set + SymmetricDifference(set2 Set[T]) Set[T] } -type set struct { - elements map[any]bool +type set[T comparable] struct { + elements map[T]bool } -func (st *set) Add(value any) { +func (st *set[T]) Add(value T) { st.elements[value] = true } -func (st *set) Delete(value any) { +func (st *set[T]) Delete(value T) { delete(st.elements, value) } -func (st *set) GetItems() []any { - keys := make([]any, 0, len(st.elements)) +func (st *set[T]) GetItems() []T { + keys := make([]T, 0, len(st.elements)) for k := range st.elements { keys = append(keys, k) } return keys } -func (st *set) Len() int { +func (st *set[T]) Len() int { return len(st.elements) } -func (st *set) In(value any) bool { +func (st *set[T]) In(value T) bool { if _, in := st.elements[value]; in { return true } return false } -func (st *set) IsSubsetOf(superSet Set) bool { +func (st *set[T]) IsSubsetOf(superSet Set[T]) bool { if st.Len() > superSet.Len() { return false } @@ -94,26 +94,26 @@ func (st *set) IsSubsetOf(superSet Set) bool { return true } -func (st *set) IsProperSubsetOf(superSet Set) bool { +func (st *set[T]) IsProperSubsetOf(superSet Set[T]) bool { if st.Len() == superSet.Len() { return false } return st.IsSubsetOf(superSet) } -func (st *set) IsSupersetOf(subSet Set) bool { +func (st *set[T]) IsSupersetOf(subSet Set[T]) bool { return subSet.IsSubsetOf(st) } -func (st *set) IsProperSupersetOf(subSet Set) bool { +func (st *set[T]) IsProperSupersetOf(subSet Set[T]) bool { if st.Len() == subSet.Len() { return false } return st.IsSupersetOf(subSet) } -func (st *set) Union(st2 Set) Set { - unionSet := New() +func (st *set[T]) Union(st2 Set[T]) Set[T] { + unionSet := New[T]() for _, item := range st.GetItems() { unionSet.Add(item) } @@ -123,9 +123,9 @@ func (st *set) Union(st2 Set) Set { return unionSet } -func (st *set) Intersection(st2 Set) Set { - intersectionSet := New() - var minSet, maxSet Set +func (st *set[T]) Intersection(st2 Set[T]) Set[T] { + intersectionSet := New[T]() + var minSet, maxSet Set[T] if st.Len() > st2.Len() { minSet = st2 maxSet = st @@ -141,8 +141,8 @@ func (st *set) Intersection(st2 Set) Set { return intersectionSet } -func (st *set) Difference(st2 Set) Set { - differenceSet := New() +func (st *set[T]) Difference(st2 Set[T]) Set[T] { + differenceSet := New[T]() for _, item := range st.GetItems() { if !st2.In(item) { differenceSet.Add(item) @@ -151,9 +151,9 @@ func (st *set) Difference(st2 Set) Set { return differenceSet } -func (st *set) SymmetricDifference(st2 Set) Set { - symmetricDifferenceSet := New() - dropSet := New() +func (st *set[T]) SymmetricDifference(st2 Set[T]) Set[T] { + symmetricDifferenceSet := New[T]() + dropSet := New[T]() for _, item := range st.GetItems() { if st2.In(item) { dropSet.Add(item) diff --git a/structure/set/set_test.go b/structure/set/set_test.go index 4b12a8f55..2000760ac 100644 --- a/structure/set/set_test.go +++ b/structure/set/set_test.go @@ -118,9 +118,9 @@ func TestIsProperSupersetOf(t *testing.T) { func TestUnion(t *testing.T) { td := []struct { name string - s1 Set - s2 Set - expSet Set + s1 Set[int] + s2 Set[int] + expSet Set[int] }{ {"union of different sets", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3, 4, 5, 6)}, {"union of sets with elements in common", New(1, 2, 3), New(1, 2, 4), New(1, 2, 3, 4)}, @@ -144,11 +144,11 @@ func TestUnion(t *testing.T) { func TestIntersection(t *testing.T) { td := []struct { name string - s1 Set - s2 Set - expSet Set + s1 Set[int] + s2 Set[int] + expSet Set[int] }{ - {"intersection of different sets", New(0, 1, 2, 3), New(4, 5, 6), New()}, + {"intersection of different sets", New(0, 1, 2, 3), New(4, 5, 6), New[int]()}, {"intersection of sets with elements in common", New(1, 2, 3), New(1, 2, 4), New(1, 2)}, {"intersection of same sets", New(1, 2, 3), New(1, 2, 3), New(1, 2, 3)}, } @@ -170,13 +170,13 @@ func TestIntersection(t *testing.T) { func TestDifference(t *testing.T) { td := []struct { name string - s1 Set - s2 Set - expSet Set + s1 Set[int] + s2 Set[int] + expSet Set[int] }{ {"difference of different sets", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3)}, {"difference of sets with elements in common", New(1, 2, 3), New(1, 2, 4), New(3)}, - {"difference of same sets", New(1, 2, 3), New(1, 2, 3), New()}, + {"difference of same sets", New(1, 2, 3), New(1, 2, 3), New[int]()}, } for _, tc := range td { t.Run(tc.name, func(t *testing.T) { @@ -196,13 +196,13 @@ func TestDifference(t *testing.T) { func TestSymmetricDifference(t *testing.T) { td := []struct { name string - s1 Set - s2 Set - expSet Set + s1 Set[int] + s2 Set[int] + expSet Set[int] }{ {"symmetric difference of different sets", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3, 4, 5, 6)}, {"symmetric difference of sets with elements in common", New(1, 2, 3), New(1, 2, 4), New(3, 4)}, - {"symmetric difference of same sets", New(1, 2, 3), New(1, 2, 3), New()}, + {"symmetric difference of same sets", New(1, 2, 3), New(1, 2, 3), New[int]()}, } for _, tc := range td { t.Run(tc.name, func(t *testing.T) { From 4460ba0d9fcb8e6e0ec4bf2d22d37010b381c97d Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Wed, 4 Oct 2023 06:33:10 +0200 Subject: [PATCH 136/202] style: use proper spelling (#665) --- strings/genetic/genetic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings/genetic/genetic.go b/strings/genetic/genetic.go index b385ad867..a91029433 100644 --- a/strings/genetic/genetic.go +++ b/strings/genetic/genetic.go @@ -28,7 +28,7 @@ type PopulationItem struct { Value float64 } -// Conf stands for cofigurations set provided to GeneticString function. +// Conf stands for configurations set provided to GeneticString function. type Conf struct { // Maximum size of the population. // Bigger could be faster but more memory expensive. From a52d8bf89119aa5186902bfd1e60e107dbe11e30 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Wed, 4 Oct 2023 14:49:03 +0200 Subject: [PATCH 137/202] Reactivate `horspool` (#663) --- strings/horspool/horspool.go | 145 ++++++++++++------------------ strings/horspool/horspool_test.go | 68 ++++++++++++++ 2 files changed, 123 insertions(+), 90 deletions(-) create mode 100644 strings/horspool/horspool_test.go diff --git a/strings/horspool/horspool.go b/strings/horspool/horspool.go index f210f9187..1611c0ce8 100644 --- a/strings/horspool/horspool.go +++ b/strings/horspool/horspool.go @@ -1,95 +1,60 @@ +// Implementation of the +// [Boyer–Moore–Horspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm) + package horspool -// User defined. -// Set to true to read input from two command line arguments -// Set to false to read input from two files "pattern.txt" and "text.txt" -// const commandLineInput bool = false +import "errors" + +var ErrNotFound = errors.New("pattern was not found in the input string") + +func Horspool(t, p string) (int, error) { + // in order to handle multy-byte character properly + // the input is converted into rune arrays + return horspool([]rune(t), []rune(p)) +} + +func horspool(t, p []rune) (int, error) { + shiftMap := computeShiftMap(t, p) + pos := 0 + for pos <= len(t)-len(p) { + if isMatch(pos, t, p) { + return pos, nil + } + if pos+len(p) >= len(t) { + // because the remaining length of the input string + // is the same as the length of the pattern + // and it does not match the pattern + // it is impossible to find the pattern + break + } + + // because of the check above + // t[pos+len(p)] is defined + pos += shiftMap[t[pos+len(p)]] + } -// Implementation of Boyer-Moore-Horspool algorithm (Suffix based approach). -// Requires either a two command line arguments separated by a single space, -// or two files in the same folder: "pattern.txt" containing the string to -// be searched for, "text.txt" containing the text to be searched in. -// func main() { -// if commandLineInput == true { // case of command line input -// args := os.Args -// if len(args) <= 2 { -// log.Fatal("Not enough arguments. Two string arguments separated by spaces are required!") -// } -// pattern := args[1] -// s := args[2] -// for i := 3; i < len(args); i++ { -// s = s + " " + args[i] -// } -// if len(args[1]) > len(s) { -// log.Fatal("Pattern is longer than text!") -// } -// fmt.Printf("\nRunning: Horspool algorithm.\n\n") -// fmt.Printf("Search word (%d chars long): %q.\n", len(args[1]), pattern) -// fmt.Printf("Text (%d chars long): %q.\n\n", len(s), s) -// horspool(s, pattern) -// } else if commandLineInput == false { // case of file line input -// patFile, err := ioutil.ReadFile("pattern.txt") -// if err != nil { -// log.Fatal(err) -// } -// textFile, err := ioutil.ReadFile("text.txt") -// if err != nil { -// log.Fatal(err) -// } -// if len(patFile) > len(textFile) { -// log.Fatal("Pattern is longer than text!") -// } -// fmt.Printf("\nRunning: Horspool algorithm.\n\n") -// fmt.Printf("Search word (%d chars long): %q.\n", len(patFile), patFile) -// fmt.Printf("Text (%d chars long): %q.\n\n", len(textFile), textFile) -// horspool(string(textFile), string(patFile)) -// } -// } + return -1, ErrNotFound +} -// // Function horspool performing the Horspool algorithm. -// // Prints whether the word/pattern was found and on what position in the text or not. -// func horspool(t, p string) { -// m, n, c, pos := len(p), len(t), 0, 0 -// //Perprocessing -// d := preprocess(t, p) -// //Map output -// fmt.Printf("Precomputed shifts per symbol: ") -// for key, value := range d { -// fmt.Printf("%c:%d; ", key, value) -// } -// fmt.Println() -// //Searching -// for pos <= n-m { -// j := m -// if t[pos+j-1] != p[j-1] { -// fmt.Printf("\n comparing characters %c %c at positions %d %d", t[pos+j-1], p[j-1], pos+j-1, j-1) -// c++ -// } -// for j > 0 && t[pos+j-1] == p[j-1] { -// fmt.Printf("\n comparing characters %c %c at positions %d %d", t[pos+j-1], p[j-1], pos+j-1, j-1) -// c++ -// fmt.Printf(" - match") -// j-- -// } -// if j == 0 { -// fmt.Printf("\n\nWord %q was found at position %d in %q. \n%d comparisons were done.", p, pos, t, c) -// return -// } -// pos = pos + d[t[pos+m]] -// } -// fmt.Printf("\n\nWord was not found.\n%d comparisons were done.", c) -// return -// } +// Checks if the array p matches the subarray of t starting at pos. +// Note that backward iteration. +// There are [other](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm#Tuning_the_comparison_loop) +// approaches possible. +func isMatch(pos int, t, p []rune) bool { + j := len(p) + for j > 0 && t[pos+j-1] == p[j-1] { + j-- + } + return j == 0 +} -// // Function that pre-computes map with Key: uint8 (char) Value: int. -// // Values determine safe shifting of search window. -// func preprocess(t, p string) (d map[uint8]int) { -// d = make(map[uint8]int) -// for i := 0; i < len(t); i++ { -// d[t[i]] = len(p) -// } -// for i := 0; i < len(p); i++ { -// d[p[i]] = len(p) - i -// } -// return d -// } +func computeShiftMap(t, p []rune) (res map[rune]int) { + res = make(map[rune]int) + for _, tCode := range t { + res[tCode] = len(p) + } + for i, pCode := range p { + res[pCode] = len(p) - i + } + return res +} diff --git a/strings/horspool/horspool_test.go b/strings/horspool/horspool_test.go new file mode 100644 index 000000000..6c500f3f2 --- /dev/null +++ b/strings/horspool/horspool_test.go @@ -0,0 +1,68 @@ +// horspool_test.go +// description: Tests for horspool +// see horspool.go + +package horspool + +import "testing" +import "fmt" + +func TestLHorspool(t *testing.T) { + testCases := []struct { + input string + pattern string + expected int + }{ + {"aaaaXaaa", "X", 4}, + {"aaaaXXaa", "XX", 4}, + {"Xaaab", "X", 0}, + {"XYaab", "XY", 0}, + {"abcefghXYZ", "XYZ", 7}, + {"abcefgh€YZ⌘", "€YZ", 7}, + {"⌘bcefgh€YZ⌘", "€YZ", 7}, + {"abc", "abc", 0}, + {"", "", 0}, + {"a", "", 0}, + {"a", "a", 0}, + {"aa", "a", 0}, + {"aa", "aa", 0}, + } + for _, tc := range testCases { + t.Run(fmt.Sprint("test with ", tc.input, " ", tc.pattern), func(t *testing.T) { + result, curError := Horspool(tc.input, tc.pattern) + if curError != nil { + t.Fatalf("Got unexpected error") + } + if tc.expected != result { + t.Fatalf("expected %d, got %d", tc.expected, result) + } + }) + } +} + +func TestLHorspoolNotExisintPattern(t *testing.T) { + testCases := []struct { + input string + pattern string + }{ + {"", "X"}, + {"X", "Y"}, + {"X", "XX"}, + {"aaaaaaaXaXaaaa", "XXX"}, + {"aaaaaaaXaX", "XXX"}, + {"XaX", "XXX"}, + {"XaX", "XXX"}, + {"\xe2\x8c\x98", "\x98"}, + } + for _, tc := range testCases { + t.Run(fmt.Sprint("test with ", tc.input, " ", tc.pattern), func(t *testing.T) { + result, curError := Horspool(tc.input, tc.pattern) + if curError != ErrNotFound { + t.Fatalf("Got unexpected error") + } + if result != -1 { + t.Fatalf("expected -1, got %d", result) + } + }) + } +} From c129115f33975e72953a9e2b61091c3ac77dc569 Mon Sep 17 00:00:00 2001 From: Himanshu Patel Date: Thu, 5 Oct 2023 15:47:56 +0530 Subject: [PATCH 138/202] test: Use error.Is(errorType, errorInstance) to check for error equality (#666) Checking error with == operator might fail on wrapped errors --- graph/bellmanford_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graph/bellmanford_test.go b/graph/bellmanford_test.go index 2f9d57ea6..83364b5df 100644 --- a/graph/bellmanford_test.go +++ b/graph/bellmanford_test.go @@ -125,7 +125,7 @@ func TestBellmanford(t *testing.T) { if resIsReachable != test.isReachable { t.Errorf("Reachable, Expected: %t, Computed: %t", test.isReachable, resIsReachable) } - if resError != test.err { + if !errors.Is(test.err, resError) { if resError == nil || test.err == nil { t.Errorf("Reachable, Expected: %s, Computed: %s", test.err, resError) } else if resError.Error() != test.err.Error() { From 8a5442213216069a72bec48302db60f313c24454 Mon Sep 17 00:00:00 2001 From: Himanshu Patel Date: Thu, 5 Oct 2023 15:50:31 +0530 Subject: [PATCH 139/202] test: Use error.Is(errorType, errorInstance) to check for error equality (#668) Co-authored-by: Rak Laptudirm --- search/binary_test.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/search/binary_test.go b/search/binary_test.go index 24e2a0c41..99f907797 100644 --- a/search/binary_test.go +++ b/search/binary_test.go @@ -1,6 +1,9 @@ package search -import "testing" +import ( + "errors" + "testing" +) func TestBinary(t *testing.T) { for _, test := range searchTests { @@ -8,7 +11,7 @@ func TestBinary(t *testing.T) { if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) } - if actualError != test.expectedError { + if !errors.Is(test.expectedError, actualError) { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) } } @@ -20,7 +23,7 @@ func TestBinaryIterative(t *testing.T) { if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) } - if actualError != test.expectedError { + if !errors.Is(test.expectedError, actualError) { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) } } @@ -32,7 +35,7 @@ func TestLowerBound(t *testing.T) { if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) } - if actualError != test.expectedError { + if !errors.Is(test.expectedError, actualError) { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) } } @@ -44,7 +47,7 @@ func TestUpperBound(t *testing.T) { if actualValue != test.expected { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'", test.name, test.data, test.key, test.expected, actualValue) } - if actualError != test.expectedError { + if !errors.Is(test.expectedError, actualError) { t.Errorf("test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'", test.name, test.data, test.key, test.expectedError, actualError) } } From 51a9599da04ffd149b57f3dfa790d9c9462d681e Mon Sep 17 00:00:00 2001 From: Himanshu Patel Date: Fri, 6 Oct 2023 22:22:28 +0530 Subject: [PATCH 140/202] refactor: refactor comments and variable declaration compliant with godoc (#667) Co-authored-by: Rak Laptudirm --- graph/topological.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/graph/topological.go b/graph/topological.go index feef703f1..9e99470b7 100644 --- a/graph/topological.go +++ b/graph/topological.go @@ -1,7 +1,7 @@ package graph -// Assumes that graph given is valid and possible to -// get a topo ordering. +// Topological assumes that graph given is valid and that its +// possible to get a topological ordering. // constraints are array of []int{a, b}, representing // an edge going from a to b func Topological(N int, constraints [][]int) []int { @@ -22,7 +22,7 @@ func Topological(N int, constraints [][]int) []int { edges[a][b] = true } - answer := []int{} + var answer []int for s := 0; s < N; s++ { // Only start walking from top level nodes if dependencies[s] == 0 { From 92396c1b4b4a9320b13c1b02d417af7f41564c5b Mon Sep 17 00:00:00 2001 From: Himanshu Patel Date: Fri, 6 Oct 2023 22:39:58 +0530 Subject: [PATCH 141/202] refactor: refactor comments and variable declaration compliant with godoc (#669) Co-authored-by: Rak Laptudirm --- search/binary.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search/binary.go b/search/binary.go index 3b9241af6..604341edb 100644 --- a/search/binary.go +++ b/search/binary.go @@ -37,7 +37,7 @@ func BinaryIterative(array []int, target int) (int, error) { return -1, ErrNotFound } -// Returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. +// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. // return -1 and ErrNotFound if no such element is found. func LowerBound(array []int, target int) (int, error) { startIndex := 0 @@ -59,7 +59,7 @@ func LowerBound(array []int, target int) (int, error) { return startIndex, nil } -// Returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. +// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. // return -1 and ErrNotFound if no such element is found. func UpperBound(array []int, target int) (int, error) { startIndex := 0 From 02fde76aa3d34e13378c0ca7d177d15ecc72009c Mon Sep 17 00:00:00 2001 From: migueldalberto <65927539+migueldalberto@users.noreply.github.com> Date: Sat, 7 Oct 2023 04:14:44 -0300 Subject: [PATCH 142/202] feat: Add Cocktail Sort (#660) * add cocktail sort * add test for cocktail sort * change comments * add comments on cocktailsort.go * add start and end vars to cocktailsort.go for optimization * fix: change for loop structure * fix: change constraints from integer to ordered on cocktailsort.go * test: add benchmark for cocktailsort --------- Co-authored-by: Rak Laptudirm --- sort/cocktailsort.go | 54 ++++++++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 11 ++++++++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 sort/cocktailsort.go diff --git a/sort/cocktailsort.go b/sort/cocktailsort.go new file mode 100644 index 000000000..6aee61681 --- /dev/null +++ b/sort/cocktailsort.go @@ -0,0 +1,54 @@ +// Implementation of Cocktail sorting +// reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort + +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning) +func Cocktail[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { // ignore 0 length arrays + return arr + } + + swapped := true // true if swapped two or more elements in the last loop + // if it loops through the array without swapping, the array is sorted + + // start and end indexes, this will be updated excluding already sorted elements + start := 0 + end := len(arr) - 1 + + for swapped { + swapped = false + var new_start int + var new_end int + + for i := start; i < end; i++ { // first loop, from start to end + if arr[i] > arr[i+1] { // if current and next elements are unordered + arr[i], arr[i+1] = arr[i+1], arr[i] // swap two elements + new_end = i + swapped = true + } + } + + end = new_end + + if !swapped { // early exit, skipping the second loop + break + } + + swapped = false + + for i := end; i > start; i-- { // second loop, from end to start + if arr[i] < arr[i-1] { // same process of the first loop, now going 'backwards' + arr[i], arr[i-1] = arr[i-1], arr[i] + new_start = i + swapped = true + } + } + + start = new_start + } + + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index aeb90c04e..8df55373f 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -1,11 +1,12 @@ package sort_test import ( - "github.com/TheAlgorithms/Go/sort" "math/rand" "reflect" "testing" "time" + + "github.com/TheAlgorithms/Go/sort" ) func testFramework(t *testing.T, sortingFunction func([]int) []int) { @@ -85,6 +86,10 @@ func TestBucketSort(t *testing.T) { testFramework(t, sort.Bucket[int]) } +func TestCocktailSort(t *testing.T) { + testFramework(t, sort.Cocktail[int]) +} + func TestExchange(t *testing.T) { testFramework(t, sort.Exchange[int]) } @@ -222,6 +227,10 @@ func BenchmarkBucketSort(b *testing.B) { benchmarkFramework(b, sort.Bucket[int]) } +func BenchmarkCocktailSort(b *testing.B) { + benchmarkFramework(b, sort.Cocktail[int]) +} + func BenchmarkExchange(b *testing.B) { benchmarkFramework(b, sort.Exchange[int]) } From 85451afbfad6632ed26e66770d1988200c9f0941 Mon Sep 17 00:00:00 2001 From: ")`(-@_.+_^*__*^" <55359898+11-aryan@users.noreply.github.com> Date: Tue, 10 Oct 2023 12:52:53 +0530 Subject: [PATCH 143/202] feat: optimized stack array implementation (#658) * optimized stack array implementation and modified the unit tests accordingly * Fixed formatting issues * fix exported all methods and converted tests to blackbox * Added generic parameter and fixed package name --------- Co-authored-by: Rak Laptudirm --- structure/stack/stack_test.go | 99 ++++++++++++---------- structure/stack/stackarray.go | 52 ++++++++---- structure/stack/stacklinkedlist.go | 12 +-- structure/stack/stacklinkedlistwithlist.go | 22 ++--- 4 files changed, 105 insertions(+), 80 deletions(-) diff --git a/structure/stack/stack_test.go b/structure/stack/stack_test.go index e5a77e70b..0de3dc0d6 100644 --- a/structure/stack/stack_test.go +++ b/structure/stack/stack_test.go @@ -7,23 +7,24 @@ // author [Milad](https://github.com/miraddo) // see stackarray.go, stacklinkedlist.go, stacklinkedlistwithlist.go -package stack +package stack_test import ( "container/list" + "github.com/TheAlgorithms/Go/structure/stack" "reflect" "testing" ) // TestStackLinkedList for testing Stack with LinkedList func TestStackLinkedList(t *testing.T) { - var newStack Stack + var newStack stack.Stack - newStack.push(1) - newStack.push(2) + newStack.Push(1) + newStack.Push(2) t.Run("Stack Push", func(t *testing.T) { - result := newStack.show() + result := newStack.Show() expected := []any{2, 1} for x := range result { if result[x] != expected[x] { @@ -33,20 +34,20 @@ func TestStackLinkedList(t *testing.T) { }) t.Run("Stack isEmpty", func(t *testing.T) { - if newStack.isEmpty() { - t.Error("Stack isEmpty is returned true but expected false", newStack.isEmpty()) + if newStack.IsEmpty() { + t.Error("Stack isEmpty is returned true but expected false", newStack.IsEmpty()) } }) t.Run("Stack Length", func(t *testing.T) { - if newStack.len() != 2 { - t.Error("Stack Length should be 2 but got", newStack.len()) + if newStack.Length() != 2 { + t.Error("Stack Length should be 2 but got", newStack.Length()) } }) - newStack.pop() - pop := newStack.pop() + newStack.Pop() + pop := newStack.Pop() t.Run("Stack Pop", func(t *testing.T) { if pop != 1 { @@ -55,65 +56,73 @@ func TestStackLinkedList(t *testing.T) { }) - newStack.push(52) - newStack.push(23) - newStack.push(99) - t.Run("Stack Peak", func(t *testing.T) { - if newStack.peak() != 99 { - t.Error("Stack Peak should return 99 but got ", newStack.peak()) + newStack.Push(52) + newStack.Push(23) + newStack.Push(99) + t.Run("Stack Peek", func(t *testing.T) { + if newStack.Peek() != 99 { + t.Error("Stack Peak should return 99 but got ", newStack.Peek()) } }) } // TestStackArray for testing Stack with Array func TestStackArray(t *testing.T) { + newStack := stack.NewStack[int]() t.Run("Stack With Array", func(t *testing.T) { - stackPush(2) - stackPush(3) + newStack.Push(2) + newStack.Push(3) t.Run("Stack Push", func(t *testing.T) { - if !reflect.DeepEqual([]any{3, 2}, stackArray) { - t.Errorf("Stack Push is not work we expected %v but got %v", []any{3, 2}, stackArray) + var stackElements []any + for i := 0; i < 2; i++ { + poppedElement := newStack.Pop() + stackElements = append(stackElements, poppedElement) + } + + if !reflect.DeepEqual([]any{3, 2}, stackElements) { + t.Errorf("Stack Push is not work we expected %v but got %v", []any{3, 2}, newStack) } + + newStack.Push(2) + newStack.Push(3) }) - pop := stackPop() + pop := newStack.Pop() t.Run("Stack Pop", func(t *testing.T) { - - if stackLength() == 2 && pop != 3 { + if newStack.Length() == 2 && pop != 3 { t.Errorf("Stack Pop is not work we expected %v but got %v", 3, pop) } }) - stackPush(2) - stackPush(83) + newStack.Push(2) + newStack.Push(83) t.Run("Stack Peak", func(t *testing.T) { - - if stackPeak() != 83 { - t.Errorf("Stack Peak is not work we expected %v but got %v", 83, stackPeak()) + if newStack.Peek() != 83 { + t.Errorf("Stack Peek is not work we expected %v but got %v", 83, newStack.Peek()) } }) t.Run("Stack Length", func(t *testing.T) { - if stackLength() != 3 { - t.Errorf("Stack Length is not work we expected %v but got %v", 3, stackLength()) + if newStack.Length() != 3 { + t.Errorf("Stack Length is not work we expected %v but got %v", 3, newStack.Length()) } }) t.Run("Stack Empty", func(t *testing.T) { - if stackEmpty() == true { - t.Errorf("Stack Empty is not work we expected %v but got %v", false, stackEmpty()) + if newStack.IsEmpty() == true { + t.Errorf("Stack Empty is not work we expected %v but got %v", false, newStack.IsEmpty()) } - stackPop() - stackPop() - stackPop() + newStack.Pop() + newStack.Pop() + newStack.Pop() - if stackEmpty() == false { - t.Errorf("Stack Empty is not work we expected %v but got %v", true, stackEmpty()) + if newStack.IsEmpty() == false { + t.Errorf("Stack Empty is not work we expected %v but got %v", true, newStack.IsEmpty()) } }) }) @@ -121,8 +130,8 @@ func TestStackArray(t *testing.T) { // TestStackLinkedListWithList for testing Stack with Container/List Library (STL) func TestStackLinkedListWithList(t *testing.T) { - stackList := &SList{ - stack: list.New(), + stackList := &stack.SList{ + Stack: list.New(), } t.Run("Stack Push", func(t *testing.T) { @@ -147,7 +156,7 @@ func TestStackLinkedListWithList(t *testing.T) { stackList.Push(2) stackList.Push(83) - peak, _ := stackList.Peak() + peak, _ := stackList.Peek() if peak != 83 { t.Errorf("Stack Peak is not work we expected %v but got %v", 83, peak) } @@ -160,8 +169,8 @@ func TestStackLinkedListWithList(t *testing.T) { }) t.Run("Stack Empty", func(t *testing.T) { - if stackList.Empty() == true { - t.Errorf("Stack Empty is not work we expected %v but got %v", false, stackList.Empty()) + if stackList.IsEmpty() == true { + t.Errorf("Stack Empty is not work we expected %v but got %v", false, stackList.IsEmpty()) } d1, err := stackList.Pop() @@ -172,8 +181,8 @@ func TestStackLinkedListWithList(t *testing.T) { t.Errorf("got an unexpected error %v, pop1: %v, pop2: %v, pop3: %v", err, d1, d2, d3) } - if stackList.Empty() == false { - t.Errorf("Stack Empty is not work we expected %v but got %v", true, stackList.Empty()) + if stackList.IsEmpty() == false { + t.Errorf("Stack Empty is not work we expected %v but got %v", true, stackList.IsEmpty()) } }) } diff --git a/structure/stack/stackarray.go b/structure/stack/stackarray.go index 5aba01cf4..2d0fc05c4 100644 --- a/structure/stack/stackarray.go +++ b/structure/stack/stackarray.go @@ -9,31 +9,47 @@ package stack -var stackArray []any +type Array[T any] struct { + elements []T +} + +// NewStack creates and returns a new stack. +func NewStack[T any]() *Array[T] { + return &Array[T]{} +} -// stackPush push to first index of array -func stackPush(n any) { - stackArray = append([]any{n}, stackArray...) +// Push adds an element to the top of the stack. +func (s *Array[T]) Push(value T) { + s.elements = append(s.elements, value) } -// stackLength return length of array -func stackLength() int { - return len(stackArray) +// Size returns the number of elements in the stack. +func (s *Array[T]) Length() int { + return len(s.elements) } -// stackPeak return last input of array -func stackPeak() any { - return stackArray[0] +// Peek returns the top element of the stack without removing it. +func (s *Array[T]) Peek() T { + if s.IsEmpty() { + var zeroValue T + return zeroValue // Stack is empty + } + return s.elements[len(s.elements)-1] } -// stackEmpty check array is empty or not -func stackEmpty() bool { - return len(stackArray) == 0 +// IsEmpty returns true if the stack is empty, false otherwise. +func (s *Array[T]) IsEmpty() bool { + return len(s.elements) == 0 } -// stackPop return last input and remove it in array -func stackPop() any { - pop := stackArray[0] - stackArray = stackArray[1:] - return pop +// Pop removes and returns the top element from the stack. +func (s *Array[T]) Pop() T { + if s.IsEmpty() { + var zeroValue T + return zeroValue // Stack is empty + } + index := len(s.elements) - 1 + popped := s.elements[index] + s.elements = s.elements[:index] + return popped } diff --git a/structure/stack/stacklinkedlist.go b/structure/stack/stacklinkedlist.go index 4c4973884..1328729e6 100644 --- a/structure/stack/stacklinkedlist.go +++ b/structure/stack/stacklinkedlist.go @@ -22,7 +22,7 @@ type Stack struct { } // push add value to last index -func (ll *Stack) push(n any) { +func (ll *Stack) Push(n any) { newStack := &Node{} // new node newStack.Val = n @@ -33,7 +33,7 @@ func (ll *Stack) push(n any) { } // pop remove last item as first output -func (ll *Stack) pop() any { +func (ll *Stack) Pop() any { result := ll.top.Val if ll.top.Next == nil { ll.top = nil @@ -46,22 +46,22 @@ func (ll *Stack) pop() any { } // isEmpty to check our array is empty or not -func (ll *Stack) isEmpty() bool { +func (ll *Stack) IsEmpty() bool { return ll.length == 0 } // len use to return length of our stack -func (ll *Stack) len() int { +func (ll *Stack) Length() int { return ll.length } // peak return last input value -func (ll *Stack) peak() any { +func (ll *Stack) Peek() any { return ll.top.Val } // show all value as an interface array -func (ll *Stack) show() (in []any) { +func (ll *Stack) Show() (in []any) { current := ll.top for current != nil { diff --git a/structure/stack/stacklinkedlistwithlist.go b/structure/stack/stacklinkedlistwithlist.go index ba3ce6580..ae53a499b 100644 --- a/structure/stack/stacklinkedlistwithlist.go +++ b/structure/stack/stacklinkedlistwithlist.go @@ -16,18 +16,18 @@ import ( // SList is our struct that point to stack with container/list.List library type SList struct { - stack *list.List + Stack *list.List } // Push add a value into our stack func (sl *SList) Push(val any) { - sl.stack.PushFront(val) + sl.Stack.PushFront(val) } // Peak is return last value that insert into our stack -func (sl *SList) Peak() (any, error) { - if !sl.Empty() { - element := sl.stack.Front() +func (sl *SList) Peek() (any, error) { + if !sl.IsEmpty() { + element := sl.Stack.Front() return element.Value, nil } return "", fmt.Errorf("stack list is empty") @@ -36,11 +36,11 @@ func (sl *SList) Peak() (any, error) { // Pop is return last value that insert into our stack // also it will remove it in our stack func (sl *SList) Pop() (any, error) { - if !sl.Empty() { + if !sl.IsEmpty() { // get last element that insert into stack - element := sl.stack.Front() + element := sl.Stack.Front() // remove element in stack - sl.stack.Remove(element) + sl.Stack.Remove(element) // return element value return element.Value, nil } @@ -49,12 +49,12 @@ func (sl *SList) Pop() (any, error) { // Length return length of our stack func (sl *SList) Length() int { - return sl.stack.Len() + return sl.Stack.Len() } // Empty check our stack has value or not -func (sl *SList) Empty() bool { +func (sl *SList) IsEmpty() bool { // check our stack is empty or not // if is 0 it means our stack is empty otherwise is not empty - return sl.stack.Len() == 0 + return sl.Stack.Len() == 0 } From de90bd8c5c48f9bef63aa96c1913e074013987ea Mon Sep 17 00:00:00 2001 From: Flamingo <490493499@qq.com> Date: Wed, 11 Oct 2023 14:05:41 +0800 Subject: [PATCH 144/202] fix: Update generics in counting sort (#676) Co-authored-by: Rak Laptudirm --- sort/countingsort.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/sort/countingsort.go b/sort/countingsort.go index 6961efff8..d55a13798 100644 --- a/sort/countingsort.go +++ b/sort/countingsort.go @@ -8,16 +8,27 @@ package sort import "github.com/TheAlgorithms/Go/constraints" -func Count[T constraints.Number](data []int) []int { - var aMin, aMax = -1000, 1000 +func Count[T constraints.Integer](data []T) []T { + if len(data) == 0 { + return data + } + var aMin, aMax = data[0], data[0] + for _, x := range data { + if x < aMin { + aMin = x + } + if x > aMax { + aMax = x + } + } count := make([]int, aMax-aMin+1) for _, x := range data { - count[x-aMin]++ // this is the reason for having only Number constraint instead of Ordered. + count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered. } z := 0 for i, c := range count { for c > 0 { - data[z] = i + aMin + data[z] = T(i) + aMin z++ c-- } From be1ce26bd1e08037ea8645883e52b47e25ab56cf Mon Sep 17 00:00:00 2001 From: Randheer Ramesh K <33465991+Randheerrrk@users.noreply.github.com> Date: Wed, 11 Oct 2023 11:47:48 +0530 Subject: [PATCH 145/202] feat: add binary insertion sort algorithm (#671) * feat: add binary insertion sort algorithm * Formatted with gofmt --------- Co-authored-by: randheerrrk <> Co-authored-by: Rak Laptudirm --- sort/binaryinsertionsort.go | 35 +++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 9 ++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 sort/binaryinsertionsort.go diff --git a/sort/binaryinsertionsort.go b/sort/binaryinsertionsort.go new file mode 100644 index 000000000..98b6c5a3d --- /dev/null +++ b/sort/binaryinsertionsort.go @@ -0,0 +1,35 @@ +// Binary Insertion Sort +// description: Implementation of binary insertion sort in Go +// details: Binary Insertion Sort is a variation of +// Insertion sort in which proper location to +// insert the selected element is found using the +// Binary search algorithm. +// ref: https://www.geeksforgeeks.org/binary-insertion-sort + +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +func BinaryInsertion[T constraints.Ordered](arr []T) []T { + for currentIndex := 1; currentIndex < len(arr); currentIndex++ { + temporary := arr[currentIndex] + low := 0 + high := currentIndex - 1 + + for low <= high { + mid := low + (high-low)/2 + if arr[mid] > temporary { + high = mid - 1 + } else { + low = mid + 1 + } + } + + for itr := currentIndex; itr > low; itr-- { + arr[itr] = arr[itr-1] + } + + arr[low] = temporary + } + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 8df55373f..733fa0149 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -76,7 +76,10 @@ func testFramework(t *testing.T, sortingFunction func([]int) []int) { } } -//BEGIN TESTS +// BEGIN TESTS +func TestBinaryInsertion(t *testing.T) { + testFramework(t, sort.BinaryInsertion[int]) +} func TestBubble(t *testing.T) { testFramework(t, sort.Bubble[int]) @@ -219,6 +222,10 @@ func benchmarkFramework(b *testing.B, f func(arr []int) []int) { //BEGIN BENCHMARKS +func BenchmarkBinaryInsertion(b *testing.B) { + benchmarkFramework(b, sort.BinaryInsertion[int]) +} + func BenchmarkBubble(b *testing.B) { benchmarkFramework(b, sort.Bubble[int]) } From dc7ff42efe8c6397b2edaae7fff5cdc580ecc7fe Mon Sep 17 00:00:00 2001 From: ")`(-@_.+_^*__*^" <55359898+11-aryan@users.noreply.github.com> Date: Wed, 11 Oct 2023 11:51:28 +0530 Subject: [PATCH 146/202] refactored comments to comply with godocs (#678) * refactored comments to comply with godocs * added full stop in the end --------- Co-authored-by: Rak Laptudirm --- strings/parenthesis/parenthesis.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/strings/parenthesis/parenthesis.go b/strings/parenthesis/parenthesis.go index 2ae49a641..1fb446ff4 100644 --- a/strings/parenthesis/parenthesis.go +++ b/strings/parenthesis/parenthesis.go @@ -1,14 +1,10 @@ package parenthesis // Parenthesis algorithm checks if every opened parenthesis -// is closed correctly - -// when parcounter is less than 0 is because a closing +// is closed correctly. When parcounter is less than 0 when a closing // parenthesis is detected without an opening parenthesis -// that surrounds it - -// parcounter will be 0 if all open parenthesis are closed -// correctly +// that surrounds it and parcounter will be 0 if all open +// parenthesis are closed correctly. func Parenthesis(text string) bool { parcounter := 0 From a351eab602d055be0c2b484011691895ddda14a2 Mon Sep 17 00:00:00 2001 From: Suhail Malik Date: Wed, 11 Oct 2023 17:38:58 +0530 Subject: [PATCH 147/202] =?UTF-8?q?=D0=90dd=20bogo=20sort=20(#655)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + sort/bogosort.go | 38 ++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 10 ++++++++++ 3 files changed, 49 insertions(+) create mode 100644 sort/bogosort.go diff --git a/README.md b/README.md index 40ec68ed7..7304c78aa 100644 --- a/README.md +++ b/README.md @@ -954,6 +954,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: 1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. +1. [`Bogo`](./sort/bogosort.go#L32): Bogo generates random permutations until it guesses the correct one. 2. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range. 3. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. 4. [`Count`](./sort/countingsort.go#L11): No description provided. diff --git a/sort/bogosort.go b/sort/bogosort.go new file mode 100644 index 000000000..a37d18ff8 --- /dev/null +++ b/sort/bogosort.go @@ -0,0 +1,38 @@ +// This is a pure Go implementation of the bogosort algorithm, +// also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. +// Bogosort generates random permutations until it guesses the correct one. + +// More info on: https://en.wikipedia.org/wiki/Bogosort + +package sort + +import ( + "math/rand" + + "github.com/TheAlgorithms/Go/constraints" +) + +func isSorted[T constraints.Number](arr []T) bool { + for i := 0; i < len(arr)-1; i++ { + if arr[i] > arr[i+1] { + return false + } + } + + return true +} + +func shuffle[T constraints.Number](arr []T) { + for i := range arr { + j := rand.Intn(i + 1) + arr[i], arr[j] = arr[j], arr[i] + } +} + +func Bogo[T constraints.Number](arr []T) []T { + for !isSorted(arr) { + shuffle(arr) + } + + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 733fa0149..0fd0a93fe 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -85,6 +85,11 @@ func TestBubble(t *testing.T) { testFramework(t, sort.Bubble[int]) } +func TestBogo(t *testing.T) { + t.Skip("Skipping test for Bogo Sort, as it uses a lot of resource.") + testFramework(t, sort.Bogo[int]) +} + func TestBucketSort(t *testing.T) { testFramework(t, sort.Bucket[int]) } @@ -230,6 +235,11 @@ func BenchmarkBubble(b *testing.B) { benchmarkFramework(b, sort.Bubble[int]) } +func BenchmarkBogo(b *testing.B) { + b.Skip("Skipping benchmark for Bogo Sort, as it uses a lot of resource.") + benchmarkFramework(b, sort.Bogo[int]) +} + func BenchmarkBucketSort(b *testing.B) { benchmarkFramework(b, sort.Bucket[int]) } From 7a4c099718417a43478b1f8031ed04211e012c43 Mon Sep 17 00:00:00 2001 From: Sayan Bose <111633699+bose-sayan@users.noreply.github.com> Date: Fri, 13 Oct 2023 00:21:02 +0530 Subject: [PATCH 148/202] feat: Add deque structure (#659) * Added Doubly Ended Queue data structure and a few tests to check * Added the doubly ended queue data structure along with a few tests and fixed some linting issues * Added the necessary changes: - Made the member of the DoublyEndedQueue struct private - Removed unnecessary indentations from package comment - Implemented black box testing - Used errors.New() to declare a constant error in case a dequeuing operation is called on an empty deque - Exported the methods of DoublyEndedQueue - Edited the names of getters to follow go's naming conventions. * Removed redundant zero valued variables * Transferred the test file to deque_test package * Removed redundant error variable in deque_test file * refactored the comments to satisfy godoc standard * corrected misspelled words * Update structure/deque/deque.go Refactored comments to be more descriptive Co-authored-by: Taj * Update structure/deque/deque_test.go Removed redundant comments Co-authored-by: Taj * removed redundant comments * Update structure/deque/deque.go Co-authored-by: Taj * Renamed a few method names * Update structure/deque/deque.go Co-authored-by: Taj * Renamed a few variables * Removed redundant comment --------- Co-authored-by: Rak Laptudirm Co-authored-by: Taj --- structure/deque/deque.go | 84 +++++++ structure/deque/deque_test.go | 406 ++++++++++++++++++++++++++++++++++ 2 files changed, 490 insertions(+) create mode 100644 structure/deque/deque.go create mode 100644 structure/deque/deque_test.go diff --git a/structure/deque/deque.go b/structure/deque/deque.go new file mode 100644 index 000000000..538703596 --- /dev/null +++ b/structure/deque/deque.go @@ -0,0 +1,84 @@ +// description: Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. +// References: +// Wikipedia : https://en.wikipedia.org/wiki/Double-ended_queue +// Github: https://www.geeksforgeeks.org/deque-set-1-introduction-applications/ +// author [Sayan](https://github.com/bose-sayan) + +// Package deque implements a Double Ended Queue data structure. +package deque + +import ( + "errors" +) + +// ErrEmptyDequeue is a custom error for handling cases when some dequeuing operation is performed on an empty deque. +var ErrEmptyDequeue = errors.New("DoublyEnded queue is empty, so can't perform this operation") + +type DoublyEndedQueue[T any] struct { + deque []T +} + +// New returns a new DoublyEndedQueue. +func New[T any]() *DoublyEndedQueue[T] { + return &DoublyEndedQueue[T]{deque: make([]T, 0)} +} + +// EnqueueFront adds an item at the front of Deque. +func (dq *DoublyEndedQueue[T]) EnqueueFront(item T) { + dq.deque = append([]T{item}, dq.deque...) +} + +// EnqueueRear adds an item at the rear of Deque. +func (dq *DoublyEndedQueue[T]) EnqueueRear(item T) { + dq.deque = append(dq.deque, item) +} + +// DequeueFront deletes an item from front of Deque and returns it. +func (dq *DoublyEndedQueue[T]) DequeueFront() (T, error) { + if len(dq.deque) == 0 { + var zeroVal T + return zeroVal, ErrEmptyDequeue + } + frontElement := dq.deque[0] + dq.deque = dq.deque[1:] + return frontElement, nil +} + +// DequeueRear deletes an item from rear of Deque and returns it. +func (dq *DoublyEndedQueue[T]) DequeueRear() (T, error) { + if len(dq.deque) == 0 { + var zeroVal T + return zeroVal, ErrEmptyDequeue + } + rearElement := dq.deque[len(dq.deque)-1] + dq.deque = dq.deque[:len(dq.deque)-1] + return rearElement, nil +} + +// Front gets the front item from queue. +func (dq *DoublyEndedQueue[T]) Front() (T, error) { + if (len(dq.deque)) == 0 { + var zeroVal T + return zeroVal, ErrEmptyDequeue + } + return dq.deque[0], nil +} + +// Rear gets the last item from queue. +func (dq *DoublyEndedQueue[T]) Rear() (T, error) { + if (len(dq.deque)) == 0 { + var zeroVal T + return zeroVal, ErrEmptyDequeue + } + return dq.deque[len(dq.deque)-1], nil +} + +// IsEmpty checks whether Deque is empty or not. +func (dq *DoublyEndedQueue[T]) IsEmpty() bool { + return len(dq.deque) == 0 +} + +// Length gets the length of Deque. +func (dq *DoublyEndedQueue[T]) Length() int { + return len(dq.deque) +} diff --git a/structure/deque/deque_test.go b/structure/deque/deque_test.go new file mode 100644 index 000000000..26439e5be --- /dev/null +++ b/structure/deque/deque_test.go @@ -0,0 +1,406 @@ +// +// This file contains unit tests for the deque package. +// The tests cover the following scenarios: +// - Empty deque +// - Deque with one element +// - Deque with multiple elements +// The tests are parameterized with int and string types. +// Each test case is defined with a description and a list of queries to be executed on the deque. +// The expected results and errors are also defined for each query. +// + +package deque_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/structure/deque" +) + +type QueryStructure[T any] struct { + queryType string + parameter T + expectedResult interface{} + expectedError error +} + +type TestCaseData[T any] struct { + description string + queries []QueryStructure[T] +} + +func TestDeque(t *testing.T) { + + // Test cases with ints as params + testCasesInt := []TestCaseData[int]{ + { + description: "Test empty deque", + queries: []QueryStructure[int]{ + { + queryType: "IsEmpty", + expectedResult: true, + expectedError: nil, + }, + { + queryType: "Front", + expectedError: deque.ErrEmptyDequeue, + }, + { + queryType: "Rear", + expectedError: deque.ErrEmptyDequeue, + }, + { + queryType: "DeQueueFront", + expectedError: deque.ErrEmptyDequeue, + }, + { + queryType: "DeQueueRear", + expectedError: deque.ErrEmptyDequeue, + }, + { + queryType: "Length", + expectedResult: 0, + expectedError: nil, + }, + }, + }, + { + description: "Test deque with one element", + queries: []QueryStructure[int]{ + { + queryType: "EnQueueFront", + parameter: 1, + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Front", + expectedResult: 1, + expectedError: nil, + }, + { + queryType: "Rear", + expectedResult: 1, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 1, + expectedError: nil, + }, + { + queryType: "DeQueueFront", + expectedResult: 1, + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: true, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 0, + expectedError: nil, + }, + }, + }, + { + description: "Test deque with multiple elements", + queries: []QueryStructure[int]{ + { + queryType: "EnQueueFront", + parameter: 1, + expectedError: nil, + }, + { + queryType: "EnQueueFront", + parameter: 2, + expectedError: nil, + }, + { + queryType: "EnQueueRear", + parameter: 3, + expectedError: nil, + }, + { + queryType: "EnQueueRear", + parameter: 4, + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Front", + expectedResult: 2, + expectedError: nil, + }, + { + queryType: "Rear", + expectedResult: 4, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 4, + expectedError: nil, + }, + { + queryType: "DeQueueFront", + expectedResult: 2, + expectedError: nil, + }, + { + queryType: "DeQueueRear", + expectedResult: 4, + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 2, + expectedError: nil, + }, + }, + }, + } + + // Test cases with strings as params + testCasesString := []TestCaseData[string]{ + { + description: "Test one element deque", + queries: []QueryStructure[string]{ + { + queryType: "EnQueueFront", + parameter: "a", + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Front", + expectedResult: "a", + expectedError: nil, + }, + { + queryType: "Rear", + expectedResult: "a", + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 1, + expectedError: nil, + }, + { + queryType: "DeQueueFront", + expectedResult: "a", + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: true, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 0, + expectedError: nil, + }, + }, + }, + { + description: "Test multiple elements deque", + queries: []QueryStructure[string]{ + { + queryType: "EnQueueFront", + parameter: "a", + expectedError: nil, + }, + { + queryType: "EnQueueFront", + parameter: "b", + expectedError: nil, + }, + { + queryType: "EnQueueRear", + parameter: "c", + expectedError: nil, + }, + { + queryType: "EnQueueRear", + parameter: "d", + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Front", + expectedResult: "b", + expectedError: nil, + }, + { + queryType: "Rear", + expectedResult: "d", + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 4, + expectedError: nil, + }, + { + queryType: "DeQueueFront", + expectedResult: "b", + expectedError: nil, + }, + { + queryType: "DeQueueRear", + expectedResult: "d", + expectedError: nil, + }, + { + queryType: "IsEmpty", + expectedResult: false, + expectedError: nil, + }, + { + queryType: "Length", + expectedResult: 2, + expectedError: nil, + }, + }, + }, + } + + // Run tests with ints + for _, testCase := range testCasesInt { + t.Run(testCase.description, func(t *testing.T) { + dq := deque.New[int]() + for _, query := range testCase.queries { + switch query.queryType { + case "EnQueueFront": + dq.EnqueueFront(query.parameter) + case "EnQueueRear": + dq.EnqueueRear(query.parameter) + case "DeQueueFront": + result, err := dq.DequeueFront() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "DeQueueRear": + result, err := dq.DequeueRear() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "Front": + result, err := dq.Front() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v, %v", query.expectedResult, result, testCase.description) + } + case "Rear": + result, err := dq.Rear() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "IsEmpty": + result := dq.IsEmpty() + if result != query.expectedResult { + t.Errorf("Expected error: %v, got : %v", query.expectedResult, result) + } + case "Length": + result := dq.Length() + if result != query.expectedResult { + t.Errorf("Expected %v got %v", query.expectedResult, result) + } + } + } + }) + } + + // Run tests with strings + for _, testCase := range testCasesString { + t.Run(testCase.description, func(t *testing.T) { + dq := deque.New[string]() + for _, query := range testCase.queries { + switch query.queryType { + case "EnQueueFront": + dq.EnqueueFront(query.parameter) + case "EnQueueRear": + dq.EnqueueRear(query.parameter) + case "DeQueueFront": + result, err := dq.DequeueFront() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "DeQueueRear": + result, err := dq.DequeueRear() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "Front": + result, err := dq.Front() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v, %v", query.expectedResult, result, testCase.description) + } + case "Rear": + result, err := dq.Rear() + if err != query.expectedError { + t.Errorf("Expected error: %v, got : %v", query.expectedError, err) + } + if err == nil && result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "IsEmpty": + result := dq.IsEmpty() + if result != query.expectedResult { + t.Errorf("Expected %v, got %v", query.expectedResult, result) + } + case "Length": + result := dq.Length() + if result != query.expectedResult { + t.Errorf("Expected %v got %v", query.expectedResult, result) + } + } + } + }) + } +} From 5206ad3945b2a8b58bb0a89ba78962401925dca6 Mon Sep 17 00:00:00 2001 From: Pratik Tripathy <117454569+SilverDragonOfR@users.noreply.github.com> Date: Fri, 13 Oct 2023 19:39:46 +0530 Subject: [PATCH 149/202] feat: Add Automorphic number algorithm and test (#681) * feat: add sum of digit algorithm * test: add test for sum of digit algorithm * Updated Documentation in README.md * fix: removed digit sum folder * feat: add automophic algorithm and tests * Updated Documentation in README.md * Updated Documentation in README.md * fix: remove spaces, comments. add type parameters * Updated Documentation in README.md * Updated Documentation in README.md * fix: moved automorphic files to math package * Updated Documentation in README.md * fix: removed spaces and unnecessary comments * Updated Documentation in README.md * Updated Documentation in README.md * fix: empty commit as per request --------- Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Rak Laptudirm --- README.md | 178 ++++++++++++++++++++++++++----------- math/isautomorphic.go | 32 +++++++ math/isautomorphic_test.go | 58 ++++++++++++ 3 files changed, 215 insertions(+), 53 deletions(-) create mode 100644 math/isautomorphic.go create mode 100644 math/isautomorphic_test.go diff --git a/README.md b/README.md index 7304c78aa..683c7154c 100644 --- a/README.md +++ b/README.md @@ -70,15 +70,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Abs`](./math/binary/abs.go#L10): Abs returns absolute value using binary operation Principle of operation: 1) Get the mask by right shift by the base 2) Base is the size of an integer variable in bits, for example, for int32 it will be 32, for int64 it will be 64 3) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. 4) Add the mask to the given number. 5) XOR of mask + n and mask gives the absolute value. 2. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number -3. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L21): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. -4. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L28): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 -5. [`LogBase2`](./math/binary/logarithm.go#L7): LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm) -6. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations -7. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift -8. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. -9. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n -10. [`Sqrt`](./math/binary/sqrt.go#L16): No description provided. -11. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence +3. [`FastInverseSqrt`](./math/binary/fast_inverse_sqrt.go#L15): FastInverseSqrt assumes that argument is always positive, and it does not deal with negative numbers. The "magic" number 0x5f3759df is hex for 1597463007 in decimals. The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)). +4. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L21): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition. +5. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L28): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2 +6. [`LogBase2`](./math/binary/logarithm.go#L7): LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm) +7. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations +8. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift +9. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed. +10. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n +11. [`Sqrt`](./math/binary/sqrt.go#L10): No description provided. +12. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence ---
@@ -232,6 +233,38 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 9. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string. 10. [`RomanToInt`](./conversion/romantoint.go#L40): RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown. +--- +
+ deque + +--- + +##### Package deque implements a Double Ended Queue data structure. + +--- +##### Functions: + +1. [`New`](./structure/deque/deque.go#L22): New returns a new DoublyEndedQueue. + +--- +##### Types + +1. [`DoublyEndedQueue`](./structure/deque/deque.go#L17): No description provided. + + +--- +
+ deque_test + +--- + +##### Types + +1. [`QueryStructure`](./structure/deque/deque_test.go#L20): No description provided. + +2. [`TestCaseData`](./structure/deque/deque_test.go#L27): No description provided. + + ---
diffiehellman @@ -421,7 +454,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 10. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made 11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. 12. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. -13. [`Topological`](./graph/topological.go#L7): Assumes that graph given is valid and possible to get a topo ordering. constraints are array of []int{a, b}, representing an edge going from a to b +13. [`Topological`](./graph/topological.go#L7): Topological assumes that graph given is valid and that its possible to get a topological ordering. constraints are array of []int{a, b}, representing an edge going from a to b --- ##### Types @@ -509,6 +542,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. Methods: 1. [`Less`](./structure/heap/heap_test.go#L20): No description provided. +--- +
+ horspool + +--- + +##### Functions: + +1. [`Horspool`](./strings/horspool/horspool.go#L10): No description provided. + ---
kmp @@ -592,7 +635,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### filename : krishnamurthy.go description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. Ex: 1! = 1, 145 = 1! + 4! + 5! author(s): [GooMonk](https://github.com/GooMonk) see krishnamurthy_test.go Package math is a package that contains mathematical algorithms and its different implementations. +##### Package math is a package that contains mathematical algorithms and its different implementations. filename : krishnamurthy.go description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. Ex: 1! = 1, 145 = 1! + 4! + 5! author(s): [GooMonk](https://github.com/GooMonk) see krishnamurthy_test.go --- ##### Functions: @@ -604,20 +647,21 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 5. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n 6. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. 7. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process. -8. [`IsKrishnamurthyNumber`](./math/krishnamurthy.go#L12): IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not. -9. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number -10. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. -11. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1' -12. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number -13. [`Mean`](./math/mean.go#L7): No description provided. -14. [`Median`](./math/median.go#L12): No description provided. -15. [`Mode`](./math/mode.go#L19): No description provided. -16. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number -17. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. -18. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 -19. [`PronicNumber`](./math/pronicnumber.go#L15): PronicNumber returns true if argument passed to the function is pronic and false otherwise. -20. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) -21. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. +8. [`IsAutomorphic`](./math/isautomorphic.go#L16): No description provided. +9. [`IsKrishnamurthyNumber`](./math/krishnamurthy.go#L12): IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not. +10. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number +11. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package. +12. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1' +13. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number +14. [`Mean`](./math/mean.go#L7): No description provided. +15. [`Median`](./math/median.go#L12): No description provided. +16. [`Mode`](./math/mode.go#L19): No description provided. +17. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number +18. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n. +19. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2 +20. [`PronicNumber`](./math/pronicnumber.go#L15): PronicNumber returns true if argument passed to the function is pronic and false otherwise. +21. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) +22. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. ---
@@ -718,7 +762,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`Parenthesis`](./strings/parenthesis/parenthesis.go#L12): parcounter will be 0 if all open parenthesis are closed correctly +1. [`Parenthesis`](./strings/parenthesis/parenthesis.go#L8): Parenthesis algorithm checks if every opened parenthesis is closed correctly. When parcounter is less than 0 when a closing parenthesis is detected without an opening parenthesis that surrounds it and parcounter will be 0 if all open parenthesis are closed correctly. ---
@@ -925,7 +969,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- -##### package set implements a Set using generics and a golang map with comparable interface key. This implies that only the types that are accepted as valid map keys can be used as set elements +##### package set implements a Set using a golang map. This implies that only the types that are accepted as valid map keys can be used as set elements. For instance, do not try to Add a slice, or the program will panic. --- ##### Functions: @@ -953,29 +997,31 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. --- ##### Functions: -1. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. -1. [`Bogo`](./sort/bogosort.go#L32): Bogo generates random permutations until it guesses the correct one. -2. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range. -3. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. -4. [`Count`](./sort/countingsort.go#L11): No description provided. -5. [`Cycle`](./sort/cyclesort.go#L10): Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It is theoretically optimal in terms of the total number of writes to the original array. -6. [`Exchange`](./sort/exchangesort.go#L8): No description provided. -7. [`HeapSort`](./sort/heapsort.go#L116): No description provided. -8. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort -9. [`Insertion`](./sort/insertionsort.go#L5): No description provided. -10. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice -11. [`MergeIter`](./sort/mergesort.go#L55): No description provided. -12. [`Pancake`](./sort/pancakesort.go#L8): Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`. -13. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines -14. [`Partition`](./sort/quicksort.go#L12): No description provided. -15. [`Patience`](./sort/patiencesort.go#L13): No description provided. -16. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. -17. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array -18. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array -19. [`RadixSort`](./sort/radixsort.go#L43): No description provided. -20. [`Selection`](./sort/selectionsort.go#L5): No description provided. -21. [`Shell`](./sort/shellsort.go#L5): No description provided. -22. [`Simple`](./sort/simplesort.go#L13): No description provided. +1. [`BinaryInsertion`](./sort/binaryinsertionsort.go#L13): No description provided. +2. [`Bogo`](./sort/bogosort.go#L32): No description provided. +3. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm. +4. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range. +5. [`Cocktail`](./sort/cocktailsort.go#L9): Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning) +6. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm. +7. [`Count`](./sort/countingsort.go#L11): No description provided. +8. [`Cycle`](./sort/cyclesort.go#L10): Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It is theoretically optimal in terms of the total number of writes to the original array. +9. [`Exchange`](./sort/exchangesort.go#L8): No description provided. +10. [`HeapSort`](./sort/heapsort.go#L116): No description provided. +11. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort +12. [`Insertion`](./sort/insertionsort.go#L5): No description provided. +13. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice +14. [`MergeIter`](./sort/mergesort.go#L55): No description provided. +15. [`Pancake`](./sort/pancakesort.go#L8): Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`. +16. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines +17. [`Partition`](./sort/quicksort.go#L12): No description provided. +18. [`Patience`](./sort/patiencesort.go#L13): No description provided. +19. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered. +20. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array +21. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array +22. [`RadixSort`](./sort/radixsort.go#L43): No description provided. +23. [`Selection`](./sort/selectionsort.go#L5): No description provided. +24. [`Shell`](./sort/shellsort.go#L5): No description provided. +25. [`Simple`](./sort/simplesort.go#L13): No description provided. --- ##### Types @@ -983,19 +1029,45 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`MaxHeap`](./sort/heapsort.go#L5): No description provided. +--- +
+ sqrt + +--- + +##### Package sqrt contains algorithms and data structures that contains a √n in their complexity + +--- +##### Functions: + +1. [`NewSqrtDecomposition`](./sqrt/sqrtdecomposition.go#L34): Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment Assumptions: - len(elements) > 0 + +--- +##### Types + +1. [`SqrtDecomposition`](./sqrt/sqrtdecomposition.go#L21): No description provided. + + ---
stack --- +##### Functions: + +1. [`NewStack`](./structure/stack/stackarray.go#L17): NewStack creates and returns a new stack. + +--- ##### Types -1. [`Node`](./structure/stack/stacklinkedlist.go#L13): No description provided. +1. [`Array`](./structure/stack/stackarray.go#L12): No description provided. + +2. [`Node`](./structure/stack/stacklinkedlist.go#L13): No description provided. -2. [`SList`](./structure/stack/stacklinkedlistwithlist.go#L18): No description provided. +3. [`SList`](./structure/stack/stacklinkedlistwithlist.go#L18): No description provided. -3. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided. +4. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided. --- diff --git a/math/isautomorphic.go b/math/isautomorphic.go new file mode 100644 index 000000000..855d224a1 --- /dev/null +++ b/math/isautomorphic.go @@ -0,0 +1,32 @@ +// isautomorphic.go +// description: Checks whether a whole number integer is Automorphic or not. If number < 0 then returns false. +// details: +// In mathematics, a number n is said to be a Automorphic number if the square of n ends in the same digits as n itself. +// ref: (https://en.wikipedia.org/wiki/Automorphic_number) +// time complexity: O(log10(N)) +// space complexity: O(1) +// author: [SilverDragonOfR](https://github.com/SilverDragonOfR) + +package math + +import ( + "github.com/TheAlgorithms/Go/constraints" +) + +func IsAutomorphic[T constraints.Integer](n T) bool { + // handling the negetive number case + if n < 0 { + return false + } + + n_sq := n * n + for n > 0 { + if (n % 10) != (n_sq % 10) { + return false + } + n /= 10 + n_sq /= 10 + } + + return true +} diff --git a/math/isautomorphic_test.go b/math/isautomorphic_test.go new file mode 100644 index 000000000..d8494b921 --- /dev/null +++ b/math/isautomorphic_test.go @@ -0,0 +1,58 @@ +package math + +import ( + "testing" +) + +var testCases = []struct { + name string + input int + expected bool +}{ + { + "negetive number: not Automorphic", + -1, + false, + }, + { + "negetive number: not Automorphic", + -146, + false, + }, + { + "0: is Automorphic", + 0, + true, + }, + { + "1: is Automorphic", + 1, + true, + }, + { + "7: not Automorphic", + 7, + false, + }, + { + "83: not Automorphic", + 83, + false, + }, + { + "376: is Automorphic", + 376, + true, + }, +} + +func TestIsAutomorphic(t *testing.T) { + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + funcResult := IsAutomorphic(test.input) + if test.expected != funcResult { + t.Errorf("Expected answer '%t' for the number '%d' but answer given was %t", test.expected, test.input, funcResult) + } + }) + } +} From b2fc7e502f6fc7910271a11f5079a87aa2e7af07 Mon Sep 17 00:00:00 2001 From: Norman Soetbeer Date: Mon, 16 Oct 2023 18:43:40 +0200 Subject: [PATCH 150/202] feat: add recursive fibonacci (#686) --- README.md | 1 + math/fibonacci/fibonacci.go | 10 ++++++++++ math/fibonacci/fibonacci_test.go | 13 +++++++++++++ 3 files changed, 24 insertions(+) diff --git a/README.md b/README.md index 683c7154c..33134ef6f 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Formula`](./math/fibonacci/fibonacci.go#L42): Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers 2. [`Matrix`](./math/fibonacci/fibonacci.go#L15): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) +3. [`Recursive`](./math/fibonacci/fibonacci.go#L51): Recursive calculates the n-th fibonacci number recursively by adding the previous two numbers. [See](https://en.wikipedia.org/wiki/Fibonacci_sequence#Definition) ---
diff --git a/math/fibonacci/fibonacci.go b/math/fibonacci/fibonacci.go index 9718acbbc..92e69ae08 100644 --- a/math/fibonacci/fibonacci.go +++ b/math/fibonacci/fibonacci.go @@ -45,3 +45,13 @@ func Formula(n uint) uint { powPhi := math.Pow(phi, float64(n)) return uint(powPhi/sqrt5 + 0.5) } + +// Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers. +// This algorithm is extremely slow for bigger numbers, but provides a simpler implementation. +func Recursive(n uint) uint { + if n <= 1 { + return n + } + + return Recursive(n-1) + Recursive(n-2) +} diff --git a/math/fibonacci/fibonacci_test.go b/math/fibonacci/fibonacci_test.go index 990930251..bfdbed0bc 100644 --- a/math/fibonacci/fibonacci_test.go +++ b/math/fibonacci/fibonacci_test.go @@ -64,6 +64,19 @@ func TestFormula(t *testing.T) { } } +func TestRecursive(t *testing.T) { + tests := getTests() + for _, test := range tests { + if test.n <= 10 { + t.Run(test.name, func(t *testing.T) { + if got := Recursive(test.n); got != test.want { + t.Errorf("Return value = %v, want %v", got, test.want) + } + }) + } + } +} + func BenchmarkNthFibonacci(b *testing.B) { for i := 0; i < b.N; i++ { dynamic.NthFibonacci(90) From 25dea82b15b0f668ce6ba77d2187e712997eb720 Mon Sep 17 00:00:00 2001 From: Taj Date: Mon, 16 Oct 2023 20:30:53 +0100 Subject: [PATCH 151/202] Use citk (#639) --- .github/workflows/citk.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/citk.yml diff --git a/.github/workflows/citk.yml b/.github/workflows/citk.yml new file mode 100644 index 000000000..ce9360c36 --- /dev/null +++ b/.github/workflows/citk.yml @@ -0,0 +1,28 @@ +# https://github.com/golangci/golangci-lint +name: CI tool kit +on: + pull_request: + +jobs: + CITK: + name: Code style and tests + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Setup Go + uses: actions/setup-go@v3 + with: + go-version: "^1.18" + - name: Checkout branch + run: | + git fetch origin master:master + - name: Install citk tool + run: | + go install github.com/tjgurwara99/citk@latest + - name: Run citk tool + run: | + citk check -l go -b master From e255e17c00928db982dc3f8a4d68cfa7732a4b0d Mon Sep 17 00:00:00 2001 From: SANJIB GIRI <31872288+sanjibgirics@users.noreply.github.com> Date: Tue, 17 Oct 2023 11:54:24 +0530 Subject: [PATCH 152/202] feat: Add isSubsequence string algorithm (#684) --- strings/issubsequence.go | 35 ++++++++++++++++ strings/issubsequence_test.go | 75 +++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 strings/issubsequence.go create mode 100644 strings/issubsequence_test.go diff --git a/strings/issubsequence.go b/strings/issubsequence.go new file mode 100644 index 000000000..8d34177e9 --- /dev/null +++ b/strings/issubsequence.go @@ -0,0 +1,35 @@ +// Checks if a given string is a subsequence of another string. +// A subsequence of a given string is a string that can be derived from the given +// string by deleting some or no characters without changing the order of the +// remaining characters. (i.e., "dpr" is a subsequence of "depqr" while "drp" is not). +// Author: sanjibgirics + +package strings + +// Returns true if s is subsequence of t, otherwise return false. +func IsSubsequence(s string, t string) bool { + if len(s) > len(t) { + return false + } + + if s == t { + return true + } + + if len(s) == 0 { + return true + } + + sIndex := 0 + for tIndex := 0; tIndex < len(t); tIndex++ { + if s[sIndex] == t[tIndex] { + sIndex++ + } + + if sIndex == len(s) { + return true + } + } + + return false +} diff --git a/strings/issubsequence_test.go b/strings/issubsequence_test.go new file mode 100644 index 000000000..1b8c4cba4 --- /dev/null +++ b/strings/issubsequence_test.go @@ -0,0 +1,75 @@ +package strings_test + +import ( + "reflect" + "testing" + + "github.com/TheAlgorithms/Go/strings" +) + +func TestIsSubsequence(t *testing.T) { + var testCases = []struct { + name string + s string + t string + expected bool + }{ + { + "Valid case 1 ", + "ace", + "abcde", + true, + }, + { + "Invalid case 1", + "aec", + "abcde", + false, + }, + { + "Empty strings", + "", + "", + true, + }, + { + "s is more then t", + "aeccccc", + "abcde", + false, + }, + { + "s is empty", + "", + "abcde", + true, + }, + { + "Equal strings", + "aec", + "aec", + true, + }, + { + "Valid case 2", + "pyr", + "wpxqyrz", + true, + }, + { + "Invalid case 2", + "prx", + "wpxqyrz", + false, + }, + } + + for _, test := range testCases { + t.Run(test.name, func(t *testing.T) { + funcResult := strings.IsSubsequence(test.s, test.t) + if !reflect.DeepEqual(test.expected, funcResult) { + t.Errorf("expected: %v, got %v", test.expected, funcResult) + } + }) + } +} From f2de2860f61ba7601ceb2b7fbbcc147b6d34cf7c Mon Sep 17 00:00:00 2001 From: Mugdha Behere <50405769+MugdhaBehere@users.noreply.github.com> Date: Wed, 25 Oct 2023 03:21:35 +0530 Subject: [PATCH 153/202] Feat: Add Union Find Algorithm, Test: Add test for Union Find Algorithm (#687) * feat:Add Union Find(Dynamic Connectivity)Algorithm * test: Add test for Union Find Algorithm * docs: made changes to comment structure * fix: removed an error in the code * fix: removed errors in unionfind_test.go * fix: updata kruskal's algorithm * fix: update kruskal_test.go * fix: updated comments kruskal.go * fix: removed code redundancy * fix: removed main function * fix: changes to code * fix: updated the code * fix: updated code * fix: removed redundant spaces between comments * fix: formatted code with gofmt * fix: updated code * fix: formatted the files again --- graph/kruskal.go | 102 +++++++--------------------- graph/kruskal_test.go | 147 ++++++++++------------------------------ graph/unionfind.go | 59 ++++++++++++++++ graph/unionfind_test.go | 32 +++++++++ 4 files changed, 149 insertions(+), 191 deletions(-) create mode 100644 graph/unionfind.go create mode 100644 graph/unionfind_test.go diff --git a/graph/kruskal.go b/graph/kruskal.go index c6f094020..0543e2829 100644 --- a/graph/kruskal.go +++ b/graph/kruskal.go @@ -1,6 +1,10 @@ // KRUSKAL'S ALGORITHM -// https://cp-algorithms.com/data_structures/disjoint_set_union.html -// https://cp-algorithms.com/graph/mst_kruskal_with_dsu.html +// Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorithm/ +// Reference: Union Find Algorithm: https://www.scaler.com/topics/data-structures/disjoint-set/ +// Author: Author: Mugdha Behere[https://github.com/MugdhaBehere] +// Worst Case Time Complexity: O(E log E), where E is the number of edges. +// Worst Case Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges. +// see kruskal.go, kruskal_test.go package graph @@ -10,104 +14,44 @@ import ( type Vertex int -// Edge describes the edge of a weighted graph type Edge struct { Start Vertex End Vertex Weight int } -// DisjointSetUnionElement describes what an element of DSU looks like -type DisjointSetUnionElement struct { - Parent Vertex - Rank int -} - -// DisjointSetUnion is a data structure that treats its elements as separate sets -// and provides fast operations for set creation, merging sets, and finding the parent -// of the given element of a set. -type DisjointSetUnion []DisjointSetUnionElement - -// NewDSU will return an initialised DSU using the value of n -// which will be treated as the number of elements out of which -// the DSU is being made -func NewDSU(n int) *DisjointSetUnion { - - dsu := DisjointSetUnion(make([]DisjointSetUnionElement, n)) - return &dsu -} - -// MakeSet will create a set in the DSU for the given node -func (dsu DisjointSetUnion) MakeSet(node Vertex) { - - dsu[node].Parent = node - dsu[node].Rank = 0 -} - -// FindSetRepresentative will return the parent element of the set the given node -// belongs to. Since every single element in the path from node to parent -// has the same parent, we store the parent value for each element in the -// path. This reduces consequent function calls and helps in going from O(n) -// to O(log n). This is known as path compression technique. -func (dsu DisjointSetUnion) FindSetRepresentative(node Vertex) Vertex { - - if node == dsu[node].Parent { - return node - } - - dsu[node].Parent = dsu.FindSetRepresentative(dsu[node].Parent) - return dsu[node].Parent -} - -// unionSets will merge two given sets. The naive implementation of this -// always combines the secondNode's tree with the firstNode's tree. This can lead -// to creation of trees of length O(n) so we optimize by attaching the node with -// smaller rank to the node with bigger rank. Rank represents the upper bound depth of the tree. -func (dsu DisjointSetUnion) UnionSets(firstNode Vertex, secondNode Vertex) { - - firstNode = dsu.FindSetRepresentative(firstNode) - secondNode = dsu.FindSetRepresentative(secondNode) - - if firstNode != secondNode { - - if dsu[firstNode].Rank < dsu[secondNode].Rank { - firstNode, secondNode = secondNode, firstNode - } - dsu[secondNode].Parent = firstNode - - if dsu[firstNode].Rank == dsu[secondNode].Rank { - dsu[firstNode].Rank++ - } - } -} - -// KruskalMST will return a minimum spanning tree along with its total cost -// to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is -// the number of edges in the graph and n is number of nodes in it. func KruskalMST(n int, edges []Edge) ([]Edge, int) { + // Initialize variables to store the minimum spanning tree and its total cost + var mst []Edge + var cost int - var mst []Edge // The resultant minimum spanning tree - var cost int = 0 - - dsu := NewDSU(n) + // Create a new UnionFind data structure with 'n' nodes + u := NewUnionFind(n) + // Initialize each node in the UnionFind data structure for i := 0; i < n; i++ { - dsu.MakeSet(Vertex(i)) + u.parent[i] = i + u.size[i] = 1 } + // Sort the edges in non-decreasing order based on their weights sort.SliceStable(edges, func(i, j int) bool { return edges[i].Weight < edges[j].Weight }) + // Iterate through the sorted edges for _, edge := range edges { - - if dsu.FindSetRepresentative(edge.Start) != dsu.FindSetRepresentative(edge.End) { - + // Check if adding the current edge forms a cycle or not + if u.Find(int(edge.Start)) != u.Find(int(edge.End)) { + // Add the edge to the minimum spanning tree mst = append(mst, edge) + // Add the weight of the edge to the total cost cost += edge.Weight - dsu.UnionSets(edge.Start, edge.End) + // Merge the sets containing the start and end vertices of the current edge + u = u.Union(int(edge.Start), int(edge.End)) } } + // Return the minimum spanning tree and its total cost return mst, cost } diff --git a/graph/kruskal_test.go b/graph/kruskal_test.go index 86f062d53..09ed6949d 100644 --- a/graph/kruskal_test.go +++ b/graph/kruskal_test.go @@ -5,157 +5,80 @@ import ( "testing" ) -func Test_KruskalMST(t *testing.T) { - +func TestKruskalMST(t *testing.T) { + // Define test cases with inputs, expected outputs, and sample graphs var testCases = []struct { n int graph []Edge cost int }{ + // Test Case 1 { n: 5, graph: []Edge{ - { - Start: 0, - End: 1, - Weight: 4, - }, - { - Start: 0, - End: 2, - Weight: 13, - }, - { - Start: 0, - End: 3, - Weight: 7, - }, - { - Start: 0, - End: 4, - Weight: 7, - }, - { - Start: 1, - End: 2, - Weight: 9, - }, - { - Start: 1, - End: 3, - Weight: 3, - }, - { - Start: 1, - End: 4, - Weight: 7, - }, - { - Start: 2, - End: 3, - Weight: 10, - }, - { - Start: 2, - End: 4, - Weight: 14, - }, - { - Start: 3, - End: 4, - Weight: 4, - }, + {Start: 0, End: 1, Weight: 4}, + {Start: 0, End: 2, Weight: 13}, + {Start: 0, End: 3, Weight: 7}, + {Start: 0, End: 4, Weight: 7}, + {Start: 1, End: 2, Weight: 9}, + {Start: 1, End: 3, Weight: 3}, + {Start: 1, End: 4, Weight: 7}, + {Start: 2, End: 3, Weight: 10}, + {Start: 2, End: 4, Weight: 14}, + {Start: 3, End: 4, Weight: 4}, }, cost: 20, }, + // Test Case 2 { n: 3, graph: []Edge{ - { - Start: 0, - End: 1, - Weight: 12, - }, - { - Start: 0, - End: 2, - Weight: 18, - }, - { - Start: 1, - End: 2, - Weight: 6, - }, + {Start: 0, End: 1, Weight: 12}, + {Start: 0, End: 2, Weight: 18}, + {Start: 1, End: 2, Weight: 6}, }, cost: 18, }, + // Test Case 3 { n: 4, graph: []Edge{ - { - Start: 0, - End: 1, - Weight: 2, - }, - { - Start: 0, - End: 2, - Weight: 1, - }, - { - Start: 0, - End: 3, - Weight: 2, - }, - { - Start: 1, - End: 2, - Weight: 1, - }, - { - Start: 1, - End: 3, - Weight: 2, - }, - { - Start: 2, - End: 3, - Weight: 3, - }, + {Start: 0, End: 1, Weight: 2}, + {Start: 0, End: 2, Weight: 1}, + {Start: 0, End: 3, Weight: 2}, + {Start: 1, End: 2, Weight: 1}, + {Start: 1, End: 3, Weight: 2}, + {Start: 2, End: 3, Weight: 3}, }, cost: 4, }, + // Test Case 4 { n: 2, graph: []Edge{ - { - Start: 0, - End: 1, - Weight: 4000000, - }, + {Start: 0, End: 1, Weight: 4000000}, }, cost: 4000000, }, + // Test Case 5 { n: 1, graph: []Edge{ - { - Start: 0, - End: 0, - Weight: 0, - }, + {Start: 0, End: 0, Weight: 0}, }, cost: 0, }, } - for i := range testCases { - + // Iterate through the test cases and run the tests + for i, testCase := range testCases { t.Run(fmt.Sprintf("Test Case %d", i), func(t *testing.T) { + // Execute KruskalMST for the current test case + _, computed := KruskalMST(testCase.n, testCase.graph) - _, computed := KruskalMST(testCases[i].n, testCases[i].graph) - if computed != testCases[i].cost { - t.Errorf("Test Case %d, Expected: %d, Computed: %d", i, testCases[i].cost, computed) + // Compare the computed result with the expected result + if computed != testCase.cost { + t.Errorf("Test Case %d, Expected: %d, Computed: %d", i, testCase.cost, computed) } }) } diff --git a/graph/unionfind.go b/graph/unionfind.go new file mode 100644 index 000000000..7a922f3cc --- /dev/null +++ b/graph/unionfind.go @@ -0,0 +1,59 @@ +// Union Find Algorithm or Dynamic Connectivity algorithm, often implemented with the help +//of the union find data structure, +// is used to efficiently maintain connected components in a graph that undergoes dynamic changes, +// such as edges being added or removed over time +// Worst Case Time Complexity: The time complexity of find operation is nearly constant or +//O(α(n)), where where α(n) is the inverse Ackermann function +// practically, this is a very slowly growing function making the time complexity for find +//operation nearly constant. +// The time complexity of the union operation is also nearly constant or O(α(n)) +// Worst Case Space Complexity: O(n), where n is the number of nodes or element in the structure +// Reference: https://www.scaler.com/topics/data-structures/disjoint-set/ +// Author: Mugdha Behere[https://github.com/MugdhaBehere] +// see: unionfind.go, unionfind_test.go + +package graph + +// Defining the union-find data structure +type UnionFind struct { + parent []int + size []int +} + +// Initialise a new union find data structure with s nodes +func NewUnionFind(s int) UnionFind { + parent := make([]int, s) + size := make([]int, s) + for k := 0; k < s; k++ { + parent[k] = k + size[k] = 1 + } + return UnionFind{parent, size} +} + +// to find the root of the set to which the given element belongs, the Find function serves the purpose +func (u UnionFind) Find(q int) int { + for q != u.parent[q] { + q = u.parent[q] + } + return q +} + +// to merge two sets to which the given elements belong, the Union function serves the purpose +func (u UnionFind) Union(a, b int) UnionFind { + rootP := u.Find(a) + rootQ := u.Find(b) + + if rootP == rootQ { + return u + } + + if u.size[rootP] < u.size[rootQ] { + u.parent[rootP] = rootQ + u.size[rootQ] += u.size[rootP] + } else { + u.parent[rootQ] = rootP + u.size[rootP] += u.size[rootQ] + } + return u +} diff --git a/graph/unionfind_test.go b/graph/unionfind_test.go new file mode 100644 index 000000000..b95547649 --- /dev/null +++ b/graph/unionfind_test.go @@ -0,0 +1,32 @@ +package graph + +import ( + "testing" +) + +func TestUnionFind(t *testing.T) { + u := NewUnionFind(10) // Creating a Union-Find data structure with 10 elements + + //union operations + u = u.Union(0, 1) + u = u.Union(2, 3) + u = u.Union(4, 5) + u = u.Union(6, 7) + + // Testing the parent of specific elements + t.Run("Test Find", func(t *testing.T) { + if u.Find(0) != u.Find(1) || u.Find(2) != u.Find(3) || u.Find(4) != u.Find(5) || u.Find(6) != u.Find(7) { + t.Error("Union operation not functioning correctly") + } + }) + + u = u.Union(1, 5) // Additional union operation + u = u.Union(3, 7) // Additional union operation + + // Testing the parent of specific elements after more union operations + t.Run("Test Find after Union", func(t *testing.T) { + if u.Find(0) != u.Find(5) || u.Find(2) != u.Find(7) { + t.Error("Union operation not functioning correctly") + } + }) +} From 855c430f1fd2f3418360c28c8aad5efccbfa08ec Mon Sep 17 00:00:00 2001 From: Mohit Raghav Date: Thu, 26 Oct 2023 19:11:02 +0530 Subject: [PATCH 154/202] feat: Implement Matrix , its Methods and Some Functions including Strassen Matrix Multiplication in Go (#662) * feat: Implement Strassen Matrix Multiplication - Added the Strassen matrix multiplication algorithm for efficient matrix multiplication. - Added strassenmatrixmultiply.go to include the new algorithm. - Added example usage and test functions for verification. - Introduced benchmarks for performance evaluation. Closes #661 (if applicable) * This commit introduces the Strassen matrix multiplication algorithm along with the following supporting functions and test cases: 1. `AddMatrices`: Function to add two matrices. 2. `SubtractMatrices`: Function to subtract two matrices. 3. `MultiplyMatrices`: Function to multiply two matrices simply using loops. 4. `PrintMatrix`: Function to print a matrix for debugging purposes. 5. `EqualMatrix`: Function to check if two matrices are equal. 6. `StrassenMatrixMultiply` : Function to multiply two matrices using strassen algorithm * refactor: Rename functions and add implement new functionality Renamed files and functions: - addmatrices.go to add.go - addmatrices_test.go to add_test.go - matrixmultiply.go to multiply.go - matrixmultiply_test.go to multiply_test.go - subtractmatrices.go to subtract.go - subtractmatrices_test.go to subtract_test.go - printmatrix.go to print.go - printmatrix_test.go to print_test.go New files: - breadth.go - breadth_test.go - checkequal.go - checkequal_test.go - isvalid.go - isvalid_test.go - length.go - length_test.go - samedimensions.go - samedimensions_test.go Modified files: - strassenmatrixmultiply.go - strassenmatrixmultiply_test.go This commit includes renaming and restructuring files for clarity, adding new functionality, and removing some obsolete files. * Implement Matrix as a struct type This commit introduces a new type, represented as a struct with methods for creating, manipulating, and performing operations on matrices. The following changes have been made: - Added the `Matrix` struct with fields for elements, rows, and columns. - Implemented the `New` function to create a new matrix with specified dimensions and initial values. - Implemented the `NewFromElements` function to create a matrix from a provided 2D slice of elements. - Added the `Get` and `Set` methods to access and modify matrix elements by row and column indices. - Implemented the `Print` method to print the matrix to the console. - Introduced the `SameDimensions` method to check if two matrices have the same dimensions. - Implemented functions for matrix operations, including `Add`, `Subtract`, `Multiply`, and `CheckEqual`. - Added a helper function `IsValid` to check if a given matrix has consistent row lengths. These changes provide a foundation for working with matrices in Go, allowing for easy creation, manipulation, and comparison of matrices. * Implement StrassenMatrixMultiply and Matrix Methods In this commit, the following key additions have been made to the folder: - Implemented `StrassenMatrixMultiply`, a fast matrix multiplication algorithm, to efficiently multiply two matrices. - Introduced `Copy` method to create a deep copy of a matrix, allowing for independent manipulation without affecting the original matrix. - Implemented `Submatrix` method to extract a submatrix from an existing matrix based on specified row and column indices. - Added `Rows` and `Columns` methods to retrieve rows and columns of matrix. - Included comprehensive test cases to ensure the correctness and robustness of these newly implemented features. These enhancements expand the capabilities of the type, making it more versatile and efficient in performing matrix operations. * Refactor to Use Value Type `Matrix` and Add Benchmarks In this commit, the following significant changes have been made: 1. Refactored the `Matrix` type from a pointer to a value type. Using a pointer for a small structure like `Matrix` was deemed unnecessary and has been updated to enhance code simplicity. 2. Added comprehensive benchmarks to all functions. These benchmarks will help ensure that the code performs efficiently and allows for easy performance profiling. 3. Fixed code integration errors that were identified during the refactoring process. * Fixed Golang CI lint errors for file copy_test.go & submatrix_test.go * refactor: Change type variable T to constraints.Integer, rename SameDimensions to MatchDimensions, and remove unnecessary code This commit updates the type variable T to constraints.Integer, providing a more specific type constraint. It also renames the SameDimensions function to MatchDimensions for clarity. Additionally, unnecessary code lines have been removed for cleaner and more optimized code. * refractor: Implement goroutines in Add, CheckEqual, Copy, New, Multiply, SubMatrix, and Subtract functions * refractor : Handled error in StrassenMatrixMultiply method instead of ignoring it * refractor : Handle errors gracefully by returning an error message instead of causing a panic. * refractor : Updated the 'copy' function to return an empty matrix if an empty matrix is passed as input. * Updated Documentation in README.md * refactor: matrix operations to use context and sync packages Body: - Updated the Add,Subtract, SubMatrix, and Multiply functions in the matrix package to use the context and sync packages for goroutine management and error handling. - Removed the use of the errgroup package in these functions. * refactor: matrix operations to use context and sync packages Body: - Updated the Add,Subtract, SubMatrix, and Multiply functions in the matrix package to use the context and sync packages for goroutine management and error handling. - Removed the use of the errgroup package in these functions. * Updated Documentation in README.md * chore: Add empty commit to trigger actions The GoDoc action has stopped the execution of other actions. This empty commit is a workaround to trigger the other actions to run. --------- Co-authored-by: github-action <${GITHUB_ACTOR}@users.noreply.github.com> --- README.md | 58 +++-- math/matrix/add.go | 64 ++++++ math/matrix/add_test.go | 58 +++++ math/matrix/checkequal.go | 32 +++ math/matrix/checkequal_test.go | 62 +++++ math/matrix/copy.go | 53 +++++ math/matrix/copy_test.go | 115 ++++++++++ math/matrix/isvalid.go | 17 ++ math/matrix/isvalid_test.go | 64 ++++++ math/matrix/matchdimensions.go | 9 + math/matrix/matchdimensions_test.go | 40 ++++ math/matrix/matrix.go | 92 ++++++++ math/matrix/matrix_test.go | 250 +++++++++++++++++++++ math/matrix/multiply.go | 86 +++++++ math/matrix/multiply_test.go | 101 +++++++++ math/matrix/strassenmatrixmultiply.go | 227 +++++++++++++++++++ math/matrix/strassenmatrixmultiply_test.go | 131 +++++++++++ math/matrix/string.go | 15 ++ math/matrix/string_test.go | 96 ++++++++ math/matrix/submatrix.go | 79 +++++++ math/matrix/submatrix_test.go | 88 ++++++++ math/matrix/subtract.go | 64 ++++++ math/matrix/subtract_test.go | 50 +++++ 23 files changed, 1837 insertions(+), 14 deletions(-) create mode 100644 math/matrix/add.go create mode 100644 math/matrix/add_test.go create mode 100644 math/matrix/checkequal.go create mode 100644 math/matrix/checkequal_test.go create mode 100644 math/matrix/copy.go create mode 100644 math/matrix/copy_test.go create mode 100644 math/matrix/isvalid.go create mode 100644 math/matrix/isvalid_test.go create mode 100644 math/matrix/matchdimensions.go create mode 100644 math/matrix/matchdimensions_test.go create mode 100644 math/matrix/matrix.go create mode 100644 math/matrix/matrix_test.go create mode 100644 math/matrix/multiply.go create mode 100644 math/matrix/multiply_test.go create mode 100644 math/matrix/strassenmatrixmultiply.go create mode 100644 math/matrix/strassenmatrixmultiply_test.go create mode 100644 math/matrix/string.go create mode 100644 math/matrix/string_test.go create mode 100644 math/matrix/submatrix.go create mode 100644 math/matrix/submatrix_test.go create mode 100644 math/matrix/subtract.go create mode 100644 math/matrix/subtract_test.go diff --git a/README.md b/README.md index 33134ef6f..4837c61f4 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Formula`](./math/fibonacci/fibonacci.go#L42): Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers 2. [`Matrix`](./math/fibonacci/fibonacci.go#L15): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form) -3. [`Recursive`](./math/fibonacci/fibonacci.go#L51): Recursive calculates the n-th fibonacci number recursively by adding the previous two numbers. [See](https://en.wikipedia.org/wiki/Fibonacci_sequence#Definition) +3. [`Recursive`](./math/fibonacci/fibonacci.go#L51): Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers. This algorithm is extremely slow for bigger numbers, but provides a simpler implementation. ---
@@ -449,34 +449,32 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 4. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided. 5. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm 6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. -7. [`KruskalMST`](./graph/kruskal.go#L87): KruskalMST will return a minimum spanning tree along with its total cost to using Kruskal's algorithm. Time complexity is O(m * log (n)) where m is the number of edges in the graph and n is number of nodes in it. +7. [`KruskalMST`](./graph/kruskal.go#L23): No description provided. 8. [`LowestCommonAncestor`](./graph/lowestcommonancestor.go#L111): For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. 9. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) -10. [`NewDSU`](./graph/kruskal.go#L34): NewDSU will return an initialised DSU using the value of n which will be treated as the number of elements out of which the DSU is being made -11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. +10. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. +11. [`NewUnionFind`](./graph/unionfind.go#L24): Initialise a new union find data structure with s nodes 12. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. 13. [`Topological`](./graph/topological.go#L7): Topological assumes that graph given is valid and that its possible to get a topological ordering. constraints are array of []int{a, b}, representing an edge going from a to b --- ##### Types -1. [`DisjointSetUnion`](./graph/kruskal.go#L29): No description provided. +1. [`Edge`](./graph/kruskal.go#L17): No description provided. -2. [`DisjointSetUnionElement`](./graph/kruskal.go#L21): No description provided. +2. [`Graph`](./graph/graph.go#L9): No description provided. -3. [`Edge`](./graph/kruskal.go#L14): No description provided. +3. [`Item`](./graph/dijkstra.go#L5): No description provided. -4. [`Graph`](./graph/graph.go#L9): No description provided. +4. [`Query`](./graph/lowestcommonancestor_test.go#L9): No description provided. -5. [`Item`](./graph/dijkstra.go#L5): No description provided. +5. [`Tree`](./graph/lowestcommonancestor.go#L25): No description provided. -6. [`Query`](./graph/lowestcommonancestor_test.go#L9): No description provided. +6. [`TreeEdge`](./graph/lowestcommonancestor.go#L12): No description provided. -7. [`Tree`](./graph/lowestcommonancestor.go#L25): No description provided. +7. [`UnionFind`](./graph/unionfind.go#L18): No description provided. -8. [`TreeEdge`](./graph/lowestcommonancestor.go#L12): No description provided. - -9. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. +8. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided. --- @@ -664,6 +662,37 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 21. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) 22. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber. +--- +
+ matrix + +--- + +##### filename: strassenmatrixmultiply.go description: Implements matrix multiplication using the Strassen algorithm. details: This program takes two matrices as input and performs matrix multiplication using the Strassen algorithm, which is an optimized divide-and-conquer approach. It allows for efficient multiplication of large matrices. author(s): Mohit Raghav(https://github.com/mohit07raghav19) See strassenmatrixmultiply_test.go for test cases + +--- +##### Functions: + +1. [`IsValid`](./math/matrix/isvalid.go#L6): IsValid checks if the input matrix has consistent row lengths. +2. [`New`](./math/matrix/matrix.go#L17): NewMatrix creates a new Matrix based on the provided arguments. +3. [`NewFromElements`](./math/matrix/matrix.go#L43): NewFromElements creates a new Matrix from the given elements. + +--- +##### Types + +1. [`Matrix`](./math/matrix/matrix.go#L10): No description provided. + + +--- +
+ matrix_test + +--- + +##### Functions: + +1. [`MakeRandomMatrix`](./math/matrix/strassenmatrixmultiply_test.go#L105): No description provided. + ---
max @@ -1084,6 +1113,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`CountChars`](./strings/charoccurrence.go#L12): CountChars counts the number of a times a character has occurred in the provided string argument and returns a map with `rune` as keys and the count as value. 2. [`IsIsogram`](./strings/isisogram.go#L34): No description provided. +3. [`IsSubsequence`](./strings/issubsequence.go#L10): Returns true if s is subsequence of t, otherwise return false. ---
diff --git a/math/matrix/add.go b/math/matrix/add.go new file mode 100644 index 000000000..34fdf98be --- /dev/null +++ b/math/matrix/add.go @@ -0,0 +1,64 @@ +package matrix + +import ( + "context" + "errors" + "sync" +) + +// Add adds two matrices. +func (m1 Matrix[T]) Add(m2 Matrix[T]) (Matrix[T], error) { + // Check if the matrices have the same dimensions. + if !m1.MatchDimensions(m2) { + return Matrix[T]{}, errors.New("matrices are not compatible for addition") + } + + // Create a new matrix to store the result. + var zeroVal T + result := New(m1.Rows(), m1.Columns(), zeroVal) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // Make sure it's called to release resources even if no errors + + var wg sync.WaitGroup + errCh := make(chan error, 1) + + for i := 0; i < m1.rows; i++ { + i := i // Capture the loop variable for the goroutine + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < m1.columns; j++ { + select { + case <-ctx.Done(): + return // Context canceled; return without an error + default: + } + + sum := m1.elements[i][j] + m2.elements[i][j] + err := result.Set(i, j, sum) + if err != nil { + cancel() // Cancel the context on error + select { + case errCh <- err: + default: + } + return + } + } + }() + } + + // Wait for all goroutines to finish + go func() { + wg.Wait() + close(errCh) + }() + + // Check for any errors + if err := <-errCh; err != nil { + return Matrix[T]{}, err + } + + return result, nil +} diff --git a/math/matrix/add_test.go b/math/matrix/add_test.go new file mode 100644 index 000000000..f3543965c --- /dev/null +++ b/math/matrix/add_test.go @@ -0,0 +1,58 @@ +package matrix_test + +import ( + "fmt" + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestAdd(t *testing.T) { + // Create two matrices with the same dimensions for addition + m1 := matrix.New(2, 2, 1) + m2 := matrix.New(2, 2, 2) + + // Test case 1: Valid matrix addition + addedMatrix, err := m1.Add(m2) + if err != nil { + t.Errorf("Add(m1, m2) returned an error: %v, expected no error", err) + } + expectedMatrix := matrix.New(2, 2, 3) + res := addedMatrix.CheckEqual(expectedMatrix) + if !res { + t.Errorf("Add(m1, m2) returned incorrect result:\n%v\nExpected:\n%v", addedMatrix, expectedMatrix) + } + + // Create two matrices with different dimensions for addition + m3 := matrix.New(2, 2, 1) + m4 := matrix.New(2, 3, 2) + + // Test case 2: Matrices with different dimensions + _, err2 := m3.Add(m4) + expectedError2 := fmt.Errorf("matrices are not compatible for addition") + if err2 == nil || err2.Error() != expectedError2.Error() { + t.Errorf("Add(m3, m4) returned error: %v, expected error: %v", err2, expectedError2) + } + +} + +func BenchmarkAddSmallMatrix(b *testing.B) { + m1 := matrix.New(10, 10, 0) // Create a 10x10 matrix with all zeros + m2 := matrix.New(10, 10, 1) // Create a 10x10 matrix with all ones + + for i := 0; i < b.N; i++ { + _, _ = m1.Add(m2) + } +} + +func BenchmarkAddLargeMatrix(b *testing.B) { + size := 1000 // Choose an appropriate size for your large matrix + m1 := MakeRandomMatrix[int](size, size) + m2 := MakeRandomMatrix[int](size, size) + + b.ResetTimer() // Reset the timer to exclude setup time + + for i := 0; i < b.N; i++ { + _, _ = m1.Add(m2) + } +} diff --git a/math/matrix/checkequal.go b/math/matrix/checkequal.go new file mode 100644 index 000000000..c6bde8597 --- /dev/null +++ b/math/matrix/checkequal.go @@ -0,0 +1,32 @@ +package matrix + +// CheckEqual checks if the current matrix is equal to another matrix (m2). +// Two matrices are considered equal if they have the same dimensions and +// all their elements are equal. +func (m1 Matrix[T]) CheckEqual(m2 Matrix[T]) bool { + if !m1.MatchDimensions(m2) { + return false + } + + c := make(chan bool) + + for i := range m1.elements { + go func(i int) { + for j := range m1.elements[i] { + if m1.elements[i][j] != m2.elements[i][j] { + c <- false + return + } + } + c <- true + }(i) + } + + for range m1.elements { + if !<-c { + return false + } + } + + return true +} diff --git a/math/matrix/checkequal_test.go b/math/matrix/checkequal_test.go new file mode 100644 index 000000000..be93d82d7 --- /dev/null +++ b/math/matrix/checkequal_test.go @@ -0,0 +1,62 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestCheckEqual(t *testing.T) { + // Create two matrices with the same dimensions and equal values + m1 := matrix.New(2, 2, 0) + m2 := matrix.New(2, 2, 0) + + // Test case 1: Matrices are equal + equal := m1.CheckEqual(m2) + + if !equal { + t.Errorf("CheckEqual(m1, m2) returned false, expected true (matrices are equal)") + } + + // Create two matrices with the same dimensions but different values + m3 := matrix.New(2, 2, 1) + m4 := matrix.New(2, 2, 0) + + // Test case 2: Matrices are not equal + equal2 := m3.CheckEqual(m4) + if equal2 { + t.Errorf("CheckEqual(m3, m4) returned true, expected false (matrices are not equal)") + } + + // Create two matrices with different dimensions + m5 := matrix.New(2, 2, 0) + m6 := matrix.New(2, 3, 0) + + // Test case 3: Matrices have different dimensions + equal3 := m5.CheckEqual(m6) + + if equal3 { + t.Errorf("CheckEqual(m5, m6) returned true, expected false (matrices are not equal)") + } +} + +func BenchmarkCheckEqualSmallMatrix(b *testing.B) { + m1 := matrix.New(10, 10, 0) // Create a 10x10 matrix with all zeros + m2 := matrix.New(10, 10, 0) // Create another 10x10 matrix with all zeros + + for i := 0; i < b.N; i++ { + _ = m1.CheckEqual(m2) + } +} + +func BenchmarkCheckEqualLargeMatrix(b *testing.B) { + size := 1000 // Choose an appropriate size for your large matrix + m1 := MakeRandomMatrix[int](size, size) + m2 := MakeRandomMatrix[int](size, size) + + b.ResetTimer() // Reset the timer to exclude setup time + + for i := 0; i < b.N; i++ { + _ = m1.CheckEqual(m2) + } +} diff --git a/math/matrix/copy.go b/math/matrix/copy.go new file mode 100644 index 000000000..2b9949750 --- /dev/null +++ b/math/matrix/copy.go @@ -0,0 +1,53 @@ +package matrix + +import "sync" + +func (m Matrix[T]) Copy() (Matrix[T], error) { + + rows := m.Rows() + columns := m.Columns() + if rows == 0 || columns == 0 { + return Matrix[T]{}, nil + } + zeroVal, err := m.Get(0, 0) // Get the zero value of the element type + if err != nil { + return Matrix[T]{}, err + } + copyMatrix := New(rows, columns, zeroVal) + var wg sync.WaitGroup + wg.Add(rows) + errChan := make(chan error, 1) + + for i := 0; i < rows; i++ { + go func(i int) { + defer wg.Done() + for j := 0; j < columns; j++ { + val, err := m.Get(i, j) + if err != nil { + select { + case errChan <- err: + default: + } + return + } + err = copyMatrix.Set(i, j, val) + if err != nil { + select { + case errChan <- err: + default: + } + return + } + } + }(i) + } + + wg.Wait() + close(errChan) + + if err, ok := <-errChan; ok { + return Matrix[T]{}, err + } + + return copyMatrix, nil +} diff --git a/math/matrix/copy_test.go b/math/matrix/copy_test.go new file mode 100644 index 000000000..027902843 --- /dev/null +++ b/math/matrix/copy_test.go @@ -0,0 +1,115 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestMatrixCopy(t *testing.T) { + // Create a sample matrix + data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + // Ensure that the copy is not the same as the original + matrix, err := matrix.NewFromElements(data) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + copyMatrix, err := matrix.Copy() + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + + // Ensure that the copy is not the same as the original + if &matrix == ©Matrix { + t.Errorf("Copy did not create a new matrix.") + } + + for i := 0; i < matrix.Rows(); i++ { + for j := 0; j < matrix.Columns(); j++ { + val1, err := matrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + val2, err := copyMatrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + if val1 != val2 { + t.Errorf("Copy did not correctly copy element (%d, %d).", i, j) + } + } + } + +} + +func TestMatrixCopyEmpty(t *testing.T) { + // Create an empty matrix + emptyMatrix := matrix.New(0, 0, 0) + + // Make a copy of the empty matrix + copyMatrix, err := emptyMatrix.Copy() + if err != nil { // as empty matrix + t.Fatalf("Failed to copy matrix: %v", err) + } + + // Ensure that the copy is not the same as the original by comparing their addresses + if &emptyMatrix == ©Matrix { + t.Errorf("Copy did not create a new matrix for an empty matrix.") + } + + // Check if the copy is also empty + if copyMatrix.Rows() != 0 || copyMatrix.Columns() != 0 { + t.Errorf("Copy of an empty matrix should also be empty.") + } +} + +func TestMatrixCopyWithDefaultValues(t *testing.T) { + // Create a matrix with default values (zeroes) + rows, columns := 3, 3 + defaultValue := 0 + defaultMatrix := matrix.New(rows, columns, defaultValue) + + // Make a copy of the matrix + copyMatrix, err := defaultMatrix.Copy() + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + + // Ensure that the copy is not the same as the original by comparing their addresses + if &defaultMatrix == ©Matrix { + t.Errorf("Copy did not create a new matrix for default values.") + } + + // Check if the copy has the same values as the original (all zeroes) + for i := 0; i < defaultMatrix.Rows(); i++ { + for j := 0; j < defaultMatrix.Columns(); j++ { + val1, err := defaultMatrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + val2, err := copyMatrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + if val1 != val2 || val1 != defaultValue || val2 != defaultValue { + t.Errorf("Copy did not preserve default values at row %d, column %d. Expected %v, got %v", i, j, defaultValue, val2) + } + } + } +} + +func BenchmarkCopyMatrix(b *testing.B) { + // Create a matrix for benchmarking + rows := 100 + columns := 100 + initialValue := 0 + matrix := matrix.New(rows, columns, initialValue) + + // Reset the benchmark timer + b.ResetTimer() + + // Run the benchmarks + for i := 0; i < b.N; i++ { + _, _ = matrix.Copy() + } +} diff --git a/math/matrix/isvalid.go b/math/matrix/isvalid.go new file mode 100644 index 000000000..afe8f5ed3 --- /dev/null +++ b/math/matrix/isvalid.go @@ -0,0 +1,17 @@ +package matrix + +import "github.com/TheAlgorithms/Go/constraints" + +// IsValid checks if the input matrix has consistent row lengths. +func IsValid[T constraints.Integer](elements [][]T) bool { + if len(elements) == 0 { + return true + } + columns := len(elements[0]) + for _, row := range elements { + if len(row) != columns { + return false + } + } + return true +} diff --git a/math/matrix/isvalid_test.go b/math/matrix/isvalid_test.go new file mode 100644 index 000000000..ea7dae338 --- /dev/null +++ b/math/matrix/isvalid_test.go @@ -0,0 +1,64 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestIsValid(t *testing.T) { + // Test case 1: Valid matrix with consistent row lengths + validMatrix := [][]int{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + result1 := matrix.IsValid(validMatrix) + if !result1 { + t.Errorf("IsValid(validMatrix) returned false, expected true (valid matrix)") + } + + // Test case 2: Valid matrix with empty rows (no inconsistency) + validMatrixEmptyRows := [][]int{ + {}, + {}, + {}, + } + result2 := matrix.IsValid(validMatrixEmptyRows) + if !result2 { + t.Errorf("IsValid(validMatrixEmptyRows) returned false, expected true (valid matrix with empty rows)") + } + + // Test case 3: Invalid matrix with inconsistent row lengths + invalidMatrix := [][]int{ + {1, 2, 3}, + {4, 5}, + {6, 7, 8}, + } + result3 := matrix.IsValid(invalidMatrix) + if result3 { + t.Errorf("IsValid(invalidMatrix) returned true, expected false (invalid matrix with inconsistent row lengths)") + } + +} + +func BenchmarkIsValid(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + elements := make([][]int, rows) + for i := range elements { + elements[i] = make([]int, columns) + for j := range elements[i] { + elements[i][j] = i*columns + j // Some arbitrary values + } + } + + // Reset the benchmark timer + b.ResetTimer() + + // Run the benchmark + for i := 0; i < b.N; i++ { + _ = matrix.IsValid(elements) + } +} diff --git a/math/matrix/matchdimensions.go b/math/matrix/matchdimensions.go new file mode 100644 index 000000000..982409191 --- /dev/null +++ b/math/matrix/matchdimensions.go @@ -0,0 +1,9 @@ +package matrix + +// MatchDimensions checks if two matrices have the same dimensions. +func (m Matrix[T]) MatchDimensions(m1 Matrix[T]) bool { + if m.rows == m1.rows && m.columns == m1.columns { + return true + } + return false +} diff --git a/math/matrix/matchdimensions_test.go b/math/matrix/matchdimensions_test.go new file mode 100644 index 000000000..645b4211f --- /dev/null +++ b/math/matrix/matchdimensions_test.go @@ -0,0 +1,40 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestMatrixMatchDimensions(t *testing.T) { + // Create two matrices with the same dimensions + m1 := matrix.New(2, 3, 0) + m2 := matrix.New(2, 3, 0) + + // Test case 1: Same dimensions + if !m1.MatchDimensions(m2) { + t.Errorf("m1.MatchDimensions(m2) returned %t, expected 1 (same dimensions)", m1.MatchDimensions(m2)) + } + + // Create two matrices with different dimensions + m3 := matrix.New(2, 3, 0) + m4 := matrix.New(3, 2, 0) + + // Test case 2: Different dimensions + if m3.MatchDimensions(m4) { + t.Errorf("m3.MatchDimensions(m4) returned : %v, expected: %v", m3.MatchDimensions(m4), false) + } +} + +// BenchmarkMatchDimensions benchmarks the MatchDimensions method. +func BenchmarkMatchDimensions(b *testing.B) { + // Create sample matrices for benchmarking + rows := 100 + columns := 100 + m1 := matrix.New(rows, columns, 0) // Replace with appropriate values + m2 := matrix.New(rows, columns, 0) // Replace with appropriate values + + for i := 0; i < b.N; i++ { + _ = m1.MatchDimensions(m2) + } +} diff --git a/math/matrix/matrix.go b/math/matrix/matrix.go new file mode 100644 index 000000000..5a03e1e0b --- /dev/null +++ b/math/matrix/matrix.go @@ -0,0 +1,92 @@ +package matrix + +import ( + "errors" + "sync" + + "github.com/TheAlgorithms/Go/constraints" +) + +type Matrix[T constraints.Integer] struct { + elements [][]T + rows int + columns int +} + +// NewMatrix creates a new Matrix based on the provided arguments. +func New[T constraints.Integer](rows, columns int, initial T) Matrix[T] { + if rows < 0 || columns < 0 { + return Matrix[T]{} // Invalid dimensions, return an empty matrix + } + + // Initialize the matrix with the specified dimensions and fill it with the initial value. + elements := make([][]T, rows) + var wg sync.WaitGroup + wg.Add(rows) + + for i := range elements { + go func(i int) { + defer wg.Done() + elements[i] = make([]T, columns) + for j := range elements[i] { + elements[i][j] = initial + } + }(i) + } + + wg.Wait() + + return Matrix[T]{elements, rows, columns} +} + +// NewFromElements creates a new Matrix from the given elements. +func NewFromElements[T constraints.Integer](elements [][]T) (Matrix[T], error) { + if !IsValid(elements) { + return Matrix[T]{}, errors.New("rows have different numbers of columns") + } + rows := len(elements) + if rows == 0 { + return Matrix[T]{}, nil // Empty matrix + } + + columns := len(elements[0]) + matrix := Matrix[T]{ + elements: make([][]T, rows), + rows: rows, // Set the rows field + columns: columns, // Set the columns field + } + for i := range matrix.elements { + matrix.elements[i] = make([]T, columns) + copy(matrix.elements[i], elements[i]) + } + + return matrix, nil +} + +func (m Matrix[T]) Get(row, col int) (T, error) { + if row < 0 || row >= m.rows || col < 0 || col >= m.columns { + var zeroVal T + return zeroVal, errors.New("index out of range") + } + return m.elements[row][col], nil +} + +func (m Matrix[T]) Set(row, col int, val T) error { + if row < 0 || row >= m.rows || col < 0 || col >= m.columns { + return errors.New("index out of bounds") + } + + m.elements[row][col] = val + return nil +} + +func (m Matrix[T]) Rows() int { + return len(m.elements) +} + +func (m Matrix[T]) Columns() int { + if len(m.elements) == 0 { + return 0 + } + return len(m.elements[0]) +} diff --git a/math/matrix/matrix_test.go b/math/matrix/matrix_test.go new file mode 100644 index 000000000..1425bf933 --- /dev/null +++ b/math/matrix/matrix_test.go @@ -0,0 +1,250 @@ +package matrix_test + +import ( + "errors" + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestNewMatrix(t *testing.T) { + + nullMatrix := matrix.New(0, 0, 0) + if nullMatrix.Rows() != 0 || nullMatrix.Columns() != 0 { + t.Errorf("matrix.New( 0, 0, 0) returned nil, expected a matrix") + } + // Test creating a matrix of integers + intMatrix := matrix.New(3, 4, 0) + if intMatrix.Rows() != 3 || intMatrix.Columns() != 4 { + t.Errorf("matrix.New( 3, 4, 0) returned nil, expected a matrix") + } + +} + +func TestNewFromElements(t *testing.T) { + // Test case 1: Valid matrix + validElements := [][]int{ + {1, 2, 3}, + {4, 5, 6}, + } + expectedm1 := matrix.New(2, 3, 0) + for i := 0; i < len(validElements); i++ { + for j := 0; j < len(validElements[0]); j++ { + err := expectedm1.Set(i, j, validElements[i][j]) + if err != nil { + t.Errorf("copyMatrix.Set error: " + err.Error()) + } + } + } + + m1, err1 := matrix.NewFromElements(validElements) + if err1 != nil { + t.Errorf("NewFromElements(validElements) returned an error: %v", err1) + } + res := m1.CheckEqual(expectedm1) + if res != true { + t.Errorf("NewFromElements(validElements) returned %v, expected %v", m1, expectedm1) + } + + // Test case 2: Invalid matrix with different column counts + invalidElements := [][]int{ + {1, 2, 3}, + {4, 5}, + } + _, err2 := matrix.NewFromElements(invalidElements) + expectedError2 := errors.New("rows have different numbers of columns") + if err2 == nil || err2.Error() != expectedError2.Error() { + t.Errorf("NewFromElements(invalidElements) returned error: %v, expected error: %v", err2, expectedError2) + } + + // Test case 3: Empty matrix + emptyElements := [][]int{} + m3, err3 := matrix.NewFromElements(emptyElements) + if err3 != nil { + t.Errorf("NewFromElements(emptyElements) returned an error: %v", err3) + } + if m3.Rows() != 0 || m3.Columns() != 0 { + t.Errorf("NewFromElements(emptyElements) returned %v, expected nil", m3) + } +} + +func TestMatrixGet(t *testing.T) { + // Create a sample matrix for testing + matrix := matrix.New(3, 3, 0) + err := matrix.Set(1, 1, 42) // Set a specific value for testing + if err != nil { + t.Errorf("copyMatrix.Set error: " + err.Error()) + } + // Test case 1: Valid Get + val1, err1 := matrix.Get(1, 1) + if err1 != nil { + t.Errorf("matrix.Get(1, 1) returned an error: %v, expected no error", err1) + } + if val1 != 42 { + t.Errorf("matrix.Get(1, 1) returned %v, expected 42", val1) + } + + // Test case 2: Get with invalid indices + _, err2 := matrix.Get(10, 10) + expectedError2 := errors.New("index out of range") + if err2 == nil || err2.Error() != expectedError2.Error() { + t.Errorf("matrix.Get(10, 10) returned error: %v, expected error: %v", err2, expectedError2) + } + // Test case 3: Get with invalid indices + _, err3 := matrix.Get(-1, -3) + expectedError3 := errors.New("index out of range") + if err3 == nil || err3.Error() != expectedError3.Error() { + t.Errorf("matrix.Get(10, 10) returned error: %v, expected error: %v", err3, expectedError3) + } +} + +func TestMatrixSet(t *testing.T) { + // Create a sample matrix for testing + matrix := matrix.New(3, 3, 0) + + // Test case 1: Valid Set + err1 := matrix.Set(1, 1, 42) + if err1 != nil { + t.Errorf("matrix.Set(1, 1, 42) returned an error: %v, expected no error", err1) + } + val1, err := matrix.Get(1, 1) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + if val1 != 42 { + t.Errorf("matrix.Set(1, 1, 42) did not set the value correctly, expected 42, got %v", val1) + } + + // Test case 2: Set with invalid indices + err2 := matrix.Set(10, 10, 100) + expectedError2 := errors.New("index out of bounds") + if err2 == nil || err2.Error() != expectedError2.Error() { + t.Errorf("matrix.Set(10, 10, 100) returned error: %v, expected error: %v", err2, expectedError2) + } + // Test case 3: Get with invalid indices + err3 := matrix.Set(-13, -1, 100) + expectedError3 := errors.New("index out of bounds") + if err3 == nil || err3.Error() != expectedError3.Error() { + t.Errorf("matrix.Get(10, 10) returned error: %v, expected error: %v", err3, expectedError3) + } +} + +func TestMatrixRows(t *testing.T) { + // Create a sample matrix + data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + matrix, err := matrix.NewFromElements(data) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + // Check the number of rows + expectedRows := len(data) + rows := matrix.Rows() + if rows != expectedRows { + t.Errorf("Expected %d rows, but got %d", expectedRows, rows) + } +} + +func TestMatrixColumns(t *testing.T) { + // Create a sample matrix + data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + matrix, err := matrix.NewFromElements(data) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + // Check the number of columns + expectedColumns := len(data[0]) + columns := matrix.Columns() + if columns != expectedColumns { + t.Errorf("Expected %d columns, but got %d", expectedColumns, columns) + } +} + +func TestMatrixEmptyRowsAndColumns(t *testing.T) { + // Create an empty matrix + emptyMatrix := matrix.New(0, 0, 0) + + // Check the number of rows and columns for an empty matrix + rows := emptyMatrix.Rows() + columns := emptyMatrix.Columns() + + if rows != 0 { + t.Errorf("Expected 0 rows for an empty matrix, but got %d", rows) + } + + if columns != 0 { + t.Errorf("Expected 0 columns for an empty matrix, but got %d", columns) + } +} + +// BenchmarkNew benchmarks the New function. +func BenchmarkNew(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = matrix.New(100, 100, 0) // Change the arguments to match your use case + } +} + +// BenchmarkNewFromElements benchmarks the NewFromElements function. +func BenchmarkNewFromElements(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + elements := make([][]int, rows) + for i := range elements { + elements[i] = make([]int, columns) + for j := range elements[i] { + elements[i][j] = i*columns + j // Some arbitrary values + } + } + + for i := 0; i < b.N; i++ { + _, _ = matrix.NewFromElements(elements) + } +} + +// BenchmarkGet benchmarks the Get method. +func BenchmarkGet(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + matrix := matrix.New(rows, columns, 0) + + for i := 0; i < b.N; i++ { + _, _ = matrix.Get(50, 50) // Change the row and column indices as needed + } +} + +// BenchmarkSet benchmarks the Set method. +func BenchmarkSet(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + matrix := matrix.New(rows, columns, 0) + + for i := 0; i < b.N; i++ { + _ = matrix.Set(50, 50, 42) // Change the row, column, and value as needed + } +} + +// BenchmarkRows benchmarks the Rows method. +func BenchmarkRows(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + matrix := matrix.New(rows, columns, 0) + + for i := 0; i < b.N; i++ { + _ = matrix.Rows() + } +} + +// BenchmarkColumns benchmarks the Columns method. +func BenchmarkColumns(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + matrix := matrix.New(rows, columns, 0) + + for i := 0; i < b.N; i++ { + _ = matrix.Columns() + } +} diff --git a/math/matrix/multiply.go b/math/matrix/multiply.go new file mode 100644 index 000000000..718a1b068 --- /dev/null +++ b/math/matrix/multiply.go @@ -0,0 +1,86 @@ +package matrix + +import ( + "context" + "errors" + "sync" +) + +// Multiply multiplies the current matrix (m1) with another matrix (m2) and returns the result as a new matrix. +func (m1 Matrix[T]) Multiply(m2 Matrix[T]) (Matrix[T], error) { + // Check if the matrices can be multiplied. + if m1.Columns() != m2.Rows() { + return Matrix[T]{}, errors.New("matrices cannot be multiplied: column count of the first matrix must match row count of the second matrix") + } + + // Create a new matrix to store the result. + var zeroVal T + result := New(m1.Rows(), m2.Columns(), zeroVal) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // Make sure it's called to release resources even if no errors + + var wg sync.WaitGroup + errCh := make(chan error, 1) + + for i := 0; i < m1.Rows(); i++ { + for j := 0; j < m2.Columns(); j++ { + i, j := i, j // Capture the loop variable for the goroutine + wg.Add(1) + go func() { + defer wg.Done() + // Compute the dot product of the row from the first matrix and the column from the second matrix. + dotProduct := zeroVal + for k := 0; k < m1.Columns(); k++ { + select { + case <-ctx.Done(): + return // Context canceled; return without an error + default: + } + + val1, err := m1.Get(i, k) + if err != nil { + cancel() + select { + case errCh <- err: + default: + } + return + } + val2, err := m2.Get(k, j) + if err != nil { + cancel() + select { + case errCh <- err: + default: + } + return + } + dotProduct += val1 * val2 + } + err := result.Set(i, j, dotProduct) + if err != nil { + cancel() + select { + case errCh <- err: + default: + } + return + } + }() + } + } + + // Wait for all goroutines to finish + go func() { + wg.Wait() + close(errCh) + }() + + // Check for any errors + if err := <-errCh; err != nil { + return Matrix[T]{}, err + } + + return result, nil +} diff --git a/math/matrix/multiply_test.go b/math/matrix/multiply_test.go new file mode 100644 index 000000000..1a1ca39a7 --- /dev/null +++ b/math/matrix/multiply_test.go @@ -0,0 +1,101 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestMultiplyMatrix(t *testing.T) { + // Test case with compatible NULL matrices + t.Run("NULL Matrices", func(t *testing.T) { + mat1 := matrix.New(0, 0, 0) + mat2 := matrix.New(0, 0, 0) + + expected := matrix.New(0, 0, 0) + result, err := mat1.Multiply(mat2) + if err != nil { + t.Errorf("Expected no error, got %v", err) + } else if !result.CheckEqual(expected) { + t.Errorf("Result matrix does not match the expected result.") + } + + }) + // Test case with compatible matrices + t.Run("Compatible Matrices", func(t *testing.T) { + mat1 := [][]int{{1, 2, 3}, {4, 5, 6}} + mat2 := [][]int{{7, 8}, {9, 10}, {11, 12}} + m1, err := matrix.NewFromElements(mat1) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + m2, err := matrix.NewFromElements(mat2) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + exp := [][]int{{58, 64}, {139, 154}} + expected, err := matrix.NewFromElements(exp) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + result, err := m1.Multiply(m2) + if err != nil { + t.Errorf("Expected no error, got %v", err) + } else if !result.CheckEqual(expected) { + t.Errorf("Result matrix does not match the expected result.") + } + + }) + +} + +func TestMultiplyIncompatibleMatrix(t *testing.T) { + // Test case with incompatible matrices + t.Run("Incompatible Matrices", func(t *testing.T) { + mat1 := [][]int{{1, 2, 3}, {4, 5, 6}} + mat2 := [][]int{{7, 8}, {9, 10}} + m1, err := matrix.NewFromElements(mat1) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + m2, err := matrix.NewFromElements(mat2) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + + _, err = m1.Multiply(m2) + if err == nil { + t.Error("Expected an error, but got none") + } + }) + + t.Run("Incompatible Matrices", func(t *testing.T) { + mat1 := [][]int{{1, 2}} + mat2 := [][]int{{}} + m1, err := matrix.NewFromElements(mat1) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + m2, err := matrix.NewFromElements(mat2) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + _, err = m1.Multiply(m2) + + if err == nil { + t.Error("Expected an error, but got none") + } + }) +} + +func BenchmarkMatrixMultiply(b *testing.B) { + // Create sample matrices for benchmarking + rows := 10 + columns := 10 + m1 := matrix.New(rows, columns, 2) // Replace with appropriate values + m2 := matrix.New(rows, columns, 3) // Replace with appropriate values + + for i := 0; i < b.N; i++ { + _, _ = m1.Multiply(m2) + } +} diff --git a/math/matrix/strassenmatrixmultiply.go b/math/matrix/strassenmatrixmultiply.go new file mode 100644 index 000000000..86fb47809 --- /dev/null +++ b/math/matrix/strassenmatrixmultiply.go @@ -0,0 +1,227 @@ +// filename: strassenmatrixmultiply.go +// description: Implements matrix multiplication using the Strassen algorithm. +// details: +// This program takes two matrices as input and performs matrix multiplication +// using the Strassen algorithm, which is an optimized divide-and-conquer +// approach. It allows for efficient multiplication of large matrices. +// author(s): Mohit Raghav(https://github.com/mohit07raghav19) +// See strassenmatrixmultiply_test.go for test cases +package matrix + +// Perform matrix multiplication using Strassen's algorithm +func (A Matrix[T]) StrassenMatrixMultiply(B Matrix[T]) (Matrix[T], error) { + n := A.rows + // Check if matrices are 2x2 or smaller + if n == 1 { + a1, err := A.Get(0, 0) + if err != nil { + return Matrix[T]{}, err + } + b1, err := B.Get(0, 0) + if err != nil { + return Matrix[T]{}, err + } + result := New(1, 1, a1*b1) + return result, nil + } else { + // Calculate the size of submatrices + mid := n / 2 + + // Create submatrices + A11, err := A.SubMatrix(0, 0, mid, mid) + if err != nil { + return Matrix[T]{}, err + } + A12, err := A.SubMatrix(0, mid, mid, n-mid) + if err != nil { + return Matrix[T]{}, err + } + A21, err := A.SubMatrix(mid, 0, n-mid, mid) + if err != nil { + return Matrix[T]{}, err + } + A22, err := A.SubMatrix(mid, mid, n-mid, n-mid) + if err != nil { + return Matrix[T]{}, err + } + + B11, err := B.SubMatrix(0, 0, mid, mid) + if err != nil { + return Matrix[T]{}, err + } + B12, err := B.SubMatrix(0, mid, mid, n-mid) + if err != nil { + return Matrix[T]{}, err + } + B21, err := B.SubMatrix(mid, 0, n-mid, mid) + if err != nil { + return Matrix[T]{}, err + } + B22, err := B.SubMatrix(mid, mid, n-mid, n-mid) + if err != nil { + return Matrix[T]{}, err + } + + // Calculate result submatrices + A1, err := A11.Add(A22) + if err != nil { + return Matrix[T]{}, err + } + + A2, err := B11.Add(B22) + if err != nil { + return Matrix[T]{}, err + } + + A3, err := A21.Add(A22) + if err != nil { + return Matrix[T]{}, err + } + + A4, err := A11.Add(A12) + if err != nil { + return Matrix[T]{}, err + } + + A5, err := B11.Add(B12) + if err != nil { + return Matrix[T]{}, err + } + + A6, err := B21.Add(B22) + if err != nil { + return Matrix[T]{}, err + } + // + S1, err := B12.Subtract(B22) + if err != nil { + return Matrix[T]{}, err + } + S2, err := B21.Subtract(B11) + if err != nil { + return Matrix[T]{}, err + } + S3, err := A21.Subtract(A11) + if err != nil { + return Matrix[T]{}, err + } + S4, err := A12.Subtract(A22) + if err != nil { + return Matrix[T]{}, err + } + // Recursive steps + M1, err := A1.StrassenMatrixMultiply(A2) + if err != nil { + return Matrix[T]{}, err + } + M2, err := A3.StrassenMatrixMultiply(B11) + if err != nil { + return Matrix[T]{}, err + } + M3, err := A11.StrassenMatrixMultiply(S1) + if err != nil { + return Matrix[T]{}, err + } + M4, err := A22.StrassenMatrixMultiply(S2) + if err != nil { + return Matrix[T]{}, err + } + M5, err := A4.StrassenMatrixMultiply(B22) + if err != nil { + return Matrix[T]{}, err + } + M6, err := S3.StrassenMatrixMultiply(A5) + if err != nil { + return Matrix[T]{}, err + } + M7, err := S4.StrassenMatrixMultiply(A6) + + if err != nil { + return Matrix[T]{}, err + } // + A7, err := M1.Add(M4) + + if err != nil { + return Matrix[T]{}, err + } + A8, err := A7.Add(M7) + + if err != nil { + return Matrix[T]{}, err + } + A9, err := M1.Add(M3) + + if err != nil { + return Matrix[T]{}, err + } + A10, err := A9.Add(M6) + + if err != nil { + return Matrix[T]{}, err + } + // Calculate result submatrices + C11, err := A8.Subtract(M5) + if err != nil { + return Matrix[T]{}, err + } + C12, err := M3.Add(M5) + if err != nil { + return Matrix[T]{}, err + } + C21, err := M2.Add(M4) + if err != nil { + return Matrix[T]{}, err + } + C22, err := A10.Subtract(M2) + if err != nil { + return Matrix[T]{}, err + } + + // Combine subMatrices into the result matrix + var zeroVal T + C := New(n, n, zeroVal) + + for i := 0; i < mid; i++ { + for j := 0; j < mid; j++ { + val, err := C11.Get(i, j) + if err != nil { + return Matrix[T]{}, err + } + + err = C.Set(i, j, val) + if err != nil { + return Matrix[T]{}, err + } + + val, err = C12.Get(i, j) + if err != nil { + return Matrix[T]{}, err + } + + err1 := C.Set(i, j+mid, val) + if err1 != nil { + return Matrix[T]{}, err1 + } + val, err = C21.Get(i, j) + if err != nil { + return Matrix[T]{}, err + } + + err2 := C.Set(i+mid, j, val) + if err2 != nil { + return Matrix[T]{}, err2 + } + val, err = C22.Get(i, j) + if err != nil { + return Matrix[T]{}, err + } + + err3 := C.Set(i+mid, j+mid, val) + if err3 != nil { + return Matrix[T]{}, err3 + } + } + } + return C, nil + } +} diff --git a/math/matrix/strassenmatrixmultiply_test.go b/math/matrix/strassenmatrixmultiply_test.go new file mode 100644 index 000000000..a3e58d87a --- /dev/null +++ b/math/matrix/strassenmatrixmultiply_test.go @@ -0,0 +1,131 @@ +package matrix_test + +import ( + "math/rand" + "testing" + "time" + + "github.com/TheAlgorithms/Go/constraints" + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestStrassenMatrixMultiply(t *testing.T) { + // Create two sample matrices + dataA := [][]int{{1, 2}, {4, 5}} + dataB := [][]int{{9, 8}, {6, 5}} + matrixA, err := matrix.NewFromElements(dataA) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + matrixB, err := matrix.NewFromElements(dataB) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + + // Perform matrix multiplication using Strassen's algorithm + resultMatrix, err := matrixA.StrassenMatrixMultiply(matrixB) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + + // Expected result + expectedData, err := matrixA.Multiply(matrixB) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + + // Check the dimensions of the result matrix + expectedRows := expectedData.Rows() + expectedColumns := expectedData.Columns() + rows := resultMatrix.Rows() + columns := resultMatrix.Columns() + + if rows != expectedRows { + t.Errorf("Expected %d rows in result matrix, but got %d", expectedRows, rows) + } + + if columns != expectedColumns { + t.Errorf("Expected %d columns in result matrix, but got %d", expectedColumns, columns) + } + + // Check the values in the result matrix + for i := 0; i < expectedRows; i++ { + for j := 0; j < expectedColumns; j++ { + val, err := resultMatrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + expVal, err := expectedData.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + if val != expVal { + t.Errorf("Expected value %d at (%d, %d) in result matrix, but got %d", expVal, i, j, val) + } + } + } +} +func TestMatrixMultiplication(t *testing.T) { + rand.Seed(time.Now().UnixNano()) + + // Generate random matrices for testing + size := 1 << (rand.Intn(8) + 1) // tests for matrix with n as power of 2 + matrixA := MakeRandomMatrix[int](size, size) + matrixB := MakeRandomMatrix[int](size, size) + + // Calculate the expected result using the standard multiplication + expected, err := matrixA.Multiply(matrixB) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + // Calculate the result using the Strassen algorithm + result, err := matrixA.StrassenMatrixMultiply(matrixB) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + + // Check if the result matches the expected result + for i := 0; i < size; i++ { + for j := 0; j < size; j++ { + val, err := result.Get(i, j) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + exp, err := expected.Get(i, j) + if err != nil { + t.Error("copyMatrix.Set error: " + err.Error()) + } + if val != exp { + t.Errorf("Mismatch at position (%d, %d). Expected %d, but got %d.", i, j, exp, val) + } + } + } +} + +func MakeRandomMatrix[T constraints.Integer](rows, columns int) matrix.Matrix[T] { + rand.Seed(time.Now().UnixNano()) + + matrixData := make([][]T, rows) + for i := 0; i < rows; i++ { + matrixData[i] = make([]T, columns) + for j := 0; j < columns; j++ { + matrixData[i][j] = T(rand.Intn(1000)) // Generate random integers between 0 and 1000 + } + } + + randomMatrix, _ := matrix.NewFromElements(matrixData) + return randomMatrix +} + +// BenchmarkStrassenMatrixMultiply benchmarks the StrassenMatrixMultiply function. +func BenchmarkStrassenMatrixMultiply(b *testing.B) { + // Create sample matrices for benchmarking + rows := 64 // it is large enough for multiplication + columns := 64 + m1 := matrix.New(rows, columns, 2) // Replace with appropriate values + m2 := matrix.New(rows, columns, 3) // Replace with appropriate values + + for i := 0; i < b.N; i++ { + _, _ = m1.StrassenMatrixMultiply(m2) + } +} diff --git a/math/matrix/string.go b/math/matrix/string.go new file mode 100644 index 000000000..b59fe8c6c --- /dev/null +++ b/math/matrix/string.go @@ -0,0 +1,15 @@ +package matrix + +import "fmt" + +// String implements the fmt.Stringer interface for Matrix. +func (m Matrix[T]) String() string { + var result string + for i := range m.elements { + for j := range m.elements[i] { + result += fmt.Sprintf("%v ", m.elements[i][j]) + } + result += "\n" + } + return result +} diff --git a/math/matrix/string_test.go b/math/matrix/string_test.go new file mode 100644 index 000000000..59ca24510 --- /dev/null +++ b/math/matrix/string_test.go @@ -0,0 +1,96 @@ +package matrix_test + +import ( + "bytes" + "fmt" + "io" + "os" + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestMatrixString(t *testing.T) { + // Create a sample matrix for testing + m1, err := matrix.NewFromElements([][]int{{1, 2}, {3, 4}}) + if err != nil { + t.Errorf("Error creating matrix: %v", err) + } + + // Redirect stdout to capture Stringed output + old := os.Stdout + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + os.Stdout = w + + // Call the String method + fmt.Print(m1) + + // Reset stdout + w.Close() + os.Stdout = old + + // Read the captured output + var buf bytes.Buffer + _, err = io.Copy(&buf, r) + if err != nil { + t.Errorf("Error copying output: %v", err) + } + capturedOutput := buf.String() + + // Define the expected output + expectedOutput := "1 2 \n3 4 \n" + + // Compare the captured output with the expected output + if capturedOutput != expectedOutput { + t.Errorf("Matrix.Print() produced incorrect output:\n%s\nExpected:\n%s", capturedOutput, expectedOutput) + } +} + +func TestNullMatrixString(t *testing.T) { + + m1 := matrix.New(0, 0, 0) + // Redirect stdout to capture Stringed output + old := os.Stdout + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + os.Stdout = w + + // Call the String method + fmt.Print(m1) + + // Reset stdout + w.Close() + os.Stdout = old + + // Read the captured output + var buf bytes.Buffer + _, err = io.Copy(&buf, r) + if err != nil { + t.Errorf("Error copying output: %v", err) + } + capturedOutput := buf.String() + + // Define the expected output + expectedOutput := "" + + // Compare the captured output with the expected output + if capturedOutput != expectedOutput { + t.Errorf("Matrix.Print() produced incorrect output:\n%s\nExpected:\n%s", capturedOutput, expectedOutput) + } +} + +func BenchmarkString(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + m := matrix.New(rows, columns, 0) // Replace with appropriate values + + for i := 0; i < b.N; i++ { + _ = m.String() + } +} diff --git a/math/matrix/submatrix.go b/math/matrix/submatrix.go new file mode 100644 index 000000000..4d636e2c0 --- /dev/null +++ b/math/matrix/submatrix.go @@ -0,0 +1,79 @@ +package matrix + +import ( + "context" + "errors" + "sync" +) + +// SubMatrix extracts a submatrix from the current matrix. +func (m Matrix[T]) SubMatrix(rowStart, colStart, numRows, numCols int) (Matrix[T], error) { + if rowStart < 0 || colStart < 0 || numRows < 0 || numCols < 0 { + return Matrix[T]{}, errors.New("negative dimensions are not allowed") + } + + if rowStart+numRows > m.rows || colStart+numCols > m.columns { + return Matrix[T]{}, errors.New("submatrix dimensions exceed matrix bounds") + } + + var zeroVal T + if numRows == 0 || numCols == 0 { + return New(numRows, numCols, zeroVal), nil // Return an empty matrix + } + + subMatrix := New(numRows, numCols, zeroVal) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // Make sure it's called to release resources even if no errors + + var wg sync.WaitGroup + errCh := make(chan error, 1) + + for i := 0; i < numRows; i++ { + i := i // Capture the loop variable for the goroutine + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < numCols; j++ { + select { + case <-ctx.Done(): + return // Context canceled; return without an error + default: + } + + val, err := m.Get(rowStart+i, colStart+j) + if err != nil { + cancel() + select { + case errCh <- err: + default: + } + return + } + + err = subMatrix.Set(i, j, val) + if err != nil { + cancel() + select { + case errCh <- err: + default: + } + return + } + } + }() + } + + // Wait for all goroutines to finish + go func() { + wg.Wait() + close(errCh) + }() + + // Check for any errors + if err := <-errCh; err != nil { + return Matrix[T]{}, err + } + + return subMatrix, nil +} diff --git a/math/matrix/submatrix_test.go b/math/matrix/submatrix_test.go new file mode 100644 index 000000000..09452496d --- /dev/null +++ b/math/matrix/submatrix_test.go @@ -0,0 +1,88 @@ +package matrix_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestMatrixSubMatrix(t *testing.T) { + // Create a sample matrix + data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + matrix, err := matrix.NewFromElements(data) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + // Extract a submatrix + subMatrix, err := matrix.SubMatrix(1, 1, 2, 2) + if err != nil { + t.Errorf("Error extracting submatrix: %v", err) + } + + // Check the dimensions of the submatrix + expectedRows := 2 + expectedColumns := 2 + rows := subMatrix.Rows() + columns := subMatrix.Columns() + + if rows != expectedRows { + t.Errorf("Expected %d rows in submatrix, but got %d", expectedRows, rows) + } + + if columns != expectedColumns { + t.Errorf("Expected %d columns in submatrix, but got %d", expectedColumns, columns) + } + + // Check the values in the submatrix + expectedData := [][]int{{5, 6}, {8, 9}} + for i := 0; i < expectedRows; i++ { + for j := 0; j < expectedColumns; j++ { + val, err := subMatrix.Get(i, j) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + if val != expectedData[i][j] { + t.Errorf("Expected value %d at (%d, %d) in submatrix, but got %d", expectedData[i][j], i, j, val) + } + } + } +} + +func TestMatrixInvalidSubMatrix(t *testing.T) { + // Create a sample matrix + data := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} + matrix, err := matrix.NewFromElements(data) + if err != nil { + t.Fatalf("Failed to copy matrix: %v", err) + } + // Attempt to extract an invalid submatrix + _, err = matrix.SubMatrix(1, 1, 3, 3) + + // Check if an error is returned + if err == nil { + t.Error("Expected an error for invalid submatrix dimensions, but got nil") + } + + // Check the error message + expectedErrorMessage := "submatrix dimensions exceed matrix bounds" + if err.Error() != expectedErrorMessage { + t.Errorf("Expected error message '%s', but got '%s'", expectedErrorMessage, err.Error()) + } +} + +// BenchmarkSubMatrix benchmarks the SubMatrix function. +func BenchmarkSubMatrix(b *testing.B) { + // Create a sample matrix for benchmarking + rows := 100 + columns := 100 + matrix := matrix.New(rows, columns, 2) // Replace with appropriate values + + rowStart := 10 + colStart := 10 + numRows := 20 + numCols := 20 + + for i := 0; i < b.N; i++ { + _, _ = matrix.SubMatrix(rowStart, colStart, numRows, numCols) + } +} diff --git a/math/matrix/subtract.go b/math/matrix/subtract.go new file mode 100644 index 000000000..761a7ed8c --- /dev/null +++ b/math/matrix/subtract.go @@ -0,0 +1,64 @@ +package matrix + +import ( + "context" + "errors" + "sync" +) + +// Subtract subtracts two matrices. +func (m1 Matrix[T]) Subtract(m2 Matrix[T]) (Matrix[T], error) { + // Check if the matrices have the same dimensions. + if !m1.MatchDimensions(m2) { + return Matrix[T]{}, errors.New("matrices are not compatible for subtraction") + } + + // Create a new matrix to store the result. + var zeroVal T + result := New(m1.Rows(), m1.Columns(), zeroVal) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() // Make sure it's called to release resources even if no errors + + var wg sync.WaitGroup + errCh := make(chan error, 1) + + for i := 0; i < m1.rows; i++ { + i := i // Capture the loop variable for the goroutine + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < m1.columns; j++ { + select { + case <-ctx.Done(): + return // Context canceled; return without an error + default: + } + + diff := m1.elements[i][j] - m2.elements[i][j] + err := result.Set(i, j, diff) + if err != nil { + cancel() // Cancel the context on error + select { + case errCh <- err: + default: + } + return + } + } + }() + } + + // Wait for all goroutines to finish + go func() { + wg.Wait() + close(errCh) + }() + + // Check for any errors + if err := <-errCh; err != nil { + return Matrix[T]{}, err + } + + return result, nil +} diff --git a/math/matrix/subtract_test.go b/math/matrix/subtract_test.go new file mode 100644 index 000000000..827d5c9e3 --- /dev/null +++ b/math/matrix/subtract_test.go @@ -0,0 +1,50 @@ +package matrix_test + +import ( + "fmt" + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +func TestSubtract(t *testing.T) { + // Create two matrices with the same dimensions for Subtraction + m1 := matrix.New(2, 2, 1) + m2 := matrix.New(2, 2, 2) + + // Test case 1: Valid matrix Subtraction + subMatrix, err := m1.Subtract(m2) + if err != nil { + t.Errorf("Add(m1, m2) returned an error: %v, expected no error", err) + } + expectedMatrix := matrix.New(2, 2, -1) + res := subMatrix.CheckEqual(expectedMatrix) + if !res { + t.Errorf("Add(m1, m2) returned incorrect result:\n%v\nExpected:\n%v", subMatrix, expectedMatrix) + } + + // Create two matrices with different dimensions for Subtraction + m3 := matrix.New(2, 2, 1) + m4 := matrix.New(2, 3, 2) + + // Test case 2: Matrices with different dimensions + _, err2 := m3.Subtract(m4) + expectedError2 := fmt.Errorf("matrices are not compatible for subtraction") + if err2 == nil || err2.Error() != expectedError2.Error() { + t.Errorf("m3.Subtract(m4) returned error: %v, expected error: %v", err2, expectedError2) + } + +} + +// BenchmarkSubtract benchmarks the Subtract function. +func BenchmarkSubtract(b *testing.B) { + // Create sample matrices for benchmarking + rows := 100 + columns := 100 + m1 := matrix.New(rows, columns, 2) // Replace with appropriate values + m2 := matrix.New(rows, columns, 3) // Replace with appropriate values + + for i := 0; i < b.N; i++ { + _, _ = m1.Subtract(m2) + } +} From e33cfa9fc9ebb88db11cff9514c2605aeb0b07d0 Mon Sep 17 00:00:00 2001 From: Stanislav Zeman Date: Fri, 27 Oct 2023 19:43:25 +0200 Subject: [PATCH 155/202] feat: add Timsort sorting algorithm (#692) * feat: add timsort sorting algorithm implementation * test: add timsort sorting algorithm to tests * chore: remove left-over print statement * refactor: change insertionSortRun temp variable name * docs: add concise documentation to timsort algorithm * refactor: reuse insertion sort algorithm * refactor: reuse merge sort algorithm helper function * refactor: remove slice copying in merge run --------- Co-authored-by: Taj --- sort/sorts_test.go | 10 ++++++- sort/timsort.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 sort/timsort.go diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 0fd0a93fe..63ca010e0 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -186,7 +186,11 @@ func TestCycle(t *testing.T) { testFramework(t, sort.Cycle[int]) } -//END TESTS +func TestTimsort(t *testing.T) { + testFramework(t, sort.Timsort[int]) +} + +// END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { var sortTests = []struct { @@ -320,3 +324,7 @@ func BenchmarkPatience(b *testing.B) { func BenchmarkCycle(b *testing.B) { benchmarkFramework(b, sort.Cycle[int]) } + +func BenchmarkTimsort(b *testing.B) { + benchmarkFramework(b, sort.Timsort[int]) +} diff --git a/sort/timsort.go b/sort/timsort.go new file mode 100644 index 000000000..95520219a --- /dev/null +++ b/sort/timsort.go @@ -0,0 +1,71 @@ +// Implementation of Timsort algorithm +// Reference: https://en.wikipedia.org/wiki/Timsort + +package sort + +import ( + "github.com/TheAlgorithms/Go/constraints" +) + +const runSizeThreshold = 8 + +// Timsort is a simple generic implementation of Timsort algorithm. +func Timsort[T constraints.Ordered](data []T) []T { + runSize := calculateRunSize(len(data)) + insertionSortRuns(data, runSize) + mergeRuns(data, runSize) + return data +} + +// calculateRunSize returns a run size parameter that is further used +// to slice the data slice. +func calculateRunSize(dataLength int) int { + remainder := 0 + for dataLength >= runSizeThreshold { + if dataLength%2 == 1 { + remainder = 1 + } + + dataLength = dataLength / 2 + } + + return dataLength + remainder +} + +// insertionSortRuns runs insertion sort on all the data runs one by one. +func insertionSortRuns[T constraints.Ordered](data []T, runSize int) { + for lower := 0; lower < len(data); lower += runSize { + upper := lower + runSize + if upper >= len(data) { + upper = len(data) + } + + Insertion(data[lower:upper]) + } +} + +// mergeRuns merge sorts all the data runs into a single sorted data slice. +func mergeRuns[T constraints.Ordered](data []T, runSize int) { + for size := runSize; size < len(data); size *= 2 { + for lowerBound := 0; lowerBound < len(data); lowerBound += size * 2 { + middleBound := lowerBound + size - 1 + upperBound := lowerBound + 2*size - 1 + if len(data)-1 < upperBound { + upperBound = len(data) - 1 + } + + mergeRun(data, lowerBound, middleBound, upperBound) + } + } +} + +// mergeRun uses merge sort to sort adjacent data runs. +func mergeRun[T constraints.Ordered](data []T, lower, mid, upper int) { + left := data[lower : mid+1] + right := data[mid+1 : upper+1] + merged := merge(left, right) + // rewrite original data slice values with sorted values from merged slice + for i, value := range merged { + data[lower+i] = value + } +} From 75c49510b49879c736af3b8d21cc942e1a028162 Mon Sep 17 00:00:00 2001 From: Kiarash Hajian <133909368+kiarash8112@users.noreply.github.com> Date: Wed, 8 Nov 2023 07:18:29 +0330 Subject: [PATCH 156/202] feat: graph cycle detection (#689) * feat: add HasCycle algorithm * feat: add FindAllCycles algorithm * docs: add comments to findAllCycles and HasCycle algorithm * test: add test for hasCycle Algorithm * test: add test for FindAllCycles Algorithm * hide imp detail for pkg out side graph/cycle.go Co-authored-by: Taj * hide imp detail for pkg out side graph/cycle.go Co-authored-by: Taj * feat: change FindAllcycles return type to graph * test: update findAllcycles tests * fix: fix HasCycle docs dictation --------- Co-authored-by: user Co-authored-by: Taj --- graph/cycle.go | 110 ++++++++++++++++++++++++++++++++++++++++++++ graph/cycle_test.go | 53 +++++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 graph/cycle.go create mode 100644 graph/cycle_test.go diff --git a/graph/cycle.go b/graph/cycle.go new file mode 100644 index 000000000..cf45d1854 --- /dev/null +++ b/graph/cycle.go @@ -0,0 +1,110 @@ +// cycle.go +// this file handle algorithm that related to cycle in graph +// reference: https://en.wikipedia.org/wiki/Cycle_(graph_theory) +// [kiarash hajian](https://github.com/kiarash8112) + +package graph + +func (g *Graph) HasCycle() bool { + //this implimetation referred as 3-color too + all := map[int]struct{}{} + visiting := map[int]struct{}{} + visited := map[int]struct{}{} + + for v := range g.edges { + all[v] = struct{}{} + } + + for current := range all { + if g.hasCycleHelper(current, all, visiting, visited) { + return true + } + } + + return false + +} + +func (g Graph) hasCycleHelper(v int, all, visiting, visited map[int]struct{}) bool { + delete(all, v) + visiting[v] = struct{}{} + + neighbors := g.edges[v] + for v := range neighbors { + if _, ok := visited[v]; ok { + continue + } else if _, ok := visiting[v]; ok { + return true + } else if g.hasCycleHelper(v, all, visiting, visited) { + return true + } + } + delete(visiting, v) + visited[v] = struct{}{} + return false +} + +// this function can do HasCycle() job but it is slower +func (g *Graph) FindAllCycles() []Graph { + all := map[int]struct{}{} + visiting := map[int]struct{}{} + visited := map[int]struct{}{} + + allCycles := []Graph{} + + for v := range g.edges { + all[v] = struct{}{} + } + + for current := range all { + foundCycle, parents := g.findAllCyclesHelper(current, all, visiting, visited) + + if foundCycle { + foundCycleFromCurrent := false + //this loop remove additional vertex from detected cycle + //using foundCycleFromCurrent bool to make sure after removing vertex we still have cycle + for i := len(parents) - 1; i > 0; i-- { + if parents[i][1] == parents[0][0] { + parents = parents[:i+1] + foundCycleFromCurrent = true + } + } + if foundCycleFromCurrent { + graph := Graph{Directed: true} + for _, edges := range parents { + graph.AddEdge(edges[1], edges[0]) + } + allCycles = append(allCycles, graph) + } + + } + + } + + return allCycles + +} + +func (g Graph) findAllCyclesHelper(current int, all, visiting, visited map[int]struct{}) (bool, [][]int) { + parents := [][]int{} + + delete(all, current) + visiting[current] = struct{}{} + + neighbors := g.edges[current] + for v := range neighbors { + if _, ok := visited[v]; ok { + continue + } else if _, ok := visiting[v]; ok { + parents = append(parents, []int{v, current}) + return true, parents + } else if ok, savedParents := g.findAllCyclesHelper(v, all, visiting, visited); ok { + parents = append(parents, savedParents...) + parents = append(parents, []int{v, current}) + return true, parents + } + } + delete(visiting, current) + visited[current] = struct{}{} + return false, parents +} diff --git a/graph/cycle_test.go b/graph/cycle_test.go new file mode 100644 index 000000000..0ac7dfdbe --- /dev/null +++ b/graph/cycle_test.go @@ -0,0 +1,53 @@ +package graph + +import ( + "testing" +) + +func TestHasCycle(t *testing.T) { + graph := Graph{Directed: true} + edges := [][]int{{0, 1}, {1, 2}, {2, 0}, {4, 0}} + for _, edge := range edges { + graph.AddEdge(edge[0], edge[1]) + } + if !graph.HasCycle() { + t.Error("answer of hasCycle is not correct") + } + + graph = Graph{Directed: true} + edges = [][]int{{0, 1}, {1, 2}, {2, 6}, {4, 0}} + for _, edge := range edges { + graph.AddEdge(edge[0], edge[1]) + } + if graph.HasCycle() { + t.Error("answer of hasCycle is not correct") + } +} + +func TestFindAllCycles(t *testing.T) { + graph := Graph{Directed: true} + edges := [][]int{{0, 4}, {1, 3}, {2, 3}, {3, 4}, {4, 7}, {5, 2}, {6, 3}, {7, 3}} + for _, edge := range edges { + graph.AddEdge(edge[0], edge[1]) + } + + res := graph.FindAllCycles() + + if len(res) != 1 { + t.Error("number of cycles is not correct") + } + + firstCycle := res[0] + if len(firstCycle.edges) != 3 { + t.Error("number of vertex in cycle is not correct") + } + if _, ok := firstCycle.edges[3][4]; !ok { + t.Error("connection in cycle is not correct") + } + if _, ok := firstCycle.edges[4][7]; !ok { + t.Error("connection in cycle is not correct") + } + if _, ok := firstCycle.edges[7][3]; !ok { + t.Error("connection in cycle is not correct") + } +} From 5f887c50157f5b62113705be00c64566790db41d Mon Sep 17 00:00:00 2001 From: ")`(-@_.+_^*__*^" <55359898+11-aryan@users.noreply.github.com> Date: Sat, 11 Nov 2023 22:51:32 +0530 Subject: [PATCH 157/202] Added description for the NewSegmentTree function (#691) * Added description for the NewSegmentTree function * Fixed spelling errors and formatting issues * modified comments to comply with go docs * fixed spelling errors * fixed grammatical errors in comments --------- Co-authored-by: Rak Laptudirm --- structure/segmenttree/segmenttree.go | 39 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/structure/segmenttree/segmenttree.go b/structure/segmenttree/segmenttree.go index b55f69f0e..bf70f4522 100644 --- a/structure/segmenttree/segmenttree.go +++ b/structure/segmenttree/segmenttree.go @@ -1,9 +1,9 @@ -//Segment Tree Data Structure for Range Queries -//Build: O(n*log(n)) -//Query: O(log(n)) -//Update: O(log(n)) -//reference: https://cp-algorithms.com/data_structures/segment_tree.html - +// Segment Tree Data Structure for efficient range queries on an array of integers. +// It can query the sum and update the elements to a new value of any range of the array. +// Build: O(n*log(n)) +// Query: O(log(n)) +// Update: O(log(n)) +// reference: https://cp-algorithms.com/data_structures/segment_tree.html package segmenttree import ( @@ -13,14 +13,14 @@ import ( const emptyLazyNode = 0 -// SegmentTree with original Array and the Segment Tree Array +// SegmentTree represents the data structure of a segment tree with lazy propagation type SegmentTree struct { - Array []int - SegmentTree []int - LazyTree []int + Array []int // The original array + SegmentTree []int // Stores the sum of different ranges + LazyTree []int // Stores the values of lazy propagation } -// Propagate lazy tree node values +// Propagate propagates the lazy updates to the child nodes func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) { if s.LazyTree[node] != emptyLazyNode { //add lazy node value multiplied by (right-left+1), which represents all interval @@ -42,8 +42,8 @@ func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) { } } -// Query on interval [firstIndex, leftIndex] -// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 +// Query returns the sum of elements of the array in the interval [firstIndex, leftIndex]. +// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively. func (s *SegmentTree) Query(node int, leftNode int, rightNode int, firstIndex int, lastIndex int) int { if (firstIndex > lastIndex) || (leftNode > rightNode) { //outside the interval @@ -67,10 +67,9 @@ func (s *SegmentTree) Query(node int, leftNode int, rightNode int, firstIndex in return leftNodeSum + rightNodeSum } -// Update Segment Tree -// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 -// index is the Array index that you want to update -// value is the value that you want to override +// Update updates the elements of the array in the range [firstIndex, lastIndex] +// with the new value provided and recomputes the sum of different ranges. +// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively. func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex int, lastIndex int, value int) { //propagate lazy tree s.Propagate(node, leftNode, rightNode) @@ -96,8 +95,8 @@ func (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex i } } -// Build Segment Tree -// node, leftNode and rightNode always should start with 1, 0 and len(Array)-1 +// Build builds the SegmentTree by computing the sum of different ranges. +// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively. func (s *SegmentTree) Build(node int, left int, right int) { if left == right { //leaf node @@ -113,6 +112,8 @@ func (s *SegmentTree) Build(node int, left int, right int) { } } +// NewSegmentTree returns a new instance of a SegmentTree. It takes an input +// array of integers representing Array, initializes and builds the SegmentTree. func NewSegmentTree(Array []int) *SegmentTree { if len(Array) == 0 { return nil From 48a0d570da13576d5d3ae90b029d8fd1cefae0de Mon Sep 17 00:00:00 2001 From: FanOne Date: Wed, 15 Nov 2023 21:56:22 +0800 Subject: [PATCH 158/202] feat:add lfu cache alogrithm (#695) * feat:add lfu cache alogrithm * feat:add the functions and types of LFU in README.md * fix: unexport initItem func --------- Co-authored-by: Taj --- README.md | 8 ++- cache/lfu.go | 127 ++++++++++++++++++++++++++++++++++++++++++++++ cache/lfu_test.go | 58 +++++++++++++++++++++ cache/lru.go | 3 ++ 4 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 cache/lfu.go create mode 100644 cache/lfu_test.go diff --git a/README.md b/README.md index 4837c61f4..938aaa548 100644 --- a/README.md +++ b/README.md @@ -89,12 +89,16 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. ##### Functions: -1. [`NewLRU`](./cache/lru.go#L20): NewLRU represent initiate lru cache with capacity +1. [`NewLRU`](./cache/lru.go#L22): NewLRU represent initiate lru cache with capacity +2. [`NewLFU`](./cache/lfu.go#L33): NewLFU represent initiate lfu cache with capacity +3. [`Get`](./cache/lfu.go#L52): Get the value by key from LFU cache +4. [`Put`](./cache/lfu.go#L66): Put the key and value in LFU cache --- ##### Types -1. [`LRU`](./cache/lru.go#L12): No description provided. +1. [`LRU`](./cache/lru.go#L15): Default the struct of lru cache algorithm. +2. [`LFU`](./cache/lfu.go#L19): Default the struct of lfu cache algorithm. --- diff --git a/cache/lfu.go b/cache/lfu.go new file mode 100644 index 000000000..e22670c68 --- /dev/null +++ b/cache/lfu.go @@ -0,0 +1,127 @@ +// lfu.go +// description: a type of cache algorithm used to manage memory within a computer. +// details: +// The standard characteristics of this method involve the system keeping track of the number of times a block is referenced in memory. +// When the cache is full and requires more room the system will purge the item with the lowest reference frequency. +// ref: (https://en.wikipedia.org/wiki/Least_frequently_used) +// time complexity: O(N) +// space complexity: O(1) +// author: [CocaineCong](https://github.com/CocaineCong) + +package cache + +import ( + "container/list" + "math" +) + +// LFU the Least Frequently Used (LFU) page-replacement algorithm +type LFU struct { + len int // length + cap int // capacity + minFreq int // The element that operates least frequently in LFU + + // key: key of element, value: value of element + itemMap map[string]*list.Element + + // key: frequency of possible occurrences of all elements in the itemMap + // value: elements with the same frequency + freqMap map[int]*list.List +} + +// NewLFU init the LFU cache with capacity +func NewLFU(capacity int) LFU { + return LFU{ + len: 0, + cap: capacity, + minFreq: math.MaxInt, + itemMap: make(map[string]*list.Element), + freqMap: make(map[int]*list.List), + } +} + +// initItem to init item for LFU +func initItem(k string, v any, f int) item { + return item{ + key: k, + value: v, + freq: f, + } +} + +// Get the key in cache by LFU +func (c *LFU) Get(key string) any { + // if existed, will return value + if e, ok := c.itemMap[key]; ok { + // the frequency of e +1 and change freqMap + c.increaseFreq(e) + obj := e.Value.(item) + return obj.value + } + + // if not existed, return nil + return nil +} + +// Put the key in LFU cache +func (c *LFU) Put(key string, value any) { + if e, ok := c.itemMap[key]; ok { + // if key existed, update the value + obj := e.Value.(item) + obj.value = value + c.increaseFreq(e) + } else { + // if key not existed + obj := initItem(key, value, 1) + // if the length of item gets to the top line + // remove the least frequently operated element + if c.len == c.cap { + c.eliminate() + c.len-- + } + // insert in freqMap and itemMap + c.insertMap(obj) + // change minFreq to 1 because insert the newest one + c.minFreq = 1 + // length++ + c.len++ + } +} + +// increaseFreq increase the frequency if element +func (c *LFU) increaseFreq(e *list.Element) { + obj := e.Value.(item) + // remove from low frequency first + oldLost := c.freqMap[obj.freq] + oldLost.Remove(e) + // change the value of minFreq + if c.minFreq == obj.freq && oldLost.Len() == 0 { + // if it is the last node of the minimum frequency that is removed + c.minFreq++ + } + // add to high frequency list + c.insertMap(obj) +} + +// insertMap insert item in map +func (c *LFU) insertMap(obj item) { + // add in freqMap + l, ok := c.freqMap[obj.freq] + if !ok { + l = list.New() + c.freqMap[obj.freq] = l + } + e := l.PushFront(obj) + // update or add the value of itemMap key to e + c.itemMap[obj.key] = e +} + +// eliminate clear the least frequently operated element +func (c *LFU) eliminate() { + l := c.freqMap[c.minFreq] + e := l.Back() + obj := e.Value.(item) + l.Remove(e) + + delete(c.itemMap, obj.key) +} diff --git a/cache/lfu_test.go b/cache/lfu_test.go new file mode 100644 index 000000000..7e891412f --- /dev/null +++ b/cache/lfu_test.go @@ -0,0 +1,58 @@ +package cache_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/cache" +) + +func TestLFU(t *testing.T) { + lfuCache := cache.NewLFU(3) + t.Run("Test 1: Put number and Get is correct", func(t *testing.T) { + key, value := "1", 1 + lfuCache.Put(key, value) + got := lfuCache.Get(key) + + if got != value { + t.Errorf("expected: %v, got: %v", value, got) + } + }) + + t.Run("Test 2: Get data not stored in cache should return nil", func(t *testing.T) { + got := lfuCache.Get("2") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + }) + + t.Run("Test 3: Put data over capacity and Get should return nil", func(t *testing.T) { + lfuCache.Put("2", 2) + lfuCache.Put("3", 3) + lfuCache.Put("4", 4) + + got := lfuCache.Get("1") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + }) + + t.Run("test 4: Put key over capacity but recent key exists", func(t *testing.T) { + lfuCache.Put("4", 4) + lfuCache.Put("3", 3) + lfuCache.Put("2", 2) + lfuCache.Put("1", 1) + + got := lfuCache.Get("4") + if got != nil { + t.Errorf("expected: nil, got: %v", got) + } + + expected := 3 + got = lfuCache.Get("3") + + if got != expected { + t.Errorf("expected: %v, got: %v", expected, got) + } + + }) +} diff --git a/cache/lru.go b/cache/lru.go index c6b8c734e..8c27cfc1f 100644 --- a/cache/lru.go +++ b/cache/lru.go @@ -7,6 +7,9 @@ import ( type item struct { key string value any + + // the frequency of key + freq int } type LRU struct { From 778502aaeb3a98b5825a5e944f72d00218fe849b Mon Sep 17 00:00:00 2001 From: Nabin Khanal <91933095+nabinkhanal00@users.noreply.github.com> Date: Wed, 15 Nov 2023 19:53:41 +0545 Subject: [PATCH 159/202] fixed typo (#696) Co-authored-by: Nabin Khanal Co-authored-by: Rak Laptudirm --- strings/parenthesis/parenthesis_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/strings/parenthesis/parenthesis_test.go b/strings/parenthesis/parenthesis_test.go index b7f5abd6c..685c761c4 100644 --- a/strings/parenthesis/parenthesis_test.go +++ b/strings/parenthesis/parenthesis_test.go @@ -15,17 +15,17 @@ var parenthesisTestCases = []struct { true, }, { - "three nested pharentesis with three deep level", + "three nested parenthesis with three deep level", "(-1*(5+2^(3-4)*(7.44-12)+6.66/(3.43-(1+2)))*(sqrt(3-4)))", true, }, { - "one opened pharentesis without be closed", + "one opened parenthesis without be closed", "(2*9-17)*((7+3/3)*2*(-1+4)", false, }, { - "one open pharentesis for each close one but not in pairs", + "one open parenthesis for each close one but not in pairs", "(4*(39.22-7.4)/6.77))(", false, }, @@ -35,7 +35,7 @@ var parenthesisTestCases = []struct { true, }, { - "inverted pharentesis", + "inverted parenthesis", ")()()()()(", false, }, From c1688bfe84906b05c0aa2ab2def6ee3b4451042f Mon Sep 17 00:00:00 2001 From: ")`(-@_.+_^*__*^" <55359898+11-aryan@users.noreply.github.com> Date: Sun, 10 Dec 2023 13:32:33 +0530 Subject: [PATCH 160/202] Add Fenwick Tree to Structures (#685) * Add Fenwick Tree to Structures * fixed ineffectual assignment to result * removed redundant variable declaration * fixed comments to comply with godocs --------- Co-authored-by: Taj Co-authored-by: Rak Laptudirm --- structure/fenwicktree/fenwicktree.go | 60 +++++++++++++++++ structure/fenwicktree/fenwicktree_test.go | 81 +++++++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 structure/fenwicktree/fenwicktree.go create mode 100644 structure/fenwicktree/fenwicktree_test.go diff --git a/structure/fenwicktree/fenwicktree.go b/structure/fenwicktree/fenwicktree.go new file mode 100644 index 000000000..915d7b085 --- /dev/null +++ b/structure/fenwicktree/fenwicktree.go @@ -0,0 +1,60 @@ +// Fenwick Tree Data Structure for efficient range queries on an array of integers. +// Also known as Binary Indexed Tree. It can query the sum of any range of the array and +// can update the array at a specific position by adding a value to it (point update). +// Build: O(N) +// Query: O(log(N)) +// Update: O(log(N)) +// reference: https://brilliant.org/wiki/fenwick-tree/ +package fenwicktree + +// FenwickTree represents the data structure of the Fenwick Tree +type FenwickTree struct { + n int // n: Size of the input array. + array []int // array: the input array on which queries are made. + bit []int // bit: store the sum of ranges. +} + +// NewFenwickTree creates a new Fenwick tree, initializes bit with +// the values of the array. Note that the queries and updates should have +// one based indexing. +func NewFenwickTree(array []int) *FenwickTree { + newArray := []int{0} // Appending a 0 to the beginning as this implementation uses 1 based indexing + fenwickTree := &FenwickTree{ + n: len(array), + array: append(newArray, array...), + bit: append(newArray, array...), + } + for i := 1; i < fenwickTree.n; i++ { + nextPos := i + (i & -i) + if nextPos <= fenwickTree.n { + fenwickTree.bit[nextPos] += fenwickTree.bit[i] + } + } + return fenwickTree +} + +// PrefixSum returns the sum of the prefix ending at position pos. +func (f *FenwickTree) PrefixSum(pos int) int { + if pos > f.n { + return 0 + } + prefixSum := 0 + for i := pos; i > 0; i -= (i & -i) { + prefixSum += f.bit[i] + } + return prefixSum +} + +// RangeSum returns the sum of the elements in the range l to r +// both inclusive. +func (f *FenwickTree) RangeSum(l int, r int) int { + return f.PrefixSum(r) - f.PrefixSum(l-1) +} + +// Add Adds value to the element at position pos of the array +// and recomputes the range sums. +func (f *FenwickTree) Add(pos int, value int) { + for i := pos; i <= f.n; i += (i & -i) { + f.bit[i] += value + } +} diff --git a/structure/fenwicktree/fenwicktree_test.go b/structure/fenwicktree/fenwicktree_test.go new file mode 100644 index 000000000..99c9f12fc --- /dev/null +++ b/structure/fenwicktree/fenwicktree_test.go @@ -0,0 +1,81 @@ +package fenwicktree_test + +import ( + "github.com/TheAlgorithms/Go/structure/fenwicktree" + "testing" +) + +type query struct { + queryType string + firstIndex int // firstIndex and lastIndex are same for point queries + lastIndex int +} + +type update struct { + pos int + value int +} + +func TestFenwickTree(t *testing.T) { + var fenwickTreeTestData = []struct { + description string + array []int + updates []update + queries []query + expected []int + }{ + { + description: "test empty array", + array: []int{}, + queries: []query{{"point", 1, 1}}, + expected: []int{0}, + }, + { + description: "test array with size 5", + array: []int{1, 2, 3, 4, 5}, + queries: []query{{"range", 1, 5}, {"range", 1, 3}, {"range", 3, 5}}, + expected: []int{15, 6, 12}, + }, + { + description: "test array with size 5, single index updates and range queries", + array: []int{1, 2, 3, 4, 5}, + updates: []update{{pos: 2, value: 2}, {pos: 3, value: 3}}, + queries: []query{{"range", 1, 5}, {"range", 1, 3}, {"range", 3, 5}}, + expected: []int{20, 11, 15}, + }, + { + description: "test array with size 5, single index updates and point queries", + array: []int{1, 2, 3, 4, 5}, + updates: []update{{pos: 2, value: 2}, {pos: 3, value: 3}}, + queries: []query{{"point", 3, 3}, {"point", 1, 1}, {"point", 5, 5}}, + expected: []int{11, 1, 20}, + }, + } + + for _, test := range fenwickTreeTestData { + t.Run(test.description, func(t *testing.T) { + fenwickTree := fenwicktree.NewFenwickTree(test.array) + + for i := 0; i < len(test.updates); i++ { + fenwickTree.Add(test.updates[i].pos, test.updates[i].value) + } + + for i := 0; i < len(test.queries); i++ { + + var result int + + if test.queries[i].queryType == "point" { + result = fenwickTree.PrefixSum(test.queries[i].firstIndex) + } else { + result = fenwickTree.RangeSum(test.queries[i].firstIndex, test.queries[i].lastIndex) + } + + if result != test.expected[i] { + t.Logf("FAIL: %s", test.description) + t.Fatalf("Expected result: %d\nFound: %d\n", test.expected[i], result) + } + } + }) + } + +} From dc0cb361b8c5f8250355948a3e313e837f7e362d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mert=20G=C3=B6r=20=E2=98=AD?= Date: Sun, 31 Dec 2023 09:16:26 +0300 Subject: [PATCH 161/202] Copyright Holders Update to make it more clear (#700) --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index f6bcf04e7..71b9656b7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 The Algorithms +Copyright (c) 2021 The Algorithms and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From db7c875cccfd2189afaea3cfda7313f3b83fe6b1 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 13 Jan 2024 16:25:51 +0100 Subject: [PATCH 162/202] fix: use `GITHUB_ACTOR` in `git config` (#701) --- .github/workflows/godocmd.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index 454f1a632..a4ea126ca 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -20,8 +20,8 @@ jobs: go install github.com/tjgurwara99/godocmd@v0.1.3 - name: Configure Github Action run: | - git config --global user.name github-action - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git config --global user.name "$GITHUB_ACTOR" + git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com" - name: Update README.md file run: | godocmd -r -module ./ -w From ea269222a7c1f03d9d2516740f62675526eeaea9 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Tue, 23 Jan 2024 07:00:23 +0100 Subject: [PATCH 163/202] chore: add `upload_coverage_report.yml` (#697) --- .github/workflows/upload_coverage_report.yml | 31 ++++++++++++++++++++ .gitignore | 1 + 2 files changed, 32 insertions(+) create mode 100644 .github/workflows/upload_coverage_report.yml diff --git a/.github/workflows/upload_coverage_report.yml b/.github/workflows/upload_coverage_report.yml new file mode 100644 index 000000000..2308cc871 --- /dev/null +++ b/.github/workflows/upload_coverage_report.yml @@ -0,0 +1,31 @@ +--- +name: upload_coverage_report + +on: + workflow_dispatch: + push: + branches: + - master + pull_request: + +env: + REPORT_NAME: "coverage.out" + +jobs: + upload_coverage_report: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup Go + uses: actions/setup-go@v4 + with: + go-version: '^1.18' + - name: Generate code coverage + run: | + go test -coverprofile="${{ env.REPORT_NAME }}" ./... + - name: Upload coverage to codecov + uses: codecov/codecov-action@v3 + with: + files: "${{ env.REPORT_NAME }}" + fail_ci_if_error: true +... diff --git a/.gitignore b/.gitignore index 66f8fb502..1af018398 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .idea/ .vscode/ +coverage.out From 36d29bbdcedcd47ef5af36cf1087880e66f5ec5f Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 27 Jan 2024 17:55:55 +0100 Subject: [PATCH 164/202] docs: add codecov badge (#702) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 938aaa548..1d9b007cc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # The Algorithms - Go [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Go)  [![Continuous Integration](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml/badge.svg)](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/TheAlgorithms/Go/graph/badge.svg?token=aSWh7N8tNx)](https://codecov.io/gh/TheAlgorithms/Go) ![godocmd](https://github.com/tjgurwara99/Go/workflows/godocmd/badge.svg) ![](https://img.shields.io/github/repo-size/TheAlgorithms/Go.svg?label=Repo%20size&style=flat-square)  ![update_directory_md](https://github.com/TheAlgorithms/Go/workflows/update_directory_md/badge.svg) From 6d839027b6765b7cd14b00ffdd54678bd70dc63e Mon Sep 17 00:00:00 2001 From: Taj Date: Mon, 11 Mar 2024 16:03:12 +0000 Subject: [PATCH 165/202] chore: let tjguwara99 take a break (#708) --- .github/CODEOWNERS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index d709eff88..0aec70ce1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -7,4 +7,4 @@ # Order is important. The last matching pattern has the most precedence. -* @raklaptudirm @tjgurwara99 @yanglbme +* @raklaptudirm @yanglbme From 3f2fa293d60daeea59265a124ac97427a87efbc7 Mon Sep 17 00:00:00 2001 From: jafar75 Date: Tue, 12 Mar 2024 13:22:49 +0330 Subject: [PATCH 166/202] fix: remove redundant init step for unionFind (#709) --- graph/kruskal.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/graph/kruskal.go b/graph/kruskal.go index 0543e2829..193e3f236 100644 --- a/graph/kruskal.go +++ b/graph/kruskal.go @@ -28,12 +28,6 @@ func KruskalMST(n int, edges []Edge) ([]Edge, int) { // Create a new UnionFind data structure with 'n' nodes u := NewUnionFind(n) - // Initialize each node in the UnionFind data structure - for i := 0; i < n; i++ { - u.parent[i] = i - u.size[i] = 1 - } - // Sort the edges in non-decreasing order based on their weights sort.SliceStable(edges, func(i, j int) bool { return edges[i].Weight < edges[j].Weight From 237d88f7595ca5e1be20830ea7f01fe43e93d154 Mon Sep 17 00:00:00 2001 From: Joshua Cao Date: Wed, 13 Mar 2024 00:10:32 -0700 Subject: [PATCH 167/202] feat: Add btree with insertion, deletion, and search (#703) * feat: Add btree with insertion, deletion, and search * Lazy allocate root and handle cases with null root * Fix formatting --------- Co-authored-by: Rak Laptudirm --- structure/tree/btree.go | 355 +++++++++++++++++++++++++++++++++++ structure/tree/btree_test.go | 133 +++++++++++++ 2 files changed, 488 insertions(+) create mode 100644 structure/tree/btree.go create mode 100644 structure/tree/btree_test.go diff --git a/structure/tree/btree.go b/structure/tree/btree.go new file mode 100644 index 000000000..5b2e55eb7 --- /dev/null +++ b/structure/tree/btree.go @@ -0,0 +1,355 @@ +// B-tree is a self balancing tree that promotes data locality. +// For more details, see https://en.wikipedia.org/wiki/B-tree + +package tree + +import "github.com/TheAlgorithms/Go/constraints" + +type BTreeNode[T constraints.Ordered] struct { + keys []T + children []*BTreeNode[T] + numKeys int + isLeaf bool +} + +type BTree[T constraints.Ordered] struct { + root *BTreeNode[T] + maxKeys int +} + +func minKeys(maxKeys int) int { + return (maxKeys - 1) / 2 +} + +func NewBTreeNode[T constraints.Ordered](maxKeys int, isLeaf bool) *BTreeNode[T] { + if maxKeys <= 0 { + panic("BTree maxKeys cannot be zero") + } + return &BTreeNode[T]{ + keys: make([]T, maxKeys), + children: make([]*BTreeNode[T], maxKeys+1), + isLeaf: isLeaf, + } +} + +func NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] { + if maxKeys <= 2 { + panic("Must be >= 3 keys") + } + return &BTree[T]{ + root: nil, + maxKeys: maxKeys, + } +} + +func (node *BTreeNode[T]) Verify(tree *BTree[T]) { + minKeys := minKeys(tree.maxKeys) + if node != tree.root && node.numKeys < minKeys { + panic("node has too few keys") + } else if node.numKeys > tree.maxKeys { + panic("node has too many keys") + } +} + +func (node *BTreeNode[T]) IsFull(maxKeys int) bool { + return node.numKeys == maxKeys +} + +func (node *BTreeNode[T]) Search(key T) bool { + i := 0 + for ; i < node.numKeys; i++ { + if key == node.keys[i] { + return true + } + if key < node.keys[i] { + break + } + } + if node.isLeaf { + return false + } + return node.children[i].Search(key) +} + +func (tree *BTree[T]) Search(key T) bool { + if tree.root == nil { + return false + } + return tree.root.Search(key) +} + +func (node *BTreeNode[T]) InsertKeyChild(key T, child *BTreeNode[T]) { + i := node.numKeys + node.children[i+1] = node.children[i] + for ; i > 0; i-- { + if key > node.keys[i-1] { + node.keys[i] = key + node.children[i] = child + break + } + node.keys[i] = node.keys[i-1] + node.children[i] = node.children[i-1] + } + if i == 0 { + node.keys[0] = key + node.children[0] = child + } + node.numKeys++ +} + +func (node *BTreeNode[T]) Append(key T, child *BTreeNode[T]) { + node.keys[node.numKeys] = key + node.children[node.numKeys+1] = child + node.numKeys++ +} + +// Add all of other's keys starting from idx and children starting from idx + 1 +func (node *BTreeNode[T]) Concat(other *BTreeNode[T], idx int) { + for i := 0; i < other.numKeys-idx; i++ { + node.keys[node.numKeys+i] = other.keys[i+idx] + node.children[node.numKeys+i+1] = other.children[i+idx+1] + } + node.numKeys += other.numKeys - idx +} + +// Transform: +// +// A B +// | +// +// a b c d +// +// Into: +// +// A c B +// / \ +// +// a b d +func (parent *BTreeNode[T]) Split(idx int, maxKeys int) { + child := parent.children[idx] + midKeyIndex := maxKeys / 2 + rightChild := NewBTreeNode[T](maxKeys, child.isLeaf) + rightChild.Concat(child, midKeyIndex+1) + rightChild.children[0] = child.children[midKeyIndex+1] + + // Reuse child as the left node + child.numKeys = midKeyIndex + + // Insert the child's mid index to the parent + for i := parent.numKeys; i > idx; i-- { + parent.keys[i] = parent.keys[i-1] + parent.children[i+1] = parent.children[i] + } + parent.keys[idx] = child.keys[midKeyIndex] + parent.children[idx] = child + parent.children[idx+1] = rightChild + parent.numKeys += 1 +} + +func (node *BTreeNode[T]) InsertNonFull(tree *BTree[T], key T) { + node.Verify(tree) + if node.IsFull(tree.maxKeys) { + panic("Called InsertNonFull() with a full node") + } + + if node.isLeaf { + // Node is a leaf. Directly insert the key. + node.InsertKeyChild(key, nil) + return + } + + // Find the child node to insert into + i := 0 + for ; i < node.numKeys; i++ { + if key < node.keys[i] { + break + } + } + + if node.children[i].IsFull(tree.maxKeys) { + node.Split(i, tree.maxKeys) + if key > node.keys[i] { + i++ + } + } + node.children[i].InsertNonFull(tree, key) +} + +func (tree *BTree[T]) Insert(key T) { + if tree.root == nil { + tree.root = NewBTreeNode[T](tree.maxKeys, true) + tree.root.keys[0] = key + tree.root.numKeys = 1 + return + } + + if tree.root.IsFull(tree.maxKeys) { + newRoot := NewBTreeNode[T](tree.maxKeys, false) + newRoot.numKeys = 0 + newRoot.children[0] = tree.root + newRoot.Split(0, tree.maxKeys) + tree.root = newRoot + } + tree.root.InsertNonFull(tree, key) +} + +func (node *BTreeNode[T]) DeleteIthKey(i int) { + if i >= node.numKeys { + panic("deleting out of bounds key") + } + for j := i; j < node.numKeys-1; j++ { + node.keys[j] = node.keys[j+1] + node.children[j+1] = node.children[j+2] + } + node.numKeys-- +} + +// Transform: +// +// A B C +// / \ +// a b +// +// Into: +// +// A C +// | +// +// a B c +func (node *BTreeNode[T]) Merge(idx int) { + if node.isLeaf { + panic("cannot merge when leaf node is parent") + } + left := node.children[idx] + right := node.children[idx+1] + left.Append(node.keys[idx], right.children[0]) + left.Concat(right, 0) + node.DeleteIthKey(idx) +} + +func (node *BTreeNode[T]) Min() T { + if node.isLeaf { + return node.keys[0] + } + return node.children[0].Min() +} + +func (node *BTreeNode[T]) Max() T { + if node.isLeaf { + return node.keys[node.numKeys-1] + } + return node.children[node.numKeys].Max() +} + +func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) { + node.Verify(tree) + if node.isLeaf { + // Case 1: Node is a leaf. Directly delete the key. + for i := 0; i < node.numKeys; i++ { + if key == node.keys[i] { + node.DeleteIthKey(i) + return + } + } + return + } + + minKeys := minKeys(tree.maxKeys) + i := 0 + for ; i < node.numKeys; i++ { + if key == node.keys[i] { + // Case 2: key exists in a non-leaf node + left := node.children[i] + right := node.children[i+1] + if left.numKeys > minKeys { + // Replace the key we want to delete with the max key from the left + // subtree. Then delete that key from the left subtree. + // A B C + // / + // a b c + // + // If we want to delete `B`, then replace `B` with `c`, and delete `c` in the subtree. + // A c C + // / + // a b + replacementKey := left.Max() + node.keys[i] = replacementKey + left.Delete(tree, replacementKey) + } else if right.numKeys > minKeys { + // Replace the key we want to delete with the min key from the right + // subtree. Then delete that key in the right subtree. Mirrors the + // transformation above for replacing from the left subtree. + replacementKey := right.Min() + node.keys[i] = replacementKey + right.Delete(tree, replacementKey) + } else { + // Both left and right subtrees have the minimum number of keys. Merge + // the left tree, the deleted key, and the right tree together into the + // left tree. Then recursively delete the key in the left tree. + if left.numKeys != minKeys || right.numKeys != minKeys { + panic("nodes should not have less than the minimum number of keys") + } + node.Merge(i) + left.Delete(tree, key) + } + return + } + + if key < node.keys[i] { + break + } + } + + // Case 3: key may exist in a child node. + child := node.children[i] + if child.numKeys == minKeys { + // Before we recurse into the child node, make sure it has more than + // the minimum number of keys. + if i > 0 && node.children[i-1].numKeys > minKeys { + // Take a key from the left sibling + // Transform: + // A B C + // / \ + // a b c + // + // Into: + // A b C + // / \ + // a B c + left := node.children[i-1] + child.InsertKeyChild(node.keys[i-1], left.children[left.numKeys]) + node.keys[i-1] = left.keys[left.numKeys-1] + left.numKeys-- + } else if i < node.numKeys && node.children[i+1].numKeys > minKeys { + // Take a key from the right sibling. Mirrors the transformation above for taking a key from the left sibling. + right := node.children[i+1] + child.Append(node.keys[i], right.children[0]) + node.keys[i] = right.keys[0] + right.children[0] = right.children[1] + right.DeleteIthKey(0) + } else { + if i == 0 { + // Merge with right sibling + node.Merge(i) + } else { + // Merge with left sibling + node.Merge(i - 1) + child = node.children[i-1] + } + } + } + if child.numKeys == minKeys { + panic("cannot delete key from node with minimum number of keys") + } + child.Delete(tree, key) +} + +func (tree *BTree[T]) Delete(key T) { + if tree.root == nil { + return + } + tree.root.Delete(tree, key) + if tree.root.numKeys == 0 { + tree.root = tree.root.children[0] + } +} diff --git a/structure/tree/btree_test.go b/structure/tree/btree_test.go new file mode 100644 index 000000000..056461b1c --- /dev/null +++ b/structure/tree/btree_test.go @@ -0,0 +1,133 @@ +package tree_test + +import ( + bt "github.com/TheAlgorithms/Go/structure/tree" + "math/rand" + "testing" +) + +func TestBTreeIncreasing(t *testing.T) { + maxKeysCases := []int{4, 16} + sizes := []int{100, 0xBA5, 0xF00} + for _, maxKeys := range maxKeysCases { + for _, size := range sizes { + tree := bt.NewBTree[int](maxKeys) + if tree.Search(0) { + t.Errorf("Tree expected to contain 0") + } + for i := 0; i < size; i++ { + tree.Insert(i) + } + for i := 0; i < size; i++ { + if !tree.Search(i) { + t.Errorf("Tree expected to contain %d", i) + } + } + if tree.Search(size + 1) { + t.Errorf("Tree not expected to contain %d", size+1) + } + + for i := 0; i < size; i += 5 { + tree.Delete(i) + } + for i := 0; i < size; i++ { + hasKey := tree.Search(i) + if i%5 == 0 && hasKey { + t.Errorf("Tree not expected to contain %d", i) + } else if i%5 != 0 && !hasKey { + t.Errorf("Tree expected to contain %d", i) + } + } + } + } +} + +func TestBTreeDecreasing(t *testing.T) { + maxKeysCases := []int{4, 16} + sizes := []int{100, 1000} + for _, maxKeys := range maxKeysCases { + for _, size := range sizes { + tree := bt.NewBTree[int](maxKeys) + if tree.Search(0) { + t.Errorf("Tree expected to contain 0") + } + for i := size - 1; i >= 0; i-- { + tree.Insert(i) + } + for i := 0; i < size; i++ { + if !tree.Search(i) { + t.Errorf("Tree expected to contain %d", i) + } + } + if tree.Search(size + 1) { + t.Errorf("Tree not expected to contain %d", size+1) + } + + for i := 0; i < size; i += 5 { + tree.Delete(i) + } + for i := 0; i < size; i++ { + hasKey := tree.Search(i) + if i%5 == 0 && hasKey { + t.Errorf("Tree not expected to contain %d", i) + } else if i%5 != 0 && !hasKey { + t.Errorf("Tree expected to contain %d", i) + } + } + } + } +} + +func TestBTreeRandom(t *testing.T) { + maxKeysCases := []int{4, 16} + sizes := []int{100, 0xBA5, 0xF00} + for _, maxKeys := range maxKeysCases { + for _, size := range sizes { + rnd := rand.New(rand.NewSource(0)) + tree := bt.NewBTree[int](maxKeys) + nums := rnd.Perm(size) + if tree.Search(0) { + t.Errorf("Tree expected to contain 0") + } + for i := 0; i < size; i++ { + tree.Insert(nums[i]) + } + for i := 0; i < size; i++ { + if !tree.Search(nums[i]) { + t.Errorf("Tree expected to contain %d", nums[i]) + } + } + + for i := 0; i < size; i += 5 { + tree.Delete(nums[i]) + } + for i := 0; i < size; i++ { + hasKey := tree.Search(nums[i]) + if i%5 == 0 && hasKey { + t.Errorf("Tree not expected to contain %d", i) + } else if i%5 != 0 && !hasKey { + t.Errorf("Tree expected to contain %d", i) + } + } + } + } +} + +func TestBTreeDeleteEverything(t *testing.T) { + tree := bt.NewBTree[int](4) + size := 128 + for i := 0; i < size; i++ { + tree.Insert(i) + } + for i := 0; i < size; i++ { + tree.Delete(i) + } + tree.Delete(-1) + tree.Delete(1000) + + for i := 0; i < size; i++ { + if tree.Search(i) { + t.Errorf("Tree not expected to contain %d", i) + } + } +} From 0254892642fa4a9c2e55bec0a152bb721830b455 Mon Sep 17 00:00:00 2001 From: jafar75 Date: Fri, 15 Mar 2024 20:55:06 +0330 Subject: [PATCH 168/202] feat: add prim algorithm to find mst (#710) --- README.md | 13 +++-- graph/prim.go | 58 ++++++++++++++++++ graph/prim_test.go | 143 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 208 insertions(+), 6 deletions(-) create mode 100644 graph/prim.go create mode 100644 graph/prim_test.go diff --git a/README.md b/README.md index 1d9b007cc..a7ef32fb5 100644 --- a/README.md +++ b/README.md @@ -455,12 +455,13 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 5. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm 6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided. 7. [`KruskalMST`](./graph/kruskal.go#L23): No description provided. -8. [`LowestCommonAncestor`](./graph/lowestcommonancestor.go#L111): For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. -9. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) -10. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. -11. [`NewUnionFind`](./graph/unionfind.go#L24): Initialise a new union find data structure with s nodes -12. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. -13. [`Topological`](./graph/topological.go#L7): Topological assumes that graph given is valid and that its possible to get a topological ordering. constraints are array of []int{a, b}, representing an edge going from a to b +8. [`PrimMST`](./graph/prim.go#30): Computes the minimum spanning tree of a weighted undirected graph +9. [`LowestCommonAncestor`](./graph/lowestcommonancestor.go#L111): For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. +10. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default) +11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided. +12. [`NewUnionFind`](./graph/unionfind.go#L24): Initialise a new union find data structure with s nodes +13. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. +14. [`Topological`](./graph/topological.go#L7): Topological assumes that graph given is valid and that its possible to get a topological ordering. constraints are array of []int{a, b}, representing an edge going from a to b --- ##### Types diff --git a/graph/prim.go b/graph/prim.go new file mode 100644 index 000000000..d99dcd6e1 --- /dev/null +++ b/graph/prim.go @@ -0,0 +1,58 @@ +// The Prim's algorithm computes the minimum spanning tree for a weighted undirected graph +// Worst Case Time Complexity: O(E log V) using Binary heap, where V is the number of vertices and E is the number of edges +// Space Complexity: O(V + E) +// Implementation is based on the book 'Introduction to Algorithms' (CLRS) + +package graph + +import ( + "container/heap" +) + +type minEdge []Edge + +func (h minEdge) Len() int { return len(h) } +func (h minEdge) Less(i, j int) bool { return h[i].Weight < h[j].Weight } +func (h minEdge) Swap(i, j int) { h[i], h[j] = h[j], h[i] } + +func (h *minEdge) Push(x interface{}) { + *h = append(*h, x.(Edge)) +} + +func (h *minEdge) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func (g *Graph) PrimMST(start Vertex) ([]Edge, int) { + var mst []Edge + marked := make([]bool, g.vertices) + h := &minEdge{} + // Pushing neighbors of the start node to the binary heap + for neighbor, weight := range g.edges[int(start)] { + heap.Push(h, Edge{start, Vertex(neighbor), weight}) + } + marked[start] = true + cost := 0 + for h.Len() > 0 { + e := heap.Pop(h).(Edge) + end := int(e.End) + // To avoid cycles + if marked[end] { + continue + } + marked[end] = true + cost += e.Weight + mst = append(mst, e) + // Check for neighbors of the newly added edge's End vertex + for neighbor, weight := range g.edges[end] { + if !marked[neighbor] { + heap.Push(h, Edge{e.End, Vertex(neighbor), weight}) + } + } + } + return mst, cost +} diff --git a/graph/prim_test.go b/graph/prim_test.go new file mode 100644 index 000000000..8a3d42c12 --- /dev/null +++ b/graph/prim_test.go @@ -0,0 +1,143 @@ +package graph + +import ( + "fmt" + "reflect" + "testing" +) + +func TestPrimMST(t *testing.T) { + + var testCases = []struct { + edges []Edge + vertices int + start int + cost int + mst []Edge + }{ + { + edges: []Edge{ + {Start: 0, End: 1, Weight: 4}, + {Start: 0, End: 2, Weight: 13}, + {Start: 0, End: 3, Weight: 7}, + {Start: 0, End: 4, Weight: 7}, + {Start: 1, End: 2, Weight: 9}, + {Start: 1, End: 3, Weight: 3}, + {Start: 1, End: 4, Weight: 7}, + {Start: 2, End: 3, Weight: 10}, + {Start: 2, End: 4, Weight: 14}, + {Start: 3, End: 4, Weight: 4}, + }, + vertices: 5, + start: 0, + cost: 20, + mst: []Edge{ + {Start: 0, End: 1, Weight: 4}, + {Start: 1, End: 3, Weight: 3}, + {Start: 3, End: 4, Weight: 4}, + {Start: 1, End: 2, Weight: 9}, + }, + }, + { + edges: []Edge{ + {Start: 0, End: 1, Weight: 4}, + {Start: 0, End: 7, Weight: 8}, + {Start: 1, End: 2, Weight: 8}, + {Start: 1, End: 7, Weight: 11}, + {Start: 2, End: 3, Weight: 7}, + {Start: 2, End: 5, Weight: 4}, + {Start: 2, End: 8, Weight: 2}, + {Start: 3, End: 4, Weight: 9}, + {Start: 3, End: 5, Weight: 14}, + {Start: 4, End: 5, Weight: 10}, + {Start: 5, End: 6, Weight: 2}, + {Start: 6, End: 7, Weight: 1}, + {Start: 6, End: 8, Weight: 6}, + {Start: 7, End: 8, Weight: 7}, + }, + vertices: 9, + start: 3, + cost: 37, + mst: []Edge{ + {Start: 3, End: 2, Weight: 7}, + {Start: 2, End: 8, Weight: 2}, + {Start: 2, End: 5, Weight: 4}, + {Start: 5, End: 6, Weight: 2}, + {Start: 6, End: 7, Weight: 1}, + {Start: 2, End: 1, Weight: 8}, + {Start: 1, End: 0, Weight: 4}, + {Start: 3, End: 4, Weight: 9}, + }, + }, + { + edges: []Edge{ + {Start: 0, End: 1, Weight: 2}, + {Start: 0, End: 3, Weight: 6}, + {Start: 1, End: 2, Weight: 3}, + {Start: 1, End: 3, Weight: 8}, + {Start: 1, End: 4, Weight: 5}, + {Start: 2, End: 4, Weight: 7}, + {Start: 3, End: 4, Weight: 9}, + }, + vertices: 5, + start: 2, + cost: 16, + mst: []Edge{ + {Start: 2, End: 1, Weight: 3}, + {Start: 1, End: 0, Weight: 2}, + {Start: 1, End: 4, Weight: 5}, + {Start: 0, End: 3, Weight: 6}, + }, + }, + { + edges: []Edge{ + {Start: 0, End: 0, Weight: 0}, + }, + vertices: 1, + start: 0, + cost: 0, + mst: nil, + }, + { + edges: []Edge{ + {Start: 0, End: 1, Weight: 1}, + {Start: 0, End: 2, Weight: 6}, + {Start: 0, End: 3, Weight: 5}, + {Start: 1, End: 2, Weight: 2}, + {Start: 1, End: 4, Weight: 4}, + {Start: 2, End: 4, Weight: 9}, + }, + vertices: 5, + start: 4, + cost: 12, + mst: []Edge{ + {Start: 4, End: 1, Weight: 4}, + {Start: 1, End: 0, Weight: 1}, + {Start: 1, End: 2, Weight: 2}, + {Start: 0, End: 3, Weight: 5}, + }, + }, + } + + for i, testCase := range testCases { + t.Run(fmt.Sprintf("Test Case %d", i), func(t *testing.T) { + // Initializing graph, adding edges + graph := New(testCase.vertices) + graph.Directed = false + for _, edge := range testCase.edges { + graph.AddWeightedEdge(int(edge.Start), int(edge.End), edge.Weight) + } + + computedMST, computedCost := graph.PrimMST(Vertex(testCase.start)) + + // Compare the computed result with the expected result + if computedCost != testCase.cost { + t.Errorf("Test Case %d, Expected Cost: %d, Computed: %d", i, testCase.cost, computedCost) + } + + if !reflect.DeepEqual(testCase.mst, computedMST) { + t.Errorf("Test Case %d, Expected MST: %v, Computed: %v", i, testCase.mst, computedMST) + } + }) + } +} From 50ddbddec7a80bd11186cc6af6b4ca82fdc26075 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Mon, 18 Mar 2024 04:52:44 +0100 Subject: [PATCH 169/202] style: handle edge cases uniformly in all implementations of factorial (#705) * style: handle edge cases uniformly in all implementations of factorial * style: add suggestions from the review Co-authored-by: Taj * style: use `Err` suffix for error name * style: define `testCases` and `implementations` as variables * style: return 0 when negative input --------- Co-authored-by: Taj Co-authored-by: Rak Laptudirm --- math/catalan/catalannumber.go | 10 ++- math/factorial/factorial.go | 36 ++++++---- math/factorial/factorial_test.go | 110 ++++++++++++++----------------- 3 files changed, 82 insertions(+), 74 deletions(-) diff --git a/math/catalan/catalannumber.go b/math/catalan/catalannumber.go index 31a424347..9ea8acb49 100644 --- a/math/catalan/catalannumber.go +++ b/math/catalan/catalannumber.go @@ -12,7 +12,15 @@ import ( f "github.com/TheAlgorithms/Go/math/factorial" ) +func factorial(n int) int { + result, error := f.Iterative(n) + if error != nil { + panic(error) + } + return result +} + // CatalanNumber This function returns the `nth` Catalan number func CatalanNumber(n int) int { - return f.Iterative(n*2) / (f.Iterative(n) * f.Iterative(n+1)) + return factorial(n*2) / (factorial(n) * factorial(n+1)) } diff --git a/math/factorial/factorial.go b/math/factorial/factorial.go index 6b7f5f516..7472da8de 100644 --- a/math/factorial/factorial.go +++ b/math/factorial/factorial.go @@ -8,36 +8,48 @@ // Package factorial describes algorithms Factorials calculations. package factorial +import ( + "errors" +) + +var ErrNegativeArgument = errors.New("input argument must be non-negative integer") + // Iterative returns the iteratively brute forced factorial of n -func Iterative(n int) int { +func Iterative(n int) (int, error) { + if n < 0 { + return 0, ErrNegativeArgument + } result := 1 for i := 2; i <= n; i++ { result *= i } - return result + return result, nil } // Recursive This function recursively computes the factorial of a number -func Recursive(n int) int { - if n == 1 { - return 1 - } else { - return n * Recursive(n-1) +func Recursive(n int) (int, error) { + if n < 0 { + return 0, ErrNegativeArgument } + if n <= 1 { + return 1, nil + } + prev, _ := Recursive(n - 1) + return n * prev, nil } // UsingTree This function finds the factorial of a number using a binary tree -func UsingTree(n int) int { +func UsingTree(n int) (int, error) { if n < 0 { - return 0 + return 0, ErrNegativeArgument } if n == 0 { - return 1 + return 1, nil } if n == 1 || n == 2 { - return n + return n, nil } - return prodTree(2, n) + return prodTree(2, n), nil } func prodTree(l int, r int) int { diff --git a/math/factorial/factorial_test.go b/math/factorial/factorial_test.go index 04eceb973..1d3ed727d 100644 --- a/math/factorial/factorial_test.go +++ b/math/factorial/factorial_test.go @@ -1,81 +1,69 @@ // factorial_test.go // description: Test for calculating factorial -// author(s) [red_byte](https://github.com/i-redbyte) // see factorial.go package factorial import "testing" +import "fmt" -func getTests() []struct { - name string - n int - result int -} { - var tests = []struct { - name string - n int - result int - }{ - {"5!", 5, 120}, - {"3!", 3, 6}, - {"6!", 6, 720}, - {"12!", 12, 479001600}, - {"1!", 1, 1}, - } - return tests -} +type factorialFun func(int) (int, error) -func TestBruteForceFactorial(t *testing.T) { - tests := getTests() - for _, tv := range tests { - t.Run(tv.name, func(t *testing.T) { - result := Iterative(tv.n) - if result != tv.result { - t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) - } - }) - } +var implementations = map[string]factorialFun{ + "Iterative": Iterative, + "Recursive": Recursive, + "UsingTree": UsingTree, } -func TestRecursiveFactorial(t *testing.T) { - tests := getTests() - for _, tv := range tests { - t.Run(tv.name, func(t *testing.T) { - result := Recursive(tv.n) - if result != tv.result { - t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) - } - }) - } +var testCases = []struct { + n int + expected int +}{ + {0, 1}, + {1, 1}, + {2, 2}, + {3, 6}, + {4, 24}, + {5, 120}, + {6, 720}, + {7, 5040}, + {8, 40320}, + {9, 362880}, + {10, 3628800}, + {11, 39916800}, + {12, 479001600}, } -func TestCalculateFactorialUseTree(t *testing.T) { - tests := getTests() - for _, tv := range tests { - t.Run(tv.name, func(t *testing.T) { - result := UsingTree(tv.n) - if result != tv.result { - t.Errorf("Wrong result! Expected:%d, returned:%d ", tv.result, result) +func TestFactorial(t *testing.T) { + for implName, implFunction := range implementations { + t.Run(implName+" errors for negative input", func(t *testing.T) { + _, error := implFunction(-1) + if error != ErrNegativeArgument { + t.Errorf("No error captured for negative input") } }) + for _, tc := range testCases { + t.Run(fmt.Sprintf("%s with input %d", implName, tc.n), func(t *testing.T) { + actual, err := implFunction(tc.n) + if err != nil { + t.Errorf("unexpected error captured") + } + if actual != tc.expected { + t.Errorf("Expected: %d, got: %d", tc.expected, actual) + } + }) + } } } -func BenchmarkBruteForceFactorial(b *testing.B) { - for i := 0; i < b.N; i++ { - Iterative(10) - } -} - -func BenchmarkRecursiveFactorial(b *testing.B) { - for i := 0; i < b.N; i++ { - Recursive(10) - } -} - -func BenchmarkCalculateFactorialUseTree(b *testing.B) { - for i := 0; i < b.N; i++ { - Recursive(10) +func BenchmarkFactorial(b *testing.B) { + for _, input := range []int{5, 10, 15} { + for implName, implFunction := range implementations { + b.Run(fmt.Sprintf("%s_%d", implName, input), func(b *testing.B) { + for i := 0; i < b.N; i++ { + _, _ = implFunction(input) + } + }) + } } } From a938a237c5f8d8b2d0f7f7db0861f84b6a2fc725 Mon Sep 17 00:00:00 2001 From: jafar75 Date: Wed, 20 Mar 2024 20:39:53 +0330 Subject: [PATCH 170/202] fix: typo in bellmanford description (#711) --- graph/bellmanford.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graph/bellmanford.go b/graph/bellmanford.go index c9e791f6d..f130a4e06 100644 --- a/graph/bellmanford.go +++ b/graph/bellmanford.go @@ -1,5 +1,5 @@ // The Bellman–Ford algorithm is an algorithm that computes shortest paths from a -// single source vertex to all of the other vertices in a weighted durected graph. +// single source vertex to all of the other vertices in a weighted directed graph. // It is slower than Dijkstra but capable of handling negative edge weights. // https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm // Implementation is based on the book 'Introduction to Algorithms' (CLRS) From cbaed2300ade20c0526c20f48cf1ac1cbfb8b8c9 Mon Sep 17 00:00:00 2001 From: jafar75 Date: Thu, 28 Mar 2024 14:40:46 +0330 Subject: [PATCH 171/202] feat: add edmond-karp algorithm for max-flow (#712) --- README.md | 1 + graph/edmondkarp.go | 93 ++++++++++++++++++++++++++++++++++++++++ graph/edmondkarp_test.go | 79 ++++++++++++++++++++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 graph/edmondkarp.go create mode 100644 graph/edmondkarp_test.go diff --git a/README.md b/README.md index a7ef32fb5..b55033399 100644 --- a/README.md +++ b/README.md @@ -462,6 +462,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 12. [`NewUnionFind`](./graph/unionfind.go#L24): Initialise a new union find data structure with s nodes 13. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided. 14. [`Topological`](./graph/topological.go#L7): Topological assumes that graph given is valid and that its possible to get a topological ordering. constraints are array of []int{a, b}, representing an edge going from a to b +15. [`Edmond-Karp`](./graph/edmondkarp.go#L43): Computes the maximum possible flow between a pair of s-t vertices in a weighted graph --- ##### Types diff --git a/graph/edmondkarp.go b/graph/edmondkarp.go new file mode 100644 index 000000000..f6917efcb --- /dev/null +++ b/graph/edmondkarp.go @@ -0,0 +1,93 @@ +// Edmond-Karp algorithm is an implementation of the Ford-Fulkerson method +// to compute max-flow between a pair of source-sink vertices in a weighted graph +// It uses BFS (Breadth First Search) to find the residual paths +// Time Complexity: O(V * E^2) where V is the number of vertices and E is the number of edges +// Space Complexity: O(V + E) Because we keep residual graph in size of the original graph +// Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. 2009. Introduction to Algorithms, Third Edition (3rd. ed.). The MIT Press. + +package graph + +import ( + "math" +) + +// Returns a mapping of vertices as path, if there is any from source to sink +// Otherwise, returns nil +func FindPath(rGraph WeightedGraph, source int, sink int) map[int]int { + queue := make([]int, 0) + marked := make([]bool, len(rGraph)) + marked[source] = true + queue = append(queue, source) + parent := make(map[int]int) + + // BFS loop with saving the path found + for len(queue) > 0 { + v := queue[0] + queue = queue[1:] + for i := 0; i < len(rGraph[v]); i++ { + if !marked[i] && rGraph[v][i] > 0 { + parent[i] = v + // Terminate the BFS, if we reach to sink + if i == sink { + return parent + } + marked[i] = true + queue = append(queue, i) + } + } + } + // source and sink are not in the same connected component + return nil +} + +func EdmondKarp(graph WeightedGraph, source int, sink int) float64 { + // Check graph emptiness + if len(graph) == 0 { + return 0.0 + } + + // Check correct dimensions of the graph slice + for i := 0; i < len(graph); i++ { + if len(graph[i]) != len(graph) { + return 0.0 + } + } + + rGraph := make(WeightedGraph, len(graph)) + for i := 0; i < len(graph); i++ { + rGraph[i] = make([]float64, len(graph)) + } + // Init the residual graph with the same capacities as the original graph + copy(rGraph, graph) + + maxFlow := 0.0 + + for { + parent := FindPath(rGraph, source, sink) + if parent == nil { + break + } + // Finding the max flow over the path returned by BFS + // i.e. finding minimum residual capacity amonth the path edges + pathFlow := math.MaxFloat64 + for v := sink; v != source; v = parent[v] { + u := parent[v] + if rGraph[u][v] < pathFlow { + pathFlow = rGraph[u][v] + } + } + + // update residual capacities of the edges and + // reverse edges along the path + for v := sink; v != source; v = parent[v] { + u := parent[v] + rGraph[u][v] -= pathFlow + rGraph[v][u] += pathFlow + } + + // Update the total flow found so far + maxFlow += pathFlow + } + + return maxFlow +} diff --git a/graph/edmondkarp_test.go b/graph/edmondkarp_test.go new file mode 100644 index 000000000..08e104652 --- /dev/null +++ b/graph/edmondkarp_test.go @@ -0,0 +1,79 @@ +package graph + +import ( + "testing" +) + +func TestEdmondKarp(t *testing.T) { + var edmondKarpTestData = []struct { + description string + graph WeightedGraph + source int + sink int + expected float64 + }{ + { + description: "test empty graph", + graph: nil, + source: 0, + sink: 0, + expected: 0.0, + }, + { + description: "test graph with wrong dimensions", + graph: WeightedGraph{ + {1, 2}, + {0}, + }, + source: 0, + sink: 1, + expected: 0.0, + }, + { + description: "test graph with no edges", + graph: WeightedGraph{ + {0, 0}, + {0, 0}, + }, + source: 0, + sink: 1, + expected: 0.0, + }, + { + description: "test graph with 4 vertices", + graph: WeightedGraph{ + {0, 1000000, 1000000, 0}, + {0, 0, 1, 1000000}, + {0, 0, 0, 1000000}, + {0, 0, 0, 0}, + }, + source: 0, + sink: 3, + expected: 2000000, + }, + { + description: "test graph with 6 vertices and some float64 weights", + graph: WeightedGraph{ + {0, 16, 13.8, 0, 0, 0}, + {0, 0, 10, 12.7, 0, 0}, + {0, 4.2, 0, 0, 14, 0}, + {0, 0, 9.1, 0, 0, 21.3}, + {0, 0, 0, 7.5, 0, 4}, + {0, 0, 0, 0, 0, 0}, + }, + source: 0, + sink: 5, + expected: 24.2, + }, + } + for _, test := range edmondKarpTestData { + t.Run(test.description, func(t *testing.T) { + result := EdmondKarp(test.graph, test.source, test.sink) + + if !almostEqual(test.expected, result) { + t.Logf("FAIL: %s", test.description) + t.Fatalf("Expected result:%f\nFound: %f", test.expected, result) + } + }) + } +} From e9d1f3cff35f427f61011d5535d10e595f289490 Mon Sep 17 00:00:00 2001 From: SOZEL <80200848+TruongNhanNguyen@users.noreply.github.com> Date: Wed, 17 Apr 2024 02:51:16 +0700 Subject: [PATCH 172/202] Implement Trapped Rain Water algorithm. (#714) * feat: implement Trapped Rain Water algorithm * chore(tests): add test of empty `heights` --- README.md | 2 +- dynamic/traprainwater.go | 41 +++++++++++++++++++++++++++++++++++ dynamic/traprainwater_test.go | 34 +++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 dynamic/traprainwater.go create mode 100644 dynamic/traprainwater_test.go diff --git a/README.md b/README.md index b55033399..364643711 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 17. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate 18. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²) 19. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number - +20. [`TrapRainWater`](./dynamic/traprainwater.go#L17): Calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming. ---
dynamicarray diff --git a/dynamic/traprainwater.go b/dynamic/traprainwater.go new file mode 100644 index 000000000..4f87e1cd7 --- /dev/null +++ b/dynamic/traprainwater.go @@ -0,0 +1,41 @@ +// filename: traprainwater.go +// description: Provides a function to calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming. +// details: +// The TrapRainWater function calculates the amount of trapped rainwater between the bars represented by the given elevation map. +// It uses dynamic programming to precompute the maximum height of bars to the left and right of each position. +// Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights. +// Finally, it sums up the trapped rainwater for all positions and returns the total amount. +// author(s) [TruongNhanNguyen (SOZEL)](https://github.com/TruongNhanNguyen) +package dynamic + +import "math" + +// TrapRainWater calculates the amount of trapped rainwater between the bars represented by the given elevation map. +// It uses dynamic programming to precompute the maximum height of bars to the left and right of each position. +// Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights. +// Finally, it sums up the trapped rainwater for all positions and returns the total amount. +func TrapRainWater(height []int) int { + if len(height) == 0 { + return 0 + } + + leftMax := make([]int, len(height)) + rightMax := make([]int, len(height)) + + leftMax[0] = height[0] + for i := 1; i < len(height); i++ { + leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i]))) + } + + rightMax[len(height)-1] = height[len(height)-1] + for i := len(height) - 2; i >= 0; i-- { + rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i]))) + } + + trappedWater := 0 + for i := 0; i < len(height); i++ { + trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i] + } + + return trappedWater +} diff --git a/dynamic/traprainwater_test.go b/dynamic/traprainwater_test.go new file mode 100644 index 000000000..a031a3077 --- /dev/null +++ b/dynamic/traprainwater_test.go @@ -0,0 +1,34 @@ +package dynamic_test + +import ( + "fmt" + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +func TestTrapRainWater(t *testing.T) { + heights := [][]int{ + {}, + {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}, + {4, 2, 0, 3, 2, 5}, + {3, 1, 2, 4, 0, 1, 3, 2, 4}, + } + + expectedResults := []int{ + 0, + 6, + 9, + 13, + } + + for i, height := range heights { + expected := expectedResults[i] + t.Run(fmt.Sprintf("Case %d", i+1), func(t *testing.T) { + result := dynamic.TrapRainWater(height) + if result != expected { + t.Errorf("Expected %d, but got %d", expected, result) + } + }) + } +} From 0d0b97a43fcce5b1cdb5efb0d04afcaa5b98901d Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 20 Apr 2024 08:51:49 +0200 Subject: [PATCH 173/202] chore: update `codecov-action` to `v4` (#704) --- .github/workflows/upload_coverage_report.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/upload_coverage_report.yml b/.github/workflows/upload_coverage_report.yml index 2308cc871..b982b25f3 100644 --- a/.github/workflows/upload_coverage_report.yml +++ b/.github/workflows/upload_coverage_report.yml @@ -23,9 +23,17 @@ jobs: - name: Generate code coverage run: | go test -coverprofile="${{ env.REPORT_NAME }}" ./... - - name: Upload coverage to codecov - uses: codecov/codecov-action@v3 + - name: Upload coverage to codecov (tokenless) + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository + uses: codecov/codecov-action@v4 with: files: "${{ env.REPORT_NAME }}" fail_ci_if_error: true + - name: Upload coverage to codecov (with token) + if: "! github.event.pull_request.head.repo.fork " + uses: codecov/codecov-action@v4 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: "${{ env.REPORT_NAME }}" + fail_ci_if_error: true ... From c5173f35db0b90d48a7286c3124c7da53a53efcc Mon Sep 17 00:00:00 2001 From: Chandrahas77 <52702137+Chandrahas77@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:27:14 -0400 Subject: [PATCH 174/202] Add railfence cipher (#715) * added rail fence cipher implementation * updated readme * fixed typo --------- Co-authored-by: Rak Laptudirm --- README.md | 13 +++++ cipher/railfence/railfence.go | 75 ++++++++++++++++++++++++ cipher/railfence/railfence_test.go | 91 ++++++++++++++++++++++++++++++ 3 files changed, 179 insertions(+) create mode 100644 cipher/railfence/railfence.go create mode 100644 cipher/railfence/railfence_test.go diff --git a/README.md b/README.md index 364643711..ade5df81a 100644 --- a/README.md +++ b/README.md @@ -1199,6 +1199,19 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 2. [`Encrypt`](./cipher/xor/xor.go#L10): Encrypt encrypts with Xor encryption after converting each character to byte The returned value might not be readable because there is no guarantee which is within the ASCII range If using other type such as string, []int, or some other types, add the statements for converting the type to []byte. 3. [`FuzzXOR`](./cipher/xor/xor_test.go#L108): No description provided. +--- +
+ +##### Package rail fence is a classical type of transposition cipher ref : https://en.wikipedia.org/wiki/Rail_fence_cipher + +--- +##### Functions: + +1. [`Encrypt`](.cipher/railfence/railfence.go#L7): Encrypt encrypts a message using rail fence cipher +2. [`Decrypt`](.cipher/railfence/railfence.go#L44): decrypt decrypts a message using rail fence cipher +3. [`TestEncrypt`](.cipher/railfence/railfence_test.go#L7) Test function for Encrypt +4. [`TestDecrypt`](.cipher/railfence/railfence_test.go#L50) Test function for Decrypt + --- diff --git a/cipher/railfence/railfence.go b/cipher/railfence/railfence.go new file mode 100644 index 000000000..f1ea11928 --- /dev/null +++ b/cipher/railfence/railfence.go @@ -0,0 +1,75 @@ +package railfence + +import ( + "strings" +) + +func Encrypt(text string, rails int) string { + if rails == 1 { + return text + } + + // Create a matrix for the rail fence pattern + matrix := make([][]rune, rails) + for i := range matrix { + matrix[i] = make([]rune, len(text)) + } + + // Fill the matrix + dirDown := false + row, col := 0, 0 + for _, char := range text { + if row == 0 || row == rails-1 { + dirDown = !dirDown + } + matrix[row][col] = char + col++ + if dirDown { + row++ + } else { + row-- + } + } + var result strings.Builder + for _, line := range matrix { + for _, char := range line { + if char != 0 { + result.WriteRune(char) + } + } + } + + return result.String() +} +func Decrypt(cipherText string, rails int) string { + if rails == 1 || rails >= len(cipherText) { + return cipherText + } + + // Placeholder for the decrypted message + decrypted := make([]rune, len(cipherText)) + + // Calculate the zigzag pattern and place characters accordingly + index := 0 + for rail := 0; rail < rails; rail++ { + position := rail + down := true // Direction flag + for position < len(cipherText) { + decrypted[position] = rune(cipherText[index]) + index++ + + // Determine the next position based on the current rail and direction + if rail == 0 || rail == rails-1 { + position += 2 * (rails - 1) + } else if down { + position += 2 * (rails - 1 - rail) + down = false + } else { + position += 2 * rail + down = true + } + } + } + + return string(decrypted) +} diff --git a/cipher/railfence/railfence_test.go b/cipher/railfence/railfence_test.go new file mode 100644 index 000000000..7f7bfa53a --- /dev/null +++ b/cipher/railfence/railfence_test.go @@ -0,0 +1,91 @@ +package railfence + +import ( + "testing" +) + +func TestEncrypt(t *testing.T) { + var railFenceTestData = []struct { + description string + input string + rails int + expected string + }{ + { + "Encrypt with 2 rails", + "hello", + 2, + "hloel", + }, + { + "Encrypt with 3 rails", + "hello world", + 3, + "horel ollwd", + }, + { + "Encrypt with edge case: 1 rail", + "hello", + 1, + "hello", + }, + { + "Encrypt with more rails than letters", + "hi", + 100, + "hi", + }, + } + + for _, test := range railFenceTestData { + t.Run(test.description, func(t *testing.T) { + actual := Encrypt(test.input, test.rails) + if actual != test.expected { + t.Errorf("FAIL: %s - Encrypt(%s, %d) = %s, want %s", test.description, test.input, test.rails, actual, test.expected) + } + }) + } +} + +func TestDecrypt(t *testing.T) { + var railFenceTestData = []struct { + description string + input string + rails int + expected string + }{ + { + "Decrypt with 2 rails", + "hloel", + 2, + "hello", + }, + { + "Decrypt with 3 rails", + "ho l lewrdlo", + 3, + "hld olle wor", + }, + { + "Decrypt with edge case: 1 rail", + "hello", + 1, + "hello", + }, + { + "Decrypt with more rails than letters", + "hi", + 100, + "hi", + }, + } + + for _, test := range railFenceTestData { + t.Run(test.description, func(t *testing.T) { + actual := Decrypt(test.input, test.rails) + if actual != test.expected { + t.Errorf("FAIL: %s - Decrypt(%s, %d) = %s, want %s", test.description, test.input, test.rails, actual, test.expected) + } + }) + } +} From 833a3e55455afff334033b0b33fca0a1f9685e4b Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Wed, 24 Apr 2024 21:34:12 +0200 Subject: [PATCH 175/202] chore: update `actions/setup-go` to `v5` (#718) Co-authored-by: Rak Laptudirm --- .github/workflows/ci.yml | 2 +- .github/workflows/godocmd.yml | 2 +- .github/workflows/upload_coverage_report.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7bc96e6c..534f32036 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: '^1.18' - name: Run Golang CI Lint diff --git a/.github/workflows/godocmd.yml b/.github/workflows/godocmd.yml index a4ea126ca..7e7b306e3 100644 --- a/.github/workflows/godocmd.yml +++ b/.github/workflows/godocmd.yml @@ -12,7 +12,7 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version: '^1.18' - name: Install GoDocMD diff --git a/.github/workflows/upload_coverage_report.yml b/.github/workflows/upload_coverage_report.yml index b982b25f3..44867a43e 100644 --- a/.github/workflows/upload_coverage_report.yml +++ b/.github/workflows/upload_coverage_report.yml @@ -17,7 +17,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: '^1.18' - name: Generate code coverage From 235458219d929bdd0b1b4c344ccbb58b445183de Mon Sep 17 00:00:00 2001 From: jafar75 Date: Thu, 9 May 2024 11:23:42 +0330 Subject: [PATCH 176/202] feat: add next permutation problem (#720) --- README.md | 1 + math/permutation/next_permutation.go | 37 +++++++++++++++++++++ math/permutation/next_permutation_test.go | 40 +++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 math/permutation/next_permutation.go create mode 100644 math/permutation/next_permutation_test.go diff --git a/README.md b/README.md index ade5df81a..ace320588 100644 --- a/README.md +++ b/README.md @@ -834,6 +834,7 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`GenerateElementSet`](./math/permutation/heaps.go#L37): No description provided. 2. [`Heaps`](./math/permutation/heaps.go#L8): Heap's Algorithm for generating all permutations of n objects +3. [`NextPermutation`](./math/permutation/next_permutation.go#8): A solution to find next permutation of an integer array in constant memory ---
diff --git a/math/permutation/next_permutation.go b/math/permutation/next_permutation.go new file mode 100644 index 000000000..62841bb3d --- /dev/null +++ b/math/permutation/next_permutation.go @@ -0,0 +1,37 @@ +// A practice to find lexicographically next greater permutation of the given array of integers. +// If there does not exist any greater permutation, then print the lexicographically smallest permutation of the given array. +// The implementation below, finds the next permutation in linear time and constant memory and returns in place +// Useful reference: https://www.geeksforgeeks.org/next-permutation/ + +package permutation + +func NextPermutation(nums []int) { + pivot := 0 + for pivot = len(nums) - 2; pivot >= 0; pivot-- { + if nums[pivot] < nums[pivot+1] { + break + } + } + if pivot < 0 { + // current permutation is the last and must be reversed totally + for l, r := 0, len(nums)-1; l < r; l, r = l+1, r-1 { + nums[l], nums[r] = nums[r], nums[l] + } + } else { + succ := 0 + for succ = len(nums) - 1; succ > pivot; succ = succ - 1 { + if nums[succ] > nums[pivot] { + break + } + } + + // Swap the pivot and successor + nums[pivot], nums[succ] = nums[succ], nums[pivot] + + // Reverse the suffix part to minimize it + for l, r := pivot+1, len(nums)-1; l < r; l, r = l+1, r-1 { + nums[l], nums[r] = nums[r], nums[l] + } + } + +} diff --git a/math/permutation/next_permutation_test.go b/math/permutation/next_permutation_test.go new file mode 100644 index 000000000..8246876b4 --- /dev/null +++ b/math/permutation/next_permutation_test.go @@ -0,0 +1,40 @@ +package permutation + +import ( + "reflect" + "testing" +) + +func TestNextPermutation(t *testing.T) { + var nextPermutationTestData = []struct { + description string + numbers []int + next []int + }{ + { + description: "Basic case", + numbers: []int{1, 2, 3}, + next: []int{1, 3, 2}, + }, + { + description: "Should reverse the whole slice", + numbers: []int{3, 2, 1}, + next: []int{1, 2, 3}, + }, + { + description: "A more complex test", + numbers: []int{2, 4, 1, 7, 5, 0}, + next: []int{2, 4, 5, 0, 1, 7}, + }, + } + for _, test := range nextPermutationTestData { + t.Run(test.description, func(t *testing.T) { + NextPermutation(test.numbers) + + if !reflect.DeepEqual(test.numbers, test.next) { + t.Logf("FAIL: %s", test.description) + t.Fatalf("Expected result:%v\nFound: %v", test.next, test.numbers) + } + }) + } +} From 2f8c7386d296025e961cd864e83a33caba0b0ab0 Mon Sep 17 00:00:00 2001 From: Rares Date: Sat, 11 May 2024 12:22:46 +0300 Subject: [PATCH 177/202] feat(uniquepaths): add solution for unique paths problem (#716) * feat(uniquepaths): add solution for unique paths problem * fix: Remove extra unused memory --- dynamic/uniquepaths.go | 31 +++++++++++++++++++++++++++++++ dynamic/uniquepaths_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 dynamic/uniquepaths.go create mode 100644 dynamic/uniquepaths_test.go diff --git a/dynamic/uniquepaths.go b/dynamic/uniquepaths.go new file mode 100644 index 000000000..3dc96a8e7 --- /dev/null +++ b/dynamic/uniquepaths.go @@ -0,0 +1,31 @@ +// See https://leetcode.com/problems/unique-paths/ +// author: Rares Mateizer (https://github.com/rares985) +package dynamic + +// UniquePaths implements the solution to the "Unique Paths" problem +func UniquePaths(m, n int) int { + if m <= 0 || n <= 0 { + return 0 + } + + grid := make([][]int, m) + for i := range grid { + grid[i] = make([]int, n) + } + + for i := 0; i < m; i++ { + grid[i][0] = 1 + } + + for j := 0; j < n; j++ { + grid[0][j] = 1 + } + + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + grid[i][j] = grid[i-1][j] + grid[i][j-1] + } + } + + return grid[m-1][n-1] +} diff --git a/dynamic/uniquepaths_test.go b/dynamic/uniquepaths_test.go new file mode 100644 index 000000000..ac5accbb4 --- /dev/null +++ b/dynamic/uniquepaths_test.go @@ -0,0 +1,28 @@ +package dynamic + +import ( + "testing" +) + +func TestUniquePaths(t *testing.T) { + testCases := map[string]struct { + m int + n int + want int + }{ + "negative sizes": {-1, -1, 0}, + "empty matrix both dimensions": {0, 0, 0}, + "empty matrix one dimension": {0, 1, 0}, + "one element": {1, 1, 1}, + "small matrix": {2, 2, 2}, + "stress test": {1000, 1000, 2874513998398909184}, + } + + for name, test := range testCases { + t.Run(name, func(t *testing.T) { + if got := UniquePaths(test.m, test.n); got != test.want { + t.Errorf("UniquePaths(%v, %v) = %v, want %v", test.m, test.n, got, test.want) + } + }) + } +} From 6fdad95ac55cbdb5d6252c4d3329b0c5e3373571 Mon Sep 17 00:00:00 2001 From: Daniel <67126972+ddaniel27@users.noreply.github.com> Date: Sun, 23 Jun 2024 00:19:07 -0500 Subject: [PATCH 178/202] [Reimplementation] Sieve of eratosthenes (#722) --- math/prime/sieve2.go | 21 +++++++++++++++++++ math/prime/sieve2_test.go | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 math/prime/sieve2.go create mode 100644 math/prime/sieve2_test.go diff --git a/math/prime/sieve2.go b/math/prime/sieve2.go new file mode 100644 index 000000000..2e2e7b116 --- /dev/null +++ b/math/prime/sieve2.go @@ -0,0 +1,21 @@ +/* sieve2.go - Sieve of Eratosthenes + * Algorithm to generate prime numbers up to a limit + * Author: ddaniel27 + */ +package prime + +func SieveEratosthenes(limit int) []int { + primes := make([]int, 0) + sieve := make([]int, limit+1) // make a slice of size limit+1 + + for i := 2; i <= limit; i++ { + if sieve[i] == 0 { // if the number is not marked as composite + primes = append(primes, i) // add it to the list of primes + for j := i * i; j <= limit; j += i { // mark all multiples of i as composite + sieve[j] = 1 + } + } + } + + return primes +} diff --git a/math/prime/sieve2_test.go b/math/prime/sieve2_test.go new file mode 100644 index 000000000..24912e3d0 --- /dev/null +++ b/math/prime/sieve2_test.go @@ -0,0 +1,43 @@ +package prime_test + +import ( + "reflect" + "testing" + + "github.com/TheAlgorithms/Go/math/prime" +) + +func TestSieveEratosthenes(t *testing.T) { + tests := []struct { + name string + limit int + want []int + }{ + { + name: "First 10 primes test", + limit: 30, + want: []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}, + }, + { + name: "First 20 primes test", + limit: 71, + want: []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := prime.SieveEratosthenes(tt.limit) + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("SieveEratosthenes() = %v, want %v", got, tt.want) + } + }) + } +} + +func BenchmarkSieveEratosthenes(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = prime.SieveEratosthenes(10) + } +} From cddedb6fac5fb2a2ebc26624b14fb03ad04a325e Mon Sep 17 00:00:00 2001 From: Daniel <67126972+ddaniel27@users.noreply.github.com> Date: Tue, 25 Jun 2024 03:11:14 -0500 Subject: [PATCH 179/202] [IMPLEMENTATION] Compressor RLE (#726) * [NEW IMPLEMENTATION] RLE compression algorithm * [FIX] Fix typo * [FIX] Suggestion added --- compression/rlecoding.go | 73 +++++++++++++++ compression/rlecoding_test.go | 161 ++++++++++++++++++++++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 compression/rlecoding.go create mode 100644 compression/rlecoding_test.go diff --git a/compression/rlecoding.go b/compression/rlecoding.go new file mode 100644 index 000000000..c08d3e4bd --- /dev/null +++ b/compression/rlecoding.go @@ -0,0 +1,73 @@ +/* +rlecoding.go +description: run length encoding and decoding +details: +Run-length encoding (RLE) is a simple form of data compression in which runs of data are stored as a single data value and count, rather than as the original run. This is useful when the data contains many repeated values. For example, the data "WWWWWWWWWWWWBWWWWWWWWWWWWBBB" can be compressed to "12W1B12W3B". The algorithm is simple and can be implemented in a few lines of code. +author(s) [ddaniel27](https://github.com/ddaniel27) +*/ +package compression + +import ( + "bytes" + "fmt" + "regexp" + "strconv" + "strings" +) + +// RLEncode takes a string and returns its run-length encoding +func RLEncode(data string) string { + var result string + count := 1 + for i := 0; i < len(data); i++ { + if i+1 < len(data) && data[i] == data[i+1] { + count++ + continue + } + result += fmt.Sprintf("%d%c", count, data[i]) + count = 1 + } + return result +} + +// RLEdecode takes a run-length encoded string and returns the original string +func RLEdecode(data string) string { + var result string + regex := regexp.MustCompile(`(\d+)(\w)`) + + for _, match := range regex.FindAllStringSubmatch(data, -1) { + num, _ := strconv.Atoi(match[1]) + result += strings.Repeat(match[2], num) + } + + return result +} + +// RLEncodebytes takes a byte slice and returns its run-length encoding as a byte slice +func RLEncodebytes(data []byte) []byte { + var result []byte + var count byte = 1 + + for i := 0; i < len(data); i++ { + if i+1 < len(data) && data[i] == data[i+1] { + count++ + continue + } + result = append(result, count, data[i]) + count = 1 + } + + return result +} + +// RLEdecodebytes takes a run-length encoded byte slice and returns the original byte slice +func RLEdecodebytes(data []byte) []byte { + var result []byte + + for i := 0; i < len(data); i += 2 { + count := int(data[i]) + result = append(result, bytes.Repeat([]byte{data[i+1]}, count)...) + } + + return result +} diff --git a/compression/rlecoding_test.go b/compression/rlecoding_test.go new file mode 100644 index 000000000..bf9af6bf6 --- /dev/null +++ b/compression/rlecoding_test.go @@ -0,0 +1,161 @@ +package compression_test + +import ( + "bytes" + "testing" + + "github.com/TheAlgorithms/Go/compression" +) + +func TestCompressionRLEncode(t *testing.T) { + tests := []struct { + name string + data string + want string + }{ + { + name: "test 1", + data: "WWWWWWWWWWWWBWWWWWWWWWWWWBBB", + want: "12W1B12W3B", + }, + { + name: "test 2", + data: "AABCCCDEEEE", + want: "2A1B3C1D4E", + }, + { + name: "test 3", + data: "AAAABBBCCDA", + want: "4A3B2C1D1A", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := compression.RLEncode(tt.data); got != tt.want { + t.Errorf("RLEncode() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCompressionRLEDecode(t *testing.T) { + tests := []struct { + name string + data string + want string + }{ + { + name: "test 1", + data: "12W1B12W3B", + want: "WWWWWWWWWWWWBWWWWWWWWWWWWBBB", + }, + { + name: "test 2", + data: "2A1B3C1D4E", + want: "AABCCCDEEEE", + }, + { + name: "test 3", + data: "4A3B2C1D1A", + want: "AAAABBBCCDA", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := compression.RLEdecode(tt.data); got != tt.want { + t.Errorf("RLEdecode() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCompressionRLEncodeBytes(t *testing.T) { + tests := []struct { + name string + data []byte + want []byte + }{ + { + name: "test 1", + data: []byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB"), + want: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'}, + }, + { + name: "test 2", + data: []byte("AABCCCDEEEE"), + want: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'}, + }, + { + name: "test 3", + data: []byte("AAAABBBCCDA"), + want: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := compression.RLEncodebytes(tt.data); !bytes.Equal(got, tt.want) { + t.Errorf("RLEncodebytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCompressionRLEDecodeBytes(t *testing.T) { + tests := []struct { + name string + data []byte + want []byte + }{ + { + name: "test 1", + data: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'}, + want: []byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB"), + }, + { + name: "test 2", + data: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'}, + want: []byte("AABCCCDEEEE"), + }, + { + name: "test 3", + data: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'}, + want: []byte("AAAABBBCCDA"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := compression.RLEdecodebytes(tt.data); !bytes.Equal(got, tt.want) { + t.Errorf("RLEdecodebytes() = %v, want %v", got, tt.want) + } + }) + } +} + +/* --- BENCHMARKS --- */ +func BenchmarkRLEncode(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = compression.RLEncode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB") + } +} + +func BenchmarkRLEDecode(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = compression.RLEdecode("12W1B12W3B") + } +} + +func BenchmarkRLEncodeBytes(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = compression.RLEncodebytes([]byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB")) + } +} + +func BenchmarkRLEDecodeBytes(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = compression.RLEdecodebytes([]byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'}) + } +} From 483431ba65c09114400a4a8967a07cd57de70bf1 Mon Sep 17 00:00:00 2001 From: Daniel <67126972+ddaniel27@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:19:52 -0500 Subject: [PATCH 180/202] [IMPLEMENTATION] RSA algorithm (#727) * [IMPLEMENTATION] RSA algorithm * [UPDATE] Intended keyGen algorithm with randomness * [FIX] comment fixed * [UPDATE] Implement suggestions * [FIX] Implement suggestions --- cipher/rsa/rsa2.go | 123 ++++++++++++++++++++++++++++++++++++++++ cipher/rsa/rsa2_test.go | 49 ++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 cipher/rsa/rsa2.go create mode 100644 cipher/rsa/rsa2_test.go diff --git a/cipher/rsa/rsa2.go b/cipher/rsa/rsa2.go new file mode 100644 index 000000000..2eceddf10 --- /dev/null +++ b/cipher/rsa/rsa2.go @@ -0,0 +1,123 @@ +/* +rsa2.go +description: RSA encryption and decryption including key generation +details: [RSA wiki](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) +author(s): [ddaniel27](https://github.com/ddaniel27) +*/ +package rsa + +import ( + "encoding/binary" + "fmt" + "math/big" + "math/rand" + + "github.com/TheAlgorithms/Go/math/gcd" + "github.com/TheAlgorithms/Go/math/lcm" + "github.com/TheAlgorithms/Go/math/modular" + "github.com/TheAlgorithms/Go/math/prime" +) + +// rsa struct contains the public key, private key and modulus +type rsa struct { + publicKey uint64 + privateKey uint64 + modulus uint64 +} + +// New initializes the RSA algorithm +// returns the RSA object +func New() *rsa { + // The following code generates keys for RSA encryption/decryption + // 1. Choose two large prime numbers, p and q and compute n = p * q + p, q := randomPrime() // p and q stands for prime numbers + modulus := p * q // n stands for common number + + // 2. Compute the totient of n, lcm(p-1, q-1) + totient := uint64(lcm.Lcm(int64(p-1), int64(q-1))) + + // 3. Choose an integer e such that 1 < e < totient(n) and gcd(e, totient(n)) = 1 + publicKey := uint64(2) // e stands for encryption key (public key) + for publicKey < totient { + if gcd.Recursive(int64(publicKey), int64(totient)) == 1 { + break + } + publicKey++ + } + + // 4. Compute d such that d * e ≡ 1 (mod totient(n)) + inv, _ := modular.Inverse(int64(publicKey), int64(totient)) + privateKey := uint64(inv) + + return &rsa{ + publicKey: publicKey, + privateKey: privateKey, + modulus: modulus, + } +} + +// EncryptString encrypts the data using RSA algorithm +// returns the encrypted string +func (rsa *rsa) EncryptString(data string) string { + var nums []byte + + for _, char := range data { + slice := make([]byte, 8) + binary.BigEndian.PutUint64( // convert uint64 to byte slice + slice, + encryptDecryptInt(rsa.publicKey, rsa.modulus, uint64(char)), // encrypt each character + ) + nums = append(nums, slice...) + } + + return string(nums) +} + +// DecryptString decrypts the data using RSA algorithm +// returns the decrypted string +func (rsa *rsa) DecryptString(data string) string { + result := "" + middle := []byte(data) + + for i := 0; i < len(middle); i += 8 { + if i+8 > len(middle) { + break + } + + slice := middle[i : i+8] + num := binary.BigEndian.Uint64(slice) // convert byte slice to uint64 + result += fmt.Sprintf("%c", encryptDecryptInt(rsa.privateKey, rsa.modulus, num)) + } + + return result +} + +// GetPublicKey returns the public key and modulus +func (rsa *rsa) GetPublicKey() (uint64, uint64) { + return rsa.publicKey, rsa.modulus +} + +// GetPrivateKey returns the private key +func (rsa *rsa) GetPrivateKey() uint64 { + return rsa.privateKey +} + +// encryptDecryptInt encrypts or decrypts the data using RSA algorithm +func encryptDecryptInt(e, n, data uint64) uint64 { + pow := new(big.Int).Exp(big.NewInt(int64(data)), big.NewInt(int64(e)), big.NewInt(int64(n))) + return pow.Uint64() +} + +// randomPrime returns two random prime numbers +func randomPrime() (uint64, uint64) { + sieve := prime.SieveEratosthenes(1000) + sieve = sieve[10:] // remove first 10 prime numbers (small numbers) + index1 := rand.Intn(len(sieve)) + index2 := rand.Intn(len(sieve)) + + for index1 == index2 { + index2 = rand.Intn(len(sieve)) + } + + return uint64(sieve[index1]), uint64(sieve[index2]) +} diff --git a/cipher/rsa/rsa2_test.go b/cipher/rsa/rsa2_test.go new file mode 100644 index 000000000..29e15c557 --- /dev/null +++ b/cipher/rsa/rsa2_test.go @@ -0,0 +1,49 @@ +package rsa_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/cipher/rsa" +) + +func TestRSA(t *testing.T) { + tests := []struct { + name string + message string + }{ + { + name: "Encrypt letter 'a' and decrypt it back", + message: "a", + }, + { + name: "Encrypt 'Hello, World!' and decrypt it back", + message: "Hello, World!", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rsa := rsa.New() + encrypted := rsa.EncryptString(tt.message) + decrypted := rsa.DecryptString(encrypted) + if decrypted != tt.message { + t.Errorf("expected %s, got %s", tt.message, decrypted) + } + }) + } +} + +func BenchmarkRSAEncryption(b *testing.B) { + rsa := rsa.New() + for i := 0; i < b.N; i++ { + rsa.EncryptString("Hello, World!") + } +} + +func BenchmarkRSADecryption(b *testing.B) { + rsa := rsa.New() + encrypted := rsa.EncryptString("Hello, World!") + for i := 0; i < b.N; i++ { + rsa.DecryptString(encrypted) + } +} From ee6fef2680d8ebb08519fc83284a9526c114f4e1 Mon Sep 17 00:00:00 2001 From: Manuel Rojas Ramos <59751051+manuelrojas19@users.noreply.github.com> Date: Thu, 18 Jul 2024 05:41:54 -0600 Subject: [PATCH 181/202] Improved HashMap implementation (#729) * Improved HashMap implementation * Renamed Make to New --- structure/hashmap/hashmap.go | 119 +++++++++++++----------------- structure/hashmap/hashmap_test.go | 5 +- 2 files changed, 52 insertions(+), 72 deletions(-) diff --git a/structure/hashmap/hashmap.go b/structure/hashmap/hashmap.go index b0f5dbb1d..591ac8685 100644 --- a/structure/hashmap/hashmap.go +++ b/structure/hashmap/hashmap.go @@ -13,119 +13,100 @@ type node struct { next *node } -// HashMap is golang implementation of hashmap +// HashMap is a Golang implementation of a hashmap type HashMap struct { capacity uint64 size uint64 table []*node } -// New return new HashMap instance -func New() *HashMap { +// DefaultNew returns a new HashMap instance with default values +func DefaultNew() *HashMap { return &HashMap{ capacity: defaultCapacity, table: make([]*node, defaultCapacity), } } -// Make creates a new HashMap instance with input size and capacity -func Make(size, capacity uint64) HashMap { - return HashMap{ +// New creates a new HashMap instance with the specified size and capacity +func New(size, capacity uint64) *HashMap { + return &HashMap{ size: size, capacity: capacity, table: make([]*node, capacity), } } -// Get returns value associated with given key +// Get returns the value associated with the given key func (hm *HashMap) Get(key any) any { - node := hm.getNodeByHash(hm.hash(key)) - + node := hm.getNodeByKey(key) if node != nil { return node.value } - return nil } -// Put puts new key value in hashmap -func (hm *HashMap) Put(key any, value any) any { - return hm.putValue(hm.hash(key), key, value) -} - -// Contains checks if given key is stored in hashmap -func (hm *HashMap) Contains(key any) bool { - node := hm.getNodeByHash(hm.hash(key)) - return node != nil -} - -func (hm *HashMap) putValue(hash uint64, key any, value any) any { - if hm.capacity == 0 { - hm.capacity = defaultCapacity - hm.table = make([]*node, defaultCapacity) - } - - node := hm.getNodeByHash(hash) - - if node == nil { - hm.table[hash] = newNode(key, value) - - } else if node.key == key { - hm.table[hash] = newNodeWithNext(key, value, node) - return value - +// Put inserts a new key-value pair into the hashmap +func (hm *HashMap) Put(key, value any) { + index := hm.hash(key) + if hm.table[index] == nil { + hm.table[index] = &node{key: key, value: value} } else { - hm.resize() - return hm.putValue(hash, key, value) + current := hm.table[index] + for { + if current.key == key { + current.value = value + return + } + if current.next == nil { + break + } + current = current.next + } + current.next = &node{key: key, value: value} } - hm.size++ + if float64(hm.size)/float64(hm.capacity) > 0.75 { + hm.resize() + } +} - return value - +// Contains checks if the given key is stored in the hashmap +func (hm *HashMap) Contains(key any) bool { + return hm.getNodeByKey(key) != nil } -func (hm *HashMap) getNodeByHash(hash uint64) *node { - return hm.table[hash] +// getNodeByKey finds the node associated with the given key +func (hm *HashMap) getNodeByKey(key any) *node { + index := hm.hash(key) + current := hm.table[index] + for current != nil { + if current.key == key { + return current + } + current = current.next + } + return nil } +// resize doubles the capacity of the hashmap and rehashes all existing entries func (hm *HashMap) resize() { + oldTable := hm.table hm.capacity <<= 1 - - tempTable := hm.table - hm.table = make([]*node, hm.capacity) + hm.size = 0 - for i := 0; i < len(tempTable); i++ { - node := tempTable[i] - if node == nil { - continue + for _, head := range oldTable { + for current := head; current != nil; current = current.next { + hm.Put(current.key, current.value) } - - hm.table[hm.hash(node.key)] = node - } -} - -func newNode(key any, value any) *node { - return &node{ - key: key, - value: value, - } -} - -func newNodeWithNext(key any, value any, next *node) *node { - return &node{ - key: key, - value: value, - next: next, } } +// hash generates a hash value for the given key func (hm *HashMap) hash(key any) uint64 { h := fnv.New64a() _, _ = h.Write([]byte(fmt.Sprintf("%v", key))) - hashValue := h.Sum64() - return (hm.capacity - 1) & (hashValue ^ (hashValue >> 16)) } diff --git a/structure/hashmap/hashmap_test.go b/structure/hashmap/hashmap_test.go index 1699f8c25..7b55df0bb 100644 --- a/structure/hashmap/hashmap_test.go +++ b/structure/hashmap/hashmap_test.go @@ -7,8 +7,7 @@ import ( ) func TestHashMap(t *testing.T) { - - mp := hashmap.New() + mp := hashmap.DefaultNew() t.Run("Test 1: Put(10) and checking if Get() is correct", func(t *testing.T) { mp.Put("test", 10) @@ -67,7 +66,7 @@ func TestHashMap(t *testing.T) { }) t.Run("Test 8: Resizing a map", func(t *testing.T) { - mp := hashmap.Make(4, 4) + mp := hashmap.New(4, 4) for i := 0; i < 20; i++ { mp.Put(i, 40) From 32bb6714abae8fbcb6cdfb1939ca780f191eebab Mon Sep 17 00:00:00 2001 From: Ganesh Manchi <62894745+ganeshvenkatasai@users.noreply.github.com> Date: Wed, 24 Jul 2024 19:45:45 +0530 Subject: [PATCH 182/202] feat: add Circle Sort algorithm (#730) * feat: add Circle Sort algorithm * Add test and benchmark for Circle sort algorithm --- sort/circlesort.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 8 ++++++++ 2 files changed, 52 insertions(+) create mode 100644 sort/circlesort.go diff --git a/sort/circlesort.go b/sort/circlesort.go new file mode 100644 index 000000000..c18b0d408 --- /dev/null +++ b/sort/circlesort.go @@ -0,0 +1,44 @@ +// Package sort implements various sorting algorithms. +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// Circle sorts an array using the circle sort algorithm. +func Circle[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { + return arr + } + for doSort(arr, 0, len(arr)-1) { + } + return arr +} + +// doSort is the recursive function that implements the circle sort algorithm. +func doSort[T constraints.Ordered](arr []T, left, right int) bool { + if left == right { + return false + } + swapped := false + low := left + high := right + + for low < high { + if arr[low] > arr[high] { + arr[low], arr[high] = arr[high], arr[low] + swapped = true + } + low++ + high-- + } + + if low == high && arr[low] > arr[high+1] { + arr[low], arr[high+1] = arr[high+1], arr[low] + swapped = true + } + + mid := left + (right-left)/2 + leftHalf := doSort(arr, left, mid) + rightHalf := doSort(arr, mid+1, right) + + return swapped || leftHalf || rightHalf +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 63ca010e0..213b17e56 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -190,6 +190,10 @@ func TestTimsort(t *testing.T) { testFramework(t, sort.Timsort[int]) } +func TestCircle(t *testing.T) { + testFramework(t, sort.Circle[int]) +} + // END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -328,3 +332,7 @@ func BenchmarkCycle(b *testing.B) { func BenchmarkTimsort(b *testing.B) { benchmarkFramework(b, sort.Timsort[int]) } + +func BenchmarkCircle(b *testing.B) { + benchmarkFramework(b, sort.Circle[int]) +} From d7470bafe7617cd885810e3d5e9e4d19b3d8f34a Mon Sep 17 00:00:00 2001 From: Aram Ceballos Date: Sun, 11 Aug 2024 02:40:16 -0700 Subject: [PATCH 183/202] feat: add circular queue array data structure (#731) * feat: add circular queue array data structure * test: add missing error handling --- structure/circularqueue/circularqueue_test.go | 267 ++++++++++++++++++ structure/circularqueue/circularqueuearray.go | 96 +++++++ 2 files changed, 363 insertions(+) create mode 100644 structure/circularqueue/circularqueue_test.go create mode 100644 structure/circularqueue/circularqueuearray.go diff --git a/structure/circularqueue/circularqueue_test.go b/structure/circularqueue/circularqueue_test.go new file mode 100644 index 000000000..0820b0470 --- /dev/null +++ b/structure/circularqueue/circularqueue_test.go @@ -0,0 +1,267 @@ +package circularqueue + +import "testing" + +func TestCircularQueue(t *testing.T) { + t.Run("Size Check", func(t *testing.T) { + _, err := NewCircularQueue[int](-3) + if err == nil { + t.Errorf("Expected error, got nil") + } + + queue, _ := NewCircularQueue[int](5) + expectedSize := 5 + gotSize := queue.Size() + if gotSize != expectedSize { + t.Errorf("Expected size: %v, got: %v\n", expectedSize, gotSize) + } + + if err := queue.Enqueue(1); err != nil { + t.Error(err) + } + if err := queue.Enqueue(2); err != nil { + t.Error(err) + } + if err := queue.Enqueue(3); err != nil { + t.Error(err) + } + if err := queue.Enqueue(4); err != nil { + t.Error(err) + } + if err := queue.Enqueue(5); err != nil { + t.Error(err) + } + + err = queue.Enqueue(6) + if err == nil { + t.Errorf("Expected error, got nil") + } + + expectedSize = 5 + gotSize = queue.Size() + if gotSize != expectedSize { + t.Errorf("Expected size: %v, got: %v\n", expectedSize, gotSize) + } + + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + + err = queue.Enqueue(6) + if err != nil { + t.Errorf("Expected nil, got error: %v\n", err.Error()) + } + + expectedSize = 5 + gotSize = queue.Size() + if gotSize != expectedSize { + t.Errorf("Expected size: %v, got: %v\n", expectedSize, gotSize) + } + }) + t.Run("Enqueue", func(t *testing.T) { + queue, _ := NewCircularQueue[int](10) + + if err := queue.Enqueue(1); err != nil { + t.Error(err) + } + if err := queue.Enqueue(2); err != nil { + t.Error(err) + } + if err := queue.Enqueue(3); err != nil { + t.Error(err) + } + + expected := 1 + got, err := queue.Peek() + if err != nil { + t.Error(err.Error()) + } + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + }) + t.Run("Dequeue", func(t *testing.T) { + queue, _ := NewCircularQueue[string](10) + + if err := queue.Enqueue("one"); err != nil { + t.Error(err) + } + if err := queue.Enqueue("two"); err != nil { + t.Error(err) + } + if err := queue.Enqueue("three"); err != nil { + t.Error(err) + } + + expected := "one" + got, err := queue.Dequeue() + if err != nil { + t.Error(err.Error()) + } + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + + expected = "two" + got, err = queue.Peek() + if err != nil { + t.Error(err.Error()) + } + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + }) + t.Run("Circularity", func(t *testing.T) { + queue, _ := NewCircularQueue[int](10) + + if err := queue.Enqueue(1); err != nil { + t.Error(err) + } + if err := queue.Enqueue(2); err != nil { + t.Error(err) + } + if err := queue.Enqueue(3); err != nil { + t.Error(err) + } + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + if err := queue.Enqueue(4); err != nil { + t.Error(err) + } + if err := queue.Enqueue(5); err != nil { + t.Error(err) + } + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + + expected := 4 + got, err := queue.Peek() + if err != nil { + t.Error(err.Error()) + } + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + }) + t.Run("IsFull", func(t *testing.T) { + queue, _ := NewCircularQueue[bool](2) + if err := queue.Enqueue(false); err != nil { + t.Error(err) + } + if err := queue.Enqueue(true); err != nil { + t.Error(err) + } + + expected := true + got := queue.IsFull() + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + if _, err := queue.Dequeue(); err != nil { + t.Error(err) + } + + expected = false + got = queue.IsFull() + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + }) + t.Run("IsEmpty", func(t *testing.T) { + queue, _ := NewCircularQueue[float64](2) + + expected := true + got := queue.IsEmpty() + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + + if err := queue.Enqueue(1.0); err != nil { + t.Error(err) + } + + expected = false + got = queue.IsEmpty() + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + + }) + t.Run("Peak", func(t *testing.T) { + queue, _ := NewCircularQueue[rune](10) + + if err := queue.Enqueue('a'); err != nil { + t.Error(err) + } + if err := queue.Enqueue('b'); err != nil { + t.Error(err) + } + if err := queue.Enqueue('c'); err != nil { + t.Error(err) + } + + expected := 'a' + got, err := queue.Peek() + if err != nil { + t.Error(err.Error()) + } + + if got != expected { + t.Errorf("Expected: %v got: %v\n", expected, got) + } + }) +} + +// BenchmarkCircularQueue benchmarks the CircularQueue implementation. +func BenchmarkCircularQueue(b *testing.B) { + b.Run("Enqueue", func(b *testing.B) { + queue, _ := NewCircularQueue[int](1000) + for i := 0; i < b.N; i++ { + if err := queue.Enqueue(i); err != nil { + b.Error(err) + } + } + }) + + b.Run("Dequeue", func(b *testing.B) { + queue, _ := NewCircularQueue[int](1000) + for i := 0; i < 1000; i++ { + if err := queue.Enqueue(i); err != nil { + b.Error(err) + } + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := queue.Dequeue(); err != nil { + b.Error(err) + } + } + }) + + b.Run("Peek", func(b *testing.B) { + queue, _ := NewCircularQueue[int](1000) + for i := 0; i < 1000; i++ { + if err := queue.Enqueue(i); err != nil { + b.Error(err) + } + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := queue.Peek(); err != nil { + b.Error(err) + } + } + }) +} diff --git a/structure/circularqueue/circularqueuearray.go b/structure/circularqueue/circularqueuearray.go new file mode 100644 index 000000000..97447fa4a --- /dev/null +++ b/structure/circularqueue/circularqueuearray.go @@ -0,0 +1,96 @@ +// circularqueuearray.go +// description: Implementation of a circular queue data structure +// details: +// This file contains the implementation of a circular queue data structure +// using generics in Go. The circular queue supports basic operations such as +// enqueue, dequeue, peek, and checks for full and empty states. +// author(s): [Aram Ceballos](https://github.com/aramceballos) +// ref: https://www.programiz.com/dsa/circular-queue +// ref: https://en.wikipedia.org/wiki/Circular_buffer + +// Package queue provides an implementation of a circular queue data structure. +package circularqueue + +// errors package: Provides functions to create and manipulate error values +import ( + "errors" +) + +// CircularQueue represents a circular queue data structure. +type CircularQueue[T any] struct { + items []T + front int + rear int + size int +} + +// NewCircularQueue creates a new CircularQueue with the given size. +// Returns an error if the size is less than or equal to 0. +func NewCircularQueue[T any](size int) (*CircularQueue[T], error) { + if size <= 0 { + return nil, errors.New("size must be greater than 0") + } + return &CircularQueue[T]{ + items: make([]T, size), + front: -1, + rear: -1, + size: size, + }, nil +} + +// Enqueue adds an item to the rear of the queue. +// Returns an error if the queue is full. +func (cq *CircularQueue[T]) Enqueue(item T) error { + if cq.IsFull() { + return errors.New("queue is full") + } + if cq.IsEmpty() { + cq.front = 0 + } + cq.rear = (cq.rear + 1) % cq.size + cq.items[cq.rear] = item + return nil +} + +// Dequeue removes and returns the item from the front of the queue. +// Returns an error if the queue is empty. +func (cq *CircularQueue[T]) Dequeue() (T, error) { + if cq.IsEmpty() { + var zeroValue T + return zeroValue, errors.New("queue is empty") + } + retVal := cq.items[cq.front] + if cq.front == cq.rear { + cq.front = -1 + cq.rear = -1 + } else { + cq.front = (cq.front + 1) % cq.size + } + return retVal, nil +} + +// IsFull checks if the queue is full. +func (cq *CircularQueue[T]) IsFull() bool { + return (cq.front == 0 && cq.rear == cq.size-1) || cq.front == cq.rear+1 +} + +// IsEmpty checks if the queue is empty. +func (cq *CircularQueue[T]) IsEmpty() bool { + return cq.front == -1 && cq.rear == -1 +} + +// Peek returns the item at the front of the queue without removing it. +// Returns an error if the queue is empty. +func (cq *CircularQueue[T]) Peek() (T, error) { + if cq.IsEmpty() { + var zeroValue T + return zeroValue, errors.New("queue is empty") + } + + return cq.items[cq.front], nil +} + +// Size returns the size of the queue. +func (cq *CircularQueue[T]) Size() int { + return cq.size +} From 662e8e9e96d9c8d473b70fab27de9b3af54a1c22 Mon Sep 17 00:00:00 2001 From: Alok Menghrajani <441307+alokmenghrajani@users.noreply.github.com> Date: Tue, 20 Aug 2024 17:13:06 +0200 Subject: [PATCH 184/202] nit: fix code comment in binarytodecimal.go and in decimaltobinary.go (#733) --- README.md | 4 ++-- conversion/binarytodecimal.go | 2 +- conversion/decimaltobinary.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ace320588..51f244249 100644 --- a/README.md +++ b/README.md @@ -229,8 +229,8 @@ Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. 1. [`Base64Decode`](./conversion/base64.go#L57): Base64Decode decodes the received input base64 string into a byte slice. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4 2. [`Base64Encode`](./conversion/base64.go#L19): Base64Encode encodes the received input bytes slice into a base64 string. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4 -3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return it's Decimal equivalent as integer. -4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return it's Binary equivalent as string. +3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return its Decimal equivalent as integer. +4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return its Binary equivalent as string. 5. [`FuzzBase64Encode`](./conversion/base64_test.go#L113): No description provided. 6. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x) into the individual components: red, green and blue 7. [`IntToRoman`](./conversion/inttoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999. diff --git a/conversion/binarytodecimal.go b/conversion/binarytodecimal.go index bc67745fd..6181d3bc2 100644 --- a/conversion/binarytodecimal.go +++ b/conversion/binarytodecimal.go @@ -21,7 +21,7 @@ import ( var isValid = regexp.MustCompile("^[0-1]{1,}$").MatchString // BinaryToDecimal() function that will take Binary number as string, -// and return it's Decimal equivalent as integer. +// and return its Decimal equivalent as an integer. func BinaryToDecimal(binary string) (int, error) { if !isValid(binary) { return -1, errors.New("not a valid binary string") diff --git a/conversion/decimaltobinary.go b/conversion/decimaltobinary.go index 63ef8b1c0..e74765708 100644 --- a/conversion/decimaltobinary.go +++ b/conversion/decimaltobinary.go @@ -28,7 +28,7 @@ func Reverse(str string) string { } // DecimalToBinary() function that will take Decimal number as int, -// and return it's Binary equivalent as string. +// and return its Binary equivalent as a string. func DecimalToBinary(num int) (string, error) { if num < 0 { return "", errors.New("integer must have +ve value") From 24c7f1f5ede01e1a7b0f68a35a878889a8dc4045 Mon Sep 17 00:00:00 2001 From: Carter <102479896+Carter907@users.noreply.github.com> Date: Tue, 20 Aug 2024 12:04:56 -0400 Subject: [PATCH 185/202] feat: add determinant implementation for matrix (#732) * feat: add determinant implementation for matrix Added the Determinant method for the Matrix struct under math/matrix. This method returns the determinant of the matrix. * fix: determinant spelling and linting Fixed the spelling error in determinant.go. Fixed ineffectual error assignment in determinant_test.go. * test: add test for matrix determinant Added a test case for single-element matrix. --------- Co-authored-by: Rak Laptudirm --- math/matrix/determinant.go | 59 +++++++++++++ math/matrix/determinant_test.go | 142 ++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 math/matrix/determinant.go create mode 100644 math/matrix/determinant_test.go diff --git a/math/matrix/determinant.go b/math/matrix/determinant.go new file mode 100644 index 000000000..d2570f8f8 --- /dev/null +++ b/math/matrix/determinant.go @@ -0,0 +1,59 @@ +// determinant.go +// description: This method finds the determinant of a matrix. +// details: For a theoretical explanation as for what the determinant +// represents, see the [Wikipedia Article](https://en.wikipedia.org/wiki/Determinant) +// author [Carter907](https://github.com/Carter907) +// see determinant_test.go + +package matrix + +import ( + "errors" +) + +// Calculates the determinant of the matrix. +// This method only works for square matrices (e.i. matrices with equal rows and columns). +func (mat Matrix[T]) Determinant() (T, error) { + + var determinant T = 0 + var elements = mat.elements + if mat.rows != mat.columns { + + return 0, errors.New("Matrix rows and columns must equal in order to find the determinant.") + } + + // Specify base cases for different sized matrices. + switch mat.rows { + case 1: + return elements[0][0], nil + case 2: + return elements[0][0]*elements[1][1] - elements[1][0]*elements[0][1], nil + default: + for i := 0; i < mat.rows; i++ { + + var initialValue T = 0 + minor := New(mat.rows-1, mat.columns-1, initialValue) + // Fill the contents of minor excluding the 0th row and the ith column. + for j, minor_i := 1, 0; j < mat.rows && minor_i < minor.rows; j, minor_i = j+1, minor_i+1 { + for k, minor_j := 0, 0; k < mat.rows && minor_j < minor.rows; k, minor_j = k+1, minor_j+1 { + if k != i { + minor.elements[minor_i][minor_j] = elements[j][k] + } else { + minor_j-- // Decrement the column of minor to account for skipping the ith column of the matrix. + } + } + } + + if i%2 == 0 { + minor_det, _ := minor.Determinant() + + determinant += elements[0][i] * minor_det + } else { + minor_det, _ := minor.Determinant() + + determinant += elements[0][i] * minor_det + } + } + return determinant, nil + } +} diff --git a/math/matrix/determinant_test.go b/math/matrix/determinant_test.go new file mode 100644 index 000000000..801058ff2 --- /dev/null +++ b/math/matrix/determinant_test.go @@ -0,0 +1,142 @@ +package matrix_test + +import ( + "errors" + "math" + "math/rand" + "testing" + + "github.com/TheAlgorithms/Go/math/matrix" +) + +// Test different matrix contents +func TestMatrixDeterminant(t *testing.T) { + // Find Determinant of a 2 by 2 matrix. + matrix1, err := matrix.NewFromElements([][]int{ + {3, 8}, + {4, 6}, + }) + if err != nil { + t.Fatalf("Error creating 3 by 3 matrix: %v", err) + } + determinant, err := matrix1.Determinant() + if err != nil { + t.Fatalf("Error returned from 3 by 3 matrix: %v", err) + } + if determinant != -14 { + t.Fatalf("Determinant returned for a 3 by 3 matrix was %d; wanted -14", determinant) + } + + // Find Dertminant of a 1 by 1 matrix + expectedValue := rand.Intn(math.MaxInt) + matrix2, err := matrix.NewFromElements([][]int{ + {expectedValue}, + }) + if err != nil { + t.Fatalf("Error creating 1 by 1 matrix: %v", err) + } + determinant, err = matrix2.Determinant() + if err != nil { + t.Fatalf("Error returned from 1 by 1 matrix: %v", err) + } + if determinant != expectedValue { + t.Fatalf("Determinant returned for a 1 by 1 matrix was %d; wanted %d", determinant, expectedValue) + } + +} + +func TestEmptyMatrix(t *testing.T) { + emptyElements := [][]int{} + matrix, err := matrix.NewFromElements(emptyElements) + + if err != nil { + t.Fatalf("Error creating Matrix with empty elements: %v", err) + } + + determinant, err := matrix.Determinant() + + if err != nil { + t.Fatalf("Determinant returned an error for empty matrix: %v", err) + } + + // Check that 0 is returned from an empty matrix. + expectedValue := 0 + if determinant != expectedValue { + t.Errorf("Determinant returned from empty matrix was %d; wanted %d", determinant, expectedValue) + } + +} + +func TestNonSquareMatrix(t *testing.T) { + // Creating non-square matrix for testing. + initialValue := 0 + initialRows := 4 + initialCols := 2 + + nonSquareMatrix := matrix.New(initialRows, initialCols, initialValue) + + determinant, err := nonSquareMatrix.Determinant() + // Check if non square matrix returns an error. + if err == nil { + t.Fatalf("No error was returned for a non-square matrix") + } + + // Check if the correct error was returned. + expectedError := errors.New("Matrix rows and columns must equal in order to find the determinant.") + + if err.Error() != expectedError.Error() { + t.Errorf("Error returned from non-square matrix was \n\"%v\"; \nwanted \n\"%v\"", err, expectedError) + } + + // Check if the determinant of the non-square matrix is 0. + if determinant != 0 { + t.Errorf("Determinant of non-square matrix was not 0 but was %d", determinant) + } + +} + +// Test matrix returned from matrix.New +func TestDefaultMatrix(t *testing.T) { + initialValue := 0 + initialRows := 3 + initialCols := 3 + defaultMatrix := matrix.New(initialRows, initialCols, initialValue) + + determinant, err := defaultMatrix.Determinant() + + if err != nil { + t.Fatalf("Error finding the determinant of 3 by 3 default matrix: %v.", err) + } + expectedValue := 0 + if determinant != expectedValue { + t.Errorf("Determinant of the default matrix with an initial value 0 was %d; wanted %d.", initialValue, expectedValue) + } +} + +// Benchmark a 3 by 3 matrix for computational throughput +func BenchmarkSmallMatrixDeterminant(b *testing.B) { + // Create a 3 by 3 matrix for benchmarking + rows := 3 + columns := 3 + initialValue := 0 + matrix := matrix.New(rows, columns, initialValue) + + for i := 0; i < b.N; i++ { + _, _ = matrix.Determinant() + } +} + +// Benchmark a 10 by 10 matrix for computational throughput. +func BenchmarkMatrixDeterminant(b *testing.B) { + // Create a 10 by 10 matrix for benchmarking + rows := 10 + columns := 10 + initialValue := 0 + matrix := matrix.New(rows, columns, initialValue) + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + _, _ = matrix.Determinant() + } +} From 67eebcba7b384f69aa1e8c9d2bee48f9966953f0 Mon Sep 17 00:00:00 2001 From: Y L <86551259+soondubu137@users.noreply.github.com> Date: Sun, 8 Sep 2024 15:27:10 -0500 Subject: [PATCH 186/202] feat: add Kahn's algorithm for topological sort (#735) * feat: implemented kahn's algorithm * doc: added doc for graph/kahn.go * test: added tests for graph/kahn.go --- graph/kahn.go | 66 ++++++++++++++++++++++++++ graph/kahn_test.go | 115 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 graph/kahn.go create mode 100644 graph/kahn_test.go diff --git a/graph/kahn.go b/graph/kahn.go new file mode 100644 index 000000000..6f9d44d71 --- /dev/null +++ b/graph/kahn.go @@ -0,0 +1,66 @@ +// Kahn's algorithm computes a topological ordering of a directed acyclic graph (DAG). +// Time Complexity: O(V + E) +// Space Complexity: O(V + E) +// Reference: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm +// see graph.go, topological.go, kahn_test.go + +package graph + +// Kahn's algorithm computes a topological ordering of a directed acyclic graph (DAG). +// `n` is the number of vertices, +// `dependencies` is a list of directed edges, where each pair [a, b] represents +// a directed edge from a to b (i.e. b depends on a). +// Vertices are assumed to be labelled 0, 1, ..., n-1. +// If the graph is not a DAG, the function returns nil. +func Kahn(n int, dependencies [][]int) []int { + g := Graph{vertices: n, Directed: true} + // track the in-degree (number of incoming edges) of each vertex + inDegree := make([]int, n) + + // populate g with edges, increase the in-degree counts accordingly + for _, d := range dependencies { + // make sure we don't add the same edge twice + if _, ok := g.edges[d[0]][d[1]]; !ok { + g.AddEdge(d[0], d[1]) + inDegree[d[1]]++ + } + } + + // queue holds all vertices with in-degree 0 + // these vertices have no dependency and thus can be ordered first + queue := make([]int, 0, n) + + for i := 0; i < n; i++ { + if inDegree[i] == 0 { + queue = append(queue, i) + } + } + + // order holds a valid topological order + order := make([]int, 0, n) + + // process the dependency-free vertices + // every time we process a vertex, we "remove" it from the graph + for len(queue) > 0 { + // pop the first vertex from the queue + vtx := queue[0] + queue = queue[1:] + // add the vertex to the topological order + order = append(order, vtx) + // "remove" all the edges coming out of this vertex + // every time we remove an edge, the corresponding in-degree reduces by 1 + // if all dependencies on a vertex is removed, enqueue the vertex + for neighbour := range g.edges[vtx] { + inDegree[neighbour]-- + if inDegree[neighbour] == 0 { + queue = append(queue, neighbour) + } + } + } + + // if the graph is a DAG, order should contain all the certices + if len(order) != n { + return nil + } + return order +} diff --git a/graph/kahn_test.go b/graph/kahn_test.go new file mode 100644 index 000000000..71536b4f6 --- /dev/null +++ b/graph/kahn_test.go @@ -0,0 +1,115 @@ +package graph + +import ( + "testing" +) + +func TestKahn(t *testing.T) { + testCases := []struct { + name string + n int + dependencies [][]int + wantNil bool + }{ + { + "linear graph", + 3, + [][]int{{0, 1}, {1, 2}}, + false, + }, + { + "diamond graph", + 4, + [][]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}}, + false, + }, + { + "star graph", + 5, + [][]int{{0, 1}, {0, 2}, {0, 3}, {0, 4}}, + false, + }, + { + "disconnected graph", + 5, + [][]int{{0, 1}, {0, 2}, {3, 4}}, + false, + }, + { + "cycle graph 1", + 4, + [][]int{{0, 1}, {1, 2}, {2, 3}, {3, 0}}, + true, + }, + { + "cycle graph 2", + 4, + [][]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}}, + true, + }, + { + "single node graph", + 1, + [][]int{}, + false, + }, + { + "empty graph", + 0, + [][]int{}, + false, + }, + { + "redundant dependencies", + 4, + [][]int{{0, 1}, {1, 2}, {1, 2}, {2, 3}}, + false, + }, + { + "island vertex", + 4, + [][]int{{0, 1}, {0, 2}}, + false, + }, + { + "more complicated graph", + 14, + [][]int{{1, 9}, {2, 0}, {3, 2}, {4, 5}, {4, 6}, {4, 7}, {6, 7}, + {7, 8}, {9, 4}, {10, 0}, {10, 1}, {10, 12}, {11, 13}, + {12, 0}, {12, 11}, {13, 5}}, + false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actual := Kahn(tc.n, tc.dependencies) + if tc.wantNil { + if actual != nil { + t.Errorf("Kahn(%d, %v) = %v; want nil", tc.n, tc.dependencies, actual) + } + } else { + if actual == nil { + t.Errorf("Kahn(%d, %v) = nil; want valid order", tc.n, tc.dependencies) + } else { + seen := make([]bool, tc.n) + positions := make([]int, tc.n) + for i, v := range actual { + seen[v] = true + positions[v] = i + } + for i, v := range seen { + if !v { + t.Errorf("missing vertex %v", i) + } + } + for _, d := range tc.dependencies { + if positions[d[0]] > positions[d[1]] { + t.Errorf("dependency %v not satisfied", d) + } + } + } + } + }) + } +} From 495cff8b21625552eb173351fb99345ae49682a6 Mon Sep 17 00:00:00 2001 From: Y L <86551259+soondubu137@users.noreply.github.com> Date: Sun, 8 Sep 2024 15:41:20 -0500 Subject: [PATCH 187/202] fix: added path compression to UnionFind (#734) * fix: implemented path compression in Find & removed unnecessary return value of Union * feat: added a few test cases * fix: modified kruskal implementation to conform to the updated Union method * fix: changed to pointer receivers --------- Co-authored-by: Rak Laptudirm --- graph/kruskal.go | 2 +- graph/unionfind.go | 45 ++++++++++++++++++++++------------------- graph/unionfind_test.go | 23 ++++++++++++++------- 3 files changed, 41 insertions(+), 29 deletions(-) diff --git a/graph/kruskal.go b/graph/kruskal.go index 193e3f236..1b0328da3 100644 --- a/graph/kruskal.go +++ b/graph/kruskal.go @@ -42,7 +42,7 @@ func KruskalMST(n int, edges []Edge) ([]Edge, int) { // Add the weight of the edge to the total cost cost += edge.Weight // Merge the sets containing the start and end vertices of the current edge - u = u.Union(int(edge.Start), int(edge.End)) + u.Union(int(edge.Start), int(edge.End)) } } diff --git a/graph/unionfind.go b/graph/unionfind.go index 7a922f3cc..42714ab39 100644 --- a/graph/unionfind.go +++ b/graph/unionfind.go @@ -3,12 +3,13 @@ // is used to efficiently maintain connected components in a graph that undergoes dynamic changes, // such as edges being added or removed over time // Worst Case Time Complexity: The time complexity of find operation is nearly constant or -//O(α(n)), where where α(n) is the inverse Ackermann function +//O(α(n)), where α(n) is the inverse Ackermann function // practically, this is a very slowly growing function making the time complexity for find //operation nearly constant. // The time complexity of the union operation is also nearly constant or O(α(n)) // Worst Case Space Complexity: O(n), where n is the number of nodes or element in the structure // Reference: https://www.scaler.com/topics/data-structures/disjoint-set/ +// https://en.wikipedia.org/wiki/Disjoint-set_data_structure // Author: Mugdha Behere[https://github.com/MugdhaBehere] // see: unionfind.go, unionfind_test.go @@ -17,43 +18,45 @@ package graph // Defining the union-find data structure type UnionFind struct { parent []int - size []int + rank []int } // Initialise a new union find data structure with s nodes func NewUnionFind(s int) UnionFind { parent := make([]int, s) - size := make([]int, s) - for k := 0; k < s; k++ { - parent[k] = k - size[k] = 1 + rank := make([]int, s) + for i := 0; i < s; i++ { + parent[i] = i + rank[i] = 1 } - return UnionFind{parent, size} + return UnionFind{parent, rank} } -// to find the root of the set to which the given element belongs, the Find function serves the purpose -func (u UnionFind) Find(q int) int { - for q != u.parent[q] { - q = u.parent[q] +// Find finds the root of the set to which the given element belongs. +// It performs path compression to make future Find operations faster. +func (u *UnionFind) Find(q int) int { + if q != u.parent[q] { + u.parent[q] = u.Find(u.parent[q]) } - return q + return u.parent[q] } -// to merge two sets to which the given elements belong, the Union function serves the purpose -func (u UnionFind) Union(a, b int) UnionFind { - rootP := u.Find(a) - rootQ := u.Find(b) +// Union merges the sets, if not already merged, to which the given elements belong. +// It performs union by rank to keep the tree as flat as possible. +func (u *UnionFind) Union(p, q int) { + rootP := u.Find(p) + rootQ := u.Find(q) if rootP == rootQ { - return u + return } - if u.size[rootP] < u.size[rootQ] { + if u.rank[rootP] < u.rank[rootQ] { u.parent[rootP] = rootQ - u.size[rootQ] += u.size[rootP] + } else if u.rank[rootP] > u.rank[rootQ] { + u.parent[rootQ] = rootP } else { u.parent[rootQ] = rootP - u.size[rootP] += u.size[rootQ] + u.rank[rootP]++ } - return u } diff --git a/graph/unionfind_test.go b/graph/unionfind_test.go index b95547649..35eea59d4 100644 --- a/graph/unionfind_test.go +++ b/graph/unionfind_test.go @@ -8,10 +8,10 @@ func TestUnionFind(t *testing.T) { u := NewUnionFind(10) // Creating a Union-Find data structure with 10 elements //union operations - u = u.Union(0, 1) - u = u.Union(2, 3) - u = u.Union(4, 5) - u = u.Union(6, 7) + u.Union(0, 1) + u.Union(2, 3) + u.Union(4, 5) + u.Union(6, 7) // Testing the parent of specific elements t.Run("Test Find", func(t *testing.T) { @@ -20,12 +20,21 @@ func TestUnionFind(t *testing.T) { } }) - u = u.Union(1, 5) // Additional union operation - u = u.Union(3, 7) // Additional union operation + u.Union(1, 5) // Additional union operation + u.Union(3, 7) // Additional union operation // Testing the parent of specific elements after more union operations t.Run("Test Find after Union", func(t *testing.T) { - if u.Find(0) != u.Find(5) || u.Find(2) != u.Find(7) { + if u.Find(0) != u.Find(5) || u.Find(1) != u.Find(4) || u.Find(2) != u.Find(7) || u.Find(3) != u.Find(6) { + t.Error("Union operation not functioning correctly") + } + }) + + u.Union(3, 7) // Repeated union operation + + // Testing that repeated union operations are idempotent + t.Run("Test Find after repeated Union", func(t *testing.T) { + if u.Find(2) != u.Find(6) || u.Find(2) != u.Find(7) || u.Find(3) != u.Find(6) || u.Find(3) != u.Find(7) { t.Error("Union operation not functioning correctly") } }) From 822634f03786e88d2024fe25b77e24ea83d2686e Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 16 Oct 2024 20:25:55 +0200 Subject: [PATCH 188/202] Keep GitHub Actions up to date with GitHub's Dependabot (#746) --- .github/dependabot.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..be006de9a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Keep GitHub Actions up to date with GitHub's Dependabot... +# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + groups: + github-actions: + patterns: + - "*" # Group all Actions updates into a single larger pull request + schedule: + interval: weekly From ff32defde291d698018b827e8e84a7be89d8989a Mon Sep 17 00:00:00 2001 From: "Daniel." <67126972+ddaniel27@users.noreply.github.com> Date: Sun, 20 Oct 2024 02:33:33 -0500 Subject: [PATCH 189/202] fix: code style (#743) Co-authored-by: Rak Laptudirm --- dynamic/subsetsum_test.go | 7 ++----- math/matrix/matrix_test.go | 4 ++-- math/matrix/strassenmatrixmultiply_test.go | 4 ++-- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/dynamic/subsetsum_test.go b/dynamic/subsetsum_test.go index 2fdfb6cc5..acb24f18e 100644 --- a/dynamic/subsetsum_test.go +++ b/dynamic/subsetsum_test.go @@ -1,9 +1,6 @@ package dynamic -import ( - "fmt" - "testing" -) +import "testing" func TestSubsetSum(t *testing.T) { @@ -74,7 +71,7 @@ func TestSubsetSum(t *testing.T) { for i := range subsetSumTestData { - t.Run(fmt.Sprintf(subsetSumTestData[i].description), func(t *testing.T) { + t.Run(subsetSumTestData[i].description, func(t *testing.T) { array := subsetSumTestData[i].array sum := subsetSumTestData[i].sum diff --git a/math/matrix/matrix_test.go b/math/matrix/matrix_test.go index 1425bf933..b8c0f7c72 100644 --- a/math/matrix/matrix_test.go +++ b/math/matrix/matrix_test.go @@ -32,7 +32,7 @@ func TestNewFromElements(t *testing.T) { for j := 0; j < len(validElements[0]); j++ { err := expectedm1.Set(i, j, validElements[i][j]) if err != nil { - t.Errorf("copyMatrix.Set error: " + err.Error()) + t.Errorf("copyMatrix.Set error: %s", err.Error()) } } } @@ -73,7 +73,7 @@ func TestMatrixGet(t *testing.T) { matrix := matrix.New(3, 3, 0) err := matrix.Set(1, 1, 42) // Set a specific value for testing if err != nil { - t.Errorf("copyMatrix.Set error: " + err.Error()) + t.Errorf("copyMatrix.Set error: %s", err.Error()) } // Test case 1: Valid Get val1, err1 := matrix.Get(1, 1) diff --git a/math/matrix/strassenmatrixmultiply_test.go b/math/matrix/strassenmatrixmultiply_test.go index a3e58d87a..b47b4c8fc 100644 --- a/math/matrix/strassenmatrixmultiply_test.go +++ b/math/matrix/strassenmatrixmultiply_test.go @@ -66,7 +66,7 @@ func TestStrassenMatrixMultiply(t *testing.T) { } } func TestMatrixMultiplication(t *testing.T) { - rand.Seed(time.Now().UnixNano()) + rand.New(rand.NewSource(time.Now().UnixNano())) // Generate random matrices for testing size := 1 << (rand.Intn(8) + 1) // tests for matrix with n as power of 2 @@ -103,7 +103,7 @@ func TestMatrixMultiplication(t *testing.T) { } func MakeRandomMatrix[T constraints.Integer](rows, columns int) matrix.Matrix[T] { - rand.Seed(time.Now().UnixNano()) + rand.New(rand.NewSource(time.Now().UnixNano())) matrixData := make([][]T, rows) for i := 0; i < rows; i++ { From b9f7d554227aeca6215ddd7ad500e63821564ae4 Mon Sep 17 00:00:00 2001 From: "Daniel." <67126972+ddaniel27@users.noreply.github.com> Date: Wed, 23 Oct 2024 09:09:07 -0500 Subject: [PATCH 190/202] [IMPLEMENTATION] DSA algorithm implementation (#737) Co-authored-by: Rak Laptudirm --- cipher/dsa/dsa.go | 196 +++++++++++++++++++++++++++++++++++++++++ cipher/dsa/dsa_test.go | 114 ++++++++++++++++++++++++ 2 files changed, 310 insertions(+) create mode 100644 cipher/dsa/dsa.go create mode 100644 cipher/dsa/dsa_test.go diff --git a/cipher/dsa/dsa.go b/cipher/dsa/dsa.go new file mode 100644 index 000000000..7d4eb574a --- /dev/null +++ b/cipher/dsa/dsa.go @@ -0,0 +1,196 @@ +/* +dsa.go +description: DSA encryption and decryption including key generation +details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm) +author(s): [ddaniel27](https://github.com/ddaniel27) +*/ +package dsa + +import ( + "crypto/rand" + "io" + "math/big" +) + +const ( + numMRTests = 64 // Number of Miller-Rabin tests + L = 1024 // Number of bits in p + N = 160 // Number of bits in q +) + +type ( + // parameters represents the DSA parameters + parameters struct { + P, Q, G *big.Int + } + + // dsa represents the DSA + dsa struct { + parameters + pubKey *big.Int // public key (y) + privKey *big.Int // private key (x) + } +) + +// New creates a new DSA instance +func New() *dsa { + d := new(dsa) + d.dsaParameterGeneration() + d.keyGen() + return d +} + +// Parameter generation for DSA +// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256) +// 2. Choose a N-bit prime q +// 3. Choose a L-bit prime p such that p-1 is a multiple of q +// 4. Choose an integer h randomly from the range [2, p-2] +// 5. Compute g = h^((p-1)/q) mod p +// 6. Return (p, q, g) +func (dsa *dsa) dsaParameterGeneration() { + var err error + p, q, bigInt := new(big.Int), new(big.Int), new(big.Int) + one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2) + pBytes := make([]byte, L/8) + + // GPLoop is a label for the loop + // We use this loop to change the prime q if we don't find a prime p +GPLoop: + for { + // 2. Choose a N-bit prime q + q, err = rand.Prime(rand.Reader, N) + if err != nil { + panic(err) + } + + for i := 0; i < 4*L; i++ { + // 3. Choose a L-bit prime p such that p-1 is a multiple of q + // In this case we generate a random number of L bits + if _, err := io.ReadFull(rand.Reader, pBytes); err != nil { + panic(err) + } + + // This are the minimum conditions for p being a possible prime + pBytes[len(pBytes)-1] |= 1 // p is odd + pBytes[0] |= 0x80 // p has the highest bit set + p.SetBytes(pBytes) + + // Instead of using (p-1)%q == 0 + // We ensure that p-1 is a multiple of q and validates if p is prime + bigInt.Mod(p, q) + bigInt.Sub(bigInt, one) + p.Sub(p, bigInt) + if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits + continue + } + + dsa.P = p + dsa.Q = q + break GPLoop + } + } + + // 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2 + // 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1 + pm1 := new(big.Int).Sub(p, one) + + for g.Cmp(one) == 0 { + g.Exp(h, new(big.Int).Div(pm1, q), p) + h.Add(h, one) + } + + dsa.G = g +} + +// keyGen is key generation for DSA +// 1. Choose a random integer x from the range [1, q-1] +// 2. Compute y = g^x mod p +func (dsa *dsa) keyGen() { + // 1. Choose a random integer x from the range [1, q-1] + x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1))) + if err != nil { + panic(err) + } + + dsa.privKey = x + + // 2. Compute y = g^x mod p + dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P) +} + +// Sign is signature generation for DSA +// 1. Choose a random integer k from the range [1, q-1] +// 2. Compute r = (g^k mod p) mod q +// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q +func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) { + // 1. Choose a random integer k from the range [1, q-1] + k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1))) + if err != nil { + panic(err) + } + + // 2. Compute r = (g^k mod p) mod q + r = new(big.Int).Exp(g, k, p) + r.Mod(r, q) + + // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q + h := new(big.Int).SetBytes(m) // This should be the hash of the message + s = new(big.Int).ModInverse(k, q) // k^-1 mod q + s.Mul( + s, + new(big.Int).Add( // (H(m) + x*r) + h, + new(big.Int).Mul(x, r), + ), + ) + s.Mod(s, q) // mod q + + return r, s +} + +// Verify is signature verification for DSA +// 1. Compute w = s^-1 mod q +// 2. Compute u1 = (H(m) * w) mod q +// 3. Compute u2 = (r * w) mod q +// 4. Compute v = ((g^u1 * y^u2) mod p) mod q +// 5. If v == r, the signature is valid +func Verify(m []byte, r, s, p, q, g, y *big.Int) bool { + // 1. Compute w = s^-1 mod q + w := new(big.Int).ModInverse(s, q) + + // 2. Compute u1 = (H(m) * w) mod q + h := new(big.Int).SetBytes(m) // This should be the hash of the message + u1 := new(big.Int).Mul(h, w) + u1.Mod(u1, q) + + // 3. Compute u2 = (r * w) mod q + u2 := new(big.Int).Mul(r, w) + u2.Mod(u2, q) + + // 4. Compute v = ((g^u1 * y^u2) mod p) mod q + v := new(big.Int).Exp(g, u1, p) + v.Mul( + v, + new(big.Int).Exp(y, u2, p), + ) + v.Mod(v, p) + v.Mod(v, q) + + // 5. If v == r, the signature is valid + return v.Cmp(r) == 0 +} + +// GetPublicKey returns the public key (y) +func (dsa *dsa) GetPublicKey() *big.Int { + return dsa.pubKey +} + +// GetParameters returns the DSA parameters (p, q, g) +func (dsa *dsa) GetParameters() parameters { + return dsa.parameters +} + +// GetPrivateKey returns the private Key (x) +func (dsa *dsa) GetPrivateKey() *big.Int { + return dsa.privKey +} diff --git a/cipher/dsa/dsa_test.go b/cipher/dsa/dsa_test.go new file mode 100644 index 000000000..3ef1930e4 --- /dev/null +++ b/cipher/dsa/dsa_test.go @@ -0,0 +1,114 @@ +package dsa_test + +import ( + "math/big" + "testing" + + "github.com/TheAlgorithms/Go/cipher/dsa" +) + +func TestDSA(t *testing.T) { + tests := []struct { + name string + message string + alter bool + want bool + }{ + { + name: "valid signature", + message: "Hello, world!", + alter: false, + want: true, + }, + { + name: "invalid signature", + message: "Hello, world!", + alter: true, + want: false, + }, + } + // Generate a DSA key pair + dsaInstance := dsa.New() + pubKey := dsaInstance.GetPublicKey() + params := dsaInstance.GetParameters() + privKey := dsaInstance.GetPrivateKey() + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + // Sign the message + r, s := dsa.Sign( + []byte(tt.message), + params.P, + params.Q, + params.G, + privKey, + ) + + if tt.alter { + // Alter the signature + r.Add(r, big.NewInt(1)) + } + + // Verify the signature + if got := dsa.Verify( + []byte(tt.message), + r, + s, + params.P, + params.Q, + params.G, + pubKey, + ); got != tt.want { + t.Errorf("got %v, want %v", got, tt.want) + } + }) + } +} + +/* ------------------- BENCHMARKS ------------------- */ +func BenchmarkDSANew(b *testing.B) { + for i := 0; i < b.N; i++ { + dsa.New() + } +} + +func BenchmarkDSASign(b *testing.B) { + dsaInstance := dsa.New() + params := dsaInstance.GetParameters() + privKey := dsaInstance.GetPrivateKey() + for i := 0; i < b.N; i++ { + dsa.Sign( + []byte("Hello, World!"), + params.P, + params.Q, + params.G, + privKey, + ) + } +} + +func BenchmarkDSAVerify(b *testing.B) { + dsaInstance := dsa.New() + pubKey := dsaInstance.GetPublicKey() + params := dsaInstance.GetParameters() + privKey := dsaInstance.GetPrivateKey() + r, s := dsa.Sign( + []byte("Hello, World!"), + params.P, + params.Q, + params.G, + privKey, + ) + for i := 0; i < b.N; i++ { + dsa.Verify( + []byte("Hello, World!"), + r, + s, + params.P, + params.Q, + params.G, + pubKey, + ) + } +} From e64d1f5b3ea70a7f183f72bae57843e690c68952 Mon Sep 17 00:00:00 2001 From: Alireza Azadi <53966167+alirezaazadi@users.noreply.github.com> Date: Fri, 25 Oct 2024 09:39:39 +0200 Subject: [PATCH 191/202] feat: add string hamming distance algorithm (#747) * feat: add string hamming distance algorithm * refactor: use only a double quote for a single package import --------- Co-authored-by: Rak Laptudirm --- strings/hamming/hammingdistance.go | 31 ++++++++++++++ strings/hamming/hammingdistance_test.go | 56 +++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 strings/hamming/hammingdistance.go create mode 100644 strings/hamming/hammingdistance_test.go diff --git a/strings/hamming/hammingdistance.go b/strings/hamming/hammingdistance.go new file mode 100644 index 000000000..a8c41f3fd --- /dev/null +++ b/strings/hamming/hammingdistance.go @@ -0,0 +1,31 @@ +/* +This algorithm calculates the hamming distance between two equal length strings. +The Hamming distance between two equal-length strings of symbols is the number of positions +at which the corresponding symbols are different: +https://en.wikipedia.org/wiki/Hamming_distance + +Note that we didn't consider strings as an array of bytes, therefore, we didn't use the XOR operator. +In this case, we used a simple loop to compare each character of the strings, and if they are different, +we increment the hamming distance by 1. + +Parameters: two strings to compare +Output: distance between both strings */ + +package hamming + +import "errors" + +func Distance(str1, str2 string) (int, error) { + if len(str1) != len(str2) { + return -1, errors.New("strings must have a same length") + } + + hammingDistance := 0 + for i := 0; i < len(str1); i++ { + if str1[i] != str2[i] { + hammingDistance++ + } + } + + return hammingDistance, nil +} diff --git a/strings/hamming/hammingdistance_test.go b/strings/hamming/hammingdistance_test.go new file mode 100644 index 000000000..663c4daee --- /dev/null +++ b/strings/hamming/hammingdistance_test.go @@ -0,0 +1,56 @@ +package hamming + +import "testing" + +var testCases = []struct { + name string + string1 string + string2 string + expected int +}{ + { + "empty strings", + "", + "", + 0, + }, + { + "single character strings", + "A", + "A", + 0, + }, + { + "two different strings with a same length", + "TestString 1", + "TestString 2", + 1, + }, + { + "two different strings with a different length", + "TestString1", + "TestString", + -1, + }, + { + "two same strings with a same length", + "TestString", + "TestString", + 0, + }, +} + +func TestHammingDistance(t *testing.T) { + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actual, err := Distance(tc.string1, tc.string2) + if err != nil { + if tc.expected != -1 { + t.Fatalf("Expected no error, but got %v", err) + } + } else if actual != tc.expected { + t.Errorf("Expected Hamming distance between strings: '%s' and '%s' is %v, but got: %v", tc.string1, tc.string2, tc.expected, actual) + } + }) + } +} From 94689d8100f678a90dce5b8d265366394d739fde Mon Sep 17 00:00:00 2001 From: Aadish Jain <121042282+mapcrafter2048@users.noreply.github.com> Date: Thu, 31 Oct 2024 13:14:42 +0530 Subject: [PATCH 192/202] Adding Kosaraju's Algorithm to find strongly connected components (#745) * Add time and space complexity information to various algorithms * Added the implementation of Kosaraju algorithm * Revert "Add time and space complexity information to various algorithms" This reverts commit 51915ff37134d326bf630615b0a1c37205abe5d9. --------- Co-authored-by: Rak Laptudirm --- graph/kosaraju.go | 92 +++++++++++++++++++++++++++++++++++ graph/kosaraju_test.go | 106 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 graph/kosaraju.go create mode 100644 graph/kosaraju_test.go diff --git a/graph/kosaraju.go b/graph/kosaraju.go new file mode 100644 index 000000000..d36949e5f --- /dev/null +++ b/graph/kosaraju.go @@ -0,0 +1,92 @@ +// kosaraju.go +// description: Implementation of Kosaraju's algorithm to find Strongly Connected Components (SCCs) in a directed graph. +// details: The algorithm consists of three steps: +// 1. Perform DFS and fill the stack with vertices in the order of their finish times. +// 2. Create a transposed graph by reversing all edges. +// 3. Perform DFS on the transposed graph in the order defined by the stack to find SCCs. +// time: O(V + E), where V is the number of vertices and E is the number of edges in the graph. +// space: O(V), where V is the number of vertices in the graph. +// ref link: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm +// author: mapcrafter2048 + +package graph + +// Kosaraju returns a list of Strongly Connected Components (SCCs). +func (g *Graph) Kosaraju() [][]int { + stack := []int{} + visited := make([]bool, g.vertices) + + // Step 1: Perform DFS and fill stack based on finish times. + for i := 0; i < g.vertices; i++ { + if !visited[i] { + g.fillOrder(i, visited, &stack) + } + } + + // Step 2: Create a transposed graph. + transposed := g.transpose() + + // Step 3: Perform DFS on the transposed graph in the order defined by the stack. + visited = make([]bool, g.vertices) + var sccs [][]int + + for len(stack) > 0 { + // Pop vertex from stack + v := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + // Perform DFS if not already visited. + if !visited[v] { + scc := []int{} + transposed.dfs(v, visited, &scc) + sccs = append(sccs, scc) + } + } + + return sccs +} + +// Helper function to fill the stack with vertices in the order of their finish times. +func (g *Graph) fillOrder(v int, visited []bool, stack *[]int) { + visited[v] = true + + for neighbor := range g.edges[v] { + if !visited[neighbor] { + g.fillOrder(neighbor, visited, stack) + } + } + + // Push the current vertex to the stack after exploring all neighbors. + *stack = append(*stack, v) +} + +// Helper function to create a transposed (reversed) graph. +func (g *Graph) transpose() *Graph { + transposed := &Graph{ + vertices: g.vertices, + edges: make(map[int]map[int]int), + } + + for v, neighbors := range g.edges { + for neighbor := range neighbors { + if transposed.edges[neighbor] == nil { + transposed.edges[neighbor] = make(map[int]int) + } + transposed.edges[neighbor][v] = 1 // Add the reversed edge + } + } + + return transposed +} + +// Helper DFS function used in the transposed graph to collect SCCs. +func (g *Graph) dfs(v int, visited []bool, scc *[]int) { + visited[v] = true + *scc = append(*scc, v) + + for neighbor := range g.edges[v] { + if !visited[neighbor] { + g.dfs(neighbor, visited, scc) + } + } +} diff --git a/graph/kosaraju_test.go b/graph/kosaraju_test.go new file mode 100644 index 000000000..360b72a3e --- /dev/null +++ b/graph/kosaraju_test.go @@ -0,0 +1,106 @@ +package graph + +import ( + "reflect" + "sort" + "testing" +) + +func TestKosaraju(t *testing.T) { + tests := []struct { + name string + vertices int + edges map[int][]int + expected [][]int + }{ + { + name: "Single SCC", + vertices: 5, + edges: map[int][]int{ + 0: {1}, + 1: {2}, + 2: {0, 3}, + 3: {4}, + 4: {}, + }, + expected: [][]int{{4}, {3}, {0, 2, 1}}, + }, + { + name: "Multiple SCCs", + vertices: 8, + edges: map[int][]int{ + 0: {1}, + 1: {2}, + 2: {0, 3}, + 3: {4}, + 4: {5}, + 5: {3, 6}, + 6: {7}, + 7: {6}, + }, + expected: [][]int{{6, 7}, {3, 4, 5}, {0, 2, 1}}, + }, + { + name: "Disconnected graph", + vertices: 4, + edges: map[int][]int{ + 0: {1}, + 1: {}, + 2: {3}, + 3: {}, + }, + expected: [][]int{{1}, {0}, {3}, {2}}, + }, + { + name: "No edges", + vertices: 3, + edges: map[int][]int{ + 0: {}, + 1: {}, + 2: {}, + }, + expected: [][]int{{0}, {1}, {2}}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Initializing graph + graph := &Graph{ + vertices: tt.vertices, + edges: make(map[int]map[int]int), + } + for v, neighbors := range tt.edges { + graph.edges[v] = make(map[int]int) + for _, neighbor := range neighbors { + graph.edges[v][neighbor] = 1 + } + } + + // Running Kosaraju's algorithm to get the SCCs + result := graph.Kosaraju() + + // Sort the expected and result SCCs to ensure order doesn't matter + sortSlices(tt.expected) + sortSlices(result) + + // Compare the sorted SCCs + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("expected %v, got %v", tt.expected, result) + } + }) + } +} + +// Utility function to sort the slices and their contents +func sortSlices(s [][]int) { + for _, inner := range s { + sort.Ints(inner) + } + sort.Slice(s, func(i, j int) bool { + if len(s[i]) == 0 || len(s[j]) == 0 { + return len(s[i]) < len(s[j]) + } + return s[i][0] < s[j][0] + }) +} From 4263dac181736e937c735d380a15bd7e75b0fc30 Mon Sep 17 00:00:00 2001 From: Aadish Jain <121042282+mapcrafter2048@users.noreply.github.com> Date: Sat, 16 Nov 2024 21:39:37 +0530 Subject: [PATCH 193/202] Add time and space complexity information to various algorithms (#744) * Add time and space complexity information to various algorithms * Added the implementation of Kosaraju algorithm * Added some style issues in articulationpoints.go * Formatted code with gofmt -s to meet style requirements --------- Co-authored-by: Rak Laptudirm --- cache/lru.go | 7 ++ checksum/crc8.go | 2 + checksum/luhn.go | 2 + cipher/caesar/caesar.go | 4 + .../diffiehellman/diffiehellmankeyexchange.go | 4 + cipher/polybius/polybius.go | 4 + cipher/railfence/railfence.go | 6 + cipher/rot13/rot13.go | 4 + cipher/rsa/rsa.go | 2 + cipher/rsa/rsa2.go | 2 + cipher/transposition/transposition.go | 2 + cipher/xor/xor.go | 4 + compression/huffmancoding.go | 2 + compression/rlecoding.go | 3 + conversion/base64.go | 2 + conversion/binarytodecimal.go | 2 + conversion/decimaltobinary.go | 2 + conversion/inttoroman.go | 6 + conversion/rgbhex.go | 2 + conversion/romantoint.go | 2 + dynamic/abbreviation.go | 2 + dynamic/binomialcoefficient.go | 5 + dynamic/catalan.go | 4 +- dynamic/coinchange.go | 6 + dynamic/editdistance.go | 2 + dynamic/fibonacci.go | 4 + dynamic/knapsack.go | 3 + dynamic/longestcommonsubsequence.go | 3 + dynamic/longestincreasingsubsequence.go | 6 + dynamic/longestpalindromicsubsequence.go | 2 + dynamic/matrixmultiplication.go | 2 + dynamic/rodcutting.go | 2 + dynamic/subsetsum.go | 3 +- dynamic/traprainwater.go | 2 + dynamic/uniquepaths.go | 2 + graph/articulationpoints.go | 107 ++++++++---------- graph/bellmanford.go | 2 + graph/breadthfirstsearch.go | 4 +- graph/coloring/backtracking.go | 2 + graph/coloring/bfs.go | 2 + graph/coloring/bipartite.go | 16 ++- graph/coloring/greedy.go | 2 + graph/cycle.go | 2 + graph/depthfirstsearch.go | 6 + graph/dijkstra.go | 7 ++ graph/floydwarshall.go | 2 + graph/lowestcommonancestor.go | 2 + graph/topological.go | 7 ++ hashing/sha256/sha256.go | 2 + math/aliquotsum.go | 2 + math/armstrong/isarmstrong.go | 2 + math/binary/abs.go | 5 + math/binary/arithmeticmean.go | 2 + math/binary/bitcounter.go | 2 + math/binary/checkisnumberpoweroftwo.go | 2 + math/binary/fast_inverse_sqrt.go | 2 + math/binary/logarithm.go | 2 + math/binary/rbc.go | 2 + math/binary/reversebits.go | 2 + math/binary/sqrt.go | 2 + math/binary/xorsearch.go | 2 + math/binomialcoefficient.go | 2 + math/catalan/catalannumber.go | 2 + math/factorial/factorial.go | 2 + math/fibonacci/fibonacci.go | 2 + math/gcd/extended.go | 2 + math/gcd/extendedgcd.go | 5 + math/gcd/gcd.go | 3 + math/gcd/gcditerative.go | 3 + math/geometry/distance.go | 2 + math/krishnamurthy.go | 2 + math/liouville.go | 2 + math/matrix/add.go | 5 + math/matrix/checkequal.go | 3 + math/matrix/copy.go | 6 + math/matrix/determinant.go | 2 + math/matrix/multiply.go | 5 + math/matrix/strassenmatrixmultiply.go | 2 + math/max/bitwisemax.go | 2 + math/median.go | 2 + math/mobius.go | 2 + math/mode.go | 2 + math/modular/exponentiation.go | 2 + math/modular/inverse.go | 2 + math/moserdebruijnsequence/sequence.go | 2 + math/pascal/pascaltriangle.go | 2 + math/perfectnumber.go | 2 + math/permutation/heaps.go | 5 + math/permutation/next_permutation.go | 2 + math/pi/montecarlopi.go | 2 + math/pi/spigotpi.go | 2 + math/pollard.go | 2 + math/power/powvialogarithm.go | 2 + math/prime/millerrabintest.go | 3 +- math/prime/primecheck.go | 2 + math/prime/primefactorization.go | 5 + math/prime/sieve2.go | 2 + math/prime/twin.go | 2 + math/pronicnumber.go | 6 +- other/nested/nestedbrackets.go | 3 + other/password/generator.go | 3 + search/jump.go | 2 + sort/bogosort.go | 3 +- sort/combSort.go | 3 + sort/countingsort.go | 3 + sort/exchangesort.go | 3 + sort/heapsort.go | 6 + sort/insertionsort.go | 6 + sort/mergesort.go | 6 + sort/patiencesort.go | 3 + sort/pigeonholesort.go | 2 + sort/quicksort.go | 3 + sort/radixsort.go | 3 + sort/simplesort.go | 3 + 114 files changed, 385 insertions(+), 72 deletions(-) diff --git a/cache/lru.go b/cache/lru.go index 8c27cfc1f..b9578a9fe 100644 --- a/cache/lru.go +++ b/cache/lru.go @@ -1,3 +1,10 @@ +// lru.go +// description : Least Recently Used (LRU) cache +// details : A Least Recently Used (LRU) cache is a type of cache algorithm used to manage memory within a computer. The LRU algorithm is designed to remove the least recently used items first when the cache reaches its limit. +// time complexity : O(1) +// space complexity : O(n) +// ref : https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU) + package cache import ( diff --git a/checksum/crc8.go b/checksum/crc8.go index fc73a9a40..29c6214b5 100644 --- a/checksum/crc8.go +++ b/checksum/crc8.go @@ -3,6 +3,8 @@ // details: // A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks // and storage devices to detect accidental changes to raw data. +// time complexity: O(n) +// space complexity: O(1) // See more [CRC](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) // author(s) [red_byte](https://github.com/i-redbyte) // see crc8_test.go diff --git a/checksum/luhn.go b/checksum/luhn.go index e9f7dd6b1..b28236d95 100644 --- a/checksum/luhn.go +++ b/checksum/luhn.go @@ -1,6 +1,8 @@ // lunh.go // description: Luhn algorithm // details: is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, etc [Lunh](https://en.wikipedia.org/wiki/Luhn_algorithm) +// time complexity: O(n) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see lunh_test.go diff --git a/cipher/caesar/caesar.go b/cipher/caesar/caesar.go index 8c1cb47f7..f2f945e71 100644 --- a/cipher/caesar/caesar.go +++ b/cipher/caesar/caesar.go @@ -1,4 +1,8 @@ // Package caesar is the shift cipher +// description: Caesar cipher +// details : Caesar cipher is a type of substitution cipher in which each letter in the plaintext is shifted a certain number of places down the alphabet. +// time complexity: O(n) +// space complexity: O(n) // ref: https://en.wikipedia.org/wiki/Caesar_cipher package caesar diff --git a/cipher/diffiehellman/diffiehellmankeyexchange.go b/cipher/diffiehellman/diffiehellmankeyexchange.go index 2621e3cca..8a779efd4 100644 --- a/cipher/diffiehellman/diffiehellmankeyexchange.go +++ b/cipher/diffiehellman/diffiehellmankeyexchange.go @@ -1,4 +1,8 @@ // Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm +// description: Diffie-Hellman key exchange +// details : Diffie-Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel by combining private keys of two parties to generate a shared secret key. +// time complexity: O(log(n)) +// space complexity: O(1) // for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI package diffiehellman diff --git a/cipher/polybius/polybius.go b/cipher/polybius/polybius.go index 7b57ab344..e022dabae 100644 --- a/cipher/polybius/polybius.go +++ b/cipher/polybius/polybius.go @@ -1,4 +1,8 @@ // Package polybius is encrypting method with polybius square +// description: Polybius square +// details : The Polybius algorithm is a simple algorithm that is used to encode a message by converting each letter to a pair of numbers. +// time complexity: O(n) +// space complexity: O(n) // ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher package polybius diff --git a/cipher/railfence/railfence.go b/cipher/railfence/railfence.go index f1ea11928..aeeaed3fa 100644 --- a/cipher/railfence/railfence.go +++ b/cipher/railfence/railfence.go @@ -1,3 +1,9 @@ +// railfence.go +// description: Rail Fence Cipher +// details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext. +// time complexity: O(n) +// space complexity: O(n) +// ref: https://en.wikipedia.org/wiki/Rail_fence_cipher package railfence import ( diff --git a/cipher/rot13/rot13.go b/cipher/rot13/rot13.go index 9b822332b..d50d97c53 100644 --- a/cipher/rot13/rot13.go +++ b/cipher/rot13/rot13.go @@ -1,4 +1,8 @@ // Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. +// description: ROT13 +// details: ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. it is a special case of the Caesar cipher +// time complexity: O(n) +// space complexity: O(n) // ref: https://en.wikipedia.org/wiki/ROT13 package rot13 diff --git a/cipher/rsa/rsa.go b/cipher/rsa/rsa.go index 44cf767b3..1eb506e2c 100644 --- a/cipher/rsa/rsa.go +++ b/cipher/rsa/rsa.go @@ -6,6 +6,8 @@ // thus both the Encrypt and Decrypt are not a production // ready implementation. The OpenSSL implementation of RSA // also adds a padding which is not present in this algorithm. +// time complexity: O(n) +// space complexity: O(n) // author(s) [Taj](https://github.com/tjgurwara99) // see rsa_test.go diff --git a/cipher/rsa/rsa2.go b/cipher/rsa/rsa2.go index 2eceddf10..18b6e1391 100644 --- a/cipher/rsa/rsa2.go +++ b/cipher/rsa/rsa2.go @@ -2,6 +2,8 @@ rsa2.go description: RSA encryption and decryption including key generation details: [RSA wiki](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) +time complexity: O(n) +space complexity: O(1) author(s): [ddaniel27](https://github.com/ddaniel27) */ package rsa diff --git a/cipher/transposition/transposition.go b/cipher/transposition/transposition.go index 6365ffa4a..7a18293ea 100644 --- a/cipher/transposition/transposition.go +++ b/cipher/transposition/transposition.go @@ -2,6 +2,8 @@ // description: Transposition cipher // details: // Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes a permutation of the plaintext [Transposition cipher](https://en.wikipedia.org/wiki/Transposition_cipher) +// time complexity: O(n) +// space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see transposition_test.go diff --git a/cipher/xor/xor.go b/cipher/xor/xor.go index 0296c97ce..61181b1aa 100644 --- a/cipher/xor/xor.go +++ b/cipher/xor/xor.go @@ -1,4 +1,8 @@ // Package xor is an encryption algorithm that operates the exclusive disjunction(XOR) +// description: XOR encryption +// details: The XOR encryption is an algorithm that operates the exclusive disjunction(XOR) on each character of the plaintext with a given key +// time complexity: O(n) +// space complexity: O(n) // ref: https://en.wikipedia.org/wiki/XOR_cipher package xor diff --git a/compression/huffmancoding.go b/compression/huffmancoding.go index f6515872e..ecdaa1fb2 100644 --- a/compression/huffmancoding.go +++ b/compression/huffmancoding.go @@ -3,6 +3,8 @@ // details: // We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding. // It assumes that the list of symbol-frequencies is sorted. +// time complexity: O(n) +// space complexity: O(n) // author(s) [pedromsrocha](https://github.com/pedromsrocha) // see also huffmancoding_test.go diff --git a/compression/rlecoding.go b/compression/rlecoding.go index c08d3e4bd..9aa9399bb 100644 --- a/compression/rlecoding.go +++ b/compression/rlecoding.go @@ -3,6 +3,9 @@ rlecoding.go description: run length encoding and decoding details: Run-length encoding (RLE) is a simple form of data compression in which runs of data are stored as a single data value and count, rather than as the original run. This is useful when the data contains many repeated values. For example, the data "WWWWWWWWWWWWBWWWWWWWWWWWWBBB" can be compressed to "12W1B12W3B". The algorithm is simple and can be implemented in a few lines of code. +time complexity: O(n) +space complexity: O(n) +ref: https://en.wikipedia.org/wiki/Run-length_encoding author(s) [ddaniel27](https://github.com/ddaniel27) */ package compression diff --git a/conversion/base64.go b/conversion/base64.go index 8828f6a7a..bf3a383c5 100644 --- a/conversion/base64.go +++ b/conversion/base64.go @@ -1,6 +1,8 @@ // base64.go // description: The base64 encoding algorithm as defined in the RFC4648 standard. // author: [Paul Leydier] (https://github.com/paul-leydier) +// time complexity: O(n) +// space complexity: O(n) // ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4 // ref: https://en.wikipedia.org/wiki/Base64 // see base64_test.go diff --git a/conversion/binarytodecimal.go b/conversion/binarytodecimal.go index 6181d3bc2..aa308e6a8 100644 --- a/conversion/binarytodecimal.go +++ b/conversion/binarytodecimal.go @@ -9,6 +9,8 @@ Date: 19-Oct-2021 // https://en.wikipedia.org/wiki/Decimal // Function receives a Binary Number as string and returns the Decimal number as integer. // Supported Binary number range is 0 to 2^(31-1). +// time complexity: O(n) +// space complexity: O(1) package conversion diff --git a/conversion/decimaltobinary.go b/conversion/decimaltobinary.go index e74765708..54153b0d2 100644 --- a/conversion/decimaltobinary.go +++ b/conversion/decimaltobinary.go @@ -8,6 +8,8 @@ Date: 14-Oct-2021 // https://en.wikipedia.org/wiki/Binary_number // Function receives a integer as a Decimal number and returns the Binary number. // Supported integer value range is 0 to 2^(31 -1). +// time complexity: O(log(n)) +// space complexity: O(1) package conversion diff --git a/conversion/inttoroman.go b/conversion/inttoroman.go index c1764db1f..1b9c39a0e 100644 --- a/conversion/inttoroman.go +++ b/conversion/inttoroman.go @@ -1,3 +1,9 @@ +// inttoroman.go +// description: Convert an integer to a roman numeral +// details: This program converts an integer to a roman numeral. The program uses a lookup array to convert the integer to a roman numeral. +// time complexity: O(1) +// space complexity: O(1) + package conversion import ( diff --git a/conversion/rgbhex.go b/conversion/rgbhex.go index d050edc8d..3d7265d2c 100644 --- a/conversion/rgbhex.go +++ b/conversion/rgbhex.go @@ -1,5 +1,7 @@ // rgbhex.go // description: convert hex input to red, green and blue and vice versa +// time complexity: O(1) +// space complexity: O(1) // author(s) [darmiel](https://github.com/darmiel) // see rgbhex_test.go diff --git a/conversion/romantoint.go b/conversion/romantoint.go index dda0000f3..629952320 100644 --- a/conversion/romantoint.go +++ b/conversion/romantoint.go @@ -3,6 +3,8 @@ // Function receives a string as a roman number and outputs an integer // Maximum output will be 3999 // Only standard form is supported +// time complexity: O(n) +// space complexity: O(1) package conversion diff --git a/dynamic/abbreviation.go b/dynamic/abbreviation.go index ebfe92171..e5b7ad6e9 100644 --- a/dynamic/abbreviation.go +++ b/dynamic/abbreviation.go @@ -11,6 +11,8 @@ // Given a = "ABcde" and b = "ABCD" // We can capitalize "c" and "d" in a to get "ABCde" then delete all the lowercase letters (which is only "e") in a to get "ABCD" which equals b. // Author: [duongoku](https://github.com/duongoku) +// Time Complexity: O(n*m) where n is the length of a and m is the length of b +// Space Complexity: O(n*m) where n is the length of a and m is the length of b // See abbreviation_test.go for test cases package dynamic diff --git a/dynamic/binomialcoefficient.go b/dynamic/binomialcoefficient.go index b26dbcbbf..fed664fd5 100644 --- a/dynamic/binomialcoefficient.go +++ b/dynamic/binomialcoefficient.go @@ -1,3 +1,8 @@ +// binomialcoefficient.go +// description: Implementation of the binomial coefficient using dynamic programming +// details: The binomial coefficient C(n, k) is the number of ways to choose a subset of k elements from a set of n elements. The binomial coefficient is calculated using the formula C(n, k) = C(n-1, k-1) + C(n-1, k) with base cases C(n, 0) = C(n, n) = 1. +// time complexity: O(n*k) where n is the number of elements and k is the number of elements to choose +// space complexity: O(n*k) where n is the number of elements and k is the number of elements to choose package dynamic import "github.com/TheAlgorithms/Go/math/min" diff --git a/dynamic/catalan.go b/dynamic/catalan.go index 7e0076fba..2f53c3edb 100644 --- a/dynamic/catalan.go +++ b/dynamic/catalan.go @@ -1,5 +1,7 @@ //The Catalan numbers are a sequence of positive integers that appear in many counting -//problems in combinatorics. +// problems in combinatorics. +// time complexity: O(n²) +// space complexity: O(n) //reference: https://brilliant.org/wiki/catalan-numbers/ package dynamic diff --git a/dynamic/coinchange.go b/dynamic/coinchange.go index 1098ea4e1..2ba6064ab 100644 --- a/dynamic/coinchange.go +++ b/dynamic/coinchange.go @@ -1,3 +1,9 @@ +// coinchange.go +// description: Implementation of the coin change problem using dynamic programming +// details: The coin change problem is a problem that asks for the number of ways to make change for a given amount of money using a given set of coins. The problem can be solved using dynamic programming. +// time complexity: O(n*m) where n is the number of coins and m is the amount of money +// space complexity: O(m) where m is the amount of money + package dynamic // CoinChange finds the number of possible combinations of coins diff --git a/dynamic/editdistance.go b/dynamic/editdistance.go index 92abe9583..6d4778a3e 100644 --- a/dynamic/editdistance.go +++ b/dynamic/editdistance.go @@ -1,4 +1,6 @@ // EDIT DISTANCE PROBLEM +// time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. +// space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. // https://www.geeksforgeeks.org/edit-distance-dp-5/ // https://leetcode.com/problems/edit-distance/ diff --git a/dynamic/fibonacci.go b/dynamic/fibonacci.go index 288b82b1c..6025b59f0 100644 --- a/dynamic/fibonacci.go +++ b/dynamic/fibonacci.go @@ -1,3 +1,7 @@ +// fibonacci.go +// description: Implementation of the Fibonacci sequence using dynamic programming +// time complexity: O(n) +// space complexity: O(1) package dynamic // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ diff --git a/dynamic/knapsack.go b/dynamic/knapsack.go index b07bf6b40..6b637ca54 100644 --- a/dynamic/knapsack.go +++ b/dynamic/knapsack.go @@ -2,6 +2,9 @@ package dynamic // Knapsack Problem // https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ +// https://en.wikipedia.org/wiki/Knapsack_problem +// time complexity: O(n*maxWeight) +// space complexity: O(n*maxWeight) import ( "math" diff --git a/dynamic/longestcommonsubsequence.go b/dynamic/longestcommonsubsequence.go index 739aeb8c1..087d986e0 100644 --- a/dynamic/longestcommonsubsequence.go +++ b/dynamic/longestcommonsubsequence.go @@ -1,6 +1,9 @@ // LONGEST COMMON SUBSEQUENCE // DP - 4 // https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ +// https://leetcode.com/problems/longest-common-subsequence/ +// time complexity: O(m*n) where m and n are lengths of the strings +// space complexity: O(m*n) where m and n are lengths of the strings package dynamic diff --git a/dynamic/longestincreasingsubsequence.go b/dynamic/longestincreasingsubsequence.go index cce099510..a1e70e53f 100644 --- a/dynamic/longestincreasingsubsequence.go +++ b/dynamic/longestincreasingsubsequence.go @@ -1,3 +1,9 @@ +// longestincreasingsubsequence.go +// description: Implementation of the Longest Increasing Subsequence using dynamic programming +// reference: https://en.wikipedia.org/wiki/Longest_increasing_subsequence +// time complexity: O(n^2) +// space complexity: O(n) + package dynamic import ( diff --git a/dynamic/longestpalindromicsubsequence.go b/dynamic/longestpalindromicsubsequence.go index bc5df07b6..700fb8f87 100644 --- a/dynamic/longestpalindromicsubsequence.go +++ b/dynamic/longestpalindromicsubsequence.go @@ -1,4 +1,6 @@ // longest palindromic subsequence +// time complexity: O(n^2) +// space complexity: O(n^2) // http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/ package dynamic diff --git a/dynamic/matrixmultiplication.go b/dynamic/matrixmultiplication.go index 373936e62..10fccdbda 100644 --- a/dynamic/matrixmultiplication.go +++ b/dynamic/matrixmultiplication.go @@ -1,6 +1,8 @@ // matrix chain multiplication problem // https://en.wikipedia.org/wiki/Matrix_chain_multiplication // www.geeksforgeeks.org/dynamic_programming-set-8-matrix-chain-multiplication/ +// time complexity: O(n^3) +// space complexity: O(n^2) package dynamic diff --git a/dynamic/rodcutting.go b/dynamic/rodcutting.go index ce721e18b..4d37f4ecc 100644 --- a/dynamic/rodcutting.go +++ b/dynamic/rodcutting.go @@ -1,6 +1,8 @@ // Solution to Rod cutting problem // https://en.wikipedia.org/wiki/Cutting_stock_problem // http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ +// time complexity: O(n^2) +// space complexity: O(n) package dynamic diff --git a/dynamic/subsetsum.go b/dynamic/subsetsum.go index 1f7da69b8..db04c32de 100644 --- a/dynamic/subsetsum.go +++ b/dynamic/subsetsum.go @@ -1,7 +1,8 @@ //Given a set of non-negative integers, and a (positive) value sum, //determine if there is a subset of the given set with sum //equal to given sum. -//Complexity: O(n*sum) +// time complexity: O(n*sum) +// space complexity: O(n*sum) //references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ package dynamic diff --git a/dynamic/traprainwater.go b/dynamic/traprainwater.go index 4f87e1cd7..3b1c6a966 100644 --- a/dynamic/traprainwater.go +++ b/dynamic/traprainwater.go @@ -5,6 +5,8 @@ // It uses dynamic programming to precompute the maximum height of bars to the left and right of each position. // Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights. // Finally, it sums up the trapped rainwater for all positions and returns the total amount. +// time complexity: O(n) +// space complexity: O(n) // author(s) [TruongNhanNguyen (SOZEL)](https://github.com/TruongNhanNguyen) package dynamic diff --git a/dynamic/uniquepaths.go b/dynamic/uniquepaths.go index 3dc96a8e7..978a81c7e 100644 --- a/dynamic/uniquepaths.go +++ b/dynamic/uniquepaths.go @@ -1,4 +1,6 @@ // See https://leetcode.com/problems/unique-paths/ +// time complexity: O(m*n) where m and n are the dimensions of the grid +// space complexity: O(m*n) where m and n are the dimensions of the grid // author: Rares Mateizer (https://github.com/rares985) package dynamic diff --git a/graph/articulationpoints.go b/graph/articulationpoints.go index 618107890..26b3a6b78 100644 --- a/graph/articulationpoints.go +++ b/graph/articulationpoints.go @@ -1,56 +1,48 @@ +// Package graph provides algorithms to analyze graph structures. package graph import "github.com/TheAlgorithms/Go/math/min" +// apHelper stores auxiliary data used to identify articulation points in a graph. type apHelper struct { - is_ap []bool - visited []bool - child_cnt []int - discovery_time []int - earliest_discovery []int + isAP []bool + visited []bool + childCount []int + discoveryTime []int + earliestDiscovery []int } -// ArticulationPoint is a function to identify articulation points in a graph. -// The function takes the graph as an argument and returns a boolean slice -// which indicates whether a vertex is an articulation point or not. +// ArticulationPoint identifies articulation points in a graph. It returns a boolean slice +// where each element indicates whether a vertex is an articulation point. // Worst Case Time Complexity: O(|V| + |E|) // Auxiliary Space: O(|V|) -// reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point +// Reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point func ArticulationPoint(graph *Graph) []bool { - // time variable to keep track of the time of discovery_time of a vertex + // Time variable to keep track of the discovery time of a vertex time := 0 - //initialize all the variables + // Initialize apHelper instance with the required data structures apHelperInstance := &apHelper{ - is_ap: make([]bool, graph.vertices), - visited: make([]bool, graph.vertices), - child_cnt: make([]int, graph.vertices), - // integer slice to store the discovery time of a vertex as we traverse - // the graph in a depth first manner - discovery_time: make([]int, graph.vertices), - // integer slice to store the earliest discovered vertex reachable from a vertex - earliest_discovery: make([]int, graph.vertices), + isAP: make([]bool, graph.vertices), + visited: make([]bool, graph.vertices), + childCount: make([]int, graph.vertices), + discoveryTime: make([]int, graph.vertices), + earliestDiscovery: make([]int, graph.vertices), } - articulationPointHelper( - apHelperInstance, - 0, - -1, - &time, - graph, - ) - if apHelperInstance.child_cnt[0] == 1 { - // if the root has only one child, it is not an articulation point - apHelperInstance.is_ap[0] = false + // Start traversal from the root (0) + articulationPointHelper(apHelperInstance, 0, -1, &time, graph) + + // Check if the root has only one child, making it non-articulate + if apHelperInstance.childCount[0] == 1 { + apHelperInstance.isAP[0] = false } - return apHelperInstance.is_ap + return apHelperInstance.isAP } -// articulationPointHelper is a recursive function to traverse the graph -// and mark articulation points. Based on the depth first search transversal -// of the graph, however modified to keep track and update the -// `child_cnt`, `discovery_time` and `earliest_discovery` slices defined above +// articulationPointHelper recursively traverses the graph using DFS and marks articulation points. +// It updates `childCount`, `discoveryTime`, and `earliestDiscovery` slices for the given vertex. func articulationPointHelper( apHelperInstance *apHelper, vertex int, @@ -60,41 +52,38 @@ func articulationPointHelper( ) { apHelperInstance.visited[vertex] = true - // Mark the time of discovery of a vertex - // set the earliest discovery time to the discovered time - // increment the time - apHelperInstance.discovery_time[vertex] = *time - apHelperInstance.earliest_discovery[vertex] = apHelperInstance.discovery_time[vertex] + // Set discovery and earliest discovery times for the vertex + apHelperInstance.discoveryTime[vertex] = *time + apHelperInstance.earliestDiscovery[vertex] = *time *time++ - for next_vertex := range graph.edges[vertex] { - if next_vertex == parent { + for nextVertex := range graph.edges[vertex] { + if nextVertex == parent { continue } - if apHelperInstance.visited[next_vertex] { - apHelperInstance.earliest_discovery[vertex] = min.Int( - apHelperInstance.earliest_discovery[vertex], - apHelperInstance.discovery_time[next_vertex], + if apHelperInstance.visited[nextVertex] { + // Update the earliest discovery time to the smallest reachable discovery time + apHelperInstance.earliestDiscovery[vertex] = min.Int( + apHelperInstance.earliestDiscovery[vertex], + apHelperInstance.discoveryTime[nextVertex], ) continue } - apHelperInstance.child_cnt[vertex]++ - articulationPointHelper( - apHelperInstance, - next_vertex, - vertex, - time, - graph, - ) - apHelperInstance.earliest_discovery[vertex] = min.Int( - apHelperInstance.earliest_discovery[vertex], - apHelperInstance.earliest_discovery[next_vertex], + // Increment child count and perform recursive traversal for DFS + apHelperInstance.childCount[vertex]++ + articulationPointHelper(apHelperInstance, nextVertex, vertex, time, graph) + + // Update the earliest discovery time post DFS + apHelperInstance.earliestDiscovery[vertex] = min.Int( + apHelperInstance.earliestDiscovery[vertex], + apHelperInstance.earliestDiscovery[nextVertex], ) - if apHelperInstance.earliest_discovery[next_vertex] >= apHelperInstance.discovery_time[vertex] { - apHelperInstance.is_ap[vertex] = true - } + // Mark vertex as articulation point if condition meets + if apHelperInstance.earliestDiscovery[nextVertex] >= apHelperInstance.discoveryTime[vertex] { + apHelperInstance.isAP[vertex] = true + } } } diff --git a/graph/bellmanford.go b/graph/bellmanford.go index f130a4e06..d1db29c5c 100644 --- a/graph/bellmanford.go +++ b/graph/bellmanford.go @@ -3,6 +3,8 @@ // It is slower than Dijkstra but capable of handling negative edge weights. // https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm // Implementation is based on the book 'Introduction to Algorithms' (CLRS) +// time complexity: O(V*E) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph package graph diff --git a/graph/breadthfirstsearch.go b/graph/breadthfirstsearch.go index 7325c06a3..bac2f04cc 100644 --- a/graph/breadthfirstsearch.go +++ b/graph/breadthfirstsearch.go @@ -3,8 +3,8 @@ package graph // BreadthFirstSearch is an algorithm for traversing and searching graph data structures. // It starts at an arbitrary node of a graph, and explores all of the neighbor nodes // at the present depth prior to moving on to the nodes at the next depth level. -// Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) -// Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) +// Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node. +// Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node. // reference: https://en.wikipedia.org/wiki/Breadth-first_search func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) { queue := make([]int, 0) diff --git a/graph/coloring/backtracking.go b/graph/coloring/backtracking.go index 1ae657d45..885b79e28 100644 --- a/graph/coloring/backtracking.go +++ b/graph/coloring/backtracking.go @@ -1,4 +1,6 @@ // This file contains the graph coloring implementation using backtracking +// time complexity: O(V^V) where V is the number of vertices in the graph +// space complexity: O(V) where V is the number of vertices in the graph // Author(s): [Shivam](https://github.com/Shivam010) package coloring diff --git a/graph/coloring/bfs.go b/graph/coloring/bfs.go index d73b0ed31..22f0bc899 100644 --- a/graph/coloring/bfs.go +++ b/graph/coloring/bfs.go @@ -1,4 +1,6 @@ // This file contains the graph coloring implementation using BFS +// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph // Author(s): [Shivam](https://github.com/Shivam010) package coloring diff --git a/graph/coloring/bipartite.go b/graph/coloring/bipartite.go index f27c7dc54..1f0e3c62c 100644 --- a/graph/coloring/bipartite.go +++ b/graph/coloring/bipartite.go @@ -1,7 +1,13 @@ package coloring +// Bipartite.go +// description: Implementation of the Bipartite graph coloring algorithm +// details: A bipartite graph is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V. The Bipartite graph coloring algorithm is used to determine if a graph is bipartite or not. +// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph + func (g *Graph) TryBipartiteColoring() map[int]Color { - // 0 is uncolored, 1/2 is colors + // 0 is uncolored, 1/2 are colors colors := make(map[int]Color) visited := make(map[int]bool) @@ -10,8 +16,8 @@ func (g *Graph) TryBipartiteColoring() map[int]Color { visited[i] = false } - var color_node func(int) - color_node = func(s int) { + var colorNode func(int) + colorNode = func(s int) { visited[s] = true coloring := []Color{0, 2, 1} @@ -20,7 +26,7 @@ func (g *Graph) TryBipartiteColoring() map[int]Color { colors[n] = coloring[colors[s]] } if !visited[n] { - color_node(n) + colorNode(n) } } } @@ -28,7 +34,7 @@ func (g *Graph) TryBipartiteColoring() map[int]Color { for i := range g.edges { if colors[i] == 0 { colors[i] = 1 - color_node(i) + colorNode(i) } } diff --git a/graph/coloring/greedy.go b/graph/coloring/greedy.go index 907395d96..07ca6af1b 100644 --- a/graph/coloring/greedy.go +++ b/graph/coloring/greedy.go @@ -1,4 +1,6 @@ // This file contains the graph coloring implementation using Greedy Approach. +// time complexity: O(V^2) where V is the number of vertices in the graph +// space complexity: O(V) where V is the number of vertices in the graph // Author(s): [Shivam](https://github.com/Shivam010) package coloring diff --git a/graph/cycle.go b/graph/cycle.go index cf45d1854..c55cd6bed 100644 --- a/graph/cycle.go +++ b/graph/cycle.go @@ -1,5 +1,7 @@ // cycle.go // this file handle algorithm that related to cycle in graph +// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph // reference: https://en.wikipedia.org/wiki/Cycle_(graph_theory) // [kiarash hajian](https://github.com/kiarash8112) diff --git a/graph/depthfirstsearch.go b/graph/depthfirstsearch.go index c035c79f5..76bed3106 100644 --- a/graph/depthfirstsearch.go +++ b/graph/depthfirstsearch.go @@ -1,3 +1,9 @@ +// depthfirstsearch.go +// description: this file contains the implementation of the depth first search algorithm +// details: Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking. +// time complexity: O(n) +// space complexity: O(n) + package graph func GetIdx(target int, nodes []int) int { diff --git a/graph/dijkstra.go b/graph/dijkstra.go index 685cf02e8..ad7a8a778 100644 --- a/graph/dijkstra.go +++ b/graph/dijkstra.go @@ -1,3 +1,10 @@ +// dijkstra.go +// description: this file contains the implementation of the Dijkstra algorithm +// details: Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. The algorithm exists in many variants; Dijkstra's original variant found the shortest path between two nodes, but a more common variant fixes a single node as the "source" node and finds shortest paths from the source to all other nodes in the graph, producing a shortest-path tree. +// time complexity: O((V+E) log V) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph +// reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm + package graph import "github.com/TheAlgorithms/Go/sort" diff --git a/graph/floydwarshall.go b/graph/floydwarshall.go index 33b97a2c1..9544e587b 100644 --- a/graph/floydwarshall.go +++ b/graph/floydwarshall.go @@ -1,4 +1,6 @@ // Floyd-Warshall algorithm +// time complexity: O(V^3) where V is the number of vertices in the graph +// space complexity: O(V^2) where V is the number of vertices in the graph // https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm package graph diff --git a/graph/lowestcommonancestor.go b/graph/lowestcommonancestor.go index 8ce575187..891bac50d 100644 --- a/graph/lowestcommonancestor.go +++ b/graph/lowestcommonancestor.go @@ -3,6 +3,8 @@ // detail: // Let `T` be a tree. The LCA of `u` and `v` in T is the shared ancestor of `u` and `v` // that is located farthest from the root. +// time complexity: O(n log n) where n is the number of vertices in the tree +// space complexity: O(n log n) where n is the number of vertices in the tree // references: [cp-algorithms](https://cp-algorithms.com/graph/lca_binary_lifting.html) // author(s) [Dat](https://github.com/datbeohbbh) // see lowestcommonancestor_test.go for a test implementation. diff --git a/graph/topological.go b/graph/topological.go index 9e99470b7..8cd1856e0 100644 --- a/graph/topological.go +++ b/graph/topological.go @@ -1,3 +1,10 @@ +// topological.go +// description: Topological sort +// details: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. +// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph +// space complexity: O(V) where V is the number of vertices in the graph +// reference: https://en.wikipedia.org/wiki/Topological_sorting + package graph // Topological assumes that graph given is valid and that its diff --git a/hashing/sha256/sha256.go b/hashing/sha256/sha256.go index 9061f3801..0dd38a557 100644 --- a/hashing/sha256/sha256.go +++ b/hashing/sha256/sha256.go @@ -1,5 +1,7 @@ // sha256.go // description: The sha256 cryptographic hash function as defined in the RFC6234 standard. +// time complexity: O(n) +// space complexity: O(n) // author: [Paul Leydier] (https://github.com/paul-leydier) // ref: https://datatracker.ietf.org/doc/html/rfc6234 // ref: https://en.wikipedia.org/wiki/SHA-2 diff --git a/math/aliquotsum.go b/math/aliquotsum.go index 6e3af6cc0..cc6bd326a 100644 --- a/math/aliquotsum.go +++ b/math/aliquotsum.go @@ -5,6 +5,8 @@ // is the sum of all proper divisors of n, // that is, all divisors of n other than n itself // wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum +// time complexity: O(n) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see aliquotsum_test.go diff --git a/math/armstrong/isarmstrong.go b/math/armstrong/isarmstrong.go index 68055dee8..851b9612a 100644 --- a/math/armstrong/isarmstrong.go +++ b/math/armstrong/isarmstrong.go @@ -1,6 +1,8 @@ // isarmstrong.go // description: Checks if the given number is armstrong number or not // details: An Armstrong number is a n-digit number that is equal to the sum of each of its digits taken to the nth power. +// time complexity: O(log(n)) +// space complexity: O(1) // ref: https://mathlair.allfunandgames.ca/armstrong.php // author: Kavitha J diff --git a/math/binary/abs.go b/math/binary/abs.go index 9762c7c8a..5c95fa5e8 100644 --- a/math/binary/abs.go +++ b/math/binary/abs.go @@ -1,3 +1,8 @@ +// abs.go +// description: returns absolute value using binary operation +// time complexity: O(1) +// space complexity: O(1) + package binary // Abs returns absolute value using binary operation diff --git a/math/binary/arithmeticmean.go b/math/binary/arithmeticmean.go index 9fa56560e..f7812b6be 100644 --- a/math/binary/arithmeticmean.go +++ b/math/binary/arithmeticmean.go @@ -2,6 +2,8 @@ // description: Arithmetic mean // details: // The most common type of average is the arithmetic mean. If n numbers are given, each number denoted by ai (where i = 1,2, ..., n), the arithmetic mean is the sum of the as divided by n or - [Arithmetic mean](https://en.wikipedia.org/wiki/Average#Arithmetic_mean) +// time complexity: O(1) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see arithmeticmean_test.go diff --git a/math/binary/bitcounter.go b/math/binary/bitcounter.go index 33e24256d..baf8dcd7b 100644 --- a/math/binary/bitcounter.go +++ b/math/binary/bitcounter.go @@ -2,6 +2,8 @@ // description: Counts the number of set bits in a number // details: // For unsigned integer number N, return the number of bits set to 1 - [Bit numbering](https://en.wikipedia.org/wiki/Bit_numbering) +// time complexity: O(log(n)) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see bitcounter_test.go diff --git a/math/binary/checkisnumberpoweroftwo.go b/math/binary/checkisnumberpoweroftwo.go index 29c023e5a..d836396f5 100644 --- a/math/binary/checkisnumberpoweroftwo.go +++ b/math/binary/checkisnumberpoweroftwo.go @@ -2,6 +2,8 @@ // description: Is the number a power of two // details: // Checks if a number is a power of two- [Power of two](https://en.wikipedia.org/wiki/Power_of_two) +// time complexity: O(1) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see checkisnumberpoweroftwo_test.go diff --git a/math/binary/fast_inverse_sqrt.go b/math/binary/fast_inverse_sqrt.go index 24ee41a82..c8689b451 100644 --- a/math/binary/fast_inverse_sqrt.go +++ b/math/binary/fast_inverse_sqrt.go @@ -1,4 +1,6 @@ // Calculating the inverse square root +// time complexity: O(1) +// space complexity: O(1) // [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root) package binary diff --git a/math/binary/logarithm.go b/math/binary/logarithm.go index 205b0235b..3d73ac428 100644 --- a/math/binary/logarithm.go +++ b/math/binary/logarithm.go @@ -1,4 +1,6 @@ // author(s) [red_byte](https://github.com/i-redbyte) +// time complexity: O(1) +// space complexity: O(1) // see logarithm_test.go package binary diff --git a/math/binary/rbc.go b/math/binary/rbc.go index c0a6e78f1..b6ef45f68 100644 --- a/math/binary/rbc.go +++ b/math/binary/rbc.go @@ -2,6 +2,8 @@ // description: Reflected binary code (RBC) // details: // The reflected binary code (RBC), also known just as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). - [RBC](https://en.wikipedia.org/wiki/Gray_code) +// time complexity: O(n) +// space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see rbc_test.go diff --git a/math/binary/reversebits.go b/math/binary/reversebits.go index f4367cc94..751fbcfd5 100644 --- a/math/binary/reversebits.go +++ b/math/binary/reversebits.go @@ -2,6 +2,8 @@ // description: Reverse bits // details: // Reverse the bits of an integer number +// time complexity: O(log(n)) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see reversebits_test.go diff --git a/math/binary/sqrt.go b/math/binary/sqrt.go index 520338eb6..8c967bf91 100644 --- a/math/binary/sqrt.go +++ b/math/binary/sqrt.go @@ -3,6 +3,8 @@ // details: // Calculating the square root using binary operations and a magic number 0x5f3759df [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root) // author(s) [red_byte](https://github.com/i-redbyte) +// time complexity: O(1) +// space complexity: O(1) // see sqrt_test.go package binary diff --git a/math/binary/xorsearch.go b/math/binary/xorsearch.go index b16b7846b..9e914da83 100644 --- a/math/binary/xorsearch.go +++ b/math/binary/xorsearch.go @@ -2,6 +2,8 @@ // description: Find a missing number in a sequence // details: // Given an array A containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. - [xor](https://en.wikipedia.org/wiki/Exclusive_or) +// time complexity: O(n) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see xorsearch_test.go diff --git a/math/binomialcoefficient.go b/math/binomialcoefficient.go index d3c123a6f..614f4b7db 100644 --- a/math/binomialcoefficient.go +++ b/math/binomialcoefficient.go @@ -4,6 +4,8 @@ // a binomial coefficient C(n,k) gives number ways // in which k objects can be chosen from n objects. // wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient +// time complexity: O(k) or O(n-k) whichever is smaller (O(n) in worst case) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see binomialcoefficient_test.go diff --git a/math/catalan/catalannumber.go b/math/catalan/catalannumber.go index 9ea8acb49..5f81cb9f4 100644 --- a/math/catalan/catalannumber.go +++ b/math/catalan/catalannumber.go @@ -2,6 +2,8 @@ // description: Returns the Catalan number // details: // In combinatorial mathematics, the Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. - [Catalan number](https://en.wikipedia.org/wiki/Catalan_number) +// time complexity: O(n) +// space complexity: O(1) // The input is the number of the Catalan number n, at the output we get the value of the number // author(s) [red_byte](https://github.com/i-redbyte) // see catalannumber_test.go diff --git a/math/factorial/factorial.go b/math/factorial/factorial.go index 7472da8de..6703e6c75 100644 --- a/math/factorial/factorial.go +++ b/math/factorial/factorial.go @@ -2,6 +2,8 @@ // description: Calculating factorial // details: // The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n - [Factorial](https://en.wikipedia.org/wiki/Factorial) +// time complexity: O(n) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see factorial_test.go diff --git a/math/fibonacci/fibonacci.go b/math/fibonacci/fibonacci.go index 92e69ae08..c2fd1b2e2 100644 --- a/math/fibonacci/fibonacci.go +++ b/math/fibonacci/fibonacci.go @@ -2,6 +2,8 @@ // description: Get the nth Fibonacci Number // details: // In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number) +// time complexity: O(log n) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see fibonacci_test.go diff --git a/math/gcd/extended.go b/math/gcd/extended.go index eea32e9e9..229630141 100644 --- a/math/gcd/extended.go +++ b/math/gcd/extended.go @@ -3,6 +3,8 @@ // details: // A simple implementation of Extended GCD algorithm, that returns GCD, a and b // which solves ax + by = gcd(a, b) +// time complexity: O(log(min(a, b))) where a and b are the two numbers +// space complexity: O(log(min(a, b))) where a and b are the two numbers // author(s) [Taj](https://github.com/tjgurwara99) // see extended_test.go diff --git a/math/gcd/extendedgcd.go b/math/gcd/extendedgcd.go index 004a91ead..0f5a750dc 100644 --- a/math/gcd/extendedgcd.go +++ b/math/gcd/extendedgcd.go @@ -1,3 +1,8 @@ +// extendedgcd.go +// description: Implementation of Extended GCD Algorithm +// time complexity: O(log(min(a, b))) where a and b are the two numbers +// space complexity: O(log(min(a, b))) where a and b are the two numbers + package gcd // ExtendedRecursive finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b). diff --git a/math/gcd/gcd.go b/math/gcd/gcd.go index e76e8396f..2045d0901 100644 --- a/math/gcd/gcd.go +++ b/math/gcd/gcd.go @@ -1,3 +1,6 @@ +// time complexity: O(log(min(a, b))) where a and b are the two numbers +// space complexity: O(1) + package gcd // Recursive finds and returns the greatest common divisor of a given integer. diff --git a/math/gcd/gcditerative.go b/math/gcd/gcditerative.go index e87dfce6f..96c217cfa 100644 --- a/math/gcd/gcditerative.go +++ b/math/gcd/gcditerative.go @@ -1,3 +1,6 @@ +// time complexity: O(log(min(a, b))) where a and b are the two numbers +// space complexity: O(1) + package gcd // Iterative Faster iterative version of GcdRecursive without holding up too much of the stack diff --git a/math/geometry/distance.go b/math/geometry/distance.go index 5b1c3c82e..0baf64562 100644 --- a/math/geometry/distance.go +++ b/math/geometry/distance.go @@ -1,5 +1,7 @@ // distance.go // Find Euclidean distance between two points +// time complexity: O(n) where n is the number of dimensions +// space complexity: O(1) // author(s) [Chetan Patil](https://github.com/Chetan07j) // Package geometry contains geometric algorithms diff --git a/math/krishnamurthy.go b/math/krishnamurthy.go index 641dfbf92..63bb6dbf6 100644 --- a/math/krishnamurthy.go +++ b/math/krishnamurthy.go @@ -2,6 +2,8 @@ // description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. // details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. // Ex: 1! = 1, 145 = 1! + 4! + 5! +// time complexity: O(log n) +// space complexity: O(1) // author(s): [GooMonk](https://github.com/GooMonk) // see krishnamurthy_test.go package math diff --git a/math/liouville.go b/math/liouville.go index 908a4deac..55d2c95f4 100644 --- a/math/liouville.go +++ b/math/liouville.go @@ -6,6 +6,8 @@ // λ(n) = +1 if n is a positive integer with an even number of prime factors. // λ(n) = −1 if n is a positive integer with an odd number of prime factors. // wikipedia: https://en.wikipedia.org/wiki/Liouville_function +// time complexity: O(log n) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see liouville_test.go diff --git a/math/matrix/add.go b/math/matrix/add.go index 34fdf98be..d5d79efdd 100644 --- a/math/matrix/add.go +++ b/math/matrix/add.go @@ -1,3 +1,8 @@ +// add.go +// description: Add two matrices +// time complexity: O(n^2) +// space complexity: O(n^2) + package matrix import ( diff --git a/math/matrix/checkequal.go b/math/matrix/checkequal.go index c6bde8597..005c657af 100644 --- a/math/matrix/checkequal.go +++ b/math/matrix/checkequal.go @@ -3,6 +3,9 @@ package matrix // CheckEqual checks if the current matrix is equal to another matrix (m2). // Two matrices are considered equal if they have the same dimensions and // all their elements are equal. +// time complexity: O(n*m) where n and m are the dimensions of the matrix +// space complexity: O(1) + func (m1 Matrix[T]) CheckEqual(m2 Matrix[T]) bool { if !m1.MatchDimensions(m2) { return false diff --git a/math/matrix/copy.go b/math/matrix/copy.go index 2b9949750..11afb9237 100644 --- a/math/matrix/copy.go +++ b/math/matrix/copy.go @@ -1,3 +1,9 @@ +// copy.go +// description: Copy a matrix +// details: This function creates a new matrix with the same dimensions as the original matrix and copies all the elements from the original matrix to the new matrix. +// time complexity: O(n*m) where n and m are the dimensions of the matrix +// space complexity: O(n*m) where n and m are the dimensions of the matrix + package matrix import "sync" diff --git a/math/matrix/determinant.go b/math/matrix/determinant.go index d2570f8f8..371b1fa0a 100644 --- a/math/matrix/determinant.go +++ b/math/matrix/determinant.go @@ -2,6 +2,8 @@ // description: This method finds the determinant of a matrix. // details: For a theoretical explanation as for what the determinant // represents, see the [Wikipedia Article](https://en.wikipedia.org/wiki/Determinant) +// time complexity: O(n!) where n is the number of rows and columns in the matrix. +// space complexity: O(n^2) where n is the number of rows and columns in the matrix. // author [Carter907](https://github.com/Carter907) // see determinant_test.go diff --git a/math/matrix/multiply.go b/math/matrix/multiply.go index 718a1b068..f59213da6 100644 --- a/math/matrix/multiply.go +++ b/math/matrix/multiply.go @@ -1,3 +1,8 @@ +// multiply.go +// description: Implementation of matrix multiplication +// time complexity: O(n^3) where n is the number of rows in the first matrix +// space complexity: O(n^2) where n is the number of rows in the first matrix + package matrix import ( diff --git a/math/matrix/strassenmatrixmultiply.go b/math/matrix/strassenmatrixmultiply.go index 86fb47809..9b5f01fdf 100644 --- a/math/matrix/strassenmatrixmultiply.go +++ b/math/matrix/strassenmatrixmultiply.go @@ -4,6 +4,8 @@ // This program takes two matrices as input and performs matrix multiplication // using the Strassen algorithm, which is an optimized divide-and-conquer // approach. It allows for efficient multiplication of large matrices. +// time complexity: O(n^2.81) +// space complexity: O(n^2) // author(s): Mohit Raghav(https://github.com/mohit07raghav19) // See strassenmatrixmultiply_test.go for test cases package matrix diff --git a/math/max/bitwisemax.go b/math/max/bitwisemax.go index b6c3a4623..a54f94654 100644 --- a/math/max/bitwisemax.go +++ b/math/max/bitwisemax.go @@ -3,6 +3,8 @@ // details: // implementation of finding the maximum of two numbers using only binary operations without using conditions // author(s) [red_byte](https://github.com/i-redbyte) +// time complexity: O(1) +// space complexity: O(1) // see bitwiseMax_test.go package max diff --git a/math/median.go b/math/median.go index d8cd02796..1b9dac834 100644 --- a/math/median.go +++ b/math/median.go @@ -1,5 +1,7 @@ // author(s) [jo3zeph](https://github.com/jo3zeph) // description: Find the median from a set of values +// time complexity: O(n log n) +// space complexity: O(1) // see median_test.go package math diff --git a/math/mobius.go b/math/mobius.go index 76b50da14..0f9fac639 100644 --- a/math/mobius.go +++ b/math/mobius.go @@ -7,6 +7,8 @@ // μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. // μ(n) = 0 if n has a squared prime factor. // wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function +// time complexity: O(n) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see mobius_test.go diff --git a/math/mode.go b/math/mode.go index 164084bb6..87f233304 100644 --- a/math/mode.go +++ b/math/mode.go @@ -1,5 +1,7 @@ // mode.go // author(s): [CalvinNJK] (https://github.com/CalvinNJK) +// time complexity: O(n) +// space complexity: O(n) // description: Finding Mode Value In an Array // see mode.go diff --git a/math/modular/exponentiation.go b/math/modular/exponentiation.go index f71a8d3ff..85a397e4f 100644 --- a/math/modular/exponentiation.go +++ b/math/modular/exponentiation.go @@ -2,6 +2,8 @@ // description: Implementation of Modular Exponentiation Algorithm // details: // A simple implementation of Modular Exponentiation - [Modular Exponenetation wiki](https://en.wikipedia.org/wiki/Modular_exponentiation) +// time complexity: O(log(n)) where n is the exponent +// space complexity: O(1) // author(s) [Taj](https://github.com/tjgurwara99) // see exponentiation_test.go diff --git a/math/modular/inverse.go b/math/modular/inverse.go index 819ffda8d..f20d70b11 100644 --- a/math/modular/inverse.go +++ b/math/modular/inverse.go @@ -2,6 +2,8 @@ // description: Implementation of Modular Inverse Algorithm // details: // A simple implementation of Modular Inverse - [Modular Inverse wiki](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) +// time complexity: O(log(min(a, b))) where a and b are the two numbers +// space complexity: O(1) // author(s) [Taj](https://github.com/tjgurwara99) // see inverse_test.go diff --git a/math/moserdebruijnsequence/sequence.go b/math/moserdebruijnsequence/sequence.go index dd846b5a1..09d2c7776 100644 --- a/math/moserdebruijnsequence/sequence.go +++ b/math/moserdebruijnsequence/sequence.go @@ -1,5 +1,7 @@ // The Moser-de Bruijn sequence is the sequence obtained by // adding up the distinct powers of the number 4 (For example 1, 4, 16, 64, etc). +// time complexity: O(n) +// space complexity: O(n) // You can get more details on https://en.wikipedia.org/wiki/Moser%E2%80%93de_Bruijn_sequence. package moserdebruijnsequence diff --git a/math/pascal/pascaltriangle.go b/math/pascal/pascaltriangle.go index 12f227fd0..742b735d7 100644 --- a/math/pascal/pascaltriangle.go +++ b/math/pascal/pascaltriangle.go @@ -16,6 +16,8 @@ //1 10 45 120 210 252 210 120 45 10 1 //... // author(s) [red_byte](https://github.com/i-redbyte) +// time complexity: O(n^2) +// space complexity: O(n^2) // see pascaltriangle_test.go package pascal diff --git a/math/perfectnumber.go b/math/perfectnumber.go index e21c89b64..37be71a2b 100644 --- a/math/perfectnumber.go +++ b/math/perfectnumber.go @@ -7,6 +7,8 @@ // A number is called perfect, if it is a sum of its proper divisors, // cf. https://en.wikipedia.org/wiki/Perfect_number, // https://mathworld.wolfram.com/PerfectNumber.html +// time complexity: O(sqrt(n)) +// space complexity: O(1) // https://oeis.org/A000396 // author(s) [Piotr Idzik](https://github.com/vil02) // see perfectnumber_test.go diff --git a/math/permutation/heaps.go b/math/permutation/heaps.go index f3d79f464..5f4ebaed3 100644 --- a/math/permutation/heaps.go +++ b/math/permutation/heaps.go @@ -1,3 +1,8 @@ +// heaps.go +// description: Implementation of Heap's Algorithm for generating all permutations of n objects +// time complexity: O(n!) +// space complexity: O(n) + package permutation import ( diff --git a/math/permutation/next_permutation.go b/math/permutation/next_permutation.go index 62841bb3d..6aff11296 100644 --- a/math/permutation/next_permutation.go +++ b/math/permutation/next_permutation.go @@ -1,6 +1,8 @@ // A practice to find lexicographically next greater permutation of the given array of integers. // If there does not exist any greater permutation, then print the lexicographically smallest permutation of the given array. // The implementation below, finds the next permutation in linear time and constant memory and returns in place +// time complexity: O(n) +// space complexity: O(1) // Useful reference: https://www.geeksforgeeks.org/next-permutation/ package permutation diff --git a/math/pi/montecarlopi.go b/math/pi/montecarlopi.go index 7bbadf01c..a2e140f08 100644 --- a/math/pi/montecarlopi.go +++ b/math/pi/montecarlopi.go @@ -2,6 +2,8 @@ // description: Calculating pi by the Monte Carlo method // details: // implementations of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method) +// time complexity: O(n) +// space complexity: O(1) // author(s): [red_byte](https://github.com/i-redbyte), [Paul Leydier] (https://github.com/paul-leydier) // see montecarlopi_test.go diff --git a/math/pi/spigotpi.go b/math/pi/spigotpi.go index 6274176e4..349602a32 100644 --- a/math/pi/spigotpi.go +++ b/math/pi/spigotpi.go @@ -2,6 +2,8 @@ // description: A Spigot Algorithm for the Digits of Pi // details: // implementation of Spigot Algorithm for the Digits of Pi - [Spigot algorithm](https://en.wikipedia.org/wiki/Spigot_algorithm) +// time complexity: O(n) +// space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see spigotpi_test.go diff --git a/math/pollard.go b/math/pollard.go index 434a0f24f..a2cc42df1 100644 --- a/math/pollard.go +++ b/math/pollard.go @@ -2,6 +2,8 @@ // description: Pollard's rho algorithm // details: // implementation of Pollard's rho algorithm for integer factorization-[Pollard's rho algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) +// time complexity: O(n^(1/4)) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see pollard_test.go diff --git a/math/power/powvialogarithm.go b/math/power/powvialogarithm.go index df1de157f..c2a395e3b 100644 --- a/math/power/powvialogarithm.go +++ b/math/power/powvialogarithm.go @@ -2,6 +2,8 @@ // description: Powers in terms of logarithms // details: // implementation of exponentiation using exponent and logarithm, without using loops - [Powers via logarithms wiki](https://en.wikipedia.org/wiki/Exponentiation#Powers_via_logarithms) +// time complexity: O(1) +// space complexity: O(1) // author(s) [red_byte](https://github.com/i-redbyte) // see powvialogarithm_test.go diff --git a/math/prime/millerrabintest.go b/math/prime/millerrabintest.go index 1f3a2ef72..5357bc45c 100644 --- a/math/prime/millerrabintest.go +++ b/math/prime/millerrabintest.go @@ -2,7 +2,8 @@ // One of the implementations is deterministic and the other is probabilistic. // The Miller-Rabin test is one of the simplest and fastest known primality // tests and is widely used. -// +// time complexity: O(k * log(n)^3) +// space complexity: O(1) // Authors: // [Taj](https://github.com/tjgurwara99) // [Rak](https://github.com/raklaptudirm) diff --git a/math/prime/primecheck.go b/math/prime/primecheck.go index 3e2a97280..7671c9cd0 100644 --- a/math/prime/primecheck.go +++ b/math/prime/primecheck.go @@ -3,6 +3,8 @@ package prime // A primality test is an algorithm for determining whether an input number is prime. Among other // fields of mathematics, it is used for cryptography. Unlike integer factorization, primality // tests do not generally give prime factors, only stating whether the input number is prime or not. +// time complexity: O(sqrt(n)) +// space complexity: O(1) // Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test // TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it. diff --git a/math/prime/primefactorization.go b/math/prime/primefactorization.go index c25522871..43479e439 100644 --- a/math/prime/primefactorization.go +++ b/math/prime/primefactorization.go @@ -1,3 +1,8 @@ +// primefactorization.go +// description: Prime factorization of a number +// time complexity: O(sqrt(n)) +// space complexity: O(sqrt(n)) + package prime // Factorize is a function that computes the exponents diff --git a/math/prime/sieve2.go b/math/prime/sieve2.go index 2e2e7b116..881ca20f5 100644 --- a/math/prime/sieve2.go +++ b/math/prime/sieve2.go @@ -1,5 +1,7 @@ /* sieve2.go - Sieve of Eratosthenes * Algorithm to generate prime numbers up to a limit + * time complexity: O(n log log n) + * space complexity: O(n) * Author: ddaniel27 */ package prime diff --git a/math/prime/twin.go b/math/prime/twin.go index 1326746e4..dfd861510 100644 --- a/math/prime/twin.go +++ b/math/prime/twin.go @@ -4,6 +4,8 @@ // For any integer n, twin prime is (n + 2) // if and only if both n and (n + 2) both are prime // wikipedia: https://en.wikipedia.org/wiki/Twin_prime +// time complexity: O(log n) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see twin_test.go diff --git a/math/pronicnumber.go b/math/pronicnumber.go index 90850d28e..47d25d17c 100644 --- a/math/pronicnumber.go +++ b/math/pronicnumber.go @@ -4,18 +4,20 @@ // Pronic number: For any integer n, if there exists integer m // such that n = m * (m + 1) then n is called a pronic number. // wikipedia: https://en.wikipedia.org/wiki/Pronic_number +// time complexity: O(1) +// space complexity: O(1) // author: Akshay Dubey (https://github.com/itsAkshayDubey) // see pronicnumber_test.go package math -import stdMath "math" +import "math" // PronicNumber returns true if argument passed to the function is pronic and false otherwise. func PronicNumber(n int) bool { if n < 0 || n%2 == 1 { return false } - x := int(stdMath.Sqrt(float64(n))) + x := int(math.Sqrt(float64(n))) return n == x*(x+1) } diff --git a/other/nested/nestedbrackets.go b/other/nested/nestedbrackets.go index ec912938c..7f220a332 100644 --- a/other/nested/nestedbrackets.go +++ b/other/nested/nestedbrackets.go @@ -17,6 +17,9 @@ package nested // **Note** Providing characters other then brackets would return false, // despite brackets sequence in the string. Make sure to filter // input before usage. +// time complexity: O(n) +// space complexity: O(n) + func IsBalanced(input string) bool { if len(input) == 0 { return true diff --git a/other/password/generator.go b/other/password/generator.go index 46237364f..71bfdbd65 100644 --- a/other/password/generator.go +++ b/other/password/generator.go @@ -3,6 +3,9 @@ // This length is not fixed if you generate multiple passwords for the same range // Package password contains functions to help generate random passwords +// time complexity: O(n) +// space complexity: O(n) + package password import ( diff --git a/search/jump.go b/search/jump.go index 163dea55d..169620d9a 100644 --- a/search/jump.go +++ b/search/jump.go @@ -5,6 +5,8 @@ // before performing a linear search // reference: https://en.wikipedia.org/wiki/Jump_search // see jump_test.go for a test implementation, test function TestJump +// time complexity: O(sqrt(n)) +// space complexity: O(1) package search diff --git a/sort/bogosort.go b/sort/bogosort.go index a37d18ff8..165397155 100644 --- a/sort/bogosort.go +++ b/sort/bogosort.go @@ -1,7 +1,8 @@ // This is a pure Go implementation of the bogosort algorithm, // also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. // Bogosort generates random permutations until it guesses the correct one. - +// worst-case time complexity: O((n+1)!) +// best-case time complexity: O(n) // More info on: https://en.wikipedia.org/wiki/Bogosort package sort diff --git a/sort/combSort.go b/sort/combSort.go index 76e523e34..15c3e8bab 100644 --- a/sort/combSort.go +++ b/sort/combSort.go @@ -1,4 +1,7 @@ // Implementation of comb sort algorithm, an improvement of bubble sort +// average time complexity: O(n^2 / 2^p) where p is the number of increments +// worst time complexity: O(n^2) +// space complexity: O(1) // Reference: https://www.geeksforgeeks.org/comb-sort/ package sort diff --git a/sort/countingsort.go b/sort/countingsort.go index d55a13798..55fbac7c0 100644 --- a/sort/countingsort.go +++ b/sort/countingsort.go @@ -1,6 +1,9 @@ // countingsort.go // description: Implementation of counting sort algorithm // details: A simple counting sort algorithm implementation +// worst-case time complexity: O(n + k) where n is the number of elements in the input array and k is the range of the input +// average-case time complexity: O(n + k) where n is the number of elements in the input array and k is the range of the input +// space complexity: O(n + k) // author [Phil](https://github.com/pschik) // see sort_test.go for a test implementation, test function TestQuickSort diff --git a/sort/exchangesort.go b/sort/exchangesort.go index cbf6b9b00..43ada90df 100644 --- a/sort/exchangesort.go +++ b/sort/exchangesort.go @@ -1,4 +1,7 @@ // Implementation of exchange sort algorithm, a variant of bubble sort +// average time complexity: O(n^2) +// worst time complexity: O(n^2) +// space complexity: O(1) // Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort package sort diff --git a/sort/heapsort.go b/sort/heapsort.go index 741b4e4e8..f4e581306 100644 --- a/sort/heapsort.go +++ b/sort/heapsort.go @@ -1,3 +1,9 @@ +// heapsort.go +// description: Implementation of heap sort algorithm +// worst-case time complexity: O(n log n) +// average-case time complexity: O(n log n) +// space complexity: O(1) + package sort import "github.com/TheAlgorithms/Go/constraints" diff --git a/sort/insertionsort.go b/sort/insertionsort.go index 13e45eeb9..55ac3130f 100644 --- a/sort/insertionsort.go +++ b/sort/insertionsort.go @@ -1,3 +1,9 @@ +// insertionsort.go +// description: Implementation of insertion sort algorithm +// worst-case time complexity: O(n^2) +// average-case time complexity: O(n^2) +// space complexity: O(1) + package sort import "github.com/TheAlgorithms/Go/constraints" diff --git a/sort/mergesort.go b/sort/mergesort.go index 9a875b428..550b13eea 100644 --- a/sort/mergesort.go +++ b/sort/mergesort.go @@ -1,3 +1,9 @@ +// mergesort.go +// description: Implementation of merge sort algorithm +// worst-case time complexity: O(n log n) +// average-case time complexity: O(n log n) +// space complexity: O(n) + package sort import ( diff --git a/sort/patiencesort.go b/sort/patiencesort.go index 746c84931..f1b2b46f2 100644 --- a/sort/patiencesort.go +++ b/sort/patiencesort.go @@ -4,6 +4,9 @@ // GeeksForGeeks article : https://www.geeksforgeeks.org/patience-sorting/ // Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting // authors [guuzaa](https://github.com/guuzaa) +// worst-case time complexity: O(n log n) +// average time complexity: O(n log n) +// space complexity: O(n) // see patiencesort.go package sort diff --git a/sort/pigeonholesort.go b/sort/pigeonholesort.go index 12941cdc9..5e735c8fd 100644 --- a/sort/pigeonholesort.go +++ b/sort/pigeonholesort.go @@ -1,5 +1,7 @@ // Pigeonhole algorithm's working at wikipedia. // https://en.wikipedia.org/wiki/Pigeonhole_sort +// time complexity: O(n + N) where n is the number of elements in the array and N is the range of input +// space complexity: O(N) package sort diff --git a/sort/quicksort.go b/sort/quicksort.go index 576db395a..8b05fe786 100644 --- a/sort/quicksort.go +++ b/sort/quicksort.go @@ -2,6 +2,9 @@ // description: Implementation of in-place quicksort algorithm // details: // A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Quicksort) +// worst time complexity: O(n^2) +// average time complexity: O(n log n) +// space complexity: O(log n) // author(s) [Taj](https://github.com/tjgurwara99) // see sort_test.go for a test implementation, test function TestQuickSort. diff --git a/sort/radixsort.go b/sort/radixsort.go index 4dbd21d64..28ddee8bf 100644 --- a/sort/radixsort.go +++ b/sort/radixsort.go @@ -2,6 +2,9 @@ // description: Implementation of in-place radixsort algorithm // details: // A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort) +// worst time complexity: O(n * k) where n is the number of elements in the input array and k is the number of digits in the largest number +// average time complexity: O(n * k) where n is the number of elements in the input array and k is the number of digits in the largest number +// space complexity: O(n) package sort diff --git a/sort/simplesort.go b/sort/simplesort.go index ec54c1db0..fc60f33de 100644 --- a/sort/simplesort.go +++ b/sort/simplesort.go @@ -5,6 +5,9 @@ // An improved version is included with slight changes to make the sort slightly more efficient // reference: https://arxiv.org/abs/2110.01111v1 // see sort_test.go for a test implementation, test function TestSimple and TestImprovedSimple +// worst-case time complexity: O(n^2) +// average-case time complexity: O(n^2) +// space complexity: O(1) package sort From fba7aba226c0b56694c06bf46b9480b0a1201816 Mon Sep 17 00:00:00 2001 From: Simon Waldherr Date: Tue, 26 Nov 2024 19:54:03 +0100 Subject: [PATCH 194/202] add md5 hashing (#764) --- hashing/md5/md5.go | 118 ++++++++++++++++++++++++++++++++++++++++ hashing/md5/md5_test.go | 42 ++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 hashing/md5/md5.go create mode 100644 hashing/md5/md5_test.go diff --git a/hashing/md5/md5.go b/hashing/md5/md5.go new file mode 100644 index 000000000..5fad61ef4 --- /dev/null +++ b/hashing/md5/md5.go @@ -0,0 +1,118 @@ +// md5.go +// description: The MD5 hashing function as defined in RFC 1321. +// author: Simon Waldherr +// ref: https://datatracker.ietf.org/doc/html/rfc1321 +// see md5_test.go for testing + +package md5 + +import ( + "encoding/binary" +) + +// Constants for MD5 +var ( + s = [64]uint32{ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + } + + K = [64]uint32{ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, + } +) + +// leftRotate rotates x left by n bits +func leftRotate(x, n uint32) uint32 { + return (x << n) | (x >> (32 - n)) +} + +// pad pads the input message so that its length is congruent to 448 modulo 512 +func pad(message []byte) []byte { + originalLength := len(message) * 8 + message = append(message, 0x80) + for (len(message)*8)%512 != 448 { + message = append(message, 0x00) + } + + lengthBytes := make([]byte, 8) + binary.LittleEndian.PutUint64(lengthBytes, uint64(originalLength)) + message = append(message, lengthBytes...) + + return message +} + +// Hash computes the MD5 hash of the input message +func Hash(message []byte) [16]byte { + message = pad(message) + + // Initialize MD5 state variables + a0, b0, c0, d0 := uint32(0x67452301), uint32(0xefcdab89), uint32(0x98badcfe), uint32(0x10325476) + + // Process the message in successive 512-bit chunks + for i := 0; i < len(message); i += 64 { + chunk := message[i : i+64] + var M [16]uint32 + for j := 0; j < 16; j++ { + M[j] = binary.LittleEndian.Uint32(chunk[j*4 : (j+1)*4]) + } + + // Initialize hash value for this chunk + A, B, C, D := a0, b0, c0, d0 + + // Main loop + for i := 0; i < 64; i++ { + var F, g uint32 + if i < 16 { + F = (B & C) | ((^B) & D) + g = uint32(i) + } else if i < 32 { + F = (D & B) | ((^D) & C) + g = uint32((5*i + 1) % 16) + } else if i < 48 { + F = B ^ C ^ D + g = uint32((3*i + 5) % 16) + } else { + F = C ^ (B | (^D)) + g = uint32((7 * i) % 16) + } + F = F + A + K[i] + M[g] + A = D + D = C + C = B + B = B + leftRotate(F, s[i]) + } + + // Add this chunk's hash to result so far + a0 += A + b0 += B + c0 += C + d0 += D + } + + // Produce the final hash value (digest) + var digest [16]byte + binary.LittleEndian.PutUint32(digest[0:4], a0) + binary.LittleEndian.PutUint32(digest[4:8], b0) + binary.LittleEndian.PutUint32(digest[8:12], c0) + binary.LittleEndian.PutUint32(digest[12:16], d0) + + return digest +} diff --git a/hashing/md5/md5_test.go b/hashing/md5/md5_test.go new file mode 100644 index 000000000..b013c0bb3 --- /dev/null +++ b/hashing/md5/md5_test.go @@ -0,0 +1,42 @@ +// md5_test.go +// description: Tests for the MD5 hashing function as defined in RFC 1321. +// author: Simon Waldherr + +package md5 + +import ( + "encoding/hex" + "testing" +) + +// Helper function to convert hash output to hex string for comparison +func toHexString(hash [16]byte) string { + return hex.EncodeToString(hash[:]) +} + +// Test vectors for MD5 (from RFC 1321 and other known sources) +var tests = []struct { + input string + expected string +}{ + {"", "d41d8cd98f00b204e9800998ecf8427e"}, + {"a", "0cc175b9c0f1b6a831c399e269772661"}, + {"abc", "900150983cd24fb0d6963f7d28e17f72"}, + {"message digest", "f96b697d7cb7938d525a2f31aaf161d0"}, + {"abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"}, + {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f"}, + {"12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a"}, +} + +// TestHash verifies that the Hash function produces the correct MD5 hash values +func TestHash(t *testing.T) { + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + result := Hash([]byte(tt.input)) + resultHex := toHexString(result) + if resultHex != tt.expected { + t.Errorf("MD5(%q) = %s; want %s", tt.input, resultHex, tt.expected) + } + }) + } +} From 8a1abce2779fe7cee417a4aab28ddf4eb2cda713 Mon Sep 17 00:00:00 2001 From: Simon Waldherr Date: Tue, 26 Nov 2024 19:57:44 +0100 Subject: [PATCH 195/202] add sha1 hashing (#763) Co-authored-by: Rak Laptudirm --- hashing/sha1/sha1.go | 110 ++++++++++++++++++++++++++++++++++++++ hashing/sha1/sha1_test.go | 42 +++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 hashing/sha1/sha1.go create mode 100644 hashing/sha1/sha1_test.go diff --git a/hashing/sha1/sha1.go b/hashing/sha1/sha1.go new file mode 100644 index 000000000..ba30fe615 --- /dev/null +++ b/hashing/sha1/sha1.go @@ -0,0 +1,110 @@ +// sha1.go +// description: The SHA-1 hashing function as defined in RFC 3174. +// author: Simon Waldherr +// ref: https://datatracker.ietf.org/doc/html/rfc3174 +// see sha1_test.go for testing + +package sha1 + +import ( + "encoding/binary" // Used for interacting with uint at the byte level +) + +// Constants for SHA-1 +const ( + h0 uint32 = 0x67452301 + h1 uint32 = 0xEFCDAB89 + h2 uint32 = 0x98BADCFE + h3 uint32 = 0x10325476 + h4 uint32 = 0xC3D2E1F0 +) + +// pad pads the input message so that its length is congruent to 448 modulo 512 +func pad(message []byte) []byte { + originalLength := len(message) * 8 + message = append(message, 0x80) + for (len(message)*8)%512 != 448 { + message = append(message, 0x00) + } + + lengthBytes := make([]byte, 8) + binary.BigEndian.PutUint64(lengthBytes, uint64(originalLength)) + message = append(message, lengthBytes...) + + return message +} + +// leftRotate rotates x left by n bits +func leftRotate(x, n uint32) uint32 { + return (x << n) | (x >> (32 - n)) +} + +// Hash computes the SHA-1 hash of the input message +func Hash(message []byte) [20]byte { + message = pad(message) + + // Initialize variables + a, b, c, d, e := h0, h1, h2, h3, h4 + + // Process the message in successive 512-bit chunks + for i := 0; i < len(message); i += 64 { + var w [80]uint32 + chunk := message[i : i+64] + + // Break chunk into sixteen 32-bit big-endian words + for j := 0; j < 16; j++ { + w[j] = binary.BigEndian.Uint32(chunk[j*4 : (j+1)*4]) + } + + // Extend the sixteen 32-bit words into eighty 32-bit words + for j := 16; j < 80; j++ { + w[j] = leftRotate(w[j-3]^w[j-8]^w[j-14]^w[j-16], 1) + } + + // Initialize hash value for this chunk + A, B, C, D, E := a, b, c, d, e + + // Main loop + for j := 0; j < 80; j++ { + var f, k uint32 + switch { + case j < 20: + f = (B & C) | ((^B) & D) + k = 0x5A827999 + case j < 40: + f = B ^ C ^ D + k = 0x6ED9EBA1 + case j < 60: + f = (B & C) | (B & D) | (C & D) + k = 0x8F1BBCDC + default: + f = B ^ C ^ D + k = 0xCA62C1D6 + } + + temp := leftRotate(A, 5) + f + E + k + w[j] + E = D + D = C + C = leftRotate(B, 30) + B = A + A = temp + } + + // Add this chunk's hash to result so far + a += A + b += B + c += C + d += D + e += E + } + + // Produce the final hash value (digest) + var digest [20]byte + binary.BigEndian.PutUint32(digest[0:4], a) + binary.BigEndian.PutUint32(digest[4:8], b) + binary.BigEndian.PutUint32(digest[8:12], c) + binary.BigEndian.PutUint32(digest[12:16], d) + binary.BigEndian.PutUint32(digest[16:20], e) + + return digest +} diff --git a/hashing/sha1/sha1_test.go b/hashing/sha1/sha1_test.go new file mode 100644 index 000000000..f7d1d2079 --- /dev/null +++ b/hashing/sha1/sha1_test.go @@ -0,0 +1,42 @@ +// sha1_test.go +// description: Tests for the SHA-1 hashing function as defined in RFC 3174. +// author: Simon Waldherr + +package sha1 + +import ( + "encoding/hex" + "testing" +) + +// Helper function to convert hash output to hex string for comparison +func toHexString(hash [20]byte) string { + return hex.EncodeToString(hash[:]) +} + +// Test vectors for SHA-1 (from RFC 3174 and other known sources) +var tests = []struct { + input string + expected string +}{ + {"", "da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"a", "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8"}, + {"abc", "a9993e364706816aba3e25717850c26c9cd0d89d"}, + {"message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3"}, + {"abcdefghijklmnopqrstuvwxyz", "32d10c7b8cf96570ca04ce37f2a19d84240d3a89"}, + {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "761c457bf73b14d27e9e9265c46f4b4dda11f940"}, + {"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", "fecfd28bbc9345891a66d7c1b8ff46e60192d284"}, +} + +// TestHash verifies that the Hash function produces the correct SHA-1 hash values +func TestHash(t *testing.T) { + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + result := Hash([]byte(tt.input)) + resultHex := toHexString(result) + if resultHex != tt.expected { + t.Errorf("SHA-1(%q) = %s; want %s", tt.input, resultHex, tt.expected) + } + }) + } +} From 82b6e969824f0ee9c36c875857d44563bdfbcfc7 Mon Sep 17 00:00:00 2001 From: Simon Waldherr Date: Wed, 27 Nov 2024 22:35:20 +0100 Subject: [PATCH 196/202] add odd-even-sort (#762) * add sleepsort and odd-even-sort * Delete sort/sleepsort.go * remove sleep sort from sorts_test.go --- sort/oddevensort.go | 39 +++++++++++++++++++++++++++++++++++++++ sort/sorts_test.go | 4 ++++ 2 files changed, 43 insertions(+) create mode 100644 sort/oddevensort.go diff --git a/sort/oddevensort.go b/sort/oddevensort.go new file mode 100644 index 000000000..5e98ef409 --- /dev/null +++ b/sort/oddevensort.go @@ -0,0 +1,39 @@ +// oddevensort.go +// Implementation of Odd-Even Sort (Brick Sort) +// Reference: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort + +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// OddEvenSort performs the odd-even sort algorithm on the given array. +// It is a variation of bubble sort that compares adjacent pairs, alternating +// between odd and even indexed elements in each pass until the array is sorted. +func OddEvenSort[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { // handle empty array + return arr + } + + swapped := true + for swapped { + swapped = false + + // Perform "odd" indexed pass + for i := 1; i < len(arr)-1; i += 2 { + if arr[i] > arr[i+1] { + arr[i], arr[i+1] = arr[i+1], arr[i] + swapped = true + } + } + + // Perform "even" indexed pass + for i := 0; i < len(arr)-1; i += 2 { + if arr[i] > arr[i+1] { + arr[i], arr[i+1] = arr[i+1], arr[i] + swapped = true + } + } + } + + return arr +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 213b17e56..a04f19eb0 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -194,6 +194,10 @@ func TestCircle(t *testing.T) { testFramework(t, sort.Circle[int]) } +func TestOddEvenSort(t *testing.T) { + testFramework(t, sort.OddEvenSort[int]) +} + // END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { From fd6061413348363ef5527b67bc80c60189708311 Mon Sep 17 00:00:00 2001 From: Laurent Egbakou <26142591+egbakou@users.noreply.github.com> Date: Tue, 31 Dec 2024 10:58:51 +0100 Subject: [PATCH 197/202] refactor(structure:linkedlist): renamed variable in singlylinkedlist.go (#772) Co-authored-by: Rak Laptudirm --- structure/linkedlist/singlylinkedlist.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/structure/linkedlist/singlylinkedlist.go b/structure/linkedlist/singlylinkedlist.go index 9f951737f..57b09b104 100644 --- a/structure/linkedlist/singlylinkedlist.go +++ b/structure/linkedlist/singlylinkedlist.go @@ -125,14 +125,14 @@ func (ll *Singly[T]) Count() int { // Reverse reverses the list. func (ll *Singly[T]) Reverse() { - var prev, Next *Node[T] + var prev, next *Node[T] cur := ll.Head for cur != nil { - Next = cur.Next + next = cur.Next cur.Next = prev prev = cur - cur = Next + cur = next } ll.Head = prev From 8c8abd99022d6ac2378a1e94156250cf5d4310ec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 31 Dec 2024 15:38:50 +0530 Subject: [PATCH 198/202] chore(deps): bump the github-actions group across 1 directory with 5 updates (#770) Bumps the github-actions group with 5 updates in the / directory: | Package | From | To | | --- | --- | --- | | [actions/checkout](https://github.com/actions/checkout) | `3` | `4` | | [actions/setup-go](https://github.com/actions/setup-go) | `3` | `5` | | [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) | `3` | `6` | | [actions/stale](https://github.com/actions/stale) | `4` | `9` | | [codecov/codecov-action](https://github.com/codecov/codecov-action) | `4` | `5` | Updates `actions/checkout` from 3 to 4 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) Updates `actions/setup-go` from 3 to 5 - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v3...v5) Updates `golangci/golangci-lint-action` from 3 to 6 - [Release notes](https://github.com/golangci/golangci-lint-action/releases) - [Commits](https://github.com/golangci/golangci-lint-action/compare/v3...v6) Updates `actions/stale` from 4 to 9 - [Release notes](https://github.com/actions/stale/releases) - [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/stale/compare/v4...v9) Updates `codecov/codecov-action` from 4 to 5 - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/codecov/codecov-action/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: golangci/golangci-lint-action dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/stale dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: codecov/codecov-action dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Rak Laptudirm --- .github/workflows/ci.yml | 2 +- .github/workflows/citk.yml | 4 ++-- .github/workflows/stale.yml | 2 +- .github/workflows/upload_coverage_report.yml | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 534f32036..7a5ce1939 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: with: go-version: '^1.18' - name: Run Golang CI Lint - uses: golangci/golangci-lint-action@v3 + uses: golangci/golangci-lint-action@v6 with: version: latest args: -E gofmt diff --git a/.github/workflows/citk.yml b/.github/workflows/citk.yml index ce9360c36..4b675f239 100644 --- a/.github/workflows/citk.yml +++ b/.github/workflows/citk.yml @@ -10,11 +10,11 @@ jobs: strategy: fail-fast: false steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: "^1.18" - name: Checkout branch diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 126bd7ad4..8118ebf78 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -6,7 +6,7 @@ jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v4 + - uses: actions/stale@v9 with: stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.' close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.' diff --git a/.github/workflows/upload_coverage_report.yml b/.github/workflows/upload_coverage_report.yml index 44867a43e..50ce54650 100644 --- a/.github/workflows/upload_coverage_report.yml +++ b/.github/workflows/upload_coverage_report.yml @@ -25,13 +25,13 @@ jobs: go test -coverprofile="${{ env.REPORT_NAME }}" ./... - name: Upload coverage to codecov (tokenless) if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 with: files: "${{ env.REPORT_NAME }}" fail_ci_if_error: true - name: Upload coverage to codecov (with token) if: "! github.event.pull_request.head.repo.fork " - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} files: "${{ env.REPORT_NAME }}" From 137d8209d21bb07915408e773f00ef5eeb80b132 Mon Sep 17 00:00:00 2001 From: Aadish Jain <121042282+mapcrafter2048@users.noreply.github.com> Date: Tue, 31 Dec 2024 19:27:56 +0530 Subject: [PATCH 199/202] Added main and test files for converting hexadecimal to binary and hexadecimal to decimal (#768) * Added main and test files for converting hexadecimal to binary and hexadecimal to decimal * Added functionality instead of using predefined function --------- Co-authored-by: Rak Laptudirm --- conversion/hexadecimaltobinary.go | 78 +++++++++++++++++++++++++ conversion/hexadecimaltobinary_test.go | 46 +++++++++++++++ conversion/hexadecimaltodecimal.go | 57 ++++++++++++++++++ conversion/hexadecimaltodecimal_test.go | 52 +++++++++++++++++ 4 files changed, 233 insertions(+) create mode 100644 conversion/hexadecimaltobinary.go create mode 100644 conversion/hexadecimaltobinary_test.go create mode 100644 conversion/hexadecimaltodecimal.go create mode 100644 conversion/hexadecimaltodecimal_test.go diff --git a/conversion/hexadecimaltobinary.go b/conversion/hexadecimaltobinary.go new file mode 100644 index 000000000..a0d262df6 --- /dev/null +++ b/conversion/hexadecimaltobinary.go @@ -0,0 +1,78 @@ +/* +Author: mapcrafter2048 +GitHub: https://github.com/mapcrafter2048 +*/ + +// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1). +// https://en.wikipedia.org/wiki/Hexadecimal +// https://en.wikipedia.org/wiki/Binary_number +// Function receives a Hexadecimal Number as string and returns the Binary number as string. +// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF. + +package conversion + +import ( + "errors" + "regexp" + "strings" +) + +var isValidHex = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString + +// hexToBinary() function that will take Hexadecimal number as string, +// and return its Binary equivalent as a string. +func hexToBinary(hex string) (string, error) { + // Trim any leading or trailing whitespace + hex = strings.TrimSpace(hex) + + // Check if the hexadecimal string is empty + if hex == "" { + return "", errors.New("input string is empty") + } + + // Check if the hexadecimal string is valid + if !isValidHex(hex) { + return "", errors.New("invalid hexadecimal string: " + hex) + } + + // Parse the hexadecimal string to an integer + var decimal int64 + for i := 0; i < len(hex); i++ { + char := hex[i] + var value int64 + if char >= '0' && char <= '9' { + value = int64(char - '0') + } else if char >= 'A' && char <= 'F' { + value = int64(char - 'A' + 10) + } else if char >= 'a' && char <= 'f' { + value = int64(char - 'a' + 10) + } else { + return "", errors.New("invalid character in hexadecimal string: " + string(char)) + } + decimal = decimal*16 + value + } + + // Convert the integer to a binary string without using predefined functions + var binaryBuilder strings.Builder + if decimal == 0 { + binaryBuilder.WriteString("0") + } else { + for decimal > 0 { + bit := decimal % 2 + if bit == 0 { + binaryBuilder.WriteString("0") + } else { + binaryBuilder.WriteString("1") + } + decimal = decimal / 2 + } + } + + // Reverse the binary string since the bits are added in reverse order + binaryRunes := []rune(binaryBuilder.String()) + for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 { + binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i] + } + + return string(binaryRunes), nil +} diff --git a/conversion/hexadecimaltobinary_test.go b/conversion/hexadecimaltobinary_test.go new file mode 100644 index 000000000..c2dee9712 --- /dev/null +++ b/conversion/hexadecimaltobinary_test.go @@ -0,0 +1,46 @@ +package conversion + +import ( + "testing" +) + +func TestHexToBinary(t *testing.T) { + tests := []struct { + hex string + want string + wantErr bool + }{ + {"", "", true}, + {"G123", "", true}, + {"12XZ", "", true}, + {"1", "1", false}, + {"A", "1010", false}, + {"10", "10000", false}, + {"1A", "11010", false}, + {"aB", "10101011", false}, + {"0Ff", "11111111", false}, + {" 1A ", "11010", false}, + {"0001A", "11010", false}, + {"7FFFFFFFFFFFFFFF", "111111111111111111111111111111111111111111111111111111111111111", false}, + } + + for _, tt := range tests { + t.Run(tt.hex, func(t *testing.T) { + got, err := hexToBinary(tt.hex) + if (err != nil) != tt.wantErr { + t.Errorf("hexToBinary(%q) error = %v, wantErr %v", tt.hex, err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("hexToBinary(%q) = %v, want %v", tt.hex, got, tt.want) + } + }) + } +} + +func BenchmarkHexToBinary(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _, _ = hexToBinary("7FFFFFFFFFFFFFFF") + } +} diff --git a/conversion/hexadecimaltodecimal.go b/conversion/hexadecimaltodecimal.go new file mode 100644 index 000000000..f0d7a81d3 --- /dev/null +++ b/conversion/hexadecimaltodecimal.go @@ -0,0 +1,57 @@ +/* +Author: mapcrafter2048 +GitHub: https://github.com/mapcrafter2048 +*/ + +// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Decimal number(0-9). +// https://en.wikipedia.org/wiki/Hexadecimal +// https://en.wikipedia.org/wiki/Decimal +// Function receives a Hexadecimal Number as string and returns the Decimal number as integer. +// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF. + +package conversion + +import ( + "fmt" + "regexp" + "strings" +) + +var isValidHexadecimal = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString + +// hexToDecimal converts a hexadecimal string to a decimal integer. +func hexToDecimal(hexStr string) (int64, error) { + + hexStr = strings.TrimSpace(hexStr) + + if len(hexStr) == 0 { + return 0, fmt.Errorf("input string is empty") + } + + // Check if the string has a valid hexadecimal prefix + if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") { + hexStr = hexStr[2:] + } + + // Validate the hexadecimal string + if !isValidHexadecimal(hexStr) { + return 0, fmt.Errorf("invalid hexadecimal string") + } + + var decimalValue int64 + for _, char := range hexStr { + var digit int64 + if char >= '0' && char <= '9' { + digit = int64(char - '0') + } else if char >= 'A' && char <= 'F' { + digit = int64(char - 'A' + 10) + } else if char >= 'a' && char <= 'f' { + digit = int64(char - 'a' + 10) + } else { + return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char) + } + decimalValue = decimalValue*16 + digit + } + + return decimalValue, nil +} diff --git a/conversion/hexadecimaltodecimal_test.go b/conversion/hexadecimaltodecimal_test.go new file mode 100644 index 000000000..4f399fe46 --- /dev/null +++ b/conversion/hexadecimaltodecimal_test.go @@ -0,0 +1,52 @@ +package conversion + +import ( + "testing" +) + +func TestHexToDecimal(t *testing.T) { + tests := []struct { + hex string + want int64 + wantErr bool + }{ + {"", 0, true}, + {"G123", 0, true}, + {"123Z", 0, true}, + {"1", 1, false}, + {"A", 10, false}, + {"10", 16, false}, + {"1A", 26, false}, + {"aB", 171, false}, + {"0Ff", 255, false}, + {" 1A ", 26, false}, + {"0x1A", 26, false}, + {"0X1A", 26, false}, + {"1A", 26, false}, + {"7FFFFFFFFFFFFFFF", 9223372036854775807, false}, + {"0001A", 26, false}, + {"0000007F", 127, false}, + {"0", 0, false}, + {"0x0", 0, false}, + } + + for _, tt := range tests { + t.Run(tt.hex, func(t *testing.T) { + got, err := hexToDecimal(tt.hex) + if (err != nil) != tt.wantErr { + t.Errorf("hexToDecimal(%q) error = %v, wantErr %v", tt.hex, err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("hexToDecimal(%q) = %v, want %v", tt.hex, got, tt.want) + } + }) + } +} + +func BenchmarkHexToDecimal(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _, _ = hexToDecimal("7FFFFFFFFFFFFFFF") + } +} From 6d6b06e6bb2121db10ce3ebf26888f9b7305d6d0 Mon Sep 17 00:00:00 2001 From: "Daniel." <67126972+ddaniel27@users.noreply.github.com> Date: Fri, 10 Jan 2025 02:39:46 -0500 Subject: [PATCH 200/202] Project Euler: First Twenty solutions (#771) * Project Euler: First Ten solutions * 11 to 15 * 16 to 20 --- project_euler/problem_1/problem1.go | 24 +++ project_euler/problem_1/problem1_test.go | 45 ++++ project_euler/problem_10/problem10.go | 23 +++ project_euler/problem_10/problem10_test.go | 40 ++++ project_euler/problem_11/problem11.go | 80 +++++++ project_euler/problem_11/problem11_test.go | 29 +++ project_euler/problem_12/problem12.go | 46 +++++ project_euler/problem_12/problem12_test.go | 31 +++ project_euler/problem_13/problem13.go | 150 ++++++++++++++ project_euler/problem_13/problem13_test.go | 27 +++ project_euler/problem_14/problem14.go | 56 +++++ project_euler/problem_14/problem14_test.go | 31 +++ project_euler/problem_15/problem15.go | 42 ++++ project_euler/problem_15/problem15_test.go | 34 +++ project_euler/problem_16/problem16.go | 33 +++ project_euler/problem_16/problem16_test.go | 30 +++ project_euler/problem_17/input.go | 8 + project_euler/problem_17/problem17.go | 31 +++ project_euler/problem_17/problem17_test.go | 30 +++ project_euler/problem_18/edge.go | 100 +++++++++ project_euler/problem_18/input.go | 42 ++++ project_euler/problem_18/leaf.go | 75 +++++++ project_euler/problem_18/problem18.go | 63 ++++++ project_euler/problem_18/problem18_test.go | 42 ++++ project_euler/problem_18/root.go | 62 ++++++ project_euler/problem_18/tree.go | 229 +++++++++++++++++++++ project_euler/problem_19/problem19.go | 63 ++++++ project_euler/problem_19/problem19_test.go | 29 +++ project_euler/problem_2/problem2.go | 30 +++ project_euler/problem_2/problem2_test.go | 45 ++++ project_euler/problem_20/problem20.go | 37 ++++ project_euler/problem_20/problem20_test.go | 31 +++ project_euler/problem_3/problem3.go | 24 +++ project_euler/problem_3/problem3_test.go | 40 ++++ project_euler/problem_4/problem4.go | 33 +++ project_euler/problem_4/problem4_test.go | 33 +++ project_euler/problem_5/problem5.go | 33 +++ project_euler/problem_5/problem5_test.go | 45 ++++ project_euler/problem_6/problem6.go | 33 +++ project_euler/problem_6/problem6_test.go | 40 ++++ project_euler/problem_7/problem7.go | 27 +++ project_euler/problem_7/problem7_test.go | 40 ++++ project_euler/problem_8/problem8.go | 33 +++ project_euler/problem_8/problem8_test.go | 40 ++++ project_euler/problem_9/problem9.go | 29 +++ project_euler/problem_9/problem9_test.go | 33 +++ 46 files changed, 2121 insertions(+) create mode 100644 project_euler/problem_1/problem1.go create mode 100644 project_euler/problem_1/problem1_test.go create mode 100644 project_euler/problem_10/problem10.go create mode 100644 project_euler/problem_10/problem10_test.go create mode 100644 project_euler/problem_11/problem11.go create mode 100644 project_euler/problem_11/problem11_test.go create mode 100644 project_euler/problem_12/problem12.go create mode 100644 project_euler/problem_12/problem12_test.go create mode 100644 project_euler/problem_13/problem13.go create mode 100644 project_euler/problem_13/problem13_test.go create mode 100644 project_euler/problem_14/problem14.go create mode 100644 project_euler/problem_14/problem14_test.go create mode 100644 project_euler/problem_15/problem15.go create mode 100644 project_euler/problem_15/problem15_test.go create mode 100644 project_euler/problem_16/problem16.go create mode 100644 project_euler/problem_16/problem16_test.go create mode 100644 project_euler/problem_17/input.go create mode 100644 project_euler/problem_17/problem17.go create mode 100644 project_euler/problem_17/problem17_test.go create mode 100644 project_euler/problem_18/edge.go create mode 100644 project_euler/problem_18/input.go create mode 100644 project_euler/problem_18/leaf.go create mode 100644 project_euler/problem_18/problem18.go create mode 100644 project_euler/problem_18/problem18_test.go create mode 100644 project_euler/problem_18/root.go create mode 100644 project_euler/problem_18/tree.go create mode 100644 project_euler/problem_19/problem19.go create mode 100644 project_euler/problem_19/problem19_test.go create mode 100644 project_euler/problem_2/problem2.go create mode 100644 project_euler/problem_2/problem2_test.go create mode 100644 project_euler/problem_20/problem20.go create mode 100644 project_euler/problem_20/problem20_test.go create mode 100644 project_euler/problem_3/problem3.go create mode 100644 project_euler/problem_3/problem3_test.go create mode 100644 project_euler/problem_4/problem4.go create mode 100644 project_euler/problem_4/problem4_test.go create mode 100644 project_euler/problem_5/problem5.go create mode 100644 project_euler/problem_5/problem5_test.go create mode 100644 project_euler/problem_6/problem6.go create mode 100644 project_euler/problem_6/problem6_test.go create mode 100644 project_euler/problem_7/problem7.go create mode 100644 project_euler/problem_7/problem7_test.go create mode 100644 project_euler/problem_8/problem8.go create mode 100644 project_euler/problem_8/problem8_test.go create mode 100644 project_euler/problem_9/problem9.go create mode 100644 project_euler/problem_9/problem9_test.go diff --git a/project_euler/problem_1/problem1.go b/project_euler/problem_1/problem1.go new file mode 100644 index 000000000..e41fbf468 --- /dev/null +++ b/project_euler/problem_1/problem1.go @@ -0,0 +1,24 @@ +/** + * Problem 1 - Multiples of 3 and 5 + * + * @see {@link https://projecteuler.net/problem=1} + * + * If we list all the natural numbers below 10 that are multiples of 3 or 5, + * we get 3, 5, 6 and 9. The sum of these multiples is 23. + * Find the sum of all the multiples of 3 or 5 below 1000. + * + * @author ddaniel27 + */ +package problem1 + +func Problem1(n uint) uint { + sum := uint(0) + + for i := uint(1); i < n; i++ { + if i%3 == 0 || i%5 == 0 { + sum += i + } + } + + return sum +} diff --git a/project_euler/problem_1/problem1_test.go b/project_euler/problem_1/problem1_test.go new file mode 100644 index 000000000..c2d649b02 --- /dev/null +++ b/project_euler/problem_1/problem1_test.go @@ -0,0 +1,45 @@ +package problem1 + +import "testing" + +// Tests +func TestProblem1_Func(t *testing.T) { + tests := []struct { + name string + threshold uint + want uint + }{ + { + name: "Testcase 1 - threshold 10", + threshold: 10, + want: 23, + }, + { + name: "Testcase 2 - threshold 100", + threshold: 100, + want: 2318, + }, + { + name: "Testcase 3 - threshold 1000", + threshold: 1000, + want: 233168, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem1(tt.threshold) + + if n != tt.want { + t.Errorf("Problem1() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem1(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem1(1000) + } +} diff --git a/project_euler/problem_10/problem10.go b/project_euler/problem_10/problem10.go new file mode 100644 index 000000000..342c79d24 --- /dev/null +++ b/project_euler/problem_10/problem10.go @@ -0,0 +1,23 @@ +/** +* Problem 10 - Summation of primes +* @see {@link https://projecteuler.net/problem=10} +* +* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. +* Find the sum of all the primes below two million. +* +* @author ddaniel27 + */ +package problem10 + +import "github.com/TheAlgorithms/Go/math/prime" + +func Problem10(n int) uint { + sum := uint(0) + sieve := prime.SieveEratosthenes(n) + + for _, v := range sieve { + sum += uint(v) + } + + return sum +} diff --git a/project_euler/problem_10/problem10_test.go b/project_euler/problem_10/problem10_test.go new file mode 100644 index 000000000..d82e6f29e --- /dev/null +++ b/project_euler/problem_10/problem10_test.go @@ -0,0 +1,40 @@ +package problem10 + +import "testing" + +// Tests +func TestProblem10_Func(t *testing.T) { + tests := []struct { + name string + input int + want uint + }{ + { + name: "Testcase 1 - input 10", + input: 10, + want: 17, + }, + { + name: "Testcase 2 - input 2000000", + input: 2000000, + want: 142913828922, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem10(tt.input) + + if n != tt.want { + t.Errorf("Problem10() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem10(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem10(2000000) + } +} diff --git a/project_euler/problem_11/problem11.go b/project_euler/problem_11/problem11.go new file mode 100644 index 000000000..5ddaea8e2 --- /dev/null +++ b/project_euler/problem_11/problem11.go @@ -0,0 +1,80 @@ +/** +* Problem 11 - Largest product in a grid +* @see {@link https://projecteuler.net/problem=11} +* +* In the 20×20 grid below, four numbers along a diagonal line have been marked in red. +* +* The product of these numbers is 26 × 63 × 78 × 14 = 1788696. +* +* What is the greatest product of four adjacent numbers in the same direction +* (up, down, left, right, or diagonally) in the 20×20 grid? +* +* @author ddaniel27 + */ +package problem11 + +var grid = [20][20]uint{ + {8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, + {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, + {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65}, + {52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91}, + {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80}, + {24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50}, + {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70}, + {67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21}, + {24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72}, + {21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95}, + {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92}, + {16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57}, + {86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58}, + {19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40}, + {4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66}, + {88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69}, + {4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36}, + {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16}, + {20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54}, + {1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}, +} + +func Problem11() uint { + max := uint(0) + + for i := 0; i < 20; i++ { + for j := 0; j < 20; j++ { + + // Vertical + if i+3 < 20 { + product := grid[i][j] * grid[i+1][j] * grid[i+2][j] * grid[i+3][j] + if product > max { + max = product + } + } + + // Horizontal + if j+3 < 20 { + product := grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3] + if product > max { + max = product + } + } + + if i+3 < 20 && j+3 < 20 { + // Diagonal + product := grid[i][j] * grid[i+1][j+1] * grid[i+2][j+2] * grid[i+3][j+3] + if product > max { + max = product + } + } + + if i+3 < 20 && j-3 >= 0 { + // Diagonal + product := grid[i][j] * grid[i+1][j-1] * grid[i+2][j-2] * grid[i+3][j-3] + if product > max { + max = product + } + } + } + } + + return max +} diff --git a/project_euler/problem_11/problem11_test.go b/project_euler/problem_11/problem11_test.go new file mode 100644 index 000000000..b6ae99e05 --- /dev/null +++ b/project_euler/problem_11/problem11_test.go @@ -0,0 +1,29 @@ +package problem11 + +import "testing" + +// Tests +func TestProblem11_Func(t *testing.T) { + testCases := []struct { + name string + expected uint + }{ + {"Test Case 1", 70600674}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + actual := Problem11() + if actual != tc.expected { + t.Errorf("Expected: %v, but got %v", tc.expected, actual) + } + }) + } +} + +// Benchmark +func BenchmarkProblem11_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem11() + } +} diff --git a/project_euler/problem_12/problem12.go b/project_euler/problem_12/problem12.go new file mode 100644 index 000000000..803add5b7 --- /dev/null +++ b/project_euler/problem_12/problem12.go @@ -0,0 +1,46 @@ +/** +* Problem 12 - Highly divisible triangular number +* @see {@link https://projecteuler.net/problem=12} +* +* The sequence of triangle numbers is generated by adding the natural numbers. +* So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. +* The first ten terms would be: +* +* 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... +* +* Let us list the factors of the first seven triangle numbers: +* +* 1: 1 +* 3: 1,3 +* 6: 1,2,3,6 +* 10: 1,2,5,10 +* 15: 1,3,5,15 +* 21: 1,3,7,21 +* 28: 1,2,4,7,14,28 +* +* We can see that 28 is the first triangle number to have over five divisors. +* What is the value of the first triangle number to have over five hundred divisors? +* +* @author ddaniel27 + */ +package problem12 + +func Problem12(limit uint) uint { + triangle := uint(0) + for i := uint(1); ; i++ { + triangle += i + if numDivisors(triangle) >= limit { + return triangle + } + } +} + +func numDivisors(n uint) uint { + divisors := uint(0) + for i := uint(1); i*i <= n; i++ { + if n%i == 0 { + divisors += 2 + } + } + return divisors +} diff --git a/project_euler/problem_12/problem12_test.go b/project_euler/problem_12/problem12_test.go new file mode 100644 index 000000000..2659fb1e9 --- /dev/null +++ b/project_euler/problem_12/problem12_test.go @@ -0,0 +1,31 @@ +package problem12 + +import "testing" + +func TestProblem12_Func(t *testing.T) { + tests := []struct { + name string + input uint + want uint + }{ + {"Test Case 1", 6, 28}, + {"Test Case 2", 7, 36}, + {"Test Case 3", 11, 120}, + {"Test Case 4", 500, 76576500}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := Problem12(tt.input) + if actual != tt.want { + t.Errorf("Expected: %v, but got %v", tt.want, actual) + } + }) + } +} + +func BenchmarkProblem12_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem12(500) + } +} diff --git a/project_euler/problem_13/problem13.go b/project_euler/problem_13/problem13.go new file mode 100644 index 000000000..d5669d271 --- /dev/null +++ b/project_euler/problem_13/problem13.go @@ -0,0 +1,150 @@ +/** +* Problem 13 - Large sum +* @see {@link https://projecteuler.net/problem=13} +* +* Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. +* +* @author ddaniel27 + */ +package problem13 + +var numbers = [100]string{ + "37107287533902102798797998220837590246510135740250", + "46376937677490009712648124896970078050417018260538", + "74324986199524741059474233309513058123726617309629", + "91942213363574161572522430563301811072406154908250", + "23067588207539346171171980310421047513778063246676", + "89261670696623633820136378418383684178734361726757", + "28112879812849979408065481931592621691275889832738", + "44274228917432520321923589422876796487670272189318", + "47451445736001306439091167216856844588711603153276", + "70386486105843025439939619828917593665686757934951", + "62176457141856560629502157223196586755079324193331", + "64906352462741904929101432445813822663347944758178", + "92575867718337217661963751590579239728245598838407", + "58203565325359399008402633568948830189458628227828", + "80181199384826282014278194139940567587151170094390", + "35398664372827112653829987240784473053190104293586", + "86515506006295864861532075273371959191420517255829", + "71693888707715466499115593487603532921714970056938", + "54370070576826684624621495650076471787294438377604", + "53282654108756828443191190634694037855217779295145", + "36123272525000296071075082563815656710885258350721", + "45876576172410976447339110607218265236877223636045", + "17423706905851860660448207621209813287860733969412", + "81142660418086830619328460811191061556940512689692", + "51934325451728388641918047049293215058642563049483", + "62467221648435076201727918039944693004732956340691", + "15732444386908125794514089057706229429197107928209", + "55037687525678773091862540744969844508330393682126", + "18336384825330154686196124348767681297534375946515", + "80386287592878490201521685554828717201219257766954", + "78182833757993103614740356856449095527097864797581", + "16726320100436897842553539920931837441497806860984", + "48403098129077791799088218795327364475675590848030", + "87086987551392711854517078544161852424320693150332", + "59959406895756536782107074926966537676326235447210", + "69793950679652694742597709739166693763042633987085", + "41052684708299085211399427365734116182760315001271", + "65378607361501080857009149939512557028198746004375", + "35829035317434717326932123578154982629742552737307", + "94953759765105305946966067683156574377167401875275", + "88902802571733229619176668713819931811048770190271", + "25267680276078003013678680992525463401061632866526", + "36270218540497705585629946580636237993140746255962", + "24074486908231174977792365466257246923322810917141", + "91430288197103288597806669760892938638285025333403", + "34413065578016127815921815005561868836468420090470", + "23053081172816430487623791969842487255036638784583", + "11487696932154902810424020138335124462181441773470", + "63783299490636259666498587618221225225512486764533", + "67720186971698544312419572409913959008952310058822", + "95548255300263520781532296796249481641953868218774", + "76085327132285723110424803456124867697064507995236", + "37774242535411291684276865538926205024910326572967", + "23701913275725675285653248258265463092207058596522", + "29798860272258331913126375147341994889534765745501", + "18495701454879288984856827726077713721403798879715", + "38298203783031473527721580348144513491373226651381", + "34829543829199918180278916522431027392251122869539", + "40957953066405232632538044100059654939159879593635", + "29746152185502371307642255121183693803580388584903", + "41698116222072977186158236678424689157993532961922", + "62467957194401269043877107275048102390895523597457", + "23189706772547915061505504953922979530901129967519", + "86188088225875314529584099251203829009407770775672", + "11306739708304724483816533873502340845647058077308", + "82959174767140363198008187129011875491310547126581", + "97623331044818386269515456334926366572897563400500", + "42846280183517070527831839425882145521227251250327", + "55121603546981200581762165212827652751691296897789", + "32238195734329339946437501907836945765883352399886", + "75506164965184775180738168837861091527357929701337", + "62177842752192623401942399639168044983993173312731", + "32924185707147349566916674687634660915035914677504", + "99518671430235219628894890102423325116913619626622", + "73267460800591547471830798392868535206946944540724", + "76841822524674417161514036427982273348055556214818", + "97142617910342598647204516893989422179826088076852", + "87783646182799346313767754307809363333018982642090", + "10848802521674670883215120185883543223812876952786", + "71329612474782464538636993009049310363619763878039", + "62184073572399794223406235393808339651327408011116", + "66627891981488087797941876876144230030984490851411", + "60661826293682836764744779239180335110989069790714", + "85786944089552990653640447425576083659976645795096", + "66024396409905389607120198219976047599490197230297", + "64913982680032973156037120041377903785566085089252", + "16730939319872750275468906903707539413042652315011", + "94809377245048795150954100921645863754710598436791", + "78639167021187492431995700641917969777599028300699", + "15368713711936614952811305876380278410754449733078", + "40789923115535562561142322423255033685442488917353", + "44889911501440648020369068063960672322193204149535", + "41503128880339536053299340368006977710650566631954", + "81234880673210146739058568557934581403627822703280", + "82616570773948327592232845941706525094512325230608", + "22918802058777319719839450180888072429661980811197", + "77158542502016545090413245809786882778948721859617", + "72107838435069186155435662884062257473692284509516", + "20849603980134001723930671666823555245252804609722", + "53503534226472524250874054075591789781264330331690", +} + +func Problem13() string { + sum := "0" + + for _, n := range numbers { + sum = add(sum, n) + } + + return sum[:10] +} + +func add(a, b string) string { + if len(a) < len(b) { + a, b = b, a + } + + carry := 0 + sum := make([]byte, len(a)+1) + + for i := 0; i < len(a); i++ { + d := int(a[len(a)-1-i] - '0') + if i < len(b) { + d += int(b[len(b)-1-i] - '0') + } + d += carry + + sum[len(sum)-1-i] = byte(d%10) + '0' + carry = d / 10 + } + + if carry > 0 { + sum[0] = byte(carry) + '0' + } else { + sum = sum[1:] + } + + return string(sum) +} diff --git a/project_euler/problem_13/problem13_test.go b/project_euler/problem_13/problem13_test.go new file mode 100644 index 000000000..e776cbb04 --- /dev/null +++ b/project_euler/problem_13/problem13_test.go @@ -0,0 +1,27 @@ +package problem13 + +import "testing" + +func TestProblem13_Func(t *testing.T) { + tests := []struct { + name string + expected string + }{ + {"Test Case 1", "5537376230"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := Problem13() + if actual != tt.expected { + t.Errorf("Expected: %v, but got %v", tt.expected, actual) + } + }) + } +} + +func BenchmarkProblem13_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem13() + } +} diff --git a/project_euler/problem_14/problem14.go b/project_euler/problem_14/problem14.go new file mode 100644 index 000000000..aa5702c12 --- /dev/null +++ b/project_euler/problem_14/problem14.go @@ -0,0 +1,56 @@ +/** +* Problem 14 - Longest Collatz sequence +* @see {@link https://projecteuler.net/problem=14} +* +* The following iterative sequence is defined for the set of positive integers: +* n → n/2 (n is even) +* n → 3n + 1 (n is odd) +* +* Using the rule above and starting with 13, we generate the following sequence: +* 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 +* +* Which starting number, under one million, produces the longest chain? +* +* NOTE: Once the chain starts the terms are allowed to go above one million. +* +* @author ddaniel27 + */ +package problem14 + +type dict map[uint64]uint64 + +var dictionary = dict{ + 1: 1, +} + +func Problem14(limit uint64) uint64 { + for i := uint64(2); i <= limit; i++ { + weightNextNode(i) + } + + var max, maxWeight uint64 + for k, v := range dictionary { + if v > maxWeight { + max = k + maxWeight = v + } + } + + return max +} + +func weightNextNode(current uint64) uint64 { + var next, weight uint64 + if current%2 == 0 { + next = current / 2 + } else { + next = (3 * current) + 1 + } + if v, ok := dictionary[next]; !ok { + weight = weightNextNode(next) + 1 + } else { + weight = v + 1 + } + dictionary[current] = weight + return weight +} diff --git a/project_euler/problem_14/problem14_test.go b/project_euler/problem_14/problem14_test.go new file mode 100644 index 000000000..801ff0fdd --- /dev/null +++ b/project_euler/problem_14/problem14_test.go @@ -0,0 +1,31 @@ +package problem14 + +import "testing" + +// Tests +func TestProblem14_Func(t *testing.T) { + tests := []struct { + name string + input uint64 + want uint64 + }{ + {"Input 30", 30, 27}, + {"Input 1e6", 1e6, 837799}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Problem14(tt.input) + if got != tt.want { + t.Errorf("Problem14() = %v, want %v", got, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem14_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem14(1e6) + } +} diff --git a/project_euler/problem_15/problem15.go b/project_euler/problem_15/problem15.go new file mode 100644 index 000000000..6adbd6977 --- /dev/null +++ b/project_euler/problem_15/problem15.go @@ -0,0 +1,42 @@ +/** +* Problem 15 - Lattice paths +* @see {@link https://projecteuler.net/problem=15} +* +* Starting in the top left corner of a 2×2 grid, +* and only being able to move to the right and down, +* there are exactly 6 routes to the bottom right corner. +* +* How many such routes are there through a 20×20 grid? +* +* @author ddaniel27 + */ +package problem15 + +import ( + "github.com/TheAlgorithms/Go/math/factorial" +) + +func Problem15(gridSize int) int { + /** + Author note: + We can solve this problem using combinatorics. + Here is a good blog post that explains the solution: + + [link](https://stemhash.com/counting-lattice-paths/) + + Btw, I'm not related to the author of the blog post. + + After some simplification, we can see that the solution is: + (2n)! / (n!)^2 + + We can use the factorial package to calculate the factorials. + */ + + n := gridSize + + numerator, _ := factorial.Iterative(2 * n) + denominator, _ := factorial.Iterative(n) + denominator *= denominator + + return numerator / denominator +} diff --git a/project_euler/problem_15/problem15_test.go b/project_euler/problem_15/problem15_test.go new file mode 100644 index 000000000..a5b729428 --- /dev/null +++ b/project_euler/problem_15/problem15_test.go @@ -0,0 +1,34 @@ +package problem15 + +import "testing" + +// Tests +func TestProblem15_Func(t *testing.T) { + tests := []struct { + name string + input int + want int + }{ + {"Input 2", 2, 6}, + // This test case is disabled + // because it needs a big integer to run successfully + // and factorial package doesn't support it + // {"Input 20", 20, 137846528820}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Problem15(tt.input) + if got != tt.want { + t.Errorf("Problem15() = %v, want %v", got, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem15_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem15(20) + } +} diff --git a/project_euler/problem_16/problem16.go b/project_euler/problem_16/problem16.go new file mode 100644 index 000000000..cc0471c66 --- /dev/null +++ b/project_euler/problem_16/problem16.go @@ -0,0 +1,33 @@ +/** +* Problem 16 - Power digit sum +* @see {@link https://projecteuler.net/problem=16} +* +* 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. +* +* What is the sum of the digits of the number 2^1000? +* +* @author ddaniel27 + */ +package problem16 + +import ( + "math/big" +) + +func Problem16(exponent int64) int64 { + var result big.Int + + bigTwo := big.NewInt(2) + bigExponent := big.NewInt(exponent) + + result.Exp(bigTwo, bigExponent, nil) + + resultStr := result.String() + + var sum int64 + for _, digit := range resultStr { + sum += int64(digit - '0') + } + + return sum +} diff --git a/project_euler/problem_16/problem16_test.go b/project_euler/problem_16/problem16_test.go new file mode 100644 index 000000000..31e3f9a02 --- /dev/null +++ b/project_euler/problem_16/problem16_test.go @@ -0,0 +1,30 @@ +package problem16 + +import "testing" + +// Tests +func TestProblem16_Func(t *testing.T) { + tests := []struct { + name string + exponent int64 + want int64 + }{ + {"2^15", 15, 26}, + {"2^1000", 1000, 1366}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Problem16(tt.exponent); got != tt.want { + t.Errorf("Problem16() = %v, want %v", got, tt.want) + } + }) + } +} + +// Benchmark +func BenchmarkProblem16_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem16(1000) + } +} diff --git a/project_euler/problem_17/input.go b/project_euler/problem_17/input.go new file mode 100644 index 000000000..3a16f8c3a --- /dev/null +++ b/project_euler/problem_17/input.go @@ -0,0 +1,8 @@ +/** +* I put this code in a separate file because it is too long. +* Also it took me a lot of time to parsing this input from +* a random html page, so, I don't want to lose it. + */ +package problem17 + +const INPUT = "One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen Twenty Twenty one Twenty two Twenty three Twenty four Twenty five Twenty six Twenty seven Twenty eight Twenty nine Thirty Thirty one Thirty two Thirty three Thirty four Thirty five Thirty six Thirty seven Thirty eight Thirty nine Forty Forty one Forty two Forty three Forty four Forty five Forty six Forty seven Forty eight Forty nine Fifty Fifty one Fifty two Fifty three Fifty four Fifty five Fifty six Fifty seven Fifty eight Fifty nine Sixty Sixty one Sixty two Sixty three Sixty four Sixty five Sixty six Sixty seven Sixty eight Sixty nine Seventy Seventy one Seventy two Seventy three Seventy four Seventy five Seventy six Seventy seven Seventy eight Seventy nine Eighty Eighty one Eighty two Eighty three Eighty four Eighty five Eighty six Eighty seven Eighty eight Eighty nine Ninety Ninety one Ninety two Ninety three Ninety four Ninety five Ninety six Ninety seven Ninety eight Ninety nine One hundred One hundred and one One hundred and two One hundred and three One hundred and four One hundred and five One hundred and six One hundred and seven One hundred and eight One hundred and nine One hundred and ten One hundred and eleven One hundred and twelve One hundred and thirteen One hundred and fourteen One hundred and fifteen One hundred and sixteen One hundred and seventeen One hundred and eighteen One hundred and nineteen One hundred and twenty One hundred and twenty one One hundred and twenty two One hundred and twenty three One hundred and twenty four One hundred and twenty five One hundred and twenty six One hundred and twenty seven One hundred and twenty eight One hundred and twenty nine One hundred and thirty One hundred and thirty one One hundred and thirty two One hundred and thirty three One hundred and thirty four One hundred and thirty five One hundred and thirty six One hundred and thirty seven One hundred and thirty eight One hundred and thirty nine One hundred and forty One hundred and forty one One hundred and forty two One hundred and forty three One hundred and forty four One hundred and forty five One hundred and forty six One hundred and forty seven One hundred and forty eight One hundred and forty nine One hundred and fifty One hundred and fifty one One hundred and fifty two One hundred and fifty three One hundred and fifty four One hundred and fifty five One hundred and fifty six One hundred and fifty seven One hundred and fifty eight One hundred and fifty nine One hundred and sixty One hundred and sixty one One hundred and sixty two One hundred and sixty three One hundred and sixty four One hundred and sixty five One hundred and sixty six One hundred and sixty seven One hundred and sixty eight One hundred and sixty nine One hundred and seventy One hundred and seventy one One hundred and seventy two One hundred and seventy three One hundred and seventy four One hundred and seventy five One hundred and seventy six One hundred and seventy seven One hundred and seventy eight One hundred and seventy nine One hundred and eighty One hundred and eighty one One hundred and eighty two One hundred and eighty three One hundred and eighty four One hundred and eighty five One hundred and eighty six One hundred and eighty seven One hundred and eighty eight One hundred and eighty nine One hundred and ninety One hundred and ninety one One hundred and ninety two One hundred and ninety three One hundred and ninety four One hundred and ninety five One hundred and ninety six One hundred and ninety seven One hundred and ninety eight One hundred and ninety nine Two hundred Two hundred and one Two hundred and two Two hundred and three Two hundred and four Two hundred and five Two hundred and six Two hundred and seven Two hundred and eight Two hundred and nine Two hundred and ten Two hundred and eleven Two hundred and twelve Two hundred and thirteen Two hundred and fourteen Two hundred and fifteen Two hundred and sixteen Two hundred and seventeen Two hundred and eighteen Two hundred and nineteen Two hundred and twenty Two hundred and twenty one Two hundred and twenty two Two hundred and twenty three Two hundred and twenty four Two hundred and twenty five Two hundred and twenty six Two hundred and twenty seven Two hundred and twenty eight Two hundred and twenty nine Two hundred and thirty Two hundred and thirty one Two hundred and thirty two Two hundred and thirty three Two hundred and thirty four Two hundred and thirty five Two hundred and thirty six Two hundred and thirty seven Two hundred and thirty eight Two hundred and thirty nine Two hundred and forty Two hundred and forty one Two hundred and forty two Two hundred and forty three Two hundred and forty four Two hundred and forty five Two hundred and forty six Two hundred and forty seven Two hundred and forty eight Two hundred and forty nine Two hundred and fifty Two hundred and fifty one Two hundred and fifty two Two hundred and fifty three Two hundred and fifty four Two hundred and fifty five Two hundred and fifty six Two hundred and fifty seven Two hundred and fifty eight Two hundred and fifty nine Two hundred and sixty Two hundred and sixty one Two hundred and sixty two Two hundred and sixty three Two hundred and sixty four Two hundred and sixty five Two hundred and sixty six Two hundred and sixty seven Two hundred and sixty eight Two hundred and sixty nine Two hundred and seventy Two hundred and seventy one Two hundred and seventy two Two hundred and seventy three Two hundred and seventy four Two hundred and seventy five Two hundred and seventy six Two hundred and seventy seven Two hundred and seventy eight Two hundred and seventy nine Two hundred and eighty Two hundred and eighty one Two hundred and eighty two Two hundred and eighty three Two hundred and eighty four Two hundred and eighty five Two hundred and eighty six Two hundred and eighty seven Two hundred and eighty eight Two hundred and eighty nine Two hundred and ninety Two hundred and ninety one Two hundred and ninety two Two hundred and ninety three Two hundred and ninety four Two hundred and ninety five Two hundred and ninety six Two hundred and ninety seven Two hundred and ninety eight Two hundred and ninety nine Three hundred Three hundred and one Three hundred and two Three hundred and three Three hundred and four Three hundred and five Three hundred and six Three hundred and seven Three hundred and eight Three hundred and nine Three hundred and ten Three hundred and eleven Three hundred and twelve Three hundred and thirteen Three hundred and fourteen Three hundred and fifteen Three hundred and sixteen Three hundred and seventeen Three hundred and eighteen Three hundred and nineteen Three hundred and twenty Three hundred and twenty one Three hundred and twenty two Three hundred and twenty three Three hundred and twenty four Three hundred and twenty five Three hundred and twenty six Three hundred and twenty seven Three hundred and twenty eight Three hundred and twenty nine Three hundred and thirty Three hundred and thirty one Three hundred and thirty two Three hundred and thirty three Three hundred and thirty four Three hundred and thirty five Three hundred and thirty six Three hundred and thirty seven Three hundred and thirty eight Three hundred and thirty nine Three hundred and forty Three hundred and forty one Three hundred and forty two Three hundred and forty three Three hundred and forty four Three hundred and forty five Three hundred and forty six Three hundred and forty seven Three hundred and forty eight Three hundred and forty nine Three hundred and fifty Three hundred and fifty one Three hundred and fifty two Three hundred and fifty three Three hundred and fifty four Three hundred and fifty five Three hundred and fifty six Three hundred and fifty seven Three hundred and fifty eight Three hundred and fifty nine Three hundred and sixty Three hundred and sixty one Three hundred and sixty two Three hundred and sixty three Three hundred and sixty four Three hundred and sixty five Three hundred and sixty six Three hundred and sixty seven Three hundred and sixty eight Three hundred and sixty nine Three hundred and seventy Three hundred and seventy one Three hundred and seventy two Three hundred and seventy three Three hundred and seventy four Three hundred and seventy five Three hundred and seventy six Three hundred and seventy seven Three hundred and seventy eight Three hundred and seventy nine Three hundred and eighty Three hundred and eighty one Three hundred and eighty two Three hundred and eighty three Three hundred and eighty four Three hundred and eighty five Three hundred and eighty six Three hundred and eighty seven Three hundred and eighty eight Three hundred and eighty nine Three hundred and ninety Three hundred and ninety one Three hundred and ninety two Three hundred and ninety three Three hundred and ninety four Three hundred and ninety five Three hundred and ninety six Three hundred and ninety seven Three hundred and ninety eight Three hundred and ninety nine Four hundred Four hundred and one Four hundred and two Four hundred and three Four hundred and four Four hundred and five Four hundred and six Four hundred and seven Four hundred and eight Four hundred and nine Four hundred and ten Four hundred and eleven Four hundred and twelve Four hundred and thirteen Four hundred and fourteen Four hundred and fifteen Four hundred and sixteen Four hundred and seventeen Four hundred and eighteen Four hundred and nineteen Four hundred and twenty Four hundred and twenty one Four hundred and twenty two Four hundred and twenty three Four hundred and twenty four Four hundred and twenty five Four hundred and twenty six Four hundred and twenty seven Four hundred and twenty eight Four hundred and twenty nine Four hundred and thirty Four hundred and thirty one Four hundred and thirty two Four hundred and thirty three Four hundred and thirty four Four hundred and thirty five Four hundred and thirty six Four hundred and thirty seven Four hundred and thirty eight Four hundred and thirty nine Four hundred and forty Four hundred and forty one Four hundred and forty two Four hundred and forty three Four hundred and forty four Four hundred and forty five Four hundred and forty six Four hundred and forty seven Four hundred and forty eight Four hundred and forty nine Four hundred and fifty Four hundred and fifty one Four hundred and fifty two Four hundred and fifty three Four hundred and fifty four Four hundred and fifty five Four hundred and fifty six Four hundred and fifty seven Four hundred and fifty eight Four hundred and fifty nine Four hundred and sixty Four hundred and sixty one Four hundred and sixty two Four hundred and sixty three Four hundred and sixty four Four hundred and sixty five Four hundred and sixty six Four hundred and sixty seven Four hundred and sixty eight Four hundred and sixty nine Four hundred and seventy Four hundred and seventy one Four hundred and seventy two Four hundred and seventy three Four hundred and seventy four Four hundred and seventy five Four hundred and seventy six Four hundred and seventy seven Four hundred and seventy eight Four hundred and seventy nine Four hundred and eighty Four hundred and eighty one Four hundred and eighty two Four hundred and eighty three Four hundred and eighty four Four hundred and eighty five Four hundred and eighty six Four hundred and eighty seven Four hundred and eighty eight Four hundred and eighty nine Four hundred and ninety Four hundred and ninety one Four hundred and ninety two Four hundred and ninety three Four hundred and ninety four Four hundred and ninety five Four hundred and ninety six Four hundred and ninety seven Four hundred and ninety eight Four hundred and ninety nine Five hundred Five hundred and one Five hundred and two Five hundred and three Five hundred and four Five hundred and five Five hundred and six Five hundred and seven Five hundred and eight Five hundred and nine Five hundred and ten Five hundred and eleven Five hundred and twelve Five hundred and thirteen Five hundred and fourteen Five hundred and fifteen Five hundred and sixteen Five hundred and seventeen Five hundred and eighteen Five hundred and nineteen Five hundred and twenty Five hundred and twenty one Five hundred and twenty two Five hundred and twenty three Five hundred and twenty four Five hundred and twenty five Five hundred and twenty six Five hundred and twenty seven Five hundred and twenty eight Five hundred and twenty nine Five hundred and thirty Five hundred and thirty one Five hundred and thirty two Five hundred and thirty three Five hundred and thirty four Five hundred and thirty five Five hundred and thirty six Five hundred and thirty seven Five hundred and thirty eight Five hundred and thirty nine Five hundred and forty Five hundred and forty one Five hundred and forty two Five hundred and forty three Five hundred and forty four Five hundred and forty five Five hundred and forty six Five hundred and forty seven Five hundred and forty eight Five hundred and forty nine Five hundred and fifty Five hundred and fifty one Five hundred and fifty two Five hundred and fifty three Five hundred and fifty four Five hundred and fifty five Five hundred and fifty six Five hundred and fifty seven Five hundred and fifty eight Five hundred and fifty nine Five hundred and sixty Five hundred and sixty one Five hundred and sixty two Five hundred and sixty three Five hundred and sixty four Five hundred and sixty five Five hundred and sixty six Five hundred and sixty seven Five hundred and sixty eight Five hundred and sixty nine Five hundred and seventy Five hundred and seventy one Five hundred and seventy two Five hundred and seventy three Five hundred and seventy four Five hundred and seventy five Five hundred and seventy six Five hundred and seventy seven Five hundred and seventy eight Five hundred and seventy nine Five hundred and eighty Five hundred and eighty one Five hundred and eighty two Five hundred and eighty three Five hundred and eighty four Five hundred and eighty five Five hundred and eighty six Five hundred and eighty seven Five hundred and eighty eight Five hundred and eighty nine Five hundred and ninety Five hundred and ninety one Five hundred and ninety two Five hundred and ninety three Five hundred and ninety four Five hundred and ninety five Five hundred and ninety six Five hundred and ninety seven Five hundred and ninety eight Five hundred and ninety nine Six hundred Six hundred and one Six hundred and two Six hundred and three Six hundred and four Six hundred and five Six hundred and six Six hundred and seven Six hundred and eight Six hundred and nine Six hundred and ten Six hundred and eleven Six hundred and twelve Six hundred and thirteen Six hundred and fourteen Six hundred and fifteen Six hundred and sixteen Six hundred and seventeen Six hundred and eighteen Six hundred and nineteen Six hundred and twenty Six hundred and twenty one Six hundred and twenty two Six hundred and twenty three Six hundred and twenty four Six hundred and twenty five Six hundred and twenty six Six hundred and twenty seven Six hundred and twenty eight Six hundred and twenty nine Six hundred and thirty Six hundred and thirty one Six hundred and thirty two Six hundred and thirty three Six hundred and thirty four Six hundred and thirty five Six hundred and thirty six Six hundred and thirty seven Six hundred and thirty eight Six hundred and thirty nine Six hundred and forty Six hundred and forty one Six hundred and forty two Six hundred and forty three Six hundred and forty four Six hundred and forty five Six hundred and forty six Six hundred and forty seven Six hundred and forty eight Six hundred and forty nine Six hundred and fifty Six hundred and fifty one Six hundred and fifty two Six hundred and fifty three Six hundred and fifty four Six hundred and fifty five Six hundred and fifty six Six hundred and fifty seven Six hundred and fifty eight Six hundred and fifty nine Six hundred and sixty Six hundred and sixty one Six hundred and sixty two Six hundred and sixty three Six hundred and sixty four Six hundred and sixty five Six hundred and sixty six Six hundred and sixty seven Six hundred and sixty eight Six hundred and sixty nine Six hundred and seventy Six hundred and seventy one Six hundred and seventy two Six hundred and seventy three Six hundred and seventy four Six hundred and seventy five Six hundred and seventy six Six hundred and seventy seven Six hundred and seventy eight Six hundred and seventy nine Six hundred and eighty Six hundred and eighty one Six hundred and eighty two Six hundred and eighty three Six hundred and eighty four Six hundred and eighty five Six hundred and eighty six Six hundred and eighty seven Six hundred and eighty eight Six hundred and eighty nine Six hundred and ninety Six hundred and ninety one Six hundred and ninety two Six hundred and ninety three Six hundred and ninety four Six hundred and ninety five Six hundred and ninety six Six hundred and ninety seven Six hundred and ninety eight Six hundred and ninety nine Seven hundred Seven hundred and one Seven hundred and two Seven hundred and three Seven hundred and four Seven hundred and five Seven hundred and six Seven hundred and seven Seven hundred and eight Seven hundred and nine Seven hundred and ten Seven hundred and eleven Seven hundred and twelve Seven hundred and thirteen Seven hundred and fourteen Seven hundred and fifteen Seven hundred and sixteen Seven hundred and seventeen Seven hundred and eighteen Seven hundred and nineteen Seven hundred and twenty Seven hundred and twenty one Seven hundred and twenty two Seven hundred and twenty three Seven hundred and twenty four Seven hundred and twenty five Seven hundred and twenty six Seven hundred and twenty seven Seven hundred and twenty eight Seven hundred and twenty nine Seven hundred and thirty Seven hundred and thirty one Seven hundred and thirty two Seven hundred and thirty three Seven hundred and thirty four Seven hundred and thirty five Seven hundred and thirty six Seven hundred and thirty seven Seven hundred and thirty eight Seven hundred and thirty nine Seven hundred and forty Seven hundred and forty one Seven hundred and forty two Seven hundred and forty three Seven hundred and forty four Seven hundred and forty five Seven hundred and forty six Seven hundred and forty seven Seven hundred and forty eight Seven hundred and forty nine Seven hundred and fifty Seven hundred and fifty one Seven hundred and fifty two Seven hundred and fifty three Seven hundred and fifty four Seven hundred and fifty five Seven hundred and fifty six Seven hundred and fifty seven Seven hundred and fifty eight Seven hundred and fifty nine Seven hundred and sixty Seven hundred and sixty one Seven hundred and sixty two Seven hundred and sixty three Seven hundred and sixty four Seven hundred and sixty five Seven hundred and sixty six Seven hundred and sixty seven Seven hundred and sixty eight Seven hundred and sixty nine Seven hundred and seventy Seven hundred and seventy one Seven hundred and seventy two Seven hundred and seventy three Seven hundred and seventy four Seven hundred and seventy five Seven hundred and seventy six Seven hundred and seventy seven Seven hundred and seventy eight Seven hundred and seventy nine Seven hundred and eighty Seven hundred and eighty one Seven hundred and eighty two Seven hundred and eighty three Seven hundred and eighty four Seven hundred and eighty five Seven hundred and eighty six Seven hundred and eighty seven Seven hundred and eighty eight Seven hundred and eighty nine Seven hundred and ninety Seven hundred and ninety one Seven hundred and ninety two Seven hundred and ninety three Seven hundred and ninety four Seven hundred and ninety five Seven hundred and ninety six Seven hundred and ninety seven Seven hundred and ninety eight Seven hundred and ninety nine Eight hundred Eight hundred and one Eight hundred and two Eight hundred and three Eight hundred and four Eight hundred and five Eight hundred and six Eight hundred and seven Eight hundred and eight Eight hundred and nine Eight hundred and ten Eight hundred and eleven Eight hundred and twelve Eight hundred and thirteen Eight hundred and fourteen Eight hundred and fifteen Eight hundred and sixteen Eight hundred and seventeen Eight hundred and eighteen Eight hundred and nineteen Eight hundred and twenty Eight hundred and twenty one Eight hundred and twenty two Eight hundred and twenty three Eight hundred and twenty four Eight hundred and twenty five Eight hundred and twenty six Eight hundred and twenty seven Eight hundred and twenty eight Eight hundred and twenty nine Eight hundred and thirty Eight hundred and thirty one Eight hundred and thirty two Eight hundred and thirty three Eight hundred and thirty four Eight hundred and thirty five Eight hundred and thirty six Eight hundred and thirty seven Eight hundred and thirty eight Eight hundred and thirty nine Eight hundred and forty Eight hundred and forty one Eight hundred and forty two Eight hundred and forty three Eight hundred and forty four Eight hundred and forty five Eight hundred and forty six Eight hundred and forty seven Eight hundred and forty eight Eight hundred and forty nine Eight hundred and fifty Eight hundred and fifty one Eight hundred and fifty two Eight hundred and fifty three Eight hundred and fifty four Eight hundred and fifty five Eight hundred and fifty six Eight hundred and fifty seven Eight hundred and fifty eight Eight hundred and fifty nine Eight hundred and sixty Eight hundred and sixty one Eight hundred and sixty two Eight hundred and sixty three Eight hundred and sixty four Eight hundred and sixty five Eight hundred and sixty six Eight hundred and sixty seven Eight hundred and sixty eight Eight hundred and sixty nine Eight hundred and seventy Eight hundred and seventy one Eight hundred and seventy two Eight hundred and seventy three Eight hundred and seventy four Eight hundred and seventy five Eight hundred and seventy six Eight hundred and seventy seven Eight hundred and seventy eight Eight hundred and seventy nine Eight hundred and eighty Eight hundred and eighty one Eight hundred and eighty two Eight hundred and eighty three Eight hundred and eighty four Eight hundred and eighty five Eight hundred and eighty six Eight hundred and eighty seven Eight hundred and eighty eight Eight hundred and eighty nine Eight hundred and ninety Eight hundred and ninety one Eight hundred and ninety two Eight hundred and ninety three Eight hundred and ninety four Eight hundred and ninety five Eight hundred and ninety six Eight hundred and ninety seven Eight hundred and ninety eight Eight hundred and ninety nine Nine hundred Nine hundred and one Nine hundred and two Nine hundred and three Nine hundred and four Nine hundred and five Nine hundred and six Nine hundred and seven Nine hundred and eight Nine hundred and nine Nine hundred and ten Nine hundred and eleven Nine hundred and twelve Nine hundred and thirteen Nine hundred and fourteen Nine hundred and fifteen Nine hundred and sixteen Nine hundred and seventeen Nine hundred and eighteen Nine hundred and nineteen Nine hundred and twenty Nine hundred and twenty one Nine hundred and twenty two Nine hundred and twenty three Nine hundred and twenty four Nine hundred and twenty five Nine hundred and twenty six Nine hundred and twenty seven Nine hundred and twenty eight Nine hundred and twenty nine Nine hundred and thirty Nine hundred and thirty one Nine hundred and thirty two Nine hundred and thirty three Nine hundred and thirty four Nine hundred and thirty five Nine hundred and thirty six Nine hundred and thirty seven Nine hundred and thirty eight Nine hundred and thirty nine Nine hundred and forty Nine hundred and forty one Nine hundred and forty two Nine hundred and forty three Nine hundred and forty four Nine hundred and forty five Nine hundred and forty six Nine hundred and forty seven Nine hundred and forty eight Nine hundred and forty nine Nine hundred and fifty Nine hundred and fifty one Nine hundred and fifty two Nine hundred and fifty three Nine hundred and fifty four Nine hundred and fifty five Nine hundred and fifty six Nine hundred and fifty seven Nine hundred and fifty eight Nine hundred and fifty nine Nine hundred and sixty Nine hundred and sixty one Nine hundred and sixty two Nine hundred and sixty three Nine hundred and sixty four Nine hundred and sixty five Nine hundred and sixty six Nine hundred and sixty seven Nine hundred and sixty eight Nine hundred and sixty nine Nine hundred and seventy Nine hundred and seventy one Nine hundred and seventy two Nine hundred and seventy three Nine hundred and seventy four Nine hundred and seventy five Nine hundred and seventy six Nine hundred and seventy seven Nine hundred and seventy eight Nine hundred and seventy nine Nine hundred and eighty Nine hundred and eighty one Nine hundred and eighty two Nine hundred and eighty three Nine hundred and eighty four Nine hundred and eighty five Nine hundred and eighty six Nine hundred and eighty seven Nine hundred and eighty eight Nine hundred and eighty nine Nine hundred and ninety Nine hundred and ninety one Nine hundred and ninety two Nine hundred and ninety three Nine hundred and ninety four Nine hundred and ninety five Nine hundred and ninety six Nine hundred and ninety seven Nine hundred and ninety eight Nine hundred and ninety nine One thousand" diff --git a/project_euler/problem_17/problem17.go b/project_euler/problem_17/problem17.go new file mode 100644 index 000000000..a5e2beee7 --- /dev/null +++ b/project_euler/problem_17/problem17.go @@ -0,0 +1,31 @@ +/** +* Problem 17 - Number letter counts +* @see {@link https://projecteuler.net/problem=17} +* +* If the numbers 1 to 5 are written out in words: one, two, three, four, five, +* then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. +* +* If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, +* how many letters would be used? +* +* NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) +* contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. +* The use of "and" when writing out numbers is in compliance with British usage. +* +* @author ddaniel27 + */ +package problem17 + +import "strings" + +func Problem17(input string) int { + var sum int + + parsed := strings.Split(input, " ") + + for _, word := range parsed { + sum += len(word) + } + + return sum +} diff --git a/project_euler/problem_17/problem17_test.go b/project_euler/problem_17/problem17_test.go new file mode 100644 index 000000000..13cf68bf4 --- /dev/null +++ b/project_euler/problem_17/problem17_test.go @@ -0,0 +1,30 @@ +package problem17 + +import "testing" + +// Tests +func TestProblem17_Func(t *testing.T) { + tests := []struct { + name string + input string + want int + }{ + {"1 to 5", "one two three four five", 19}, + {"1 to 1000", INPUT, 21124}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Problem17(tt.input); got != tt.want { + t.Errorf("Problem17() = %v, want %v", got, tt.want) + } + }) + } +} + +// Benchmark +func BenchmarkProblem17_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem17(INPUT) + } +} diff --git a/project_euler/problem_18/edge.go b/project_euler/problem_18/edge.go new file mode 100644 index 000000000..90f44b082 --- /dev/null +++ b/project_euler/problem_18/edge.go @@ -0,0 +1,100 @@ +package problem18 + +type Edge struct { + ID int + NodeValue NodeValue + NodeLeft Node + NodeRight Node + Parent Node +} + +func (n *Edge) Value() NodeValue { + return n.NodeValue +} + +func (n *Edge) Left() Node { + return n.NodeLeft +} + +func (n *Edge) Right() Node { + return n.NodeRight +} + +func (n *Edge) Kind() string { + return "edge" +} + +func (n *Edge) CreateChild(value NodeValue, id int) Node { + // When the left child is nil, it's a left edge + if n.NodeLeft == nil { + return &Edge{ + ID: id, + NodeValue: value, + Parent: n, + NodeLeft: nil, + NodeRight: nil, + } + } + + // When the left child is a leaf, it's a right edge + if n.NodeLeft.Kind() == "leaf" { + return &Edge{ + ID: id, + NodeValue: value, + Parent: n, + NodeLeft: nil, + NodeRight: nil, + } + } + + return &Leaf{ + ID: id, + NodeValue: value, + Parent: n, + NodeLeft: nil, + NodeRight: nil, + } +} + +func (n *Edge) GetID() int { + return n.ID +} + +func (n *Edge) Insert(node Node) { + // If Left is nil, always simply insert the node + if n.NodeLeft == nil { + node.SetParent(n) + n.NodeLeft = node + + return + } + + // If Right is nil, insert the node + n.NodeRight = node + + // If the node to insert is an edge, set the parent + if node.Kind() == "edge" { + node.SetParent(n) + + return + } + + // If the node to insert is a leaf, send it to the sibling right + n.Parent.Right().Insert(node) +} + +func (n *Edge) HasSpace() bool { + return n.NodeLeft == nil || n.NodeRight == nil +} + +func (n *Edge) LeftIsNil() bool { + return n.NodeLeft == nil +} + +func (n *Edge) RightIsNil() bool { + return n.NodeRight == nil +} + +func (n *Edge) SetParent(node Node) { + n.Parent = node +} diff --git a/project_euler/problem_18/input.go b/project_euler/problem_18/input.go new file mode 100644 index 000000000..e11dcc41f --- /dev/null +++ b/project_euler/problem_18/input.go @@ -0,0 +1,42 @@ +package problem18 + +import "strings" + +const problem18_input_string = ` +75 +95 64 +17 47 82 +18 35 87 10 +20 04 82 47 65 +19 01 23 75 03 34 +88 02 77 73 07 63 67 +99 65 04 28 06 16 70 92 +41 41 26 56 83 40 80 70 33 +41 48 72 33 47 32 37 16 94 29 +53 71 44 65 25 43 91 52 97 51 14 +70 11 33 28 77 73 17 78 39 68 17 57 +91 71 52 38 17 14 91 43 58 50 27 29 48 +63 66 04 68 89 53 67 30 73 16 69 87 40 31 +04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 +` + +var problem18_input_parsed_string []string = strings.Split( + strings.Trim( + strings.ReplaceAll(problem18_input_string, "\n", " "), + " ", + ), + " ") + +const problem18_test_string = ` +3 +7 4 +2 4 6 +8 5 9 3 +` + +var problem18_test_parsed_string []string = strings.Split( + strings.Trim( + strings.ReplaceAll(problem18_test_string, "\n", " "), + " ", + ), + " ") diff --git a/project_euler/problem_18/leaf.go b/project_euler/problem_18/leaf.go new file mode 100644 index 000000000..8dd452602 --- /dev/null +++ b/project_euler/problem_18/leaf.go @@ -0,0 +1,75 @@ +package problem18 + +type Leaf struct { + ID int + NodeValue NodeValue + NodeLeft *Leaf + NodeRight *Leaf + Parent Node +} + +func (n *Leaf) Value() NodeValue { + return n.NodeValue +} + +func (n *Leaf) Left() Node { + if n.NodeLeft != nil { + n.NodeLeft.Parent = n // Leaf is the parent of its left child always + } + + return n.NodeLeft +} + +func (n *Leaf) Right() Node { + return n.NodeRight +} + +func (n *Leaf) Kind() string { + return "leaf" +} + +func (n *Leaf) CreateChild(value NodeValue, id int) Node { + // Leafs only have leaf children + return &Leaf{ + ID: id, + NodeValue: value, + Parent: n, + NodeLeft: nil, + NodeRight: nil, + } +} + +func (n *Leaf) GetID() int { + return n.ID +} + +func (n *Leaf) Insert(node Node) { + // If Left is nil, always simply insert the node + if n.NodeLeft == nil { + node.SetParent(n) + n.NodeLeft = node.(*Leaf) + + return + } + + // If Right is nil, insert the node + n.NodeRight = node.(*Leaf) + // Send it to the sibling right + n.Parent.Right().Insert(node) +} + +func (n *Leaf) HasSpace() bool { + return n.NodeLeft == nil || n.NodeRight == nil +} + +func (n *Leaf) LeftIsNil() bool { + return n.NodeLeft == nil +} + +func (n *Leaf) RightIsNil() bool { + return n.NodeRight == nil +} + +func (n *Leaf) SetParent(node Node) { + n.Parent = node +} diff --git a/project_euler/problem_18/problem18.go b/project_euler/problem_18/problem18.go new file mode 100644 index 000000000..1775c6bd0 --- /dev/null +++ b/project_euler/problem_18/problem18.go @@ -0,0 +1,63 @@ +/** +* Problem 18 - Maximum path sum I +* @see {@link https://projecteuler.net/problem=18} +* +* By starting at the top of the triangle below and +* moving to adjacent numbers on the row below, +* the maximum total from top to bottom is 23. +* +* 3 +* 7 4 +* 2 4 6 +* 8 5 9 3 +* +* That is, 3 + 7 + 4 + 9 = 23. +* +* Find the maximum total from top to bottom of the triangle below: +* [refer to the problem link] +* +* NOTE: As there are only 16384 routes, it is possible +* to solve this problem by trying every route. +* However, Problem 67, is the same challenge with a triangle +* containing one-hundred rows; it cannot be solved by brute force, +* and requires a clever method! ;o) +* +* @author ddaniel27 + */ +package problem18 + +import "strconv" + +type ( + NodeValue int + NodeType string + + Node interface { + Value() NodeValue + GetID() int + Left() Node + Right() Node + LeftIsNil() bool + RightIsNil() bool + HasSpace() bool + Kind() string + SetParent(Node) + CreateChild(NodeValue, int) Node + Insert(Node) + } +) + +func Problem18(input []string, deep int) int { + tree := &Tree{} + + for _, num := range input { + v, err := strconv.Atoi(num) + if err != nil { + panic(err) + } + + tree.BFSInsert(NodeValue(v)) + } + + return tree.MaxPathValueSearch(deep) +} diff --git a/project_euler/problem_18/problem18_test.go b/project_euler/problem_18/problem18_test.go new file mode 100644 index 000000000..50baab2ed --- /dev/null +++ b/project_euler/problem_18/problem18_test.go @@ -0,0 +1,42 @@ +package problem18 + +import "testing" + +// Tests +func TestProblem18_Func(t *testing.T) { + tests := []struct { + name string + input []string + deep int + expected int + }{ + { + name: "Test case 1", + input: problem18_test_parsed_string, + deep: 2, + expected: 23, + }, + { + name: "Test case 2", + input: problem18_input_parsed_string, + deep: 2, + expected: 1074, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + actual := Problem18(test.input, test.deep) + if actual != test.expected { + t.Errorf("Expected %d, but got %d", test.expected, actual) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem18_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem18(problem18_input_parsed_string, 2) + } +} diff --git a/project_euler/problem_18/root.go b/project_euler/problem_18/root.go new file mode 100644 index 000000000..4ee018629 --- /dev/null +++ b/project_euler/problem_18/root.go @@ -0,0 +1,62 @@ +package problem18 + +type Root struct { + ID int + NodeValue NodeValue + NodeLeft *Edge + NodeRight *Edge +} + +func (n *Root) Value() NodeValue { + return n.NodeValue +} + +func (n *Root) Left() Node { + return n.NodeLeft +} + +func (n *Root) Right() Node { + return n.NodeRight +} + +func (n *Root) Kind() string { + return "root" +} + +func (n *Root) CreateChild(value NodeValue, id int) Node { + return &Edge{ + ID: id, + NodeValue: value, + Parent: n, + NodeLeft: nil, + NodeRight: nil, + } +} + +func (n *Root) GetID() int { + return n.ID +} + +func (n *Root) Insert(node Node) { + if n.NodeLeft == nil { + n.NodeLeft = node.(*Edge) + } else { + n.NodeRight = node.(*Edge) + } +} + +func (n *Root) HasSpace() bool { + return n.NodeLeft == nil || n.NodeRight == nil +} + +func (n *Root) LeftIsNil() bool { + return n.NodeLeft == nil +} + +func (n *Root) RightIsNil() bool { + return n.NodeRight == nil +} + +func (n *Root) SetParent(node Node) { + panic("Root node cannot have a parent") +} diff --git a/project_euler/problem_18/tree.go b/project_euler/problem_18/tree.go new file mode 100644 index 000000000..6f98f3b1c --- /dev/null +++ b/project_euler/problem_18/tree.go @@ -0,0 +1,229 @@ +package problem18 + +import ( + "fmt" + "strings" +) + +type Tree struct { + Root *Root + Nodes map[int]struct{} + ID int +} + +func (t *Tree) BFSInsert(value NodeValue) { + t.Nodes = make(map[int]struct{}) // Reset the nodes map + + if t.Root == nil { + t.Root = &Root{NodeValue: value, ID: 0} + t.ID = 1 + return + } + + queue := make([]Node, 0) + queue = append(queue, t.Root) + t.isInQueue(t.Root.GetID()) + + head := 0 + + for head < len(queue) { + current := queue[head] + head++ + childNode := current.CreateChild(value, t.ID) + + if current.HasSpace() { + current.Insert(childNode) + t.ID++ + return + } + + if !t.isInQueue(current.Left().GetID()) { // Avoid duplicates + queue = append(queue, current.Left()) + } + if !t.isInQueue(current.Right().GetID()) { + queue = append(queue, current.Right()) + } + } +} + +// MaxPathValueSearch is a method that searches the maximum path value in a tree +// given a certain depth +func (r *Tree) MaxPathValueSearch(deep int) int { + if r.Root == nil { + return 0 + } + + type DFSNode struct { + Node Node + StepsLeft int + Sum int + } + + var pivot Node = r.Root + pivotEnded := false + maxPathValue := int(pivot.Value()) + + stack := make([]DFSNode, 0) + + for !pivotEnded { + stack = append(stack, DFSNode{Node: pivot, StepsLeft: deep, Sum: maxPathValue}) + + for len(stack) > 0 { + current := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + // If we run out of steps, we check the sum of the path, + // update the maxPathValue if necessary and continue + if current.StepsLeft == 0 { + if current.Sum > maxPathValue { + maxPathValue = current.Sum + pivot = current.Node + } + continue + } + + if !current.Node.RightIsNil() { + stack = append(stack, DFSNode{ + Node: current.Node.Right(), + StepsLeft: current.StepsLeft - 1, + Sum: current.Sum + int(current.Node.Right().Value()), + }) + } + + // If the left child is nil, we have reached the end of the path + if !current.Node.LeftIsNil() { + stack = append(stack, DFSNode{ + Node: current.Node.Left(), + StepsLeft: current.StepsLeft - 1, + Sum: current.Sum + int(current.Node.Left().Value()), + }) + } else { + if current.Sum > maxPathValue { + maxPathValue = current.Sum + pivot = current.Node + } + } + } + + // If we don't have reached the end of the left side of the tree, + // we continue with the search using the pivot node + // We use the left child only because how the tree is built + if pivot.LeftIsNil() { + pivotEnded = true + } + } + + return maxPathValue +} + +// PrintReport is a method that prints a report of the tree +// Node by node +func (t *Tree) PrintReport() { + t.Nodes = make(map[int]struct{}) + if t.Root == nil { + return + } + + queue := make([]Node, 0) + queue = append(queue, t.Root) + + head := 0 + + for head < len(queue) { + current := queue[head] + head++ + + print("ID:", current.GetID()) + print(", Current node:", current.Value()) + + if !current.LeftIsNil() { + print(", Left Child:", current.Left().Value()) + + if !t.isInQueue(current.Left().GetID()) { + queue = append(queue, current.Left()) + } + } + + if !current.RightIsNil() { + print(", Right Child:", current.Right().Value()) + + if !t.isInQueue(current.Right().GetID()) { + queue = append(queue, current.Right()) + } + } + + println() + } +} + +// PrintPyramid is a method that prints the tree as a pyramid +func (t *Tree) PrintPyramid() { + t.Nodes = make(map[int]struct{}) + if t.Root == nil { + return + } + + queue := []Node{t.Root} + levels := []int{0} + outputByLevel := []string{} + + head := 0 + currentLevel := 0 + + output := "" + + for head < len(queue) { + current := queue[head] + level := levels[head] + head++ + + // Level change + if level > currentLevel { + currentLevel = level + outputByLevel = append(outputByLevel, output+"\n") + output = "" + } + + // Add current node to the output + if current.Value() < 10 { + output += fmt.Sprintf("0%d ", current.Value()) + } else { + output += fmt.Sprintf("%d ", current.Value()) + } + + // Add children to the queue + if !current.LeftIsNil() { + if !t.isInQueue(current.Left().GetID()) { + queue = append(queue, current.Left()) + levels = append(levels, level+1) + } + } + + if !current.RightIsNil() { + if !t.isInQueue(current.Right().GetID()) { + queue = append(queue, current.Right()) + levels = append(levels, level+1) + } + } + } + // Add the last level + outputByLevel = append(outputByLevel, output+"\n") + + totalLevels := len(outputByLevel) + + // Print the pyramid + for i, level := range outputByLevel { + str := strings.Repeat(" ", 2*(totalLevels-i)) + level + print(str) + } +} + +// isInQueue is a method that avoids duplicates in the tree +func (n *Tree) isInQueue(nv int) bool { + if _, ok := n.Nodes[nv]; ok { + return true + } + + n.Nodes[nv] = struct{}{} + return false +} diff --git a/project_euler/problem_19/problem19.go b/project_euler/problem_19/problem19.go new file mode 100644 index 000000000..9a86f0dea --- /dev/null +++ b/project_euler/problem_19/problem19.go @@ -0,0 +1,63 @@ +package problem19 + +/** +* Problem 19 - Counting Sundays +* @see {@link https://projecteuler.net/problem=19} +* +* You are given the following information, +* but you may prefer to do some research for yourself. +* +* 1 Jan 1900 was a Monday. +* Thirty days has September, +* April, June and November. +* All the rest have thirty-one, +* Saving February alone, +* Which has twenty-eight, rain or shine. +* And on leap years, twenty-nine. +* A leap year occurs on any year evenly divisible by 4, +* but not on a century unless it is divisible by 400. +* +* How many Sundays fell on the first of the month during +* the twentieth century (1 Jan 1901 to 31 Dec 2000)? +* +* @author ddaniel27 + */ + +func Problem19() int { + count := 0 + dayOfWeek := 2 // 1 Jan 1901 was a Tuesday + + for year := 1901; year <= 2000; year++ { + for month := 1; month <= 12; month++ { + if dayOfWeek == 0 { + count++ + } + + daysInMonth := 31 + switch month { + case 4, 6, 9, 11: + daysInMonth = 30 + case 2: + if IsLeapYear(year) { + daysInMonth = 29 + } else { + daysInMonth = 28 + } + } + + dayOfWeek = (dayOfWeek + daysInMonth) % 7 + } + } + + return count +} + +func IsLeapYear(year int) bool { + if year%4 == 0 { + if year%100 == 0 { + return year%400 == 0 + } + return true + } + return false +} diff --git a/project_euler/problem_19/problem19_test.go b/project_euler/problem_19/problem19_test.go new file mode 100644 index 000000000..d26c10938 --- /dev/null +++ b/project_euler/problem_19/problem19_test.go @@ -0,0 +1,29 @@ +package problem19 + +import "testing" + +// Tests +func TestProblem19_Func(t *testing.T) { + tests := []struct { + name string + expected int + }{ + {"Problem 19 - Counting Sundays", 171}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Problem19() + if got != test.expected { + t.Errorf("Problem19() = got %v, want %v", got, test.expected) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem19_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem19() + } +} diff --git a/project_euler/problem_2/problem2.go b/project_euler/problem_2/problem2.go new file mode 100644 index 000000000..e8eaeb85e --- /dev/null +++ b/project_euler/problem_2/problem2.go @@ -0,0 +1,30 @@ +/** +* Problem 2 - Even Fibonacci numbers +* @see {@link https://projecteuler.net/problem=2} +* +* Each new term in the Fibonacci sequence is generated by adding the previous two terms. +* By starting with 1 and 2, the first 10 terms will be: +* +* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... +* +* By considering the terms in the Fibonacci sequence whose values do not exceed four million, +* find the sum of the even-valued terms. +* +* @author ddaniel27 + */ +package problem2 + +func Problem2(n uint) uint { + sum := uint(0) + a, b := uint(1), uint(2) + + for b < n { + if b%2 == 0 { + sum += b + } + + a, b = b, a+b + } + + return sum +} diff --git a/project_euler/problem_2/problem2_test.go b/project_euler/problem_2/problem2_test.go new file mode 100644 index 000000000..32c3834c6 --- /dev/null +++ b/project_euler/problem_2/problem2_test.go @@ -0,0 +1,45 @@ +package problem2 + +import "testing" + +// Tests +func TestProblem2_Func(t *testing.T) { + tests := []struct { + name string + input uint + want uint + }{ + { + name: "Testcase 1 - input 10", + input: 10, + want: 10, + }, + { + name: "Testcase 2 - input 100", + input: 100, + want: 44, + }, + { + name: "Testcase 3 - input 4e6", + input: 4e6, + want: 4613732, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem2(tt.input) + + if n != tt.want { + t.Errorf("Problem2() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem2(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem2(4e6) + } +} diff --git a/project_euler/problem_20/problem20.go b/project_euler/problem_20/problem20.go new file mode 100644 index 000000000..fc731da6b --- /dev/null +++ b/project_euler/problem_20/problem20.go @@ -0,0 +1,37 @@ +/** +* Problem 20 - Factorial digit sum +* @see {@link https://projecteuler.net/problem=20} +* +* n! means n × (n − 1) × ... × 3 × 2 × 1 +* +* For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, +* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. +* +* Find the sum of the digits in the number 100! +* +* @author ddaniel27 + */ +package problem20 + +import "math/big" + +func Problem20(input int) int { + factorial := bigFactorial(input) + sum := 0 + for _, digit := range factorial.String() { + sum += int(digit - '0') + } + return sum +} + +// bigFactorial returns the factorial of n as a big.Int +// Use big package to handle large numbers +func bigFactorial(n int) *big.Int { + if n < 0 { + return big.NewInt(0) + } + if n == 0 { + return big.NewInt(1) + } + return big.NewInt(0).Mul(big.NewInt(int64(n)), bigFactorial(n-1)) +} diff --git a/project_euler/problem_20/problem20_test.go b/project_euler/problem_20/problem20_test.go new file mode 100644 index 000000000..f1ac574c6 --- /dev/null +++ b/project_euler/problem_20/problem20_test.go @@ -0,0 +1,31 @@ +package problem20 + +import "testing" + +// Tests +func TestProblem20_Func(t *testing.T) { + tests := []struct { + name string + input int + expected int + }{ + {"Problem 20 - Factorial digit sum", 10, 27}, + {"Problem 20 - Factorial digit sum", 100, 648}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Problem20(test.input) + if got != test.expected { + t.Errorf("Problem20() = got %v, want %v", got, test.expected) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem20_Func(b *testing.B) { + for i := 0; i < b.N; i++ { + Problem20(100) + } +} diff --git a/project_euler/problem_3/problem3.go b/project_euler/problem_3/problem3.go new file mode 100644 index 000000000..f13525fb6 --- /dev/null +++ b/project_euler/problem_3/problem3.go @@ -0,0 +1,24 @@ +/** +* Problem 3 - Largest prime factor +* @see {@link https://projecteuler.net/problem=3} +* +* The prime factors of 13195 are 5, 7, 13 and 29. +* What is the largest prime factor of the number 600851475143 ? +* +* @author ddaniel27 + */ +package problem3 + +func Problem3(n uint) uint { + i := uint(2) + + for n > 1 { + if n%i == 0 { + n /= i + } else { + i++ + } + } + + return i +} diff --git a/project_euler/problem_3/problem3_test.go b/project_euler/problem_3/problem3_test.go new file mode 100644 index 000000000..d00379f8e --- /dev/null +++ b/project_euler/problem_3/problem3_test.go @@ -0,0 +1,40 @@ +package problem3 + +import "testing" + +// Tests +func TestProblem3_Func(t *testing.T) { + tests := []struct { + name string + input uint + want uint + }{ + { + name: "Testcase 1 - input 13195", + input: 13195, + want: 29, + }, + { + name: "Testcase 2 - input 600851475143", + input: 600851475143, + want: 6857, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem3(tt.input) + + if n != tt.want { + t.Errorf("Problem3() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem3(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem3(600851475143) + } +} diff --git a/project_euler/problem_4/problem4.go b/project_euler/problem_4/problem4.go new file mode 100644 index 000000000..b48d81e41 --- /dev/null +++ b/project_euler/problem_4/problem4.go @@ -0,0 +1,33 @@ +/** +* Problem 4 - Largest palindrome product +* @see {@link https://projecteuler.net/problem=4} +* +* A palindromic number reads the same both ways. +* The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. +* Find the largest palindrome made from the product of two 3-digit numbers. +* +* @author ddaniel27 + */ +package problem4 + +import ( + "fmt" + + "github.com/TheAlgorithms/Go/strings/palindrome" +) + +func Problem4() uint { + max := uint(0) + + for i := 999; i >= 100; i-- { + for j := 999; j >= 100; j-- { + n := uint(i * j) + + if palindrome.IsPalindrome(fmt.Sprintf("%d", n)) && n > max { + max = n + } + } + } + + return max +} diff --git a/project_euler/problem_4/problem4_test.go b/project_euler/problem_4/problem4_test.go new file mode 100644 index 000000000..6b91fd2b0 --- /dev/null +++ b/project_euler/problem_4/problem4_test.go @@ -0,0 +1,33 @@ +package problem4 + +import "testing" + +// Tests +func TestProblem4_Func(t *testing.T) { + tests := []struct { + name string + want uint + }{ + { + name: "Testcase 1", + want: 906609, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem4() + + if n != tt.want { + t.Errorf("Problem4() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem4(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem4() + } +} diff --git a/project_euler/problem_5/problem5.go b/project_euler/problem_5/problem5.go new file mode 100644 index 000000000..dad415738 --- /dev/null +++ b/project_euler/problem_5/problem5.go @@ -0,0 +1,33 @@ +/** +* Problem 5 - Smallest multiple +* @see {@link https://projecteuler.net/problem=5} +* +* 2520 is the smallest number that can be divided by +* each of the numbers from 1 to 10 without any remainder. +* What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? +* +* @author ddaniel27 + */ +package problem5 + +func Problem5(limit uint) uint { + n := limit * limit + + for { + if isDivisible(n, limit) { + return n + } + + n++ + } +} + +func isDivisible(n, limit uint) bool { + for i := uint(1); i <= limit; i++ { + if n%i != 0 { + return false + } + } + + return true +} diff --git a/project_euler/problem_5/problem5_test.go b/project_euler/problem_5/problem5_test.go new file mode 100644 index 000000000..43e7d8ec9 --- /dev/null +++ b/project_euler/problem_5/problem5_test.go @@ -0,0 +1,45 @@ +package problem5 + +import "testing" + +// Tests +func TestProblem5_Func(t *testing.T) { + tests := []struct { + name string + input uint + want uint + }{ + { + name: "Testcase 1 - input 10", + input: 10, + want: 2520, + }, + { + name: "Testcase 2 - input 20", + input: 20, + want: 232792560, + }, + { + name: "Testcase 3 - input 5", + input: 5, + want: 60, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem5(tt.input) + + if n != tt.want { + t.Errorf("Problem5() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem5(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem5(20) + } +} diff --git a/project_euler/problem_6/problem6.go b/project_euler/problem_6/problem6.go new file mode 100644 index 000000000..83287b87d --- /dev/null +++ b/project_euler/problem_6/problem6.go @@ -0,0 +1,33 @@ +/** +* Problem 6 - Sum square difference +* @see {@link https://projecteuler.net/problem=6} +* +* The sum of the squares of the first ten natural numbers is, +* 1^2 + 2^2 + ... + 10^2 = 385 +* +* The square of the sum of the first ten natural numbers is, +* (1 + 2 + ... + 10)^2 = 55^2 = 3025 +* +* Hence the difference between the sum of the squares of the first ten natural numbers +* and the square of the sum is 3025 − 385 = 2640. +* +* Find the difference between the sum of the squares of the first one hundred natural numbers +* and the square of the sum. +* +* @author ddaniel27 + */ +package problem6 + +func Problem6(n uint) uint { + sumOfSquares := uint(0) + squareOfSum := uint(0) + + for i := uint(1); i <= n; i++ { + sumOfSquares += i * i + squareOfSum += i + } + + squareOfSum *= squareOfSum + + return squareOfSum - sumOfSquares +} diff --git a/project_euler/problem_6/problem6_test.go b/project_euler/problem_6/problem6_test.go new file mode 100644 index 000000000..afa4e5fb7 --- /dev/null +++ b/project_euler/problem_6/problem6_test.go @@ -0,0 +1,40 @@ +package problem6 + +import "testing" + +// Tests +func TestProblem6_Func(t *testing.T) { + tests := []struct { + name string + input uint + want uint + }{ + { + name: "Testcase 1 - input 10", + input: 10, + want: 2640, + }, + { + name: "Testcase 2 - input 100", + input: 100, + want: 25164150, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem6(tt.input) + + if n != tt.want { + t.Errorf("Problem6() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem6(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem6(100) + } +} diff --git a/project_euler/problem_7/problem7.go b/project_euler/problem_7/problem7.go new file mode 100644 index 000000000..481844fed --- /dev/null +++ b/project_euler/problem_7/problem7.go @@ -0,0 +1,27 @@ +/** +* Problem 7 - 10001st prime +* @see {@link https://projecteuler.net/problem=7} +* +* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, +* we can see that the 6th prime is 13. +* +* What is the 10 001st prime number? +* +* @author ddaniel27 + */ +package problem7 + +import "github.com/TheAlgorithms/Go/math/prime" + +func Problem7(n uint) int64 { + count, i := uint(0), int64(1) + + for count < n { + i++ + if prime.OptimizedTrialDivision(i) { + count++ + } + } + + return i +} diff --git a/project_euler/problem_7/problem7_test.go b/project_euler/problem_7/problem7_test.go new file mode 100644 index 000000000..d2ab03e74 --- /dev/null +++ b/project_euler/problem_7/problem7_test.go @@ -0,0 +1,40 @@ +package problem7 + +import "testing" + +// Tests +func TestProblem7_Func(t *testing.T) { + tests := []struct { + name string + input uint + want int64 + }{ + { + name: "Testcase 1 - input 6", + input: 6, + want: 13, + }, + { + name: "Testcase 2 - input 10001", + input: 10001, + want: 104743, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem7(tt.input) + + if n != tt.want { + t.Errorf("Problem7() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem7(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem7(10001) + } +} diff --git a/project_euler/problem_8/problem8.go b/project_euler/problem_8/problem8.go new file mode 100644 index 000000000..0c800dcdb --- /dev/null +++ b/project_euler/problem_8/problem8.go @@ -0,0 +1,33 @@ +/** +* Problem 8 - Largest product in a series +* @see {@link https://projecteuler.net/problem=8} +* +* The four adjacent digits in the 1000-digit number that +* have the greatest product are 9 × 9 × 8 × 9 = 5832. +* Find the thirteen adjacent digits in the 1000-digit number +* that have the greatest product. What is the value of this product? +* +* @author ddaniel27 + */ +package problem8 + +const number = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450" + +func Problem8(window int) uint { + max := uint(0) + + for i := 0; i < len(number)-window; i++ { + product := uint(1) + + for j := 0; j < window; j++ { + n := uint(number[i+j] - '0') + product *= n + } + + if product > max { + max = product + } + } + + return max +} diff --git a/project_euler/problem_8/problem8_test.go b/project_euler/problem_8/problem8_test.go new file mode 100644 index 000000000..eecde4bc6 --- /dev/null +++ b/project_euler/problem_8/problem8_test.go @@ -0,0 +1,40 @@ +package problem8 + +import "testing" + +// Tests +func TestProblem8_Func(t *testing.T) { + tests := []struct { + name string + input int + want uint + }{ + { + name: "Testcase 1 - input 4", + input: 4, + want: 5832, + }, + { + name: "Testcase 2 - input 13", + input: 13, + want: 23514624000, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem8(tt.input) + + if n != tt.want { + t.Errorf("Problem8() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem8(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem8(13) + } +} diff --git a/project_euler/problem_9/problem9.go b/project_euler/problem_9/problem9.go new file mode 100644 index 000000000..0f784c022 --- /dev/null +++ b/project_euler/problem_9/problem9.go @@ -0,0 +1,29 @@ +/** +* Problem 9 - Special Pythagorean triplet +* @see {@link https://projecteuler.net/problem=9} +* +* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, +* a^2 + b^2 = c^2 +* +* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. +* +* There exists exactly one Pythagorean triplet for which a + b + c = 1000. +* Find the product abc. +* +* @author ddaniel27 + */ +package problem9 + +func Problem9() uint { + for a := uint(1); a < 1000; a++ { + for b := a + 1; b < 1000; b++ { + c := 1000 - a - b + + if a*a+b*b == c*c { + return a * b * c + } + } + } + + return 0 +} diff --git a/project_euler/problem_9/problem9_test.go b/project_euler/problem_9/problem9_test.go new file mode 100644 index 000000000..d75226103 --- /dev/null +++ b/project_euler/problem_9/problem9_test.go @@ -0,0 +1,33 @@ +package problem9 + +import "testing" + +// Tests +func TestProblem9_Func(t *testing.T) { + tests := []struct { + name string + want uint + }{ + { + name: "Testcase 1", + want: 31875000, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := Problem9() + + if n != tt.want { + t.Errorf("Problem9() = %v, want %v", n, tt.want) + } + }) + } +} + +// Benchmarks +func BenchmarkProblem9(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = Problem9() + } +} From e8cbbce8349a730ec1d94ff32a77ad3d975b3bdd Mon Sep 17 00:00:00 2001 From: Sublics <142167785+lyqio@users.noreply.github.com> Date: Sun, 12 Jan 2025 09:50:44 +0000 Subject: [PATCH 201/202] add stooge sort (#774) --- sort/sorts_test.go | 8 ++++++++ sort/stooge_sort.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 sort/stooge_sort.go diff --git a/sort/sorts_test.go b/sort/sorts_test.go index a04f19eb0..f2394c334 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -198,6 +198,10 @@ func TestOddEvenSort(t *testing.T) { testFramework(t, sort.OddEvenSort[int]) } +func TestStooge(t *testing.T) { + testFramework(t, sort.Stooge[int]) +} + // END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -340,3 +344,7 @@ func BenchmarkTimsort(b *testing.B) { func BenchmarkCircle(b *testing.B) { benchmarkFramework(b, sort.Circle[int]) } + +func BenchmarkStooge(b *testing.B) { + benchmarkFramework(b, sort.Stooge[int]) +} diff --git a/sort/stooge_sort.go b/sort/stooge_sort.go new file mode 100644 index 000000000..45d2206c4 --- /dev/null +++ b/sort/stooge_sort.go @@ -0,0 +1,34 @@ +// implementation of the Stooge sort +// more info at https://en.wikipedia.org/wiki/Stooge_sort +// worst-case time complexity O(n^2.709511) +// worst-case space complexity O(n) + +package sort + +import ( + "github.com/TheAlgorithms/Go/constraints" + + // math imported for floor division + "math" +) + +func innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T { + if arr[i] > arr[j] { + arr[i], arr[j] = arr[j], arr[i] + } + if (j - i + 1) > 2 { + t := int32(math.Floor(float64(j-i+1) / 3.0)) + arr = innerStooge(arr, i, j-t) + arr = innerStooge(arr, i+t, j) + arr = innerStooge(arr, i, j-t) + } + return arr +} + +func Stooge[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { + return arr + } + + return innerStooge(arr, 0, int32(len(arr)-1)) +} From 5ba447ec5ff3d1213de65b92e726ee74c5d5cc19 Mon Sep 17 00:00:00 2001 From: Ganesh Manchi <62894745+ganeshvenkatasai@users.noreply.github.com> Date: Thu, 23 Jan 2025 21:21:13 +0530 Subject: [PATCH 202/202] Add Dynamic Programming Algorithms (#776) * Add dynamic programming problem implementations and their tests * Fix bugs and improve test cases for dynamic programming algorithms * Fix linters * Modify Dice Throw Test Function Name --- dynamic/burstballoons.go | 31 ++++++++++ dynamic/burstballoons_test.go | 33 +++++++++++ dynamic/dicethrow.go | 33 +++++++++++ dynamic/dicethrow_test.go | 42 ++++++++++++++ dynamic/eggdropping.go | 47 +++++++++++++++ dynamic/eggdropping_test.go | 35 +++++++++++ dynamic/interleavingstrings.go | 36 ++++++++++++ dynamic/interleavingstrings_test.go | 38 ++++++++++++ dynamic/longestarithmeticsubsequence.go | 34 +++++++++++ dynamic/longestarithmeticsubsequence_test.go | 38 ++++++++++++ dynamic/longestpalindromicsubstring.go | 43 ++++++++++++++ dynamic/longestpalindromicsubstring_test.go | 37 ++++++++++++ dynamic/maxsubarraysum.go | 22 +++++++ dynamic/maxsubarraysum_test.go | 37 ++++++++++++ dynamic/optimalbst.go | 61 ++++++++++++++++++++ dynamic/optimalbst_test.go | 35 +++++++++++ dynamic/partitionproblem.go | 30 ++++++++++ dynamic/partitionproblem_test.go | 39 +++++++++++++ dynamic/tilingproblem.go | 22 +++++++ dynamic/tilingproblem_test.go | 38 ++++++++++++ dynamic/wildcardmatching.go | 33 +++++++++++ dynamic/wildcardmatching_test.go | 44 ++++++++++++++ dynamic/wordbreak.go | 28 +++++++++ dynamic/wordbreak_test.go | 40 +++++++++++++ 24 files changed, 876 insertions(+) create mode 100644 dynamic/burstballoons.go create mode 100644 dynamic/burstballoons_test.go create mode 100644 dynamic/dicethrow.go create mode 100644 dynamic/dicethrow_test.go create mode 100644 dynamic/eggdropping.go create mode 100644 dynamic/eggdropping_test.go create mode 100644 dynamic/interleavingstrings.go create mode 100644 dynamic/interleavingstrings_test.go create mode 100644 dynamic/longestarithmeticsubsequence.go create mode 100644 dynamic/longestarithmeticsubsequence_test.go create mode 100644 dynamic/longestpalindromicsubstring.go create mode 100644 dynamic/longestpalindromicsubstring_test.go create mode 100644 dynamic/maxsubarraysum.go create mode 100644 dynamic/maxsubarraysum_test.go create mode 100644 dynamic/optimalbst.go create mode 100644 dynamic/optimalbst_test.go create mode 100644 dynamic/partitionproblem.go create mode 100644 dynamic/partitionproblem_test.go create mode 100644 dynamic/tilingproblem.go create mode 100644 dynamic/tilingproblem_test.go create mode 100644 dynamic/wildcardmatching.go create mode 100644 dynamic/wildcardmatching_test.go create mode 100644 dynamic/wordbreak.go create mode 100644 dynamic/wordbreak_test.go diff --git a/dynamic/burstballoons.go b/dynamic/burstballoons.go new file mode 100644 index 000000000..492b00d8c --- /dev/null +++ b/dynamic/burstballoons.go @@ -0,0 +1,31 @@ +package dynamic + +import "github.com/TheAlgorithms/Go/math/max" + +// MaxCoins returns the maximum coins we can collect by bursting the balloons +func MaxCoins(nums []int) int { + n := len(nums) + if n == 0 { + return 0 + } + + nums = append([]int{1}, nums...) + nums = append(nums, 1) + + dp := make([][]int, n+2) + for i := range dp { + dp[i] = make([]int, n+2) + } + + for length := 1; length <= n; length++ { + for left := 1; left+length-1 <= n; left++ { + right := left + length - 1 + for k := left; k <= right; k++ { + coins := nums[left-1] * nums[k] * nums[right+1] + dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins) + } + } + } + + return dp[1][n] +} diff --git a/dynamic/burstballoons_test.go b/dynamic/burstballoons_test.go new file mode 100644 index 000000000..c36e08824 --- /dev/null +++ b/dynamic/burstballoons_test.go @@ -0,0 +1,33 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseBurstBalloons struct { + nums []int + expected int +} + +func getBurstBalloonsTestCases() []testCaseBurstBalloons { + return []testCaseBurstBalloons{ + {[]int{3, 1, 5, 8}, 167}, // Maximum coins from [3,1,5,8] + {[]int{1, 5}, 10}, // Maximum coins from [1,5] + {[]int{1}, 1}, // Single balloon + {[]int{}, 0}, // No balloons + } + +} + +func TestMaxCoins(t *testing.T) { + t.Run("Burst Balloons test cases", func(t *testing.T) { + for _, tc := range getBurstBalloonsTestCases() { + actual := dynamic.MaxCoins(tc.nums) + if actual != tc.expected { + t.Errorf("MaxCoins(%v) = %d; expected %d", tc.nums, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/dicethrow.go b/dynamic/dicethrow.go new file mode 100644 index 000000000..69711ca14 --- /dev/null +++ b/dynamic/dicethrow.go @@ -0,0 +1,33 @@ +// dicethrow.go +// description: Solves the Dice Throw Problem using dynamic programming +// reference: https://www.geeksforgeeks.org/dice-throw-problem/ +// time complexity: O(m * n) +// space complexity: O(m * n) + +package dynamic + +// DiceThrow returns the number of ways to get sum `sum` using `m` dice with `n` faces +func DiceThrow(m, n, sum int) int { + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, sum+1) + } + + for i := 1; i <= n; i++ { + if i <= sum { + dp[1][i] = 1 + } + } + + for i := 2; i <= m; i++ { + for j := 1; j <= sum; j++ { + for k := 1; k <= n; k++ { + if j-k >= 0 { + dp[i][j] += dp[i-1][j-k] + } + } + } + } + + return dp[m][sum] +} diff --git a/dynamic/dicethrow_test.go b/dynamic/dicethrow_test.go new file mode 100644 index 000000000..dad25e533 --- /dev/null +++ b/dynamic/dicethrow_test.go @@ -0,0 +1,42 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseDiceThrow struct { + numDice int + numFaces int + targetSum int + expected int +} + +// getDiceThrowTestCases provides the test cases for DiceThrow +func getDiceThrowTestCases() []testCaseDiceThrow { + return []testCaseDiceThrow{ + {2, 6, 7, 6}, // Two dice, six faces each, sum = 7 + {1, 6, 3, 1}, // One die, six faces, sum = 3 + {3, 4, 5, 6}, // Three dice, four faces each, sum = 5 + {1, 6, 1, 1}, // One die, six faces, sum = 1 + {2, 6, 12, 1}, // Two dice, six faces each, sum = 12 + {3, 6, 18, 1}, // Three dice, six faces each, sum = 18 + {2, 6, 20, 0}, // Two dice, six faces each, sum = 20 (impossible) + {1, 1, 1, 1}, // One die, one face, sum = 1 + {1, 1, 2, 0}, // One die, one face, sum = 2 (impossible) + {2, 1, 2, 1}, // Two dice, one face each, sum = 2 + } +} + +// TestDiceThrow tests the DiceThrow function with basic test cases +func TestDiceThrow(t *testing.T) { + t.Run("Basic test cases", func(t *testing.T) { + for _, tc := range getDiceThrowTestCases() { + actual := dynamic.DiceThrow(tc.numDice, tc.numFaces, tc.targetSum) + if actual != tc.expected { + t.Errorf("DiceThrow(%d, %d, %d) = %d; expected %d", tc.numDice, tc.numFaces, tc.targetSum, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/eggdropping.go b/dynamic/eggdropping.go new file mode 100644 index 000000000..b6d379389 --- /dev/null +++ b/dynamic/eggdropping.go @@ -0,0 +1,47 @@ +package dynamic + +import ( + "github.com/TheAlgorithms/Go/math/max" + "github.com/TheAlgorithms/Go/math/min" +) + +// EggDropping finds the minimum number of attempts needed to find the critical floor +// with `eggs` number of eggs and `floors` number of floors +func EggDropping(eggs, floors int) int { + // Edge case: If there are no floors, no attempts needed + if floors == 0 { + return 0 + } + // Edge case: If there is one floor, one attempt needed + if floors == 1 { + return 1 + } + // Edge case: If there is one egg, need to test all floors one by one + if eggs == 1 { + return floors + } + + // Initialize DP table + dp := make([][]int, eggs+1) + for i := range dp { + dp[i] = make([]int, floors+1) + } + + // Fill the DP table for 1 egg + for j := 1; j <= floors; j++ { + dp[1][j] = j + } + + // Fill the DP table for more than 1 egg + for i := 2; i <= eggs; i++ { + for j := 2; j <= floors; j++ { + dp[i][j] = int(^uint(0) >> 1) // initialize with a large number + for x := 1; x <= j; x++ { + // Recurrence relation to fill the DP table + res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1 + dp[i][j] = min.Int(dp[i][j], res) + } + } + } + return dp[eggs][floors] +} diff --git a/dynamic/eggdropping_test.go b/dynamic/eggdropping_test.go new file mode 100644 index 000000000..5e3232f70 --- /dev/null +++ b/dynamic/eggdropping_test.go @@ -0,0 +1,35 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseEggDropping struct { + eggs int + floors int + expected int +} + +func getEggDroppingTestCases() []testCaseEggDropping { + return []testCaseEggDropping{ + {1, 10, 10}, // One egg, need to test all floors + {2, 10, 4}, // Two eggs and ten floors + {3, 14, 4}, // Three eggs and fourteen floors + {2, 36, 8}, // Two eggs and thirty-six floors + {2, 0, 0}, // Two eggs, zero floors + } + +} + +func TestEggDropping(t *testing.T) { + t.Run("Egg Dropping test cases", func(t *testing.T) { + for _, tc := range getEggDroppingTestCases() { + actual := dynamic.EggDropping(tc.eggs, tc.floors) + if actual != tc.expected { + t.Errorf("EggDropping(%d, %d) = %d; expected %d", tc.eggs, tc.floors, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/interleavingstrings.go b/dynamic/interleavingstrings.go new file mode 100644 index 000000000..da13840b2 --- /dev/null +++ b/dynamic/interleavingstrings.go @@ -0,0 +1,36 @@ +// interleavingstrings.go +// description: Solves the Interleaving Strings problem using dynamic programming +// reference: https://en.wikipedia.org/wiki/Interleaving_strings +// time complexity: O(m*n) +// space complexity: O(m*n) + +package dynamic + +// IsInterleave checks if string `s1` and `s2` can be interleaved to form string `s3` +func IsInterleave(s1, s2, s3 string) bool { + if len(s1)+len(s2) != len(s3) { + return false + } + + dp := make([][]bool, len(s1)+1) + for i := range dp { + dp[i] = make([]bool, len(s2)+1) + } + + dp[0][0] = true + for i := 1; i <= len(s1); i++ { + dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1] + } + + for j := 1; j <= len(s2); j++ { + dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1] + } + + for i := 1; i <= len(s1); i++ { + for j := 1; j <= len(s2); j++ { + dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]) + } + } + + return dp[len(s1)][len(s2)] +} diff --git a/dynamic/interleavingstrings_test.go b/dynamic/interleavingstrings_test.go new file mode 100644 index 000000000..a1559e932 --- /dev/null +++ b/dynamic/interleavingstrings_test.go @@ -0,0 +1,38 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseInterleaving struct { + s1, s2, s3 string + expected bool +} + +func getInterleavingTestCases() []testCaseInterleaving { + return []testCaseInterleaving{ + {"aab", "axy", "aaxaby", true}, // Valid interleaving + {"aab", "axy", "abaaxy", false}, // Invalid interleaving + {"", "", "", true}, // All empty strings + {"abc", "", "abc", true}, // Only s1 matches s3 + {"", "xyz", "xyz", true}, // Only s2 matches s3 + {"abc", "xyz", "abxcyz", true}, // Valid interleaving + {"aaa", "aaa", "aaaaaa", true}, // Identical strings + {"aaa", "aaa", "aaaaaaa", false}, // Extra character + {"abc", "def", "abcdef", true}, // Concatenation order + {"abc", "def", "adbcef", true}, // Valid mixed interleaving + } +} + +func TestIsInterleave(t *testing.T) { + t.Run("Interleaving Strings test cases", func(t *testing.T) { + for _, tc := range getInterleavingTestCases() { + actual := dynamic.IsInterleave(tc.s1, tc.s2, tc.s3) + if actual != tc.expected { + t.Errorf("IsInterleave(%q, %q, %q) = %v; expected %v", tc.s1, tc.s2, tc.s3, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/longestarithmeticsubsequence.go b/dynamic/longestarithmeticsubsequence.go new file mode 100644 index 000000000..a187b9cea --- /dev/null +++ b/dynamic/longestarithmeticsubsequence.go @@ -0,0 +1,34 @@ +// longestarithmeticsubsequence.go +// description: Implementation of the Longest Arithmetic Subsequence problem +// reference: https://en.wikipedia.org/wiki/Longest_arithmetic_progression +// time complexity: O(n^2) +// space complexity: O(n^2) + +package dynamic + +// LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence +func LongestArithmeticSubsequence(nums []int) int { + n := len(nums) + if n <= 1 { + return n + } + + dp := make([]map[int]int, n) + for i := range dp { + dp[i] = make(map[int]int) + } + + maxLength := 1 + + for i := 1; i < n; i++ { + for j := 0; j < i; j++ { + diff := nums[i] - nums[j] + dp[i][diff] = dp[j][diff] + 1 + if dp[i][diff]+1 > maxLength { + maxLength = dp[i][diff] + 1 + } + } + } + + return maxLength +} diff --git a/dynamic/longestarithmeticsubsequence_test.go b/dynamic/longestarithmeticsubsequence_test.go new file mode 100644 index 000000000..2a971fbd7 --- /dev/null +++ b/dynamic/longestarithmeticsubsequence_test.go @@ -0,0 +1,38 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseLongestArithmeticSubsequence struct { + nums []int + expected int +} + +func getLongestArithmeticSubsequenceTestCases() []testCaseLongestArithmeticSubsequence { + return []testCaseLongestArithmeticSubsequence{ + {[]int{3, 6, 9, 12}, 4}, // Arithmetic sequence of length 4 + {[]int{9, 4, 7, 2, 10}, 3}, // Arithmetic sequence of length 3 + {[]int{20, 1, 15, 3, 10, 5, 8}, 4}, // Arithmetic sequence of length 4 + {[]int{1, 2, 3, 4, 5}, 5}, // Arithmetic sequence of length 5 + {[]int{10, 7, 4, 1}, 4}, // Arithmetic sequence of length 4 + {[]int{1, 5, 7, 8, 5, 3, 4, 3, 1, 2}, 4}, // Arithmetic sequence of length 4 + {[]int{1, 3, 5, 7, 9}, 5}, // Arithmetic sequence of length 5 + {[]int{5, 10, 15, 20}, 4}, // Arithmetic sequence of length 4 + {[]int{1}, 1}, // Single element, length is 1 + {[]int{}, 0}, // Empty array, length is 0 + } +} + +func TestLongestArithmeticSubsequence(t *testing.T) { + t.Run("Longest Arithmetic Subsequence test cases", func(t *testing.T) { + for _, tc := range getLongestArithmeticSubsequenceTestCases() { + actual := dynamic.LongestArithmeticSubsequence(tc.nums) + if actual != tc.expected { + t.Errorf("LongestArithmeticSubsequence(%v) = %v; expected %v", tc.nums, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/longestpalindromicsubstring.go b/dynamic/longestpalindromicsubstring.go new file mode 100644 index 000000000..01d105629 --- /dev/null +++ b/dynamic/longestpalindromicsubstring.go @@ -0,0 +1,43 @@ +// longestpalindromicsubstring.go +// description: Implementation of finding the longest palindromic substring +// reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring +// time complexity: O(n^2) +// space complexity: O(n^2) + +package dynamic + +// LongestPalindromicSubstring returns the longest palindromic substring in the input string +func LongestPalindromicSubstring(s string) string { + n := len(s) + if n == 0 { + return "" + } + + dp := make([][]bool, n) + for i := range dp { + dp[i] = make([]bool, n) + } + + start := 0 + maxLength := 1 + for i := 0; i < n; i++ { + dp[i][i] = true + } + + for length := 2; length <= n; length++ { + for i := 0; i < n-length+1; i++ { + j := i + length - 1 + if length == 2 { + dp[i][j] = (s[i] == s[j]) + } else { + dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1] + } + + if dp[i][j] && length > maxLength { + maxLength = length + start = i + } + } + } + return s[start : start+maxLength] +} diff --git a/dynamic/longestpalindromicsubstring_test.go b/dynamic/longestpalindromicsubstring_test.go new file mode 100644 index 000000000..e8424eabe --- /dev/null +++ b/dynamic/longestpalindromicsubstring_test.go @@ -0,0 +1,37 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseLongestPalindromicSubstring struct { + s string + expected string +} + +func getLongestPalindromicSubstringTestCases() []testCaseLongestPalindromicSubstring { + return []testCaseLongestPalindromicSubstring{ + {"babad", "bab"}, // Example with multiple palindromes + {"cbbd", "bb"}, // Example with longest even palindrome + {"a", "a"}, // Single character, palindrome is itself + {"", ""}, // Empty string, no palindrome + {"racecar", "racecar"}, // Whole string is a palindrome + {"abcba", "abcba"}, // Palindrome in the middle + {"aabbcc", "aa"}, // Multiple substrings, longest "aa" + {"madam", "madam"}, // Full palindrome string + {"forgeeksskeegfor", "geeksskeeg"}, // Complex palindrome in the middle + } +} + +func TestLongestPalindromicSubstring(t *testing.T) { + t.Run("Longest Palindromic Substring test cases", func(t *testing.T) { + for _, tc := range getLongestPalindromicSubstringTestCases() { + actual := dynamic.LongestPalindromicSubstring(tc.s) + if actual != tc.expected { + t.Errorf("LongestPalindromicSubstring(%q) = %q; expected %q", tc.s, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/maxsubarraysum.go b/dynamic/maxsubarraysum.go new file mode 100644 index 000000000..4e283e1b9 --- /dev/null +++ b/dynamic/maxsubarraysum.go @@ -0,0 +1,22 @@ +// maxsubarraysum.go +// description: Implementation of Kadane's algorithm for Maximum Subarray Sum +// reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem +// time complexity: O(n) +// space complexity: O(1) + +package dynamic + +import "github.com/TheAlgorithms/Go/math/max" + +// MaxSubArraySum returns the sum of the maximum subarray in the input array +func MaxSubArraySum(nums []int) int { + maxSum := nums[0] + currentSum := nums[0] + + for i := 1; i < len(nums); i++ { + currentSum = max.Int(nums[i], currentSum+nums[i]) + maxSum = max.Int(maxSum, currentSum) + } + + return maxSum +} diff --git a/dynamic/maxsubarraysum_test.go b/dynamic/maxsubarraysum_test.go new file mode 100644 index 000000000..20492c3f7 --- /dev/null +++ b/dynamic/maxsubarraysum_test.go @@ -0,0 +1,37 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseMaxSubArraySum struct { + nums []int + expected int +} + +func getMaxSubArraySumTestCases() []testCaseMaxSubArraySum { + return []testCaseMaxSubArraySum{ + {[]int{-2, -3, 4, -1, -2, 1, 5, -3}, 7}, // Kadane's algorithm example + {[]int{-1, -2, -3, -4}, -1}, // All negative numbers, max single element + {[]int{5, 4, -1, 7, 8}, 23}, // Positive numbers with a large sum + {[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, 6}, // Mixed with a maximum subarray of length 4 + {[]int{1, 2, 3, 4, 5}, 15}, // All positive numbers, sum is the entire array + {[]int{-1, -2, -3, -4, -5}, -1}, // Only negative numbers, largest single element + {[]int{0, 0, 0, 0, 0}, 0}, // Array of zeros, maximum subarray is zero + {[]int{3}, 3}, // Single positive number + {[]int{-1}, -1}, // Single negative number + } +} + +func TestMaxSubArraySum(t *testing.T) { + t.Run("Max SubArray Sum test cases", func(t *testing.T) { + for _, tc := range getMaxSubArraySumTestCases() { + actual := dynamic.MaxSubArraySum(tc.nums) + if actual != tc.expected { + t.Errorf("MaxSubArraySum(%v) = %v; expected %v", tc.nums, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/optimalbst.go b/dynamic/optimalbst.go new file mode 100644 index 000000000..b80f2163c --- /dev/null +++ b/dynamic/optimalbst.go @@ -0,0 +1,61 @@ +package dynamic + +import "github.com/TheAlgorithms/Go/math/min" + +// OptimalBST returns the minimum cost of constructing a Binary Search Tree +func OptimalBST(keys []int, freq []int, n int) int { + // Initialize DP table with size n x n + dp := make([][]int, n) + for i := range dp { + dp[i] = make([]int, n) + } + + // Base case: single key cost + for i := 0; i < n; i++ { + dp[i][i] = freq[i] + } + + // Build the DP table for sequences of length 2 to n + for length := 2; length <= n; length++ { + for i := 0; i < n-length+1; i++ { + j := i + length - 1 + dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value + sum := sum(freq, i, j) + + // Try every key as root and compute cost + for k := i; k <= j; k++ { + // Left cost: dp[i][k-1] is valid only if k > i + var leftCost int + if k > i { + leftCost = dp[i][k-1] + } else { + leftCost = 0 + } + + // Right cost: dp[k+1][j] is valid only if k < j + var rightCost int + if k < j { + rightCost = dp[k+1][j] + } else { + rightCost = 0 + } + + // Total cost for root k + cost := sum + leftCost + rightCost + + // Update dp[i][j] with the minimum cost + dp[i][j] = min.Int(dp[i][j], cost) + } + } + } + return dp[0][n-1] +} + +// Helper function to sum the frequencies +func sum(freq []int, i, j int) int { + total := 0 + for k := i; k <= j; k++ { + total += freq[k] + } + return total +} diff --git a/dynamic/optimalbst_test.go b/dynamic/optimalbst_test.go new file mode 100644 index 000000000..362b45449 --- /dev/null +++ b/dynamic/optimalbst_test.go @@ -0,0 +1,35 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseOptimalBST struct { + keys []int + freq []int + n int + expected int +} + +func getOptimalBSTTestCases() []testCaseOptimalBST { + return []testCaseOptimalBST{ + {[]int{10, 12, 20}, []int{34, 8, 50}, 3, 142}, // Example with 3 keys + {[]int{10, 20, 30, 40, 50}, []int{10, 20, 30, 40, 50}, 5, 300}, // Example with 5 keys + {[]int{10}, []int{100}, 1, 100}, // Single key case + } +} + +func TestOptimalBST(t *testing.T) { + t.Run("Optimal Binary Search Tree test cases", func(t *testing.T) { + for _, tc := range getOptimalBSTTestCases() { + t.Run("testing optimal BST", func(t *testing.T) { + actual := dynamic.OptimalBST(tc.keys, tc.freq, tc.n) + if actual != tc.expected { + t.Errorf("OptimalBST(%v, %v, %d) = %d; expected %d", tc.keys, tc.freq, tc.n, actual, tc.expected) + } + }) + } + }) +} diff --git a/dynamic/partitionproblem.go b/dynamic/partitionproblem.go new file mode 100644 index 000000000..bb3ca5496 --- /dev/null +++ b/dynamic/partitionproblem.go @@ -0,0 +1,30 @@ +// partitionproblem.go +// description: Solves the Partition Problem using dynamic programming +// reference: https://en.wikipedia.org/wiki/Partition_problem +// time complexity: O(n*sum) +// space complexity: O(n*sum) + +package dynamic + +// PartitionProblem checks whether the given set can be partitioned into two subsets +// such that the sum of the elements in both subsets is the same. +func PartitionProblem(nums []int) bool { + sum := 0 + for _, num := range nums { + sum += num + } + if sum%2 != 0 { + return false + } + + target := sum / 2 + dp := make([]bool, target+1) + dp[0] = true + + for _, num := range nums { + for i := target; i >= num; i-- { + dp[i] = dp[i] || dp[i-num] + } + } + return dp[target] +} diff --git a/dynamic/partitionproblem_test.go b/dynamic/partitionproblem_test.go new file mode 100644 index 000000000..c85742ecf --- /dev/null +++ b/dynamic/partitionproblem_test.go @@ -0,0 +1,39 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +// testCasePartitionProblem holds the test cases for the Partition Problem +type testCasePartitionProblem struct { + nums []int + expected bool +} + +// getPartitionProblemTestCases returns a list of test cases for the Partition Problem +func getPartitionProblemTestCases() []testCasePartitionProblem { + return []testCasePartitionProblem{ + {[]int{1, 5, 11, 5}, true}, // Example with a partitionable set + {[]int{1, 2, 3, 5}, false}, // Example where partition is not possible + {[]int{1, 2, 5}, false}, // Set cannot be partitioned into two subsets + {[]int{2, 2, 2, 2}, true}, // Even split possible with equal elements + {[]int{7, 3, 2, 1}, false}, // Set cannot be partitioned + {[]int{}, true}, // Empty set, can be partitioned trivially + {[]int{1}, false}, // Single element, cannot be partitioned + {[]int{10, 10, 10, 10}, true}, // Equal elements, partitionable + } +} + +// TestPartitionProblem tests the PartitionProblem function with different test cases +func TestPartitionProblem(t *testing.T) { + t.Run("Partition Problem test cases", func(t *testing.T) { + for _, tc := range getPartitionProblemTestCases() { + actual := dynamic.PartitionProblem(tc.nums) + if actual != tc.expected { + t.Errorf("PartitionProblem(%v) = %v; expected %v", tc.nums, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/tilingproblem.go b/dynamic/tilingproblem.go new file mode 100644 index 000000000..0407f320d --- /dev/null +++ b/dynamic/tilingproblem.go @@ -0,0 +1,22 @@ +// tilingproblem.go +// description: Solves the Tiling Problem using dynamic programming +// reference: https://en.wikipedia.org/wiki/Tiling_problem +// time complexity: O(n) +// space complexity: O(n) + +package dynamic + +// TilingProblem returns the number of ways to tile a 2xN grid using 2x1 dominoes +func TilingProblem(n int) int { + if n <= 1 { + return 1 + } + dp := make([]int, n+1) + dp[0] = 1 + dp[1] = 1 + + for i := 2; i <= n; i++ { + dp[i] = dp[i-1] + dp[i-2] + } + return dp[n] +} diff --git a/dynamic/tilingproblem_test.go b/dynamic/tilingproblem_test.go new file mode 100644 index 000000000..4f103cd21 --- /dev/null +++ b/dynamic/tilingproblem_test.go @@ -0,0 +1,38 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseTilingProblem struct { + n int + expected int +} + +func getTilingProblemTestCases() []testCaseTilingProblem { + return []testCaseTilingProblem{ + {1, 1}, // Base case: 1 way to tile a 2x1 grid + {2, 2}, // 2 ways to tile a 2x2 grid + {3, 3}, // 3 ways to tile a 2x3 grid + {4, 5}, // 5 ways to tile a 2x4 grid + {5, 8}, // 8 ways to tile a 2x5 grid + {6, 13}, // 13 ways to tile a 2x6 grid + {10, 89}, // 89 ways to tile a 2x10 grid + {0, 1}, // Edge case: 1 way to tile a 2x0 grid (no tiles) + {7, 21}, // 21 ways to tile a 2x7 grid + {8, 34}, // 34 ways to tile a 2x8 grid + } +} + +func TestTilingProblem(t *testing.T) { + t.Run("Tiling Problem test cases", func(t *testing.T) { + for _, tc := range getTilingProblemTestCases() { + actual := dynamic.TilingProblem(tc.n) + if actual != tc.expected { + t.Errorf("TilingProblem(%d) = %d; expected %d", tc.n, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/wildcardmatching.go b/dynamic/wildcardmatching.go new file mode 100644 index 000000000..26b4530af --- /dev/null +++ b/dynamic/wildcardmatching.go @@ -0,0 +1,33 @@ +// wildcardmatching.go +// description: Solves the Wildcard Matching problem using dynamic programming +// reference: https://en.wikipedia.org/wiki/Wildcard_matching +// time complexity: O(m*n) +// space complexity: O(m*n) + +package dynamic + +// IsMatch checks if the string `s` matches the wildcard pattern `p` +func IsMatch(s, p string) bool { + dp := make([][]bool, len(s)+1) + for i := range dp { + dp[i] = make([]bool, len(p)+1) + } + + dp[0][0] = true + for j := 1; j <= len(p); j++ { + if p[j-1] == '*' { + dp[0][j] = dp[0][j-1] + } + } + + for i := 1; i <= len(s); i++ { + for j := 1; j <= len(p); j++ { + if p[j-1] == s[i-1] || p[j-1] == '?' { + dp[i][j] = dp[i-1][j-1] + } else if p[j-1] == '*' { + dp[i][j] = dp[i-1][j] || dp[i][j-1] + } + } + } + return dp[len(s)][len(p)] +} diff --git a/dynamic/wildcardmatching_test.go b/dynamic/wildcardmatching_test.go new file mode 100644 index 000000000..cc6cd4fde --- /dev/null +++ b/dynamic/wildcardmatching_test.go @@ -0,0 +1,44 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +// testCaseWildcardMatching holds the test cases for the Wildcard Matching problem +type testCaseWildcardMatching struct { + s string + p string + expected bool +} + +// getWildcardMatchingTestCases returns a list of test cases for the Wildcard Matching problem +func getWildcardMatchingTestCases() []testCaseWildcardMatching { + return []testCaseWildcardMatching{ + {"aa", "a*", true}, // '*' can match zero or more characters + {"aa", "a", false}, // No match due to no wildcard + {"ab", "?*", true}, // '?' matches any single character, '*' matches remaining + {"abcd", "a*d", true}, // '*' matches the characters between 'a' and 'd' + {"abcd", "a*c", false}, // No match as 'c' doesn't match the last character 'd' + {"abc", "*", true}, // '*' matches the entire string + {"abc", "a*c", true}, // '*' matches 'b' + {"abc", "a?c", true}, // '?' matches 'b' + {"abc", "a?d", false}, // '?' cannot match 'd' + {"", "", true}, // Both strings empty, so they match + {"a", "?", true}, // '?' matches any single character + {"a", "*", true}, // '*' matches any number of characters, including one + } +} + +// TestIsMatch tests the IsMatch function with various test cases +func TestIsMatch(t *testing.T) { + t.Run("Wildcard Matching test cases", func(t *testing.T) { + for _, tc := range getWildcardMatchingTestCases() { + actual := dynamic.IsMatch(tc.s, tc.p) + if actual != tc.expected { + t.Errorf("IsMatch(%q, %q) = %v; expected %v", tc.s, tc.p, actual, tc.expected) + } + } + }) +} diff --git a/dynamic/wordbreak.go b/dynamic/wordbreak.go new file mode 100644 index 000000000..6d7ad5d58 --- /dev/null +++ b/dynamic/wordbreak.go @@ -0,0 +1,28 @@ +// wordbreak.go +// description: Solves the Word Break Problem using dynamic programming +// reference: https://en.wikipedia.org/wiki/Word_break_problem +// time complexity: O(n^2) +// space complexity: O(n) + +package dynamic + +// WordBreak checks if the input string can be segmented into words from a dictionary +func WordBreak(s string, wordDict []string) bool { + wordSet := make(map[string]bool) + for _, word := range wordDict { + wordSet[word] = true + } + + dp := make([]bool, len(s)+1) + dp[0] = true + + for i := 1; i <= len(s); i++ { + for j := 0; j < i; j++ { + if dp[j] && wordSet[s[j:i]] { + dp[i] = true + break + } + } + } + return dp[len(s)] +} diff --git a/dynamic/wordbreak_test.go b/dynamic/wordbreak_test.go new file mode 100644 index 000000000..afcf62cb6 --- /dev/null +++ b/dynamic/wordbreak_test.go @@ -0,0 +1,40 @@ +package dynamic_test + +import ( + "testing" + + "github.com/TheAlgorithms/Go/dynamic" +) + +type testCaseWordBreak struct { + s string + wordDict []string + expected bool +} + +func getWordBreakTestCases() []testCaseWordBreak { + return []testCaseWordBreak{ + {"leetcode", []string{"leet", "code"}, true}, // "leetcode" can be segmented into "leet" and "code" + {"applepenapple", []string{"apple", "pen"}, true}, // "applepenapple" can be segmented into "apple", "pen", "apple" + {"catsanddog", []string{"cats", "dog", "sand", "and", "cat"}, true}, // "catsanddog" can be segmented into "cats", "and", "dog" + {"bb", []string{"a", "b", "bbb", "aaaa", "aaa"}, true}, // "bb" can be segmented into "b" and "b" + {"", []string{"cat", "dog", "sand", "and"}, true}, // Empty string can always be segmented (empty words) + {"applepie", []string{"apple", "pie"}, true}, // "applepie" can be segmented into "apple" and "pie" + {"catsandog", []string{"cats", "dog", "sand", "and", "cat"}, false}, // "catsandog" cannot be segmented + {"ilovecoding", []string{"i", "love", "coding"}, true}, // "ilovecoding" can be segmented into "i", "love", "coding" + {"cars", []string{"car", "ca", "rs"}, true}, // "cars" can be segmented into "car" and "s" + {"pen", []string{"pen", "pencil"}, true}, // "pen" is a direct match + {"apple", []string{"orange", "banana"}, false}, // "apple" is not in the word dictionary + } +} + +func TestWordBreak(t *testing.T) { + t.Run("Word Break test cases", func(t *testing.T) { + for _, tc := range getWordBreakTestCases() { + actual := dynamic.WordBreak(tc.s, tc.wordDict) + if actual != tc.expected { + t.Errorf("WordBreak(%q, %v) = %v; expected %v", tc.s, tc.wordDict, actual, tc.expected) + } + } + }) +}