Dataset Viewer
Auto-converted to Parquet Duplicate
function_name
stringlengths
2
36
file_path
stringlengths
16
68
focal_code
stringlengths
258
11.6k
file_content
stringlengths
404
43.8k
language
stringclasses
1 value
function_component
dict
metadata
dict
IsSubsequence
Go-master/strings/issubsequence.go
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...
// 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...
go
{ "argument_definitions": [], "end_line": 34, "name": "IsSubsequence", "signature": "func IsSubsequence(s string, t string) bool", "start_line": 9 }
{ "package": "strings" }
IsIsogram
Go-master/strings/isisogram.go
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 c...
// 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/w...
go
{ "argument_definitions": [ { "definitions": [ "type IsogramOrder int" ], "name": "order", "type": "IsogramOrder" } ], "end_line": 70, "name": "IsIsogram", "signature": "func IsIsogram(text string, order IsogramOrder) (bool, error)", "start_line": 33 }
{ "package": "strings" }
GeneticString
Go-master/strings/genetic/genetic.go
func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) { populationNum := conf.PopulationNum if populationNum == 0 { populationNum = 200 } selectionNum := conf.SelectionNum if selectionNum == 0 { selectionNum = 50 } // Verify if 'populationNum' s bigger than 'selectionNum' if popul...
// Package genetic provides functions to work with strings // using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm // // Author: D4rkia package genetic import ( "errors" "fmt" "math/rand" "sort" "strconv" "time" "unicode/utf8" ) // Population item represent a single step in the evolution pr...
go
{ "argument_definitions": [ { "definitions": [ "type Conf struct {\n\t// Maximum size of the population.\n\t// Bigger could be faster but more memory expensive.\n\tPopulationNum int\n\n\t// Number of elements selected in every generation for evolution\n\t// the selection takes. Place from the best t...
{ "package": "genetic" }
Distance
Go-master/strings/levenshtein/levenshteindistance.go
func Distance(str1, str2 string, icost, scost, dcost int) int { row1 := make([]int, len(str2)+1) row2 := make([]int, len(str2)+1) for i := 1; i <= len(str2); i++ { row1[i] = i * icost } for i := 1; i <= len(str1); i++ { row2[0] = i * dcost for j := 1; j <= len(str2); j++ { if str1[i-1] == str2[j-1] { ...
/* This algorithm calculates the distance between two strings. Parameters: two strings to compare and weights of insertion, substitution and deletion. Output: distance between both strings */ package levenshtein // Distance Function that gives Levenshtein Distance func Distance(str1, str2 string, icost, scost, dcost ...
go
{ "argument_definitions": [], "end_line": 41, "name": "Distance", "signature": "func Distance(str1, str2 string, icost, scost, dcost int) int", "start_line": 9 }
{ "package": "levenshtein" }
LongestPalindrome
Go-master/strings/manacher/longestpalindrome.go
func LongestPalindrome(s string) string { boundaries := makeBoundaries(s) b := make([]int, len(boundaries)) k := 0 index := 0 maxLen := 0 maxCenterSize := 0 for i := range b { if i < k { b[i] = min.Int(b[2*index-i], k-i) } else { b[i] = 1 } for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[...
// longestpalindrome.go // description: Manacher's algorithm (Longest palindromic substring) // details: // An algorithm with linear running time that allows you to get compressed information about all palindromic substrings of a given string. - [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_s...
go
{ "argument_definitions": [], "end_line": 62, "name": "LongestPalindrome", "signature": "func LongestPalindrome(s string) string", "start_line": 36 }
{ "package": "manacher" }
horspool
Go-master/strings/horspool/horspool.go
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 matc...
// Implementation of the // [Boyer–Moore–Horspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm) package horspool 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...
go
{ "argument_definitions": [], "end_line": 36, "name": "horspool", "signature": "func horspool(t, p []rune) (int, error)", "start_line": 15 }
{ "package": "horspool" }
ConstructTrie
Go-master/strings/ahocorasick/shared.go
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) { trie = make(map[int]map[uint8]int) stateIsTerminal = make([]bool, 1) f = make(map[int][]int) state := 1 CreateNewState(0, trie) for i := 0; i < len(p); i++ { current := 0 j := 0 for j < len(p[i]) && GetTra...
package ahocorasick // ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings. func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) { trie = make(map[int]map[uint8]int) stateIsTerminal = make([]bool, 1) f = make(map[int][]i...
go
{ "argument_definitions": [], "end_line": 35, "name": "ConstructTrie", "signature": "func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int)", "start_line": 3 }
{ "package": "ahocorasick" }
Advanced
Go-master/strings/ahocorasick/advancedahocorasick.go
func Advanced(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f := BuildExtendedAc(p) current := 0 for pos := 0; pos < len(t); pos++ { if GetTransition(current, t[pos], ac) != -1 { current = GetTransition(current, t[pos], ac) } else { current = 0 } _, ok ...
package ahocorasick import ( "fmt" "time" ) // Advanced Function performing the Advanced Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func Advanced(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f := BuildExtendedAc(p) current := 0 for ...
go
{ "argument_definitions": [], "end_line": 42, "name": "Advanced", "signature": "func Advanced(t string, p []string) Result", "start_line": 9 }
{ "package": "ahocorasick" }
BuildExtendedAc
Go-master/strings/ahocorasick/advancedahocorasick.go
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) { acTrie, stateIsTerminal, f := ConstructTrie(p) s := make([]int, len(stateIsTerminal)) //supply function i := 0 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(state...
package ahocorasick import ( "fmt" "time" ) // Advanced Function performing the Advanced Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func Advanced(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f := BuildExtendedAc(p) current := 0 for ...
go
{ "argument_definitions": [], "end_line": 81, "name": "BuildExtendedAc", "signature": "func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int)", "start_line": 45 }
{ "package": "ahocorasick" }
AhoCorasick
Go-master/strings/ahocorasick/ahocorasick.go
func AhoCorasick(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f, s := BuildAc(p) current := 0 for pos := 0; pos < len(t); pos++ { for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 { current = s[current] } if GetTransition(current, t[pos], ac)...
package ahocorasick import ( "fmt" "time" ) // Result structure to hold occurrences type Result struct { occurrences map[string][]int } // AhoCorasick Function performing the Basic Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func AhoCorasick(t string, p []string) Result { startTime :...
go
{ "argument_definitions": [], "end_line": 50, "name": "AhoCorasick", "signature": "func AhoCorasick(t string, p []string) Result", "start_line": 14 }
{ "package": "ahocorasick" }
BuildAc
Go-master/strings/ahocorasick/ahocorasick.go
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) { acTrie, stateIsTerminal, f := ConstructTrie(p) s = make([]int, len(stateIsTerminal)) //supply function i := 0 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(stateI...
package ahocorasick import ( "fmt" "time" ) // Result structure to hold occurrences type Result struct { occurrences map[string][]int } // AhoCorasick Function performing the Basic Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func AhoCorasick(t string, p []string) Result { startTime :...
go
{ "argument_definitions": [], "end_line": 76, "name": "BuildAc", "signature": "func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int)", "start_line": 53 }
{ "package": "ahocorasick" }
HuffTree
Go-master/compression/huffmancoding.go
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...
// 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. // time complexity: O(n) // space complexity: O(n) // a...
go
{ "argument_definitions": [ { "definitions": [ "type SymbolFreq struct {\n\tSymbol rune\ntype SymbolFreq struct {\n\tSymbol rune\n\tFreq int\n}" ], "name": "listfreq", "type": "[]SymbolFreq" } ], "end_line": 56, "name": "HuffTree", "signature": "func HuffTree(listfreq...
{ "package": "compression" }
DepthFirstSearchHelper
Go-master/graph/depthfirstsearch.go
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) { var route []int var stack []int startIdx := GetIdx(start, nodes) stack = append(stack, startIdx) for len(stack) > 0 { now := stack[len(stack)-1] route = append(route, nodes[now]) if len(stack) > 1 { st...
// 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 ...
go
{ "argument_definitions": [], "end_line": 56, "name": "DepthFirstSearchHelper", "signature": "func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool)", "start_line": 26 }
{ "package": "graph" }
EdmondKarp
Go-master/graph/edmondkarp.go
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)) fo...
// 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 // S...
go
{ "argument_definitions": [ { "definitions": [ "type WeightedGraph [][]float64" ], "name": "graph", "type": "WeightedGraph" } ], "end_line": 92, "name": "EdmondKarp", "signature": "func EdmondKarp(graph WeightedGraph, source int, sink int) float64", "start_line": 42 }
{ "package": "graph" }
BreadthFirstSearch
Go-master/graph/breadthfirstsearch.go
func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) { queue := make([]int, 0) discovered := make([]int, nodes) discovered[start] = 1 queue = append(queue, start) for len(queue) > 0 { v := queue[0] queue = queue[1:] for i := 0; i < len(edges[v]); i++ { if discover...
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})}...
go
{ "argument_definitions": [], "end_line": 27, "name": "BreadthFirstSearch", "signature": "func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int)", "start_line": 8 }
{ "package": "graph" }
FloydWarshall
Go-master/graph/floydwarshall.go
func FloydWarshall(graph WeightedGraph) WeightedGraph { // If graph is empty, returns nil if len(graph) == 0 || len(graph) != len(graph[0]) { return nil } for i := 0; i < len(graph); i++ { //If graph matrix width is different than the height, returns nil if len(graph[i]) != len(graph) { return nil } } ...
// 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 import "math" // WeightedGraph defining matrix to use 2d arr...
go
{ "argument_definitions": [ { "definitions": [ "type WeightedGraph [][]float64" ], "name": "graph", "type": "WeightedGraph" } ], "end_line": 54, "name": "FloydWarshall", "signature": "func FloydWarshall(graph WeightedGraph) WeightedGraph", "start_line": 16 }
{ "package": "graph" }
KruskalMST
Go-master/graph/kruskal.go
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 // Create a new UnionFind data structure with 'n' nodes u := NewUnionFind(n) // Sort the edges in non-decreasing order based on their weights sort.Slice...
// KRUSKAL'S ALGORITHM // 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 ...
go
{ "argument_definitions": [ { "definitions": [ "type Edge struct {\n\tStart Vertex\n\tEnd Vertex\ntype Edge struct {\n\tStart Vertex\n\tEnd Vertex\n\tWeight int\n}" ], "name": "edges", "type": "[]Edge" } ], "end_line": 50, "name": "KruskalMST", "signature": "fun...
{ "package": "graph" }
NewTree
Go-master/graph/lowestcommonancestor.go
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)...
// 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. // time complexity: O(n log n) where n is the number of vertices in the tree ...
go
{ "argument_definitions": [ { "definitions": [ "type TreeEdge struct {\n\tfrom int\ntype TreeEdge struct {\n\tfrom int\n\tto int\n}" ], "name": "edges", "type": "[]TreeEdge" } ], "end_line": 107, "name": "NewTree", "signature": "func NewTree(numbersVertex, root int, e...
{ "package": "graph" }
Sign
Go-master/cipher/dsa/dsa.go
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 = ...
/* 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-Ra...
go
{ "argument_definitions": [ { "definitions": [ "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs nat // absolute value of the integer\n}" ], "name": "x", "type": "big.Int" } ], "end_line": 148, "name": "Sign", "signature": "func Sign(...
{ "package": "dsa" }
Verify
Go-master/cipher/dsa/dsa.go
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 := ...
/* 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-Ra...
go
{ "argument_definitions": [ { "definitions": [ "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs nat // absolute value of the integer\n}" ], "name": "y", "type": "big.Int" } ], "end_line": 180, "name": "Verify", "signature": "func Ver...
{ "package": "dsa" }
Encrypt
Go-master/cipher/railfence/railfence.go
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 ro...
// 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: ...
go
{ "argument_definitions": [], "end_line": 48, "name": "Encrypt", "signature": "func Encrypt(text string, rails int) string", "start_line": 12 }
{ "package": "railfence" }
Decrypt
Go-master/cipher/railfence/railfence.go
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...
// 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: ...
go
{ "argument_definitions": [], "end_line": 80, "name": "Decrypt", "signature": "func Decrypt(cipherText string, rails int) string", "start_line": 49 }
{ "package": "railfence" }
Encrypt
Go-master/cipher/transposition/transposition.go
func Encrypt(text []rune, keyWord string) ([]rune, error) { key := getKey(keyWord) keyLength := len(key) textLength := len(text) if keyLength <= 0 { return nil, ErrKeyMissing } if textLength <= 0 { return nil, ErrNoTextToEncrypt } if text[len(text)-1] == placeholder { return nil, fmt.Errorf("%w: cannot en...
// transposition.go // 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 ...
go
{ "argument_definitions": [], "end_line": 80, "name": "Encrypt", "signature": "func Encrypt(text []rune, keyWord string) ([]rune, error)", "start_line": 52 }
{ "package": "transposition" }
Decrypt
Go-master/cipher/transposition/transposition.go
func Decrypt(text []rune, keyWord string) ([]rune, error) { key := getKey(keyWord) textLength := len(text) if textLength <= 0 { return nil, ErrNoTextToEncrypt } keyLength := len(key) if keyLength <= 0 { return nil, ErrKeyMissing } n := textLength % keyLength for i := 0; i < keyLength-n; i++ { text = appe...
// transposition.go // 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 ...
go
{ "argument_definitions": [], "end_line": 106, "name": "Decrypt", "signature": "func Decrypt(text []rune, keyWord string) ([]rune, error)", "start_line": 82 }
{ "package": "transposition" }
NewPolybius
Go-master/cipher/polybius/polybius.go
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,...
// 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/wik...
go
{ "argument_definitions": [], "end_line": 48, "name": "NewPolybius", "signature": "func NewPolybius(key string, size int, chars string) (*Polybius, error)", "start_line": 24 }
{ "package": "polybius" }
EggDropping
Go-master/dynamic/eggdropping.go
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 floo...
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 ...
go
{ "argument_definitions": [], "end_line": 46, "name": "EggDropping", "signature": "func EggDropping(eggs, floors int) int", "start_line": 9 }
{ "package": "dynamic" }
MaxCoins
Go-master/dynamic/burstballoons.go
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 + ...
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 d...
go
{ "argument_definitions": [], "end_line": 30, "name": "MaxCoins", "signature": "func MaxCoins(nums []int) int", "start_line": 5 }
{ "package": "dynamic" }
MatrixChainDp
Go-master/dynamic/matrixmultiplication.go
func MatrixChainDp(D []int) int { // d[i-1] x d[i] : dimension of matrix i N := len(D) dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j) for i := 0; i < N; i++ { dp[i] = make([]int, N) dp[i][i] = 0 } for l := 2; l < N; l++ { for i := 1; i < N-l+1; i++ { j := i + l - 1 dp[i][j] = 1 << 31 ...
// 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 import "github.com/TheAlgorithms/Go/math/min" // MatrixChainRec fu...
go
{ "argument_definitions": [], "end_line": 47, "name": "MatrixChainDp", "signature": "func MatrixChainDp(D []int) int", "start_line": 25 }
{ "package": "dynamic" }
LongestPalindromicSubstring
Go-master/dynamic/longestpalindromicsubstring.go
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+...
// 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 ...
go
{ "argument_definitions": [], "end_line": 42, "name": "LongestPalindromicSubstring", "signature": "func LongestPalindromicSubstring(s string) string", "start_line": 9 }
{ "package": "dynamic" }
PartitionProblem
Go-master/dynamic/partitionproblem.go
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] }
// 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 //...
go
{ "argument_definitions": [], "end_line": 29, "name": "PartitionProblem", "signature": "func PartitionProblem(nums []int) bool", "start_line": 10 }
{ "package": "dynamic" }
LongestArithmeticSubsequence
Go-master/dynamic/longestarithmeticsubsequence.go
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[...
// 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 lo...
go
{ "argument_definitions": [], "end_line": 33, "name": "LongestArithmeticSubsequence", "signature": "func LongestArithmeticSubsequence(nums []int) int", "start_line": 9 }
{ "package": "dynamic" }
IsInterleave
Go-master/dynamic/interleavingstrings.go
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++ {...
// 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 ...
go
{ "argument_definitions": [], "end_line": 35, "name": "IsInterleave", "signature": "func IsInterleave(s1, s2, s3 string) bool", "start_line": 9 }
{ "package": "dynamic" }
OptimalBST
Go-master/dynamic/optimalbst.go
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;...
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...
go
{ "argument_definitions": [], "end_line": 51, "name": "OptimalBST", "signature": "func OptimalBST(keys []int, freq []int, n int) int", "start_line": 5 }
{ "package": "dynamic" }
DiceThrow
Go-master/dynamic/dicethrow.go
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] ...
// 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...
go
{ "argument_definitions": [], "end_line": 32, "name": "DiceThrow", "signature": "func DiceThrow(m, n, sum int) int", "start_line": 9 }
{ "package": "dynamic" }
LongestCommonSubsequence
Go-master/dynamic/longestcommonsubsequence.go
func LongestCommonSubsequence(a string, b string) int { 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) for i := 0; i <= aLen; i++ { lcs[i] = make([]int, bLen+1) } // block that implements LCS for i :...
// 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...
go
{ "argument_definitions": [], "end_line": 39, "name": "LongestCommonSubsequence", "signature": "func LongestCommonSubsequence(a string, b string) int", "start_line": 15 }
{ "package": "dynamic" }
EditDistanceRecursive
Go-master/dynamic/editdistance.go
func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int { if pointerFirst == 0 { return pointerSecond } if pointerSecond == 0 { return pointerFirst } // Characters match, so we recur for the remaining portions if first[pointerFirst-1] == second[pointerSecond-1] { ...
// 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...
go
{ "argument_definitions": [], "end_line": 30, "name": "EditDistanceRecursive", "signature": "func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int", "start_line": 11 }
{ "package": "dynamic" }
EditDistanceDP
Go-master/dynamic/editdistance.go
func EditDistanceDP(first string, second string) int { m := len(first) n := len(second) // Create the DP table dp := make([][]int, m+1) for i := 0; i <= m; i++ { dp[i] = make([]int, n+1) } for i := 0; i <= m; i++ { for j := 0; j <= n; j++ { if i == 0 { dp[i][j] = j continue } if j == 0 ...
// 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...
go
{ "argument_definitions": [], "end_line": 70, "name": "EditDistanceDP", "signature": "func EditDistanceDP(first string, second string) int", "start_line": 36 }
{ "package": "dynamic" }
IsSubsetSum
Go-master/dynamic/subsetsum.go
func IsSubsetSum(array []int, sum int) (bool, error) { if sum < 0 { //not allow negative sum return false, ErrNegativeSum } //create subset matrix arraySize := len(array) subset := make([][]bool, arraySize+1) for i := 0; i <= arraySize; i++ { subset[i] = make([]bool, sum+1) } for i := 0; i <= arraySize;...
//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. // time complexity: O(n*sum) // space complexity: O(n*sum) //references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ package dynamic import "fmt" var ErrInv...
go
{ "argument_definitions": [], "end_line": 55, "name": "IsSubsetSum", "signature": "func IsSubsetSum(array []int, sum int) (bool, error)", "start_line": 14 }
{ "package": "dynamic" }
TrapRainWater
Go-master/dynamic/traprainwater.go
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] = heig...
// 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 ...
go
{ "argument_definitions": [], "end_line": 42, "name": "TrapRainWater", "signature": "func TrapRainWater(height []int) int", "start_line": 18 }
{ "package": "dynamic" }
LpsDp
Go-master/dynamic/longestpalindromicsubsequence.go
func LpsDp(word string) int { N := len(word) dp := make([][]int, N) for i := 0; i < N; i++ { dp[i] = make([]int, N) dp[i][i] = 1 } for l := 2; l <= N; l++ { // for length l for i := 0; i < N-l+1; i++ { j := i + l - 1 if word[i] == word[j] { if l == 2 { dp[i][j] = 2 } else { dp[i][...
// 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 func lpsRec(word string, i, j int) int { if i == j { return 1 } if i > j { return 0 } if word[i] == word[j] { ...
go
{ "argument_definitions": [], "end_line": 52, "name": "LpsDp", "signature": "func LpsDp(word string) int", "start_line": 26 }
{ "package": "dynamic" }
UniquePaths
Go-master/dynamic/uniquepaths.go
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...
// 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 // UniquePaths implements the solution to the "Uniq...
go
{ "argument_definitions": [], "end_line": 32, "name": "UniquePaths", "signature": "func UniquePaths(m, n int) int", "start_line": 7 }
{ "package": "dynamic" }
Abbreviation
Go-master/dynamic/abbreviation.go
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] ...
// 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 ...
go
{ "argument_definitions": [], "end_line": 46, "name": "Abbreviation", "signature": "func Abbreviation(a string, b string) bool", "start_line": 25 }
{ "package": "dynamic" }
IsMatch
Go-master/dynamic/wildcardmatching.go
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...
// 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...
go
{ "argument_definitions": [], "end_line": 32, "name": "IsMatch", "signature": "func IsMatch(s, p string) bool", "start_line": 9 }
{ "package": "dynamic" }
Generate
Go-master/other/password/generator.go
func Generate(minLength int, maxLength int) string { var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~") length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength))) if err != nil { panic(err) // handle this gracefully } length.Add(lengt...
// This program generates a password from a list of possible chars // You must provide a minimum length and a maximum length // 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 compl...
go
{ "argument_definitions": [], "end_line": 48, "name": "Generate", "signature": "func Generate(minLength int, maxLength int) string", "start_line": 17 }
{ "package": "password" }
IsBalanced
Go-master/other/nested/nestedbrackets.go
func IsBalanced(input string) bool { if len(input) == 0 { return true } if len(input)%2 != 0 { return false } // Brackets such as '{', '[', '(' are valid UTF-8 characters, // which means that only one byte is required to code them, // so can be stored as bytes. var stack []byte for i := 0; i < len(input...
// Package nested provides functions for testing // strings proper brackets nesting. package nested // 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 th...
go
{ "argument_definitions": [], "end_line": 64, "name": "IsBalanced", "signature": "func IsBalanced(input string) bool", "start_line": 22 }
{ "package": "nested" }
hexToDecimal
Go-master/conversion/hexadecimaltodecimal.go
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:] } // Vali...
/* 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 D...
go
{ "argument_definitions": [], "end_line": 56, "name": "hexToDecimal", "signature": "func hexToDecimal(hexStr string) (int64, error)", "start_line": 22 }
{ "package": "conversion" }
Base64Encode
Go-master/conversion/base64.go
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 pe...
// 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 // se...
go
{ "argument_definitions": [], "end_line": 53, "name": "Base64Encode", "signature": "func Base64Encode(input []byte) string", "start_line": 20 }
{ "package": "conversion" }
hexToBinary
Go-master/conversion/hexadecimaltobinary.go
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 "", err...
/* 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 retur...
go
{ "argument_definitions": [], "end_line": 77, "name": "hexToBinary", "signature": "func hexToBinary(hex string) (string, error)", "start_line": 23 }
{ "package": "conversion" }
add
Go-master/project_euler/problem_13/problem13.go
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...
/** * 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", "4637693767749000971...
go
{ "argument_definitions": [], "end_line": 149, "name": "add", "signature": "func add(a, b string) string", "start_line": 123 }
{ "package": "problem13" }
Jump
Go-master/search/jump.go
func Jump(array []int, target int) (int, error) { n := len(array) if n == 0 { return -1, ErrNotFound } // the optimal value of step is square root of the length of list step := int(math.Round(math.Sqrt(float64(n)))) prev := 0 // previous index curr := step // current index for array[curr-1] < target { ...
// jump.go // description: Implementation of jump search // details: // A search algorithm for ordered list that jump through the list to narrow down the range // before performing a linear search // reference: https://en.wikipedia.org/wiki/Jump_search // see jump_test.go for a test implementation, test function TestJu...
go
{ "argument_definitions": [], "end_line": 56, "name": "Jump", "signature": "func Jump(array []int, target int) (int, error)", "start_line": 16 }
{ "package": "search" }
Interpolation
Go-master/search/interpolation.go
func Interpolation(sortedData []int, guess int) (int, error) { if len(sortedData) == 0 { return -1, ErrNotFound } var ( low, high = 0, len(sortedData) - 1 lowVal, highVal = sortedData[low], sortedData[high] ) for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) { mid := low + int(float6...
package search // Interpolation searches for the entity in the given sortedData. // 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 uni...
go
{ "argument_definitions": [], "end_line": 50, "name": "Interpolation", "signature": "func Interpolation(sortedData []int, guess int) (int, error)", "start_line": 14 }
{ "package": "search" }
Jump2
Go-master/search/jump2.go
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] ...
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 { ...
go
{ "argument_definitions": [], "end_line": 23, "name": "Jump2", "signature": "func Jump2(arr []int, target int) (int, error)", "start_line": 4 }
{ "package": "search" }
doSort
Go-master/sort/circlesort.go
func doSort(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], ...
// 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 } // do...
go
{ "argument_definitions": [], "end_line": 43, "name": "doSort", "signature": "func doSort(arr []T, left, right int) bool", "start_line": 16 }
{ "package": "sort" }
Mode
Go-master/math/mode.go
func Mode(numbers []T) (T, error) { countMap := make(map[T]int) n := len(numbers) if n == 0 { return 0, ErrEmptySlice } for _, number := range numbers { countMap[number]++ } var mode T count := 0 for k, v := range countMap { if v > count { count = v mode = k } } return mode, nil }
// 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 package math import ( "errors" "github.com/TheAlgorithms/Go/constraints" ) // ErrEmptySlice is the error returned by functions in mat...
go
{ "argument_definitions": [], "end_line": 46, "name": "Mode", "signature": "func Mode(numbers []T) (T, error)", "start_line": 20 }
{ "package": "math" }
IsKrishnamurthyNumber
Go-master/math/krishnamurthy.go
func IsKrishnamurthyNumber(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 :=...
// 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! // time complex...
go
{ "argument_definitions": [], "end_line": 33, "name": "IsKrishnamurthyNumber", "signature": "func IsKrishnamurthyNumber(n T) bool", "start_line": 13 }
{ "package": "math" }
Spigot
Go-master/math/pi/spigotpi.go
func Spigot(n int) string { pi := "" boxes := n * 10 / 3 remainders := make([]int, boxes) for i := 0; i < boxes; i++ { remainders[i] = 2 } digitsHeld := 0 for i := 0; i < n; i++ { carriedOver := 0 sum := 0 for j := boxes - 1; j >= 0; j-- { remainders[j] *= 10 sum = remainders[j] + carriedOver qu...
// spigotpi.go // 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) // s...
go
{ "argument_definitions": [], "end_line": 55, "name": "Spigot", "signature": "func Spigot(n int) string", "start_line": 13 }
{ "package": "pi" }
MonteCarloPiConcurrent
Go-master/math/pi/montecarlopi.go
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 ...
// montecarlopi.go // 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://githu...
go
{ "argument_definitions": [], "end_line": 56, "name": "MonteCarloPiConcurrent", "signature": "func MonteCarloPiConcurrent(n int) (float64, error)", "start_line": 37 }
{ "package": "pi" }
splitInt
Go-master/math/pi/montecarlopi.go
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...
// montecarlopi.go // 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://githu...
go
{ "argument_definitions": [], "end_line": 94, "name": "splitInt", "signature": "func splitInt(x int, n int) ([]int, error)", "start_line": 75 }
{ "package": "pi" }
Exponentiation
Go-master/math/modular/exponentiation.go
func Exponentiation(base, exponent, mod int64) (int64, error) { if mod == 1 { return 0, nil } if exponent < 0 { return -1, ErrorNegativeExponent } _, err := Multiply64BitInt(mod-1, mod-1) if err != nil { return -1, err } var result int64 = 1 base = base % mod for exponent > 0 { if exponent%2 == 1...
// exponentiation.go // 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) /...
go
{ "argument_definitions": [], "end_line": 49, "name": "Exponentiation", "signature": "func Exponentiation(base, exponent, mod int64) (int64, error)", "start_line": 23 }
{ "package": "modular" }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4