repo
stringclasses
6 values
id
int64
0
371
target_function_prompt
stringlengths
258
11.6k
function_signature
stringlengths
258
11.6k
focal_code
stringlengths
258
11.6k
function_name
stringlengths
2
36
start_line
int64
3
1.61k
end_line
int64
23
1.64k
file_path
stringlengths
7
56
context
stringlengths
3.33k
9.15k
Go-master
0
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...
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...
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...
IsSubsequence
9
34
strings/issubsequence.go
#FILE: Go-master/structure/trie/trie.go ##CHUNK 1 } return r } // remove lazily a word from the Trie node, no node is actually removed. func (n *Node) remove(s string) { if len(s) == 0 { return } next, ok := n, false for _, c := range s { next, ok = next.children[c] if !ok { // word cannot be found - we...
Go-master
1
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...
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...
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...
IsIsogram
33
70
strings/isisogram.go
#FILE: Go-master/graph/cycle.go ##CHUNK 1 } } 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 { ...
Go-master
2
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...
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...
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...
GeneticString
70
196
strings/genetic/genetic.go
#FILE: Go-master/math/pi/montecarlopi.go ##CHUNK 1 } // 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...
Go-master
3
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] { ...
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] { ...
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] { ...
Distance
9
41
strings/levenshtein/levenshteindistance.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
4
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[...
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[...
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
36
62
strings/manacher/longestpalindrome.go
#FILE: Go-master/strings/search/boyermoore.go ##CHUNK 1 skip := 0 jump := n for i := 0; i < l-n+1; { skip = skips[jump] for k := n - 1; k > -1; k-- { if text[i+k] != pattern[k] { jump, ok := bcr[text[i+k]] if !ok { jump = n } i += jump break } if k == n-jump { k -= skip ...
Go-master
5
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...
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...
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...
horspool
15
36
strings/horspool/horspool.go
#FILE: Go-master/strings/bom/bom.go ##CHUNK 1 // currentOcc := 0 // pos = 0 // if debugMode == true { // fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1) // } // for pos <= n-m { // current = 0 //initial state of the oracle // j = m // for j > 0 && stat...
Go-master
6
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...
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...
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...
ConstructTrie
3
35
strings/ahocorasick/shared.go
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go ##CHUNK 1 stateIsTerminal[current] = true f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current)) } } else { s[current] = i //initial state? } } a := ComputeAlphabet(p) // concat of all patterns in ...
Go-master
7
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 ...
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 ...
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 ...
Advanced
9
42
strings/ahocorasick/advancedahocorasick.go
#FILE: Go-master/strings/ahocorasick/ahocorasick.go ##CHUNK 1 if ok { for i := range f[current] { if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match newOccurrences := IntArrayCapUp(occurrences[f[current][i]]) occurrences[f[current][i]] = newOccurrences o...
Go-master
8
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...
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...
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...
BuildExtendedAc
45
81
strings/ahocorasick/advancedahocorasick.go
#FILE: Go-master/strings/ahocorasick/ahocorasick.go ##CHUNK 1 } // Functions that builds Aho Corasick automaton. 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 ...
Go-master
9
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)...
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)...
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)...
AhoCorasick
14
50
strings/ahocorasick/ahocorasick.go
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go ##CHUNK 1 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 { ...
Go-master
10
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...
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...
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...
BuildAc
53
76
strings/ahocorasick/ahocorasick.go
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go ##CHUNK 1 resultOccurrences, } } // BuildExtendedAc Functions that builds extended Aho Corasick automaton. func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) { acTrie, stateIsTerminal, f := ConstructTrie(p) s := make([]i...
Go-master
11
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...
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...
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...
HuffTree
34
56
compression/huffmancoding.go
#FILE: Go-master/sqrt/sqrtdecomposition_test.go ##CHUNK 1 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...
Go-master
12
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...
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...
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...
DepthFirstSearchHelper
26
56
graph/depthfirstsearch.go
#FILE: Go-master/structure/tree/tree.go ##CHUNK 1 return searchTreeHelper(node.Left(), nilNode, key) } return searchTreeHelper(node.Right(), nilNode, key) } func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T { var stack []Node[T] var ret []T for node != nilNode || len(stack) > 0 { for node ...
Go-master
13
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...
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...
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...
EdmondKarp
42
92
graph/edmondkarp.go
#FILE: Go-master/graph/floydwarshall.go ##CHUNK 1 } 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 } } numVertices := len(graph) // Initializing result matrix and filling it up with same values as given gra...
Go-master
14
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...
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...
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...
BreadthFirstSearch
8
27
graph/breadthfirstsearch.go
#FILE: Go-master/graph/edmondkarp.go ##CHUNK 1 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 ...
Go-master
15
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 } } ...
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 } } ...
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 } } ...
FloydWarshall
16
54
graph/floydwarshall.go
#FILE: Go-master/graph/edmondkarp.go ##CHUNK 1 } 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 } ...
Go-master
16
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...
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...
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...
KruskalMST
22
50
graph/kruskal.go
#FILE: Go-master/dynamic/optimalbst.go ##CHUNK 1 } // 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 ...
Go-master
17
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)...
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)...
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)...
NewTree
85
107
graph/lowestcommonancestor.go
#FILE: Go-master/graph/lowestcommonancestor_test.go ##CHUNK 1 const MAXVERTEX int = 2000 var numbersVertex int = rnd.Intn(MAXVERTEX) + 1 var root int = rnd.Intn(numbersVertex) var edges []TreeEdge var fullGraph []TreeEdge for u := 0; u < numbersVertex; u++ { for v := 0; v < numbersVertex; v++ { fullGraph =...
Go-master
18
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 = ...
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 = ...
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 = ...
Sign
124
148
cipher/dsa/dsa.go
#CURRENT FILE: Go-master/cipher/dsa/dsa.go ##CHUNK 1 // 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 } // 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 *...
Go-master
19
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 := ...
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 := ...
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 := ...
Verify
156
180
cipher/dsa/dsa.go
#FILE: Go-master/cipher/rsa/rsa2.go ##CHUNK 1 // 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...
Go-master
20
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...
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...
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...
Encrypt
12
48
cipher/railfence/railfence.go
#FILE: Go-master/math/matrix/isvalid.go ##CHUNK 1 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 _, ...
Go-master
21
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...
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...
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...
Decrypt
49
80
cipher/railfence/railfence.go
#FILE: Go-master/structure/linkedlist/singlylinkedlist.go ##CHUNK 1 if ll.Head.Next == nil { return ll.DelAtBeg() } cur := ll.Head for ; cur.Next.Next != nil; cur = cur.Next { } retval := cur.Next.Val cur.Next = nil ll.length-- return retval, true } // DelByPos deletes the node at the middle based on po...
Go-master
22
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...
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...
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...
Encrypt
52
80
cipher/transposition/transposition.go
#FILE: Go-master/dynamic/editdistance.go ##CHUNK 1 // 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 { dp[i][j] = i continue } #...
Go-master
23
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...
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...
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...
Decrypt
82
106
cipher/transposition/transposition.go
#FILE: Go-master/dynamic/editdistance.go ##CHUNK 1 // 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 { dp[i][j] = i continue } #...
Go-master
24
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,...
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,...
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,...
NewPolybius
24
48
cipher/polybius/polybius.go
#FILE: Go-master/math/factorial/factorial.go ##CHUNK 1 if n == 1 || n == 2 { return n, nil } return prodTree(2, n), nil } func prodTree(l int, r int) int { if l > r { return 1 } if l == r { return l } if r-l == 1 { return l * r } m := (l + r) / 2 return prodTree(l, m) * prodTree(m+1, r) } #FILE: Go...
Go-master
25
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...
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...
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...
EggDropping
9
46
dynamic/eggdropping.go
#FILE: Go-master/dynamic/editdistance.go ##CHUNK 1 // 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 { dp[i][j] = i continue } #...
Go-master
26
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 + ...
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 + ...
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 + ...
MaxCoins
5
30
dynamic/burstballoons.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
27
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 ...
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 ...
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 ...
MatrixChainDp
25
47
dynamic/matrixmultiplication.go
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go ##CHUNK 1 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][j] ...
Go-master
28
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+...
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+...
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
9
42
dynamic/longestpalindromicsubstring.go
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go ##CHUNK 1 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][j] ...
Go-master
29
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] }
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] }
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
10
29
dynamic/partitionproblem.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
30
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[...
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[...
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
9
33
dynamic/longestarithmeticsubsequence.go
#FILE: Go-master/dynamic/longestpalindromicsubstring.go ##CHUNK 1 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 < ...
Go-master
31
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++ {...
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++ {...
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++ {...
IsInterleave
9
35
dynamic/interleavingstrings.go
#FILE: Go-master/dynamic/wildcardmatching.go ##CHUNK 1 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...
Go-master
32
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;...
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;...
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;...
OptimalBST
5
51
dynamic/optimalbst.go
#FILE: Go-master/dynamic/eggdropping.go ##CHUNK 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 ...
Go-master
33
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] ...
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] ...
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
9
32
dynamic/dicethrow.go
#FILE: Go-master/dynamic/editdistance.go ##CHUNK 1 // 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 { dp[i][j] = i continue } #...
Go-master
34
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 :...
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 :...
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 :...
LongestCommonSubsequence
15
39
dynamic/longestcommonsubsequence.go
#FILE: Go-master/dynamic/binomialcoefficient.go ##CHUNK 1 // } // } // Bin2 function func Bin2(n int, k int) int { var i, j int B := make([][]int, (n + 1)) for i := range B { B[i] = make([]int, k+1) } for i = 0; i <= n; i++ { for j = 0; j <= min.Int(i, k); j++ { if j == 0 || j == i { B[i][j] = 1 ...
Go-master
35
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] { ...
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] { ...
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] { ...
EditDistanceRecursive
11
30
dynamic/editdistance.go
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go ##CHUNK 1 // 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 ...
Go-master
36
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 ...
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 ...
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 ...
EditDistanceDP
36
70
dynamic/editdistance.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
37
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;...
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;...
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;...
IsSubsetSum
14
55
dynamic/subsetsum.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
38
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...
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...
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...
TrapRainWater
18
42
dynamic/traprainwater.go
#FILE: Go-master/sort/radixsort.go ##CHUNK 1 digits[(item/exp)%10]++ } for i := 1; i < 10; i++ { digits[i] += digits[i-1] } for i := len(arr) - 1; i >= 0; i-- { output[digits[(arr[i]/exp)%10]-1] = arr[i] digits[(arr[i]/exp)%10]-- } return output } func unsignedRadixSort[T constraints.Integer](arr []T) ...
Go-master
39
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][...
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][...
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][...
LpsDp
26
52
dynamic/longestpalindromicsubsequence.go
#FILE: Go-master/dynamic/matrixmultiplication.go ##CHUNK 1 } return q } // MatrixChainDp function 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 ...
Go-master
40
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...
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...
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...
UniquePaths
7
32
dynamic/uniquepaths.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
41
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] ...
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] ...
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] ...
Abbreviation
25
46
dynamic/abbreviation.go
#FILE: Go-master/dynamic/wildcardmatching.go ##CHUNK 1 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...
Go-master
42
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...
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...
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...
IsMatch
9
32
dynamic/wildcardmatching.go
#FILE: Go-master/dynamic/interleavingstrings.go ##CHUNK 1 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 <= ...
Go-master
43
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...
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...
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...
Generate
17
48
other/password/generator.go
#FILE: Go-master/strings/guid/guid.go ##CHUNK 1 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.Sprint...
Go-master
44
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...
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...
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...
IsBalanced
22
64
other/nested/nestedbrackets.go
#FILE: Go-master/structure/stack/stacklinkedlistwithlist.go ##CHUNK 1 element := sl.Stack.Front() // remove element in stack sl.Stack.Remove(element) // return element value return element.Value, nil } return "", fmt.Errorf("stack list is empty") } // Length return length of our stack func (sl *SList) Leng...
Go-master
45
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...
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...
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...
hexToDecimal
22
56
conversion/hexadecimaltodecimal.go
#FILE: Go-master/conversion/hexadecimaltobinary.go ##CHUNK 1 } // 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...
Go-master
46
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...
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...
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...
Base64Encode
20
53
conversion/base64.go
#FILE: Go-master/compression/rlecoding.go ##CHUNK 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...
Go-master
47
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...
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...
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...
hexToBinary
23
77
conversion/hexadecimaltobinary.go
#FILE: Go-master/conversion/hexadecimaltodecimal.go ##CHUNK 1 // 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 hexadec...
Go-master
48
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...
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...
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...
add
123
149
project_euler/problem_13/problem13.go
#FILE: Go-master/sort/shellsort.go ##CHUNK 1 package sort 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 { arr[j], arr[j-d] = arr[j-d...
Go-master
49
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 { ...
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 { ...
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
16
56
search/jump.go
#FILE: Go-master/search/binary.go ##CHUNK 1 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 } // UpperBound returns index to the first element in the range [lowIndex, len(a...
Go-master
50
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...
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...
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...
Interpolation
14
50
search/interpolation.go
#FILE: Go-master/search/binary.go ##CHUNK 1 } else if array[mid] < target { startIndex = mid + 1 } else { return mid, nil } } return -1, ErrNotFound } // 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 ...
Go-master
51
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] ...
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] ...
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] ...
Jump2
4
23
search/jump2.go
#FILE: Go-master/sort/exchangesort.go ##CHUNK 1 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] { arr[i], arr[j] = arr[j], arr[i] } } } return arr } #FILE: Go-master/sort/radixsort.go ##CHUNK 1 digits[(item...
Go-master
52
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], ...
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], ...
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], ...
doSort
16
43
sort/circlesort.go
#FILE: Go-master/sort/binaryinsertionsort.go ##CHUNK 1 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 } ##CHUNK 2 import "github.com/TheAlgorithms/Go/constraints" ...
Go-master
53
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 }
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 }
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
20
46
math/mode.go
#FILE: Go-master/project_euler/problem_14/problem14.go ##CHUNK 1 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 } } ret...
Go-master
54
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 :=...
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 :=...
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 :=...
IsKrishnamurthyNumber
13
33
math/krishnamurthy.go
#FILE: Go-master/math/isautomorphic.go ##CHUNK 1 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...
Go-master
55
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...
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...
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...
Spigot
13
55
math/pi/spigotpi.go
#FILE: Go-master/dynamic/dicethrow.go ##CHUNK 1 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...
Go-master
56
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 ...
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 ...
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 ...
MonteCarloPiConcurrent
37
56
math/pi/montecarlopi.go
#FILE: Go-master/math/matrix/copy.go ##CHUNK 1 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 } copy...
Go-master
57
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...
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...
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...
splitInt
75
94
math/pi/montecarlopi.go
#FILE: Go-master/dynamic/longestpalindromicsubstring.go ##CHUNK 1 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 < ...
Go-master
58
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...
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...
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
23
49
math/modular/exponentiation.go
#FILE: Go-master/cipher/diffiehellman/diffiehellmankeyexchange.go ##CHUNK 1 //uses exponentiation by squaring to speed up the process if mod == 1 { return 0 } var r int64 = 1 b = b % mod for e > 0 { if e&1 == 1 { r = (r * b) % mod } e = e >> 1 b = (b * b) % mod } return r } ##CHUNK 2 // GenerateMu...
Go-master
59
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) }
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) }
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) }
Matrix
16
39
math/fibonacci/fibonacci.go
#FILE: Go-master/project_euler/problem_9/problem9.go ##CHUNK 1 * 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 } ##CHU...
Go-master
60
func NewFromElements(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,...
func NewFromElements(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,...
func NewFromElements(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,...
NewFromElements
42
63
math/matrix/matrix.go
#FILE: Go-master/math/matrix/matrix_test.go ##CHUNK 1 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...
Go-master
61
func OptimizedTrialDivision(n int64) bool { // 0 and 1 are not prime if n < 2 { return false } // 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 } } ...
func OptimizedTrialDivision(n int64) bool { // 0 and 1 are not prime if n < 2 { return false } // 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 } } ...
func OptimizedTrialDivision(n int64) bool { // 0 and 1 are not prime if n < 2 { return false } // 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 } } ...
OptimizedTrialDivision
27
49
math/prime/primecheck.go
#FILE: Go-master/math/prime/millerrabintest.go ##CHUNK 1 func formatNum(num int64) (d int64, s int64) { d = num - 1 for num%2 == 0 { d /= 2 s++ } return } // 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...
chi-master
62
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) { ps := strings.Index(pattern, "{") ws := strings.Index(pattern, "*") if ps < 0 && ws < 0 { return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing } // Sanity check if ps >= 0 && ws >= 0 && ws < ps { panic("chi:...
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) { ps := strings.Index(pattern, "{") ws := strings.Index(pattern, "*") if ps < 0 && ws < 0 { return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing } // Sanity check if ps >= 0 && ws >= 0 && ws < ps { panic("chi:...
func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) { ps := strings.Index(pattern, "{") ws := strings.Index(pattern, "*") if ps < 0 && ws < 0 { return ntStatic, "", "", 0, 0, len(pattern) // we return the entire thing } // Sanity check if ps >= 0 && ws >= 0 && ws < ps { panic("chi:...
patNextSegment
688
754
tree.go
#FILE: chi-master/middleware/wrap_writer.go ##CHUNK 1 ) // NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to // hook into various parts of the response process. func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { _, fl := w.(http.Flusher) bw ...
chi-master
63
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { _, fl := w.(http.Flusher) bw := basicWriter{ResponseWriter: w} if protoMajor == 2 { _, ps := w.(http.Pusher) if fl && ps { return &http2FancyWriter{bw} } } else { _, hj := w.(http.Hijacker) _, rf := w.(io.ReaderFro...
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { _, fl := w.(http.Flusher) bw := basicWriter{ResponseWriter: w} if protoMajor == 2 { _, ps := w.(http.Pusher) if fl && ps { return &http2FancyWriter{bw} } } else { _, hj := w.(http.Hijacker) _, rf := w.(io.ReaderFro...
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { _, fl := w.(http.Flusher) bw := basicWriter{ResponseWriter: w} if protoMajor == 2 { _, ps := w.(http.Pusher) if fl && ps { return &http2FancyWriter{bw} } } else { _, hj := w.(http.Hijacker) _, rf := w.(io.ReaderFro...
NewWrapResponseWriter
14
43
middleware/wrap_writer.go
#FILE: chi-master/middleware/middleware_test.go ##CHUNK 1 func TestWrapWriterHTTP2(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Proto != "HTTP/2.0" { t.Fatalf("request proto should be HTTP/2.0 but was %s", r.Proto) } _, fl := w.(http.Flusher) if !fl { t...
cli-main
64
func stringifyFlag(f Flag) string { // enforce DocGeneration interface on flags to avoid reflection df, ok := f.(DocGenerationFlag) if !ok { return "" } placeholder, usage := unquoteUsage(df.GetUsage()) needsPlaceholder := df.TakesValue() // if needsPlaceholder is true, placeholder is empty if needsPlaceholde...
func stringifyFlag(f Flag) string { // enforce DocGeneration interface on flags to avoid reflection df, ok := f.(DocGenerationFlag) if !ok { return "" } placeholder, usage := unquoteUsage(df.GetUsage()) needsPlaceholder := df.TakesValue() // if needsPlaceholder is true, placeholder is empty if needsPlaceholde...
func stringifyFlag(f Flag) string { // enforce DocGeneration interface on flags to avoid reflection df, ok := f.(DocGenerationFlag) if !ok { return "" } placeholder, usage := unquoteUsage(df.GetUsage()) needsPlaceholder := df.TakesValue() // if needsPlaceholder is true, placeholder is empty if needsPlaceholde...
stringifyFlag
87
124
docs.go
#FILE: cli-main/command_parse.go ##CHUNK 1 } // no flag lookup found and short handling is disabled if !shortOptionHandling { return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName) } // try to split the flags for index, c := range flagName { tracef("processing fl...
cli-main
65
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { fc := newFlagCategories() var categorized bool for _, fl := range fs { if cf, ok := fl.(CategorizableFlag); ok { visible := false if vf, ok := fl.(VisibleFlag); ok { visible = vf.IsVisible() } if cat := cf.GetCategory(); cat != "" && vis...
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { fc := newFlagCategories() var categorized bool for _, fl := range fs { if cf, ok := fl.(CategorizableFlag); ok { visible := false if vf, ok := fl.(VisibleFlag); ok { visible = vf.IsVisible() } if cat := cf.GetCategory(); cat != "" && vis...
func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { fc := newFlagCategories() var categorized bool for _, fl := range fs { if cf, ok := fl.(CategorizableFlag); ok { visible := false if vf, ok := fl.(VisibleFlag); ok { visible = vf.IsVisible() } if cat := cf.GetCategory(); cat != "" && vis...
newFlagCategoriesFromFlags
100
133
category.go
#FILE: cli-main/flag.go ##CHUNK 1 // Sets the category of the flag SetCategory(string) } // LocalFlag is an interface to enable detection of flags which are local // to current command type LocalFlag interface { IsLocal() bool } func visibleFlags(fl []Flag) []Flag { var visible []Flag for _, f := range fl { if...
cli-main
66
func jaroDistance(a, b string) float64 { if len(a) == 0 && len(b) == 0 { return 1 } if len(a) == 0 || len(b) == 0 { return 0 } lenA := float64(len(a)) lenB := float64(len(b)) hashA := make([]bool, len(a)) hashB := make([]bool, len(b)) maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))...
func jaroDistance(a, b string) float64 { if len(a) == 0 && len(b) == 0 { return 1 } if len(a) == 0 || len(b) == 0 { return 0 } lenA := float64(len(a)) lenB := float64(len(b)) hashA := make([]bool, len(a)) hashB := make([]bool, len(b)) maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))...
func jaroDistance(a, b string) float64 { if len(a) == 0 && len(b) == 0 { return 1 } if len(a) == 0 || len(b) == 0 { return 0 } lenA := float64(len(a)) lenB := float64(len(b)) hashA := make([]bool, len(a)) hashB := make([]bool, len(b)) maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1))...
jaroDistance
23
75
suggestions.go
#FILE: cli-main/docs.go ##CHUNK 1 func unquoteUsage(usage string) (string, string) { for i := 0; i < len(usage); i++ { if usage[i] == '`' { for j := i + 1; j < len(usage); j++ { if usage[j] == '`' { name := usage[i+1 : j] usage = usage[:i] + name + usage[j+1:] return name, usage } } b...
cli-main
67
func jaroWinkler(a, b string) float64 { const ( boostThreshold = 0.7 prefixSize = 4 ) jaroDist := jaroDistance(a, b) if jaroDist <= boostThreshold { return jaroDist } prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) var prefixMatch float64 for i := 0; i < pref...
func jaroWinkler(a, b string) float64 { const ( boostThreshold = 0.7 prefixSize = 4 ) jaroDist := jaroDistance(a, b) if jaroDist <= boostThreshold { return jaroDist } prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) var prefixMatch float64 for i := 0; i < pref...
func jaroWinkler(a, b string) float64 { const ( boostThreshold = 0.7 prefixSize = 4 ) jaroDist := jaroDistance(a, b) if jaroDist <= boostThreshold { return jaroDist } prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) var prefixMatch float64 for i := 0; i < pref...
jaroWinkler
81
102
suggestions.go
#FILE: cli-main/docs.go ##CHUNK 1 if len(name) == 1 { prefix = "-" } else { prefix = "--" } return } // Returns the placeholder, if any, and the unquoted usage string. func unquoteUsage(usage string) (string, string) { for i := 0; i < len(usage); i++ { if usage[i] == '`' { for j := i + 1; j < len(usage)...
cli-main
68
func suggestFlag(flags []Flag, provided string, hideHelp bool) string { distance := 0.0 suggestion := "" for _, flag := range flags { flagNames := flag.Names() if !hideHelp && HelpFlag != nil { flagNames = append(flagNames, HelpFlag.Names()...) } for _, name := range flagNames { newDistance := jaroWin...
func suggestFlag(flags []Flag, provided string, hideHelp bool) string { distance := 0.0 suggestion := "" for _, flag := range flags { flagNames := flag.Names() if !hideHelp && HelpFlag != nil { flagNames = append(flagNames, HelpFlag.Names()...) } for _, name := range flagNames { newDistance := jaroWin...
func suggestFlag(flags []Flag, provided string, hideHelp bool) string { distance := 0.0 suggestion := "" for _, flag := range flags { flagNames := flag.Names() if !hideHelp && HelpFlag != nil { flagNames = append(flagNames, HelpFlag.Names()...) } for _, name := range flagNames { newDistance := jaroWin...
suggestFlag
104
129
suggestions.go
#FILE: cli-main/command.go ##CHUNK 1 hideHelp := cmd.hideHelp() if commandName != "" { subCmd := cmd.Command(commandName) if subCmd == nil { return "", err } flags = subCmd.Flags hideHelp = hideHelp || subCmd.HideHelp } suggestion := SuggestFlag(flags, fl, hideHelp) if len(suggestion) == 0 { retur...
cli-main
69
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) { if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) { return false, arguments } pos := len(arguments) - 1 lastArg := arguments[pos] if lastArg != completionFlag { return false, argume...
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) { if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) { return false, arguments } pos := len(arguments) - 1 lastArg := arguments[pos] if lastArg != completionFlag { return false, argume...
func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) { if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) { return false, arguments } pos := len(arguments) - 1 lastArg := arguments[pos] if lastArg != completionFlag { return false, argume...
checkShellCompleteFlag
459
481
help.go
#FILE: cli-main/command_run.go ##CHUNK 1 // arguments are parsed according to the Flag and Command // definitions and the matching Action functions are run. func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) { _, deferErr = cmd.run(ctx, osArgs) return } func (cmd *Command) run(ctx context...
cli-main
70
func checkCompletions(ctx context.Context, cmd *Command) bool { tracef("checking completions on command %[1]q", cmd.Name) if !cmd.Root().shellCompletion { tracef("completion not enabled skipping %[1]q", cmd.Name) return false } if argsArguments := cmd.Args(); argsArguments.Present() { name := argsArguments....
func checkCompletions(ctx context.Context, cmd *Command) bool { tracef("checking completions on command %[1]q", cmd.Name) if !cmd.Root().shellCompletion { tracef("completion not enabled skipping %[1]q", cmd.Name) return false } if argsArguments := cmd.Args(); argsArguments.Present() { name := argsArguments....
func checkCompletions(ctx context.Context, cmd *Command) bool { tracef("checking completions on command %[1]q", cmd.Name) if !cmd.Root().shellCompletion { tracef("completion not enabled skipping %[1]q", cmd.Name) return false } if argsArguments := cmd.Args(); argsArguments.Present() { name := argsArguments....
checkCompletions
483
507
help.go
#FILE: cli-main/command_run.go ##CHUNK 1 } } else { tracef("running ShowCommandHelp with %[1]q", cmd.Name) if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil { tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err) } } } return ctx, err } if c...
cli-main
71
func wrap(input string, offset int, wrapAt int) string { var ss []string lines := strings.Split(input, "\n") padding := strings.Repeat(" ", offset) for i, line := range lines { if line == "" { ss = append(ss, line) } else { wrapped := wrapLine(line, offset, wrapAt, padding) if i == 0 { ss = appe...
func wrap(input string, offset int, wrapAt int) string { var ss []string lines := strings.Split(input, "\n") padding := strings.Repeat(" ", offset) for i, line := range lines { if line == "" { ss = append(ss, line) } else { wrapped := wrapLine(line, offset, wrapAt, padding) if i == 0 { ss = appe...
func wrap(input string, offset int, wrapAt int) string { var ss []string lines := strings.Split(input, "\n") padding := strings.Repeat(" ", offset) for i, line := range lines { if line == "" { ss = append(ss, line) } else { wrapped := wrapLine(line, offset, wrapAt, padding) if i == 0 { ss = appe...
wrap
522
544
help.go
#FILE: cli-main/flag_test.go ##CHUNK 1 err := (&Command{ Name: "foobar", UseShortOptionHandling: true, Action: func(_ context.Context, cmd *Command) error { wasCalled = true if !cmd.Bool("i") { return fmt.Errorf("bool i not set") } if !cmd.Bool("t") { return fmt.Errorf("bo...
cli-main
72
func wrapLine(input string, offset int, wrapAt int, padding string) string { if wrapAt <= offset || len(input) <= wrapAt-offset { return input } lineWidth := wrapAt - offset words := strings.Fields(input) if len(words) == 0 { return input } wrapped := words[0] spaceLeft := lineWidth - len(wrapped) for _,...
func wrapLine(input string, offset int, wrapAt int, padding string) string { if wrapAt <= offset || len(input) <= wrapAt-offset { return input } lineWidth := wrapAt - offset words := strings.Fields(input) if len(words) == 0 { return input } wrapped := words[0] spaceLeft := lineWidth - len(wrapped) for _,...
func wrapLine(input string, offset int, wrapAt int, padding string) string { if wrapAt <= offset || len(input) <= wrapAt-offset { return input } lineWidth := wrapAt - offset words := strings.Fields(input) if len(words) == 0 { return input } wrapped := words[0] spaceLeft := lineWidth - len(wrapped) for _,...
wrapLine
546
570
help.go
#FILE: cli-main/docs.go ##CHUNK 1 break } } return "", usage } func prefixedNames(names []string, placeholder string) string { var prefixed string for i, name := range names { if name == "" { continue } prefixed += prefixFor(name) + name if placeholder != "" { prefixed += " " + placeholder } ...
cli-main
73
func lexicographicLess(i, j string) bool { iRunes := []rune(i) jRunes := []rune(j) lenShared := len(iRunes) if lenShared > len(jRunes) { lenShared = len(jRunes) } for index := 0; index < lenShared; index++ { ir := iRunes[index] jr := jRunes[index] if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr)...
func lexicographicLess(i, j string) bool { iRunes := []rune(i) jRunes := []rune(j) lenShared := len(iRunes) if lenShared > len(jRunes) { lenShared = len(jRunes) } for index := 0; index < lenShared; index++ { ir := iRunes[index] jr := jRunes[index] if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr)...
func lexicographicLess(i, j string) bool { iRunes := []rune(i) jRunes := []rune(j) lenShared := len(iRunes) if lenShared > len(jRunes) { lenShared = len(jRunes) } for index := 0; index < lenShared; index++ { ir := iRunes[index] jr := jRunes[index] if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr)...
lexicographicLess
5
28
sort.go
#FILE: cli-main/docs.go ##CHUNK 1 func unquoteUsage(usage string) (string, string) { for i := 0; i < len(usage); i++ { if usage[i] == '`' { for j := i + 1; j < len(usage); j++ { if usage[j] == '`' { name := usage[i+1 : j] usage = usage[:i] + name + usage[j+1:] return name, usage } } b...
cli-main
74
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) { const ( cliSourceFilePath = "./examples/example-cli/example-cli.go" cliBuiltFilePath = "./examples/example-cli/built-example" helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go" helloBuiltFileP...
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) { const ( cliSourceFilePath = "./examples/example-cli/example-cli.go" cliBuiltFilePath = "./examples/example-cli/built-example" helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go" helloBuiltFileP...
func checkBinarySizeActionFunc(ctx context.Context, cmd *cli.Command) (err error) { const ( cliSourceFilePath = "./examples/example-cli/example-cli.go" cliBuiltFilePath = "./examples/example-cli/built-example" helloSourceFilePath = "./examples/example-hello-world/example-hello-world.go" helloBuiltFileP...
checkBinarySizeActionFunc
408
488
scripts/build.go
#FILE: cli-main/help.go ##CHUNK 1 // bar1, b2 some other string here // // We want to offset the 2nd row usage by some amount so that everything // is aligned // // foo1, foo2, foo3 some string here // bar1, b2 some other string here // // to find that offset we find the length of all the rows and use the max...
cli-main
75
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) { args := []string{"build"} if tags != "" { args = append(args, []string{"-tags", tags}...) } args = append(args, []string{ "-o", builtPath, "-ldflags", "-s -w", sourcePath, }...) if err := runCmd(ctx, "go", args...); ...
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) { args := []string{"build"} if tags != "" { args = append(args, []string{"-tags", tags}...) } args = append(args, []string{ "-o", builtPath, "-ldflags", "-s -w", sourcePath, }...) if err := runCmd(ctx, "go", args...); ...
func getSize(ctx context.Context, sourcePath, builtPath, tags string) (int64, error) { args := []string{"build"} if tags != "" { args = append(args, []string{"-tags", tags}...) } args = append(args, []string{ "-o", builtPath, "-ldflags", "-s -w", sourcePath, }...) if err := runCmd(ctx, "go", args...); ...
getSize
652
677
scripts/build.go
#FILE: cli-main/command_run.go ##CHUNK 1 switch st { case stateSearchForToken: if token != "--" { args = append(args, token) } case stateSearchForString: // make sure string is not empty for _, t := range token { if !unicode.IsSpace(t) { args = append(args, token) } } ...
ollama-main
76
func humanDuration(d time.Duration) string { seconds := int(d.Seconds()) switch { case seconds < 1: return "Less than a second" case seconds == 1: return "1 second" case seconds < 60: return fmt.Sprintf("%d seconds", seconds) } minutes := int(d.Minutes()) switch { case minutes == 1: return "About a m...
func humanDuration(d time.Duration) string { seconds := int(d.Seconds()) switch { case seconds < 1: return "Less than a second" case seconds == 1: return "1 second" case seconds < 60: return fmt.Sprintf("%d seconds", seconds) } minutes := int(d.Minutes()) switch { case minutes == 1: return "About a m...
func humanDuration(d time.Duration) string { seconds := int(d.Seconds()) switch { case seconds < 1: return "Less than a second" case seconds == 1: return "1 second" case seconds < 60: return fmt.Sprintf("%d seconds", seconds) } minutes := int(d.Minutes()) switch { case minutes == 1: return "About a m...
humanDuration
11
46
format/time.go
#FILE: ollama-main/format/bytes.go ##CHUNK 1 switch { case value >= 10: return fmt.Sprintf("%d %s", int(value), unit) case value != math.Trunc(value): return fmt.Sprintf("%.1f %s", value, unit) default: return fmt.Sprintf("%d %s", int(value), unit) } } func HumanBytes2(b uint64) string { switch { case b ...
ollama-main
77
func fileDigestMap(path string) (map[string]string, error) { fl := make(map[string]string) fi, err := os.Stat(path) if err != nil { return nil, err } var files []string if fi.IsDir() { fs, err := filesForModel(path) if err != nil { return nil, err } for _, f := range fs { f, err := filepath.Eva...
func fileDigestMap(path string) (map[string]string, error) { fl := make(map[string]string) fi, err := os.Stat(path) if err != nil { return nil, err } var files []string if fi.IsDir() { fs, err := filesForModel(path) if err != nil { return nil, err } for _, f := range fs { f, err := filepath.Eva...
func fileDigestMap(path string) (map[string]string, error) { fl := make(map[string]string) fi, err := os.Stat(path) if err != nil { return nil, err } var files []string if fi.IsDir() { fs, err := filesForModel(path) if err != nil { return nil, err } for _, f := range fs { f, err := filepath.Eva...
fileDigestMap
141
199
parser/parser.go
#FILE: ollama-main/cmd/cmd.go ##CHUNK 1 if quantize != "" { req.Quantize = quantize } client, err := api.ClientFromEnvironment() if err != nil { return err } var g errgroup.Group g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1)) files := syncmap.NewSyncMap[string, string]() for f, digest := range req.Files { ...
ollama-main
78
func filesForModel(path string) ([]string, error) { detectContentType := func(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() var b bytes.Buffer b.Grow(512) if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) { return ""...
func filesForModel(path string) ([]string, error) { detectContentType := func(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() var b bytes.Buffer b.Grow(512) if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) { return ""...
func filesForModel(path string) ([]string, error) { detectContentType := func(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() var b bytes.Buffer b.Grow(512) if _, err := io.CopyN(&b, f, 512); err != nil && !errors.Is(err, io.EOF) { return ""...
filesForModel
220
309
parser/parser.go
#FILE: ollama-main/cmd/cmd.go ##CHUNK 1 if quantize != "" { req.Quantize = quantize } client, err := api.ClientFromEnvironment() if err != nil { return err } var g errgroup.Group g.SetLimit(max(runtime.GOMAXPROCS(0)-1, 1)) files := syncmap.NewSyncMap[string, string]() for f, digest := range req.Files { ...
ollama-main
79
func ParseFile(r io.Reader) (*Modelfile, error) { var cmd Command var curr state var currLine int = 1 var b bytes.Buffer var role string var f Modelfile tr := unicode.BOMOverride(unicode.UTF8.NewDecoder()) br := bufio.NewReader(transform.NewReader(r, tr)) for { r, _, err := br.ReadRune() if errors.Is(er...
func ParseFile(r io.Reader) (*Modelfile, error) { var cmd Command var curr state var currLine int = 1 var b bytes.Buffer var role string var f Modelfile tr := unicode.BOMOverride(unicode.UTF8.NewDecoder()) br := bufio.NewReader(transform.NewReader(r, tr)) for { r, _, err := br.ReadRune() if errors.Is(er...
func ParseFile(r io.Reader) (*Modelfile, error) { var cmd Command var curr state var currLine int = 1 var b bytes.Buffer var role string var f Modelfile tr := unicode.BOMOverride(unicode.UTF8.NewDecoder()) br := bufio.NewReader(transform.NewReader(r, tr)) for { r, _, err := br.ReadRune() if errors.Is(er...
ParseFile
362
491
parser/parser.go
#FILE: ollama-main/convert/tokenizer_spm.go ##CHUNK 1 switch st := m.AdditionalSpecialTokens.(type) { case []string: for _, s := range st { ast = append(ast, specialToken{Content: s}) } case []any: for _, s := range st { // marshal and unmarshal the object to get the special token tMap := s.(map[strin...
ollama-main
80
func parseRuneForState(r rune, cs state) (state, rune, error) { switch cs { case stateNil: switch { case r == '#': return stateComment, 0, nil case isSpace(r), isNewline(r): return stateNil, 0, nil default: return stateName, r, nil } case stateName: switch { case isAlpha(r): return stateNam...
func parseRuneForState(r rune, cs state) (state, rune, error) { switch cs { case stateNil: switch { case r == '#': return stateComment, 0, nil case isSpace(r), isNewline(r): return stateNil, 0, nil default: return stateName, r, nil } case stateName: switch { case isAlpha(r): return stateNam...
func parseRuneForState(r rune, cs state) (state, rune, error) { switch cs { case stateNil: switch { case r == '#': return stateComment, 0, nil case isSpace(r), isNewline(r): return stateNil, 0, nil default: return stateName, r, nil } case stateName: switch { case isAlpha(r): return stateNam...
parseRuneForState
493
550
parser/parser.go
#FILE: ollama-main/convert/reader_safetensors.go ##CHUNK 1 return 0, err } } switch st.Kind() { case tensorKindF32: return 0, binary.Write(w, binary.LittleEndian, f32s) case tensorKindF16: f16s := make([]uint16, len(f32s)) for i := range f32s { f16s[i] = float16.Fromfloat32(f32s[i]).Bits() } ret...
ollama-main
81
func unquote(s string) (string, bool) { // TODO: single quotes if len(s) >= 3 && s[:3] == `"""` { if len(s) >= 6 && s[len(s)-3:] == `"""` { return s[3 : len(s)-3], true } return "", false } if len(s) >= 1 && s[0] == '"' { if len(s) >= 2 && s[len(s)-1] == '"' { return s[1 : len(s)-1], true } ret...
func unquote(s string) (string, bool) { // TODO: single quotes if len(s) >= 3 && s[:3] == `"""` { if len(s) >= 6 && s[len(s)-3:] == `"""` { return s[3 : len(s)-3], true } return "", false } if len(s) >= 1 && s[0] == '"' { if len(s) >= 2 && s[len(s)-1] == '"' { return s[1 : len(s)-1], true } ret...
func unquote(s string) (string, bool) { // TODO: single quotes if len(s) >= 3 && s[:3] == `"""` { if len(s) >= 6 && s[len(s)-3:] == `"""` { return s[3 : len(s)-3], true } return "", false } if len(s) >= 1 && s[0] == '"' { if len(s) >= 2 && s[len(s)-1] == '"' { return s[1 : len(s)-1], true } ret...
unquote
564
583
parser/parser.go
#FILE: ollama-main/types/model/name.go ##CHUNK 1 return len(s) >= 1 && len(s) <= 350 case kindTag: return len(s) >= 1 && len(s) <= 80 default: return len(s) >= 1 && len(s) <= 80 } } func isValidPart(kind partKind, s string) bool { if !isValidLen(kind, s) { return false } for i := range s { if i == 0 { ...
ollama-main
82
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) { if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") { return filepath.Abs(path) } else if strings.HasPrefix(path, "~") { ...
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) { if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") { return filepath.Abs(path) } else if strings.HasPrefix(path, "~") { ...
func expandPathImpl(path, relativeDir string, currentUserFunc func() (*user.User, error), lookupUserFunc func(string) (*user.User, error)) (string, error) { if filepath.IsAbs(path) || strings.HasPrefix(path, "\\") || strings.HasPrefix(path, "/") { return filepath.Abs(path) } else if strings.HasPrefix(path, "~") { ...
expandPathImpl
614
649
parser/parser.go
#FILE: ollama-main/discover/amd_common.go ##CHUNK 1 pathEnv = "PATH" } paths := os.Getenv(pathEnv) for _, path := range filepath.SplitList(paths) { d, err := filepath.Abs(path) if err != nil { continue } if rocmLibUsable(d) { return d, nil } } // Well known location(s) for _, path := range Roc...
ollama-main
83
func Sign(ctx context.Context, bts []byte) (string, error) { keyPath, err := keyPath() if err != nil { return "", err } privateKeyFile, err := os.ReadFile(keyPath) if err != nil { slog.Info(fmt.Sprintf("Failed to load private key: %v", err)) return "", err } privateKey, err := ssh.ParsePrivateKey(private...
func Sign(ctx context.Context, bts []byte) (string, error) { keyPath, err := keyPath() if err != nil { return "", err } privateKeyFile, err := os.ReadFile(keyPath) if err != nil { slog.Info(fmt.Sprintf("Failed to load private key: %v", err)) return "", err } privateKey, err := ssh.ParsePrivateKey(private...
func Sign(ctx context.Context, bts []byte) (string, error) { keyPath, err := keyPath() if err != nil { return "", err } privateKeyFile, err := os.ReadFile(keyPath) if err != nil { slog.Info(fmt.Sprintf("Failed to load private key: %v", err)) return "", err } privateKey, err := ssh.ParsePrivateKey(private...
Sign
60
91
auth/auth.go
#FILE: ollama-main/server/internal/client/ollama/registry.go ##CHUNK 1 return "", fmt.Errorf("unsupported private key type: %T", key) } url := fmt.Sprintf("https://ollama.com?ts=%d", time.Now().Unix()) // Part 1: the checkData (e.g. the URL with a timestamp) // Part 2: the public key pubKeyShort, err := func()...
ollama-main
84
func GetModelArch(modelPath string) (string, error) { mp := C.CString(modelPath) defer C.free(unsafe.Pointer(mp)) gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)}) if gguf_ctx == nil { return "", errors.New("unable to load model file") } de...
func GetModelArch(modelPath string) (string, error) { mp := C.CString(modelPath) defer C.free(unsafe.Pointer(mp)) gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)}) if gguf_ctx == nil { return "", errors.New("unable to load model file") } de...
func GetModelArch(modelPath string) (string, error) { mp := C.CString(modelPath) defer C.free(unsafe.Pointer(mp)) gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)}) if gguf_ctx == nil { return "", errors.New("unable to load model file") } de...
GetModelArch
63
83
llama/llama.go
#FILE: ollama-main/parser/parser.go ##CHUNK 1 } defer bin.Close() hash := sha256.New() if _, err := io.Copy(hash, bin); err != nil { return "", err } return fmt.Sprintf("sha256:%x", hash.Sum(nil)), nil } func filesForModel(path string) ([]string, error) { detectContentType := func(path string) (string, error...
ollama-main
85
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) { cparams := C.llama_model_default_params() cparams.n_gpu_layers = C.int(params.NumGpuLayers) cparams.main_gpu = C.int32_t(params.MainGpu) cparams.use_mmap = C.bool(params.UseMmap) cparams.vocab_only = C.bool(params.VocabOnly) if len(pa...
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) { cparams := C.llama_model_default_params() cparams.n_gpu_layers = C.int(params.NumGpuLayers) cparams.main_gpu = C.int32_t(params.MainGpu) cparams.use_mmap = C.bool(params.UseMmap) cparams.vocab_only = C.bool(params.VocabOnly) if len(pa...
func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) { cparams := C.llama_model_default_params() cparams.n_gpu_layers = C.int(params.NumGpuLayers) cparams.main_gpu = C.int32_t(params.MainGpu) cparams.use_mmap = C.bool(params.UseMmap) cparams.vocab_only = C.bool(params.VocabOnly) if len(pa...
LoadModelFromFile
213
248
llama/llama.go
#FILE: ollama-main/server/images.go ##CHUNK 1 f, err := os.Open(fp) if err != nil { return nil, "", err } defer f.Close() sha256sum := sha256.New() var manifest Manifest if err := json.NewDecoder(io.TeeReader(f, sha256sum)).Decode(&manifest); err != nil { return nil, "", err } return &manifest, hex.Enc...
ollama-main
86
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) { b := Batch{ c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)), batchSize: batchSize, maxSeq: maxSeq, embedSize: embedSize, } // Check to see if any of the allocations in llama_batch_init() fail...
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) { b := Batch{ c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)), batchSize: batchSize, maxSeq: maxSeq, embedSize: embedSize, } // Check to see if any of the allocations in llama_batch_init() fail...
func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) { b := Batch{ c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)), batchSize: batchSize, maxSeq: maxSeq, embedSize: embedSize, } // Check to see if any of the allocations in llama_batch_init() fail...
NewBatch
312
331
llama/llama.go
#FILE: ollama-main/server/create_test.go ##CHUNK 1 files := map[string]string{ tt.filePath: model, "config.json": config, "tokenizer.json": tokenizer, } _, err := convertFromSafetensors(files, nil, false, func(resp api.ProgressResponse) {}) if (tt.wantErr == nil && err != nil) || (...
ollama-main
87
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) { var cparams C.struct_common_sampler_cparams cparams.top_k = C.int32_t(params.TopK) cparams.top_p = C.float(params.TopP) cparams.min_p = C.float(params.MinP) cparams.typical_p = C.float(params.TypicalP) cparams.temp = C.float(...
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) { var cparams C.struct_common_sampler_cparams cparams.top_k = C.int32_t(params.TopK) cparams.top_p = C.float(params.TopP) cparams.min_p = C.float(params.MinP) cparams.typical_p = C.float(params.TypicalP) cparams.temp = C.float(...
func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) { var cparams C.struct_common_sampler_cparams cparams.top_k = C.int32_t(params.TopK) cparams.top_p = C.float(params.TopP) cparams.min_p = C.float(params.MinP) cparams.typical_p = C.float(params.TypicalP) cparams.temp = C.float(...
NewSamplingContext
536
561
llama/llama.go
#FILE: ollama-main/sample/samplers.go ##CHUNK 1 minP: minP, temperature: temperature, grammar: grammar, } } type GrammarSampler struct { grammar *llama.Grammar } func NewGrammarSampler(model model.TextProcessor, grammarStr string) (*GrammarSampler, error) { vocabIds := make([]uint32, len(model.Voc...
ollama-main
88
func eat(s *Parser) (string, string, bool) { switch s.state { case thinkingState_LookingForOpening: trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace) if strings.HasPrefix(trimmed, s.OpeningTag) { after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag) after = strings.Tri...
func eat(s *Parser) (string, string, bool) { switch s.state { case thinkingState_LookingForOpening: trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace) if strings.HasPrefix(trimmed, s.OpeningTag) { after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag) after = strings.Tri...
func eat(s *Parser) (string, string, bool) { switch s.state { case thinkingState_LookingForOpening: trimmed := strings.TrimLeftFunc(s.acc.String(), unicode.IsSpace) if strings.HasPrefix(trimmed, s.OpeningTag) { after := strings.Join(strings.Split(trimmed, s.OpeningTag)[1:], s.OpeningTag) after = strings.Tri...
eat
76
159
thinking/parser.go
#FILE: ollama-main/model/sentencepiece.go ##CHUNK 1 // so they are buffered correctly by the runner instead // of being sent back to the api as "<0xEA>" if len(data) == 6 && strings.HasPrefix(data, "<0x") && strings.HasSuffix(data, ">") { byteVal, err := strconv.ParseUint(data[1:5], 0, 8) if err != nil { ...
ollama-main
89
func InferTags(t *template.Template) (string, string) { ancestors := []parse.Node{} openingTag := "" closingTag := "" enterFn := func(n parse.Node) bool { ancestors = append(ancestors, n) switch x := n.(type) { case *parse.FieldNode: if len(x.Ident) > 0 && x.Ident[0] == "Thinking" { var mostRecentRa...
func InferTags(t *template.Template) (string, string) { ancestors := []parse.Node{} openingTag := "" closingTag := "" enterFn := func(n parse.Node) bool { ancestors = append(ancestors, n) switch x := n.(type) { case *parse.FieldNode: if len(x.Ident) > 0 && x.Ident[0] == "Thinking" { var mostRecentRa...
func InferTags(t *template.Template) (string, string) { ancestors := []parse.Node{} openingTag := "" closingTag := "" enterFn := func(n parse.Node) bool { ancestors = append(ancestors, n) switch x := n.(type) { case *parse.FieldNode: if len(x.Ident) > 0 && x.Ident[0] == "Thinking" { var mostRecentRa...
InferTags
61
117
thinking/template.go
#FILE: ollama-main/llm/memory.go ##CHUNK 1 } else { overflow += gpuZeroOverhead } // For all the layers, find where they can fit on the GPU(s) for i := int(f.KV().BlockCount()) - 1; i >= 0; i-- { // Some models have inconsistent layer sizes if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok { layerSize = ...
ollama-main
90
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler { var rng *rand.Rand if seed != -1 { // PCG requires two parameters: sequence and stream // Use original seed for sequence sequence := uint64(seed) // Use golden ratio hash to generate statist...
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler { var rng *rand.Rand if seed != -1 { // PCG requires two parameters: sequence and stream // Use original seed for sequence sequence := uint64(seed) // Use golden ratio hash to generate statist...
func NewSampler(temperature float32, topK int, topP float32, minP float32, seed int, grammar *GrammarSampler) Sampler { var rng *rand.Rand if seed != -1 { // PCG requires two parameters: sequence and stream // Use original seed for sequence sequence := uint64(seed) // Use golden ratio hash to generate statist...
NewSampler
129
164
sample/samplers.go
#FILE: ollama-main/sample/samplers_benchmark_test.go ##CHUNK 1 for b.Loop() { sampler.Sample(logits) } }) } configs := []struct { name string temperature float32 topK int topP float32 minP float32 seed int }{ {"Greedy", 0, -1, 0, 0, -1}, {"Temperature",...
ollama-main
91
func Named(s string) (*named, error) { templates, err := templatesOnce() if err != nil { return nil, err } var template *named score := math.MaxInt for _, t := range templates { if s := levenshtein.ComputeDistance(s, t.Template); s < score { score = s template = t } } if score < 100 { return tem...
func Named(s string) (*named, error) { templates, err := templatesOnce() if err != nil { return nil, err } var template *named score := math.MaxInt for _, t := range templates { if s := levenshtein.ComputeDistance(s, t.Template); s < score { score = s template = t } } if score < 100 { return tem...
func Named(s string) (*named, error) { templates, err := templatesOnce() if err != nil { return nil, err } var template *named score := math.MaxInt for _, t := range templates { if s := levenshtein.ComputeDistance(s, t.Template); s < score { score = s template = t } } if score < 100 { return tem...
Named
70
90
template/template.go
#FILE: ollama-main/server/model.go ##CHUNK 1 layers = append(layers, &layerGGML{layer, nil}) } } return layers, nil } func detectChatTemplate(layers []*layerGGML) ([]*layerGGML, error) { for _, layer := range layers { if s := layer.GGML.KV().ChatTemplate(); s != "" { if t, err := template.Named(s); err !...
ollama-main
92
func New(modelPath string, params ml.BackendParams) (Model, error) { b, err := ml.NewBackend(modelPath, params) if err != nil { return nil, err } arch := b.Config().Architecture() f, ok := models[arch] if !ok { return nil, fmt.Errorf("unsupported model architecture %q", arch) } m, err := f(b.Config()) if...
func New(modelPath string, params ml.BackendParams) (Model, error) { b, err := ml.NewBackend(modelPath, params) if err != nil { return nil, err } arch := b.Config().Architecture() f, ok := models[arch] if !ok { return nil, fmt.Errorf("unsupported model architecture %q", arch) } m, err := f(b.Config()) if...
func New(modelPath string, params ml.BackendParams) (Model, error) { b, err := ml.NewBackend(modelPath, params) if err != nil { return nil, err } arch := b.Config().Architecture() f, ok := models[arch] if !ok { return nil, fmt.Errorf("unsupported model architecture %q", arch) } m, err := f(b.Config()) if...
New
100
122
model/model.go
#FILE: ollama-main/server/routes.go ##CHUNK 1 } func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) { name := model.ParseName(req.Model) if !name.IsValid() { return nil, ErrModelPathInvalid } name, err := getExistingName(name) if err != nil { return nil, err } m, err := GetModel(name.String()...
ollama-main
93
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) { if len(batch.Positions) != len(batch.Sequences) { return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences)) } if len(batch.Positions) < 1 { return nil...
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) { if len(batch.Positions) != len(batch.Sequences) { return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences)) } if len(batch.Positions) < 1 { return nil...
func Forward(ctx ml.Context, m Model, inputs []int32, batch input.Batch) (ml.Tensor, error) { if len(batch.Positions) != len(batch.Sequences) { return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences)) } if len(batch.Positions) < 1 { return nil...
Forward
280
307
model/model.go
#FILE: ollama-main/runner/ollamarunner/runner.go ##CHUNK 1 batch.Inputs = ctx.Input().FromIntSlice(batchInputs, len(batchInputs)) cache := s.model.Config().Cache if cache != nil { err := cache.StartForward(ctx, batch, true) if err != nil { return err } } t, err := s.model.Forward(ctx, batch) if err != ...
ollama-main
94
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel { slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5]) counter := map[int]int{} var maxTokenLen int for cnt := range vocab.Types { sw...
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel { slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5]) counter := map[int]int{} var maxTokenLen int for cnt := range vocab.Types { sw...
func NewSentencePieceModel(vocab *Vocabulary) SentencePieceModel { slog.Log(context.TODO(), logutil.LevelTrace, "Tokens", "num tokens", len(vocab.Values), "vals", vocab.Values[:5], "scores", vocab.Scores[:5], "types", vocab.Types[:5]) counter := map[int]int{} var maxTokenLen int for cnt := range vocab.Types { sw...
NewSentencePieceModel
26
49
model/sentencepiece.go
#FILE: ollama-main/model/bytepairencoding.go ##CHUNK 1 } } for _, merge := range merges { if len(merge.runes) > 0 { // TODO: handle the edge case where the rune isn't in the vocabulary if id := bpe.vocab.Encode(string(merge.runes)); id >= 0 { ids = append(ids, id) } } } } }...
ollama-main
95
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L...
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L...
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L...
New
32
58
model/models/mistral3/model.go
#FILE: ollama-main/model/models/qwen25vl/model.go ##CHUNK 1 BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokenizer....
ollama-main
96
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokeniz...
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokeniz...
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokeniz...
New
34
67
model/models/llama/model.go
#FILE: ollama-main/model/models/qwen2/model.go ##CHUNK 1 BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokenizer.ggm...
ollama-main
97
func New(c fs.Config) (model.Model, error) { m := Model{ SentencePieceModel: model.NewSentencePieceModel( &model.Vocabulary{ Values: c.Strings("tokenizer.ggml.tokens"), Scores: c.Floats("tokenizer.ggml.scores"), Types: c.Ints("tokenizer.ggml.token_type"), AddBOS: c.Bool("tokenizer.ggml.add_bos_to...
func New(c fs.Config) (model.Model, error) { m := Model{ SentencePieceModel: model.NewSentencePieceModel( &model.Vocabulary{ Values: c.Strings("tokenizer.ggml.tokens"), Scores: c.Floats("tokenizer.ggml.scores"), Types: c.Ints("tokenizer.ggml.token_type"), AddBOS: c.Bool("tokenizer.ggml.add_bos_to...
func New(c fs.Config) (model.Model, error) { m := Model{ SentencePieceModel: model.NewSentencePieceModel( &model.Vocabulary{ Values: c.Strings("tokenizer.ggml.tokens"), Scores: c.Floats("tokenizer.ggml.scores"), Types: c.Ints("tokenizer.ggml.token_type"), AddBOS: c.Bool("tokenizer.ggml.add_bos_to...
New
40
76
model/models/gemma2/model.go
#FILE: ollama-main/model/models/llama/model.go ##CHUNK 1 Types: c.Ints("tokenizer.ggml.token_type"), Merges: c.Strings("tokenizer.ggml.merges"), AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true), BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))}, AddEOS: c.Bool("tokenizer.ggml.add_eo...
ollama-main
98
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{L...
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{L...
func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{L...
New
33
62
model/models/llama4/model.go
#FILE: ollama-main/model/models/mllama/model.go ##CHUNK 1 ) func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S...
ollama-main
99
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokenizer.g...
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokenizer.g...
func New(c fs.Config) (model.Model, error) { m := &Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`), &model.Vocabulary{ Values: c.Strings("tokenizer.g...
New
28
53
model/models/qwen25vl/model.go
#FILE: ollama-main/model/models/mllama/model.go ##CHUNK 1 ) func New(c fs.Config) (model.Model, error) { m := Model{ BytePairEncoding: model.NewBytePairEncoding( c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S...