Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    TypeError
Message:      Couldn't cast array of type
struct<name: string, type: string, definition_content: string>
to
{'name': Value('string'), 'type': Value('string'), 'definitions': List({'type_definition': Value('string'), 'definition_location': {'uri': Value('string'), 'range': {'start': {'line': Value('int64'), 'character': Value('int64')}, 'end': {'line': Value('int64'), 'character': Value('int64')}}}})}
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1831, in _prepare_split_single
                  writer.write_table(table)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 644, in write_table
                  pa_table = table_cast(pa_table, self._schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2272, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2223, in cast_table_to_schema
                  arrays = [
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2224, in <listcomp>
                  cast_array_to_feature(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1795, in wrapper
                  return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1795, in <listcomp>
                  return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2001, in cast_array_to_feature
                  arrays = [
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2002, in <listcomp>
                  _c(array.field(name) if name in array_fields else null_array, subfeature)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1797, in wrapper
                  return func(array, *args, **kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2052, in cast_array_to_feature
                  casted_array_values = _c(array.values, feature.feature)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1797, in wrapper
                  return func(array, *args, **kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2092, in cast_array_to_feature
                  raise TypeError(f"Couldn't cast array of type\n{_short_str(array.type)}\nto\n{_short_str(feature)}")
              TypeError: Couldn't cast array of type
              struct<name: string, type: string, definition_content: string>
              to
              {'name': Value('string'), 'type': Value('string'), 'definitions': List({'type_definition': Value('string'), 'definition_location': {'uri': Value('string'), 'range': {'start': {'line': Value('int64'), 'character': Value('int64')}, 'end': {'line': Value('int64'), 'character': Value('int64')}}}})}
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1456, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1055, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 894, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 970, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1702, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1858, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

function_component
dict
function_name
string
focal_code
string
file_path
string
file_content
string
wrap_class
string
class_signature
string
struct_class
string
package_name
string
{ "name": "IsSubsequence", "signature": "func IsSubsequence(s string, t string) bool", "argument_definitions": [], "start_line": 9, "end_line": 34 }
IsSubsequence
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 }
Go-master/strings/issubsequence.go
// Checks if a given string is a subsequence of another string. // A subsequence of a given string is a string that can be derived from the given // string by deleting some or no characters without changing the order of the // remaining characters. (i.e., "dpr" is a subsequence of "depqr" while "drp" is not). // Author: sanjibgirics package strings // Returns true if s is subsequence of t, otherwise return false. func IsSubsequence(s string, t string) bool { if len(s) > len(t) { return false } if s == t { return true } if len(s) == 0 { return true } sIndex := 0 for tIndex := 0; tIndex < len(t); tIndex++ { if s[sIndex] == t[tIndex] { sIndex++ } if sIndex == len(s) { return true } } return false }
strings
{ "name": "IsIsogram", "signature": "func IsIsogram(text string, order IsogramOrder) (bool, error)", "argument_definitions": [ { "name": "order", "type": "IsogramOrder", "definitions": [ { "type_definition": "type IsogramOrder int", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/strings/isisogram.go", "range": { "start": { "line": 15, "character": 5 }, "end": { "line": 15, "character": 17 } } } } ] } ], "start_line": 33, "end_line": 70 }
IsIsogram
func IsIsogram(text string, order IsogramOrder) (bool, error) { if order < First || order > Third { return false, errors.New("Invalid isogram order provided") } text = strings.ToLower(text) text = strings.Join(strings.Fields(text), "") if hasDigit(text) || hasSymbol(text) { return false, errors.New("Cannot contain numbers or symbols") } letters := make(map[string]int) for _, c := range text { l := string(c) if _, ok := letters[l]; ok { letters[l] += 1 if letters[l] > 3 { return false, nil } continue } letters[l] = 1 } mapVals := make(map[int]bool) for _, v := range letters { mapVals[v] = true } if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 { return true, nil } return false, nil }
Go-master/strings/isisogram.go
// Checks if a given string is an isogram. // A first-order isogram is a word in which no letter of the alphabet occurs more than once. // A second-order isogram is a word in which each letter appears twice. // A third-order isogram is a word in which each letter appears three times. // wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms // Author: M3talM0nk3y package strings import ( "errors" "regexp" "strings" ) type IsogramOrder int const ( First IsogramOrder = iota + 1 Second Third ) func hasDigit(text string) bool { re := regexp.MustCompile(`\d`) return re.MatchString(text) } func hasSymbol(text string) bool { re := regexp.MustCompile(`[-!@#$%^&*()+]`) return re.MatchString(text) } func IsIsogram(text string, order IsogramOrder) (bool, error) { if order < First || order > Third { return false, errors.New("Invalid isogram order provided") } text = strings.ToLower(text) text = strings.Join(strings.Fields(text), "") if hasDigit(text) || hasSymbol(text) { return false, errors.New("Cannot contain numbers or symbols") } letters := make(map[string]int) for _, c := range text { l := string(c) if _, ok := letters[l]; ok { letters[l] += 1 if letters[l] > 3 { return false, nil } continue } letters[l] = 1 } mapVals := make(map[int]bool) for _, v := range letters { mapVals[v] = true } if _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 { return true, nil } return false, nil }
strings
{ "name": "GeneticString", "signature": "func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error)", "argument_definitions": [ { "name": "conf", "type": "Conf", "definitions": [ { "type_definition": "type Conf struct {\n\t// Maximum size of the population.\n\t// Bigger could be faster but more memory expensive.\n\tPopulationNum int\n\n\t// Number of elements selected in every generation for evolution\n\t// the selection takes. Place from the best to the worst of that\n\t// generation must be smaller than PopulationNum.\n\tSelectionNum int\n\n\t// Probability that an element of a generation can mutate changing one of\n\t// its genes this guarantees that all genes will be used during evolution.\n\tMutationProb float64\n\n\t// Enables debugging output to the console.\ntype Conf struct {\n\t// Maximum size of the population.\n\t// Bigger could be faster but more memory expensive.\n\tPopulationNum int\n\n\t// Number of elements selected in every generation for evolution\n\t// the selection takes. Place from the best to the worst of that\n\t// generation must be smaller than PopulationNum.\n\tSelectionNum int\n\n\t// Probability that an element of a generation can mutate changing one of\n\t// its genes this guarantees that all genes will be used during evolution.\n\tMutationProb float64\n\n\t// Enables debugging output to the console.\n\tDebug bool\n}", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/strings/genetic/genetic.go", "range": { "start": { "line": 31, "character": 5 }, "end": { "line": 31, "character": 9 } } } } ] } ], "start_line": 70, "end_line": 196 }
GeneticString
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 populationNum < selectionNum { return nil, errors.New("populationNum must be bigger than selectionNum") } mutationProb := conf.MutationProb if mutationProb == .0 { mutationProb = .4 } debug := conf.Debug // Just a seed to improve randomness required by the algorithm rnd := rand.New(rand.NewSource(time.Now().UnixNano())) // Verify that the target contains no genes besides the ones inside genes variable. for position, r := range target { invalid := true for _, n := range charmap { if n == r { invalid = false } } if invalid { message := fmt.Sprintf("character not available in charmap at position: %v", position) return nil, errors.New(message) } } // Generate random starting population pop := make([]PopulationItem, populationNum) for i := 0; i < populationNum; i++ { key := "" for x := 0; x < utf8.RuneCountInString(target); x++ { choice := rnd.Intn(len(charmap)) key += string(charmap[choice]) } pop[i] = PopulationItem{key, 0} } // Just some logs to know what the algorithms is doing gen, generatedPop := 0, 0 // This loop will end when we will find a perfect match for our target for { gen++ generatedPop += len(pop) // Random population created now it's time to evaluate for i, item := range pop { pop[i].Value = 0 itemKey, targetRune := []rune(item.Key), []rune(target) for x := 0; x < len(target); x++ { if itemKey[x] == targetRune[x] { pop[i].Value++ } } pop[i].Value = pop[i].Value / float64(len(targetRune)) } sort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value }) // Check if there is a matching evolution if pop[0].Key == target { break } // Print the best resultPrint the Best result every 10 generations // just to know that the algorithm is working if debug && gen%10 == 0 { fmt.Println("Generation:", strconv.Itoa(gen), "Analyzed:", generatedPop, "Best:", pop[0]) } // Generate a new population vector keeping some of the best evolutions // Keeping this avoid regression of evolution var popChildren []PopulationItem popChildren = append(popChildren, pop[0:int(selectionNum/3)]...) // This is Selection for i := 0; i < int(selectionNum); i++ { parent1 := pop[i] // Generate more child proportionally to the fitness score nChild := (parent1.Value * 100) + 1 if nChild >= 10 { nChild = 10 } for x := 0.0; x < nChild; x++ { parent2 := pop[rnd.Intn(selectionNum)] // Crossover split := rnd.Intn(utf8.RuneCountInString(target)) child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...) child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...) // Clean fitness value // Mutate if rnd.Float64() < mutationProb { child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))] } if rnd.Float64() < mutationProb { child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))] } // Push into 'popChildren' popChildren = append(popChildren, PopulationItem{string(child1), 0}) popChildren = append(popChildren, PopulationItem{string(child2), 0}) // Check if the population has already reached the maximum value and if so, // break the cycle. If this check is disabled the algorithm will take // forever to compute large strings but will also calculate small string in // a lot fewer generationsΓΉ if len(popChildren) >= selectionNum { break } } } pop = popChildren } return &Result{gen, generatedPop, pop[0]}, nil }
Go-master/strings/genetic/genetic.go
// Package genetic provides functions to work with strings // using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm // // Author: D4rkia package genetic import ( "errors" "fmt" "math/rand" "sort" "strconv" "time" "unicode/utf8" ) // Population item represent a single step in the evolution process. // One can think of population item as a single species. // Key stands for the actual data entity of the species, which is a string // in current implementation. Key can be interpreted as species DNA. // Value shows how close this species to the desired target, where 1 means, // that species DNA equals to the targeted one, 0 for no matchings in the DNA. // // **Note** In the current implementation species DNA length is suppose to be // equal to the target length for algorithm to work. type PopulationItem struct { Key string Value float64 } // Conf stands for configurations set provided to GeneticString function. type Conf struct { // Maximum size of the population. // Bigger could be faster but more memory expensive. PopulationNum int // Number of elements selected in every generation for evolution // the selection takes. Place from the best to the worst of that // generation must be smaller than PopulationNum. SelectionNum int // Probability that an element of a generation can mutate changing one of // its genes this guarantees that all genes will be used during evolution. MutationProb float64 // Enables debugging output to the console. Debug bool } // Result structure contains generation process statistics, as well as the // best resulted population item. type Result struct { // Number of generations steps performed. Generation int // Number of generated population items. Analyzed int // Result of generation with the best Value. Best PopulationItem } // GeneticString generates PopulationItem based on the imputed target // string, and a set of possible runes to build a string with. In order // to optimise string generation additional configurations can be provided // with Conf instance. Empty instance of Conf (&Conf{}) can be provided, // then default values would be set. // // Link to the same algorithm implemented in python: // https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py 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 populationNum < selectionNum { return nil, errors.New("populationNum must be bigger than selectionNum") } mutationProb := conf.MutationProb if mutationProb == .0 { mutationProb = .4 } debug := conf.Debug // Just a seed to improve randomness required by the algorithm rnd := rand.New(rand.NewSource(time.Now().UnixNano())) // Verify that the target contains no genes besides the ones inside genes variable. for position, r := range target { invalid := true for _, n := range charmap { if n == r { invalid = false } } if invalid { message := fmt.Sprintf("character not available in charmap at position: %v", position) return nil, errors.New(message) } } // Generate random starting population pop := make([]PopulationItem, populationNum) for i := 0; i < populationNum; i++ { key := "" for x := 0; x < utf8.RuneCountInString(target); x++ { choice := rnd.Intn(len(charmap)) key += string(charmap[choice]) } pop[i] = PopulationItem{key, 0} } // Just some logs to know what the algorithms is doing gen, generatedPop := 0, 0 // This loop will end when we will find a perfect match for our target for { gen++ generatedPop += len(pop) // Random population created now it's time to evaluate for i, item := range pop { pop[i].Value = 0 itemKey, targetRune := []rune(item.Key), []rune(target) for x := 0; x < len(target); x++ { if itemKey[x] == targetRune[x] { pop[i].Value++ } } pop[i].Value = pop[i].Value / float64(len(targetRune)) } sort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value }) // Check if there is a matching evolution if pop[0].Key == target { break } // Print the best resultPrint the Best result every 10 generations // just to know that the algorithm is working if debug && gen%10 == 0 { fmt.Println("Generation:", strconv.Itoa(gen), "Analyzed:", generatedPop, "Best:", pop[0]) } // Generate a new population vector keeping some of the best evolutions // Keeping this avoid regression of evolution var popChildren []PopulationItem popChildren = append(popChildren, pop[0:int(selectionNum/3)]...) // This is Selection for i := 0; i < int(selectionNum); i++ { parent1 := pop[i] // Generate more child proportionally to the fitness score nChild := (parent1.Value * 100) + 1 if nChild >= 10 { nChild = 10 } for x := 0.0; x < nChild; x++ { parent2 := pop[rnd.Intn(selectionNum)] // Crossover split := rnd.Intn(utf8.RuneCountInString(target)) child1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...) child2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...) // Clean fitness value // Mutate if rnd.Float64() < mutationProb { child1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))] } if rnd.Float64() < mutationProb { child2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))] } // Push into 'popChildren' popChildren = append(popChildren, PopulationItem{string(child1), 0}) popChildren = append(popChildren, PopulationItem{string(child2), 0}) // Check if the population has already reached the maximum value and if so, // break the cycle. If this check is disabled the algorithm will take // forever to compute large strings but will also calculate small string in // a lot fewer generationsΓΉ if len(popChildren) >= selectionNum { break } } } pop = popChildren } return &Result{gen, generatedPop, pop[0]}, nil }
genetic
{ "name": "Distance", "signature": "func Distance(str1, str2 string, icost, scost, dcost int) int", "argument_definitions": [], "start_line": 9, "end_line": 41 }
Distance
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] { row2[j] = row1[j-1] } else { ins := row2[j-1] + icost del := row1[j] + dcost sub := row1[j-1] + scost if ins < del && ins < sub { row2[j] = ins } else if del < sub { row2[j] = del } else { row2[j] = sub } } } row1, row2 = row2, row1 } return row1[len(row1)-1] }
Go-master/strings/levenshtein/levenshteindistance.go
/* This algorithm calculates the distance between two strings. Parameters: two strings to compare and weights of insertion, substitution and deletion. Output: distance between both strings */ package levenshtein // Distance Function that gives Levenshtein Distance func Distance(str1, str2 string, icost, scost, dcost 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] { row2[j] = row1[j-1] } else { ins := row2[j-1] + icost del := row1[j] + dcost sub := row1[j-1] + scost if ins < del && ins < sub { row2[j] = ins } else if del < sub { row2[j] = del } else { row2[j] = sub } } } row1, row2 = row2, row1 } return row1[len(row1)-1] }
levenshtein
{ "name": "LongestPalindrome", "signature": "func LongestPalindrome(s string) string", "argument_definitions": [], "start_line": 36, "end_line": 62 }
LongestPalindrome
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[i-b[i]] == boundaries[i+b[i]] { b[i] += 1 } if maxLen < b[i]-1 { maxLen = b[i] - 1 maxCenterSize = i } if b[i]+i-1 > k { k = b[i] + i - 1 index = i } } return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen]) }
Go-master/strings/manacher/longestpalindrome.go
// longestpalindrome.go // description: Manacher's algorithm (Longest palindromic substring) // details: // An algorithm with linear running time that allows you to get compressed information about all palindromic substrings of a given string. - [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_substring) // author(s) [red_byte](https://github.com/i-redbyte) // see longestpalindrome_test.go package manacher import ( "github.com/TheAlgorithms/Go/math/min" "strings" ) func makeBoundaries(s string) string { var result strings.Builder result.WriteRune('#') for _, ch := range s { if ch != ' ' { //ignore space as palindrome character result.WriteRune(ch) } result.WriteRune('#') } return result.String() } func nextBoundary(s string) string { var result strings.Builder for _, ch := range s { if ch != '#' { result.WriteRune(ch) } } return result.String() } 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[i-b[i]] == boundaries[i+b[i]] { b[i] += 1 } if maxLen < b[i]-1 { maxLen = b[i] - 1 maxCenterSize = i } if b[i]+i-1 > k { k = b[i] + i - 1 index = i } } return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen]) }
manacher
{ "name": "horspool", "signature": "func horspool(t, p []rune) (int, error)", "argument_definitions": [], "start_line": 15, "end_line": 36 }
horspool
func horspool(t, p []rune) (int, error) { shiftMap := computeShiftMap(t, p) pos := 0 for pos <= len(t)-len(p) { if isMatch(pos, t, p) { return pos, nil } if pos+len(p) >= len(t) { // because the remaining length of the input string // is the same as the length of the pattern // and it does not match the pattern // it is impossible to find the pattern break } // because of the check above // t[pos+len(p)] is defined pos += shiftMap[t[pos+len(p)]] } return -1, ErrNotFound }
Go-master/strings/horspool/horspool.go
// Implementation of the // [Boyer–Moore–Horspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm) package horspool import "errors" var ErrNotFound = errors.New("pattern was not found in the input string") func Horspool(t, p string) (int, error) { // in order to handle multy-byte character properly // the input is converted into rune arrays return horspool([]rune(t), []rune(p)) } func horspool(t, p []rune) (int, error) { shiftMap := computeShiftMap(t, p) pos := 0 for pos <= len(t)-len(p) { if isMatch(pos, t, p) { return pos, nil } if pos+len(p) >= len(t) { // because the remaining length of the input string // is the same as the length of the pattern // and it does not match the pattern // it is impossible to find the pattern break } // because of the check above // t[pos+len(p)] is defined pos += shiftMap[t[pos+len(p)]] } return -1, ErrNotFound } // Checks if the array p matches the subarray of t starting at pos. // Note that backward iteration. // There are [other](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm#Tuning_the_comparison_loop) // approaches possible. func isMatch(pos int, t, p []rune) bool { j := len(p) for j > 0 && t[pos+j-1] == p[j-1] { j-- } return j == 0 } func computeShiftMap(t, p []rune) (res map[rune]int) { res = make(map[rune]int) for _, tCode := range t { res[tCode] = len(p) } for i, pCode := range p { res[pCode] = len(p) - i } return res }
horspool
{ "name": "ConstructTrie", "signature": "func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int)", "argument_definitions": [], "start_line": 3, "end_line": 35 }
ConstructTrie
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]) && GetTransition(current, p[i][j], trie) != -1 { current = GetTransition(current, p[i][j], trie) j++ } for j < len(p[i]) { stateIsTerminal = BoolArrayCapUp(stateIsTerminal) CreateNewState(state, trie) stateIsTerminal[state] = false CreateTransition(current, p[i][j], state, trie) current = state j++ state++ } if stateIsTerminal[current] { newArray := IntArrayCapUp(f[current]) newArray[len(newArray)-1] = i f[current] = newArray // F(Current) <- F(Current) union {i} } else { stateIsTerminal[current] = true f[current] = []int{i} // F(Current) <- {i} } } return trie, stateIsTerminal, f }
Go-master/strings/ahocorasick/shared.go
package ahocorasick // ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings. func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) { trie = make(map[int]map[uint8]int) stateIsTerminal = make([]bool, 1) f = make(map[int][]int) state := 1 CreateNewState(0, trie) for i := 0; i < len(p); i++ { current := 0 j := 0 for j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 { current = GetTransition(current, p[i][j], trie) j++ } for j < len(p[i]) { stateIsTerminal = BoolArrayCapUp(stateIsTerminal) CreateNewState(state, trie) stateIsTerminal[state] = false CreateTransition(current, p[i][j], state, trie) current = state j++ state++ } if stateIsTerminal[current] { newArray := IntArrayCapUp(f[current]) newArray[len(newArray)-1] = i f[current] = newArray // F(Current) <- F(Current) union {i} } else { stateIsTerminal[current] = true f[current] = []int{i} // F(Current) <- {i} } } return trie, stateIsTerminal, f } // Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise. func Contains(s []int, e int) bool { for _, a := range s { if a == e { return true } } return false } // GetWord Function that returns word found in text 't' at position range 'begin' to 'end'. func GetWord(begin, end int, t string) string { for end >= len(t) { return "" } d := make([]uint8, end-begin+1) for j, i := 0, begin; i <= end; i, j = i+1, j+1 { d[j] = t[i] } return string(d) } // ComputeAlphabet Function that returns string of all the possible characters in given patterns. func ComputeAlphabet(p []string) (s string) { s = p[0] for i := 1; i < len(p); i++ { s = s + p[i] } return s } // IntArrayCapUp Dynamically increases an array size of int's by 1. func IntArrayCapUp(old []int) (new []int) { new = make([]int, cap(old)+1) copy(new, old) //copy(dst,src) // old = new return new } // BoolArrayCapUp Dynamically increases an array size of bool's by 1. func BoolArrayCapUp(old []bool) (new []bool) { new = make([]bool, cap(old)+1) copy(new, old) // old = new return new } // ArrayUnion Concats two arrays of int's into one. func ArrayUnion(to, from []int) (concat []int) { concat = to for i := range from { if !Contains(concat, from[i]) { concat = IntArrayCapUp(concat) concat[len(concat)-1] = from[i] } } return concat } // GetParent Function that finds the first previous state of a state and returns it. // Used for trie where there is only one parent. func GetParent(state int, at map[int]map[uint8]int) (uint8, int) { for beginState, transitions := range at { for c, endState := range transitions { if endState == state { return c, beginState } } } return 0, 0 //unreachable } // CreateNewState Automaton function for creating a new state 'state'. func CreateNewState(state int, at map[int]map[uint8]int) { at[state] = make(map[uint8]int) } // CreateTransition Creates a transition for function Οƒ(state,letter) = end. func CreateTransition(fromState int, overChar uint8, toState int, at map[int]map[uint8]int) { at[fromState][overChar] = toState } // GetTransition Returns ending state for transition Οƒ(fromState,overChar), '-1' if there is none. func GetTransition(fromState int, overChar uint8, at map[int]map[uint8]int) (toState int) { if !StateExists(fromState, at) { return -1 } toState, ok := at[fromState][overChar] if !ok { return -1 } return toState } // StateExists Checks if state 'state' exists. Returns 'true' if it does, 'false' otherwise. func StateExists(state int, at map[int]map[uint8]int) bool { _, ok := at[state] if !ok || state == -1 || at[state] == nil { return false } return true }
ahocorasick
{ "name": "Advanced", "signature": "func Advanced(t string, p []string) Result", "argument_definitions": [], "start_line": 9, "end_line": 42 }
Advanced
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 := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ resultOccurrences, } }
Go-master/strings/ahocorasick/advancedahocorasick.go
package ahocorasick import ( "fmt" "time" ) // Advanced Function performing the Advanced Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func Advanced(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f := BuildExtendedAc(p) current := 0 for pos := 0; pos < len(t); pos++ { if GetTransition(current, t[pos], ac) != -1 { current = GetTransition(current, t[pos], ac) } else { current = 0 } _, ok := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ 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([]int, len(stateIsTerminal)) //supply function i := 0 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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 p for j := range a { if GetTransition(i, a[j], acToReturn) == -1 { CreateTransition(i, a[j], i, acToReturn) } } for current := 1; current < len(stateIsTerminal); current++ { for j := range a { if GetTransition(current, a[j], acToReturn) == -1 { CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn) } } } return acToReturn, f }
ahocorasick
{ "name": "BuildExtendedAc", "signature": "func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int)", "argument_definitions": [], "start_line": 45, "end_line": 81 }
BuildExtendedAc
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(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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 p for j := range a { if GetTransition(i, a[j], acToReturn) == -1 { CreateTransition(i, a[j], i, acToReturn) } } for current := 1; current < len(stateIsTerminal); current++ { for j := range a { if GetTransition(current, a[j], acToReturn) == -1 { CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn) } } } return acToReturn, f }
Go-master/strings/ahocorasick/advancedahocorasick.go
package ahocorasick import ( "fmt" "time" ) // Advanced Function performing the Advanced Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func Advanced(t string, p []string) Result { startTime := time.Now() occurrences := make(map[int][]int) ac, f := BuildExtendedAc(p) current := 0 for pos := 0; pos < len(t); pos++ { if GetTransition(current, t[pos], ac) != -1 { current = GetTransition(current, t[pos], ac) } else { current = 0 } _, ok := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ 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([]int, len(stateIsTerminal)) //supply function i := 0 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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 p for j := range a { if GetTransition(i, a[j], acToReturn) == -1 { CreateTransition(i, a[j], i, acToReturn) } } for current := 1; current < len(stateIsTerminal); current++ { for j := range a { if GetTransition(current, a[j], acToReturn) == -1 { CreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn) } } } return acToReturn, f }
ahocorasick
{ "name": "AhoCorasick", "signature": "func AhoCorasick(t string, p []string) Result", "argument_definitions": [], "start_line": 14, "end_line": 50 }
AhoCorasick
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) != -1 { current = GetTransition(current, t[pos], ac) fmt.Printf(" (Continue) \n") } else { current = 0 } _, ok := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ resultOccurrences, } }
Go-master/strings/ahocorasick/ahocorasick.go
package ahocorasick import ( "fmt" "time" ) // Result structure to hold occurrences type Result struct { occurrences map[string][]int } // AhoCorasick Function performing the Basic Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func AhoCorasick(t string, p []string) Result { startTime := 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) != -1 { current = GetTransition(current, t[pos], ac) fmt.Printf(" (Continue) \n") } else { current = 0 } _, ok := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ resultOccurrences, } } // 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 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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? } } return acToReturn, f, s }
ahocorasick
{ "name": "BuildAc", "signature": "func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int)", "argument_definitions": [], "start_line": 53, "end_line": 76 }
BuildAc
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(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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? } } return acToReturn, f, s }
Go-master/strings/ahocorasick/ahocorasick.go
package ahocorasick import ( "fmt" "time" ) // Result structure to hold occurrences type Result struct { occurrences map[string][]int } // AhoCorasick Function performing the Basic Aho-Corasick algorithm. // Finds and prints occurrences of each pattern. func AhoCorasick(t string, p []string) Result { startTime := 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) != -1 { current = GetTransition(current, t[pos], ac) fmt.Printf(" (Continue) \n") } else { current = 0 } _, ok := f[current] 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 occurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1 } } } } elapsed := time.Since(startTime) fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds()) var resultOccurrences = make(map[string][]int) for key, value := range occurrences { resultOccurrences[p[key]] = value } return Result{ resultOccurrences, } } // 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 //root of acTrie acToReturn = acTrie s[i] = -1 for current := 1; current < len(stateIsTerminal); current++ { o, parent := GetParent(current, acTrie) down := s[parent] for StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 { down = s[down] } if StateExists(down, acToReturn) { s[current] = GetTransition(down, o, acToReturn) if stateIsTerminal[s[current]] { 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? } } return acToReturn, f, s }
ahocorasick
{ "name": "HuffTree", "signature": "func HuffTree(listfreq []SymbolFreq) (*Node, error)", "argument_definitions": [ { "name": "listfreq", "type": "[]SymbolFreq", "definitions": [ { "type_definition": "type SymbolFreq struct {\n\tSymbol rune\ntype SymbolFreq struct {\n\tSymbol rune\n\tFreq int\n}", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/compression/huffmancoding.go", "range": { "start": { "line": 26, "character": 5 }, "end": { "line": 26, "character": 15 } } } } ] } ], "start_line": 34, "end_line": 56 }
HuffTree
func HuffTree(listfreq []SymbolFreq) (*Node, error) { if len(listfreq) < 1 { return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs") } q1 := make([]Node, len(listfreq)) q2 := make([]Node, 0, len(listfreq)) for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq} } //loop invariant: q1, q2 are ordered by increasing weights for len(q1)+len(q2) > 1 { var node1, node2 Node node1, q1, q2 = least(q1, q2) node2, q1, q2 = least(q1, q2) node := Node{left: &node1, right: &node2, symbol: -1, weight: node1.weight + node2.weight} q2 = append(q2, node) } if len(q1) == 1 { // returns the remaining node in q1, q2 return &q1[0], nil } return &q2[0], nil }
Go-master/compression/huffmancoding.go
// huffman.go // description: Implements Huffman compression, encoding and decoding // details: // We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding. // It assumes that the list of symbol-frequencies is sorted. // time complexity: O(n) // space complexity: O(n) // author(s) [pedromsrocha](https://github.com/pedromsrocha) // see also huffmancoding_test.go package compression import "fmt" // A Node of an Huffman tree, which can either be a leaf or an internal node. // Each node has a weight. // A leaf node has an associated symbol, but no children (i.e., left == right == nil). // A parent node has a left and right child and no symbol (i.e., symbol == -1). type Node struct { left *Node right *Node symbol rune weight int } // A SymbolFreq is a pair of a symbol and its associated frequency. type SymbolFreq struct { Symbol rune Freq int } // HuffTree returns the root Node of the Huffman tree by compressing listfreq. // The compression produces the most optimal code lengths, provided listfreq is ordered, // i.e.: listfreq[i] <= listfreq[j], whenever i < j. func HuffTree(listfreq []SymbolFreq) (*Node, error) { if len(listfreq) < 1 { return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs") } q1 := make([]Node, len(listfreq)) q2 := make([]Node, 0, len(listfreq)) for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq} } //loop invariant: q1, q2 are ordered by increasing weights for len(q1)+len(q2) > 1 { var node1, node2 Node node1, q1, q2 = least(q1, q2) node2, q1, q2 = least(q1, q2) node := Node{left: &node1, right: &node2, symbol: -1, weight: node1.weight + node2.weight} q2 = append(q2, node) } if len(q1) == 1 { // returns the remaining node in q1, q2 return &q1[0], nil } return &q2[0], nil } // least removes the node with lowest weight from q1, q2. // It returns the node with lowest weight and the slices q1, q2 after the update. func least(q1 []Node, q2 []Node) (Node, []Node, []Node) { if len(q1) == 0 { return q2[0], q1, q2[1:] } if len(q2) == 0 { return q1[0], q1[1:], q2 } if q1[0].weight <= q2[0].weight { return q1[0], q1[1:], q2 } return q2[0], q1, q2[1:] } // HuffEncoding recursively traverses the Huffman tree pointed by node to obtain // the map codes, that associates a rune with a slice of booleans. // Each code is prefixed by prefix and left and right children are labelled with // the booleans false and true, respectively. func HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) { if node.symbol != -1 { //base case codes[node.symbol] = prefix return } // inductive step prefixLeft := make([]bool, len(prefix)) copy(prefixLeft, prefix) prefixLeft = append(prefixLeft, false) HuffEncoding(node.left, prefixLeft, codes) prefixRight := make([]bool, len(prefix)) copy(prefixRight, prefix) prefixRight = append(prefixRight, true) HuffEncoding(node.right, prefixRight, codes) } // HuffEncode encodes the string in by applying the mapping defined by codes. func HuffEncode(codes map[rune][]bool, in string) []bool { out := make([]bool, 0) for _, s := range in { out = append(out, codes[s]...) } return out } // HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root. // current stores the current node of the traversing algorithm. // out stores the current decoded string. func HuffDecode(root, current *Node, in []bool, out string) string { if current.symbol != -1 { out += string(current.symbol) return HuffDecode(root, root, in, out) } if len(in) == 0 { return out } if in[0] { return HuffDecode(root, current.right, in[1:], out) } return HuffDecode(root, current.left, in[1:], out) }
compression
{ "name": "DepthFirstSearchHelper", "signature": "func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool)", "argument_definitions": [], "start_line": 26, "end_line": 56 }
DepthFirstSearchHelper
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 { stack = stack[:len(stack)-1] } else { stack = stack[:len(stack)-1] } for i := 0; i < len(edges[now]); i++ { if edges[now][i] && NotExist(i, stack) { stack = append(stack, i) } edges[now][i] = false edges[i][now] = false } if route[len(route)-1] == end { return route, true } } if showroute { return route, false } else { return nil, false } }
Go-master/graph/depthfirstsearch.go
// depthfirstsearch.go // description: this file contains the implementation of the depth first search algorithm // details: Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking. // time complexity: O(n) // space complexity: O(n) package graph func GetIdx(target int, nodes []int) int { for i := 0; i < len(nodes); i++ { if nodes[i] == target { return i } } return -1 } func NotExist(target int, slice []int) bool { for i := 0; i < len(slice); i++ { if slice[i] == target { return false } } return true } 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 { stack = stack[:len(stack)-1] } else { stack = stack[:len(stack)-1] } for i := 0; i < len(edges[now]); i++ { if edges[now][i] && NotExist(i, stack) { stack = append(stack, i) } edges[now][i] = false edges[i][now] = false } if route[len(route)-1] == end { return route, true } } if showroute { return route, false } else { return nil, false } } func DepthFirstSearch(start, end int, nodes []int, edges [][]bool) ([]int, bool) { return DepthFirstSearchHelper(start, end, nodes, edges, false) } // func main() { // nodes := []int{ // 1, 2, 3, 4, 5, 6, // } // /* // sample graph // β‘ -β‘‘ // | | // β‘’-β‘£-β‘€-β‘₯ // */ // edges := [][]bool{ // {false, true, true, false, false, false}, // {true, false, false, true, false, false}, // {true, false, false, true, false, false}, // {false, true, true, false, true, false}, // {false, false, false, true, false, true}, // {false, false, false, false, true, false}, // } // start := 1 // end := 6 // route, _ := dfs(start, end, nodes, edges) // fmt.Println(route) // }
graph
{ "name": "EdmondKarp", "signature": "func EdmondKarp(graph WeightedGraph, source int, sink int) float64", "argument_definitions": [ { "name": "graph", "type": "WeightedGraph", "definitions": [ { "type_definition": "type WeightedGraph [][]float64", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/graph/floydwarshall.go", "range": { "start": { "line": 10, "character": 5 }, "end": { "line": 10, "character": 18 } } } } ] } ], "start_line": 42, "end_line": 92 }
EdmondKarp
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 { // Check graph emptiness if len(graph) == 0 { return 0.0 } // Check correct dimensions of the graph slice for i := 0; i < len(graph); i++ { if len(graph[i]) != len(graph) { return 0.0 } } rGraph := make(WeightedGraph, len(graph)) for i := 0; i < len(graph); i++ { rGraph[i] = make([]float64, len(graph)) } // Init the residual graph with the same capacities as the original graph copy(rGraph, graph) maxFlow := 0.0 for { parent := FindPath(rGraph, source, sink) if parent == nil { break } // Finding the max flow over the path returned by BFS // i.e. finding minimum residual capacity amonth the path edges pathFlow := math.MaxFloat64 for v := sink; v != source; v = parent[v] { u := parent[v] if rGraph[u][v] < pathFlow { pathFlow = rGraph[u][v] } } // update residual capacities of the edges and // reverse edges along the path for v := sink; v != source; v = parent[v] { u := parent[v] rGraph[u][v] -= pathFlow rGraph[v][u] += pathFlow } // Update the total flow found so far maxFlow += pathFlow } return maxFlow }
Go-master/graph/edmondkarp.go
// Edmond-Karp algorithm is an implementation of the Ford-Fulkerson method // to compute max-flow between a pair of source-sink vertices in a weighted graph // It uses BFS (Breadth First Search) to find the residual paths // Time Complexity: O(V * E^2) where V is the number of vertices and E is the number of edges // Space Complexity: O(V + E) Because we keep residual graph in size of the original graph // Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. 2009. Introduction to Algorithms, Third Edition (3rd. ed.). The MIT Press. package graph import ( "math" ) // Returns a mapping of vertices as path, if there is any from source to sink // Otherwise, returns nil func FindPath(rGraph WeightedGraph, source int, sink int) map[int]int { queue := make([]int, 0) marked := make([]bool, len(rGraph)) marked[source] = true queue = append(queue, source) parent := make(map[int]int) // BFS loop with saving the path found for len(queue) > 0 { v := queue[0] queue = queue[1:] for i := 0; i < len(rGraph[v]); i++ { if !marked[i] && rGraph[v][i] > 0 { parent[i] = v // Terminate the BFS, if we reach to sink if i == sink { return parent } marked[i] = true queue = append(queue, i) } } } // source and sink are not in the same connected component return nil } func EdmondKarp(graph WeightedGraph, source int, sink int) float64 { // Check graph emptiness if len(graph) == 0 { return 0.0 } // Check correct dimensions of the graph slice for i := 0; i < len(graph); i++ { if len(graph[i]) != len(graph) { return 0.0 } } rGraph := make(WeightedGraph, len(graph)) for i := 0; i < len(graph); i++ { rGraph[i] = make([]float64, len(graph)) } // Init the residual graph with the same capacities as the original graph copy(rGraph, graph) maxFlow := 0.0 for { parent := FindPath(rGraph, source, sink) if parent == nil { break } // Finding the max flow over the path returned by BFS // i.e. finding minimum residual capacity amonth the path edges pathFlow := math.MaxFloat64 for v := sink; v != source; v = parent[v] { u := parent[v] if rGraph[u][v] < pathFlow { pathFlow = rGraph[u][v] } } // update residual capacities of the edges and // reverse edges along the path for v := sink; v != source; v = parent[v] { u := parent[v] rGraph[u][v] -= pathFlow rGraph[v][u] += pathFlow } // Update the total flow found so far maxFlow += pathFlow } return maxFlow }
graph
{ "name": "BreadthFirstSearch", "signature": "func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int)", "argument_definitions": [], "start_line": 8, "end_line": 27 }
BreadthFirstSearch
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 discovered[i] == 0 && edges[v][i] > 0 { if i == end { return true, discovered[v] } discovered[i] = discovered[v] + 1 queue = append(queue, i) } } } return false, 0 }
Go-master/graph/breadthfirstsearch.go
package graph // BreadthFirstSearch is an algorithm for traversing and searching graph data structures. // It starts at an arbitrary node of a graph, and explores all of the neighbor nodes // at the present depth prior to moving on to the nodes at the next depth level. // Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node. // Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node. // reference: https://en.wikipedia.org/wiki/Breadth-first_search func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) { queue := make([]int, 0) 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 discovered[i] == 0 && edges[v][i] > 0 { if i == end { return true, discovered[v] } discovered[i] = discovered[v] + 1 queue = append(queue, i) } } } return false, 0 }
graph
{ "name": "FloydWarshall", "signature": "func FloydWarshall(graph WeightedGraph) WeightedGraph", "argument_definitions": [ { "name": "graph", "type": "WeightedGraph", "definitions": [ { "type_definition": "type WeightedGraph [][]float64", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/graph/floydwarshall.go", "range": { "start": { "line": 10, "character": 5 }, "end": { "line": 10, "character": 18 } } } } ] } ], "start_line": 16, "end_line": 54 }
FloydWarshall
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 } } numVertices := len(graph) // Initializing result matrix and filling it up with same values as given graph result := make(WeightedGraph, numVertices) for i := 0; i < numVertices; i++ { result[i] = make([]float64, numVertices) for j := 0; j < numVertices; j++ { result[i][j] = graph[i][j] } } // Running over the result matrix and following the algorithm for k := 0; k < numVertices; k++ { for i := 0; i < numVertices; i++ { for j := 0; j < numVertices; j++ { // If there is a less costly path from i to j node, remembering it if result[i][j] > result[i][k]+result[k][j] { result[i][j] = result[i][k] + result[k][j] } } } } return result }
Go-master/graph/floydwarshall.go
// Floyd-Warshall algorithm // time complexity: O(V^3) where V is the number of vertices in the graph // space complexity: O(V^2) where V is the number of vertices in the graph // https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm package graph import "math" // WeightedGraph defining matrix to use 2d array easier type WeightedGraph [][]float64 // Defining maximum value. If two vertices share this value, it means they are not connected var Inf = math.Inf(1) // FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm 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 } } numVertices := len(graph) // Initializing result matrix and filling it up with same values as given graph result := make(WeightedGraph, numVertices) for i := 0; i < numVertices; i++ { result[i] = make([]float64, numVertices) for j := 0; j < numVertices; j++ { result[i][j] = graph[i][j] } } // Running over the result matrix and following the algorithm for k := 0; k < numVertices; k++ { for i := 0; i < numVertices; i++ { for j := 0; j < numVertices; j++ { // If there is a less costly path from i to j node, remembering it if result[i][j] > result[i][k]+result[k][j] { result[i][j] = result[i][k] + result[k][j] } } } } return result }
graph
{ "name": "KruskalMST", "signature": "func KruskalMST(n int, edges []Edge) ([]Edge, int)", "argument_definitions": [ { "name": "edges", "type": "[]Edge", "definitions": [ { "type_definition": "type Edge struct {\n\tStart Vertex\n\tEnd Vertex\ntype Edge struct {\n\tStart Vertex\n\tEnd Vertex\n\tWeight int\n}", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/graph/kruskal.go", "range": { "start": { "line": 16, "character": 5 }, "end": { "line": 16, "character": 9 } } } } ] } ], "start_line": 22, "end_line": 50 }
KruskalMST
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.SliceStable(edges, func(i, j int) bool { return edges[i].Weight < edges[j].Weight }) // Iterate through the sorted edges for _, edge := range edges { // Check if adding the current edge forms a cycle or not if u.Find(int(edge.Start)) != u.Find(int(edge.End)) { // Add the edge to the minimum spanning tree mst = append(mst, edge) // Add the weight of the edge to the total cost cost += edge.Weight // Merge the sets containing the start and end vertices of the current edge u.Union(int(edge.Start), int(edge.End)) } } // Return the minimum spanning tree and its total cost return mst, cost }
Go-master/graph/kruskal.go
// KRUSKAL'S ALGORITHM // Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorithm/ // Reference: Union Find Algorithm: https://www.scaler.com/topics/data-structures/disjoint-set/ // Author: Author: Mugdha Behere[https://github.com/MugdhaBehere] // Worst Case Time Complexity: O(E log E), where E is the number of edges. // Worst Case Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges. // see kruskal.go, kruskal_test.go package graph import ( "sort" ) type Vertex int type Edge struct { Start Vertex End Vertex Weight int } 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.SliceStable(edges, func(i, j int) bool { return edges[i].Weight < edges[j].Weight }) // Iterate through the sorted edges for _, edge := range edges { // Check if adding the current edge forms a cycle or not if u.Find(int(edge.Start)) != u.Find(int(edge.End)) { // Add the edge to the minimum spanning tree mst = append(mst, edge) // Add the weight of the edge to the total cost cost += edge.Weight // Merge the sets containing the start and end vertices of the current edge u.Union(int(edge.Start), int(edge.End)) } } // Return the minimum spanning tree and its total cost return mst, cost }
graph
{ "name": "NewTree", "signature": "func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree)", "argument_definitions": [ { "name": "edges", "type": "[]TreeEdge", "definitions": [ { "type_definition": "type TreeEdge struct {\n\tfrom int\ntype TreeEdge struct {\n\tfrom int\n\tto int\n}", "definition_location": { "uri": "file:///home/dung/Study/Code/Cross_test_gen/new_benchmark/LSP/go_lang/repo/Go-master/graph/lowestcommonancestor.go", "range": { "start": { "line": 13, "character": 5 }, "end": { "line": 13, "character": 13 } } } } ] } ], "start_line": 85, "end_line": 107 }
NewTree
func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) { tree = new(Tree) tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0 tree.depth = make([]int, numbersVertex) tree.dad = make([]int, numbersVertex) for (1 << tree.MAXLOG) <= numbersVertex { (tree.MAXLOG) += 1 } (tree.MAXLOG) += 1 tree.jump = make([][]int, tree.MAXLOG) for j := 0; j < tree.MAXLOG; j++ { tree.jump[j] = make([]int, numbersVertex) } tree.edges = make([][]int, numbersVertex) for _, e := range edges { tree.addEdge(e.from, e.to) } return tree }
Go-master/graph/lowestcommonancestor.go
// lowestcommonancestor.go // description: Implementation of Lowest common ancestor (LCA) algorithm. // detail: // Let `T` be a tree. The LCA of `u` and `v` in T is the shared ancestor of `u` and `v` // that is located farthest from the root. // time complexity: O(n log n) where n is the number of vertices in the tree // space complexity: O(n log n) where n is the number of vertices in the tree // references: [cp-algorithms](https://cp-algorithms.com/graph/lca_binary_lifting.html) // author(s) [Dat](https://github.com/datbeohbbh) // see lowestcommonancestor_test.go for a test implementation. package graph type TreeEdge struct { from int to int } type ITree interface { dfs(int, int) addEdge(int, int) GetDepth(int) int GetDad(int) int GetLCA(int, int) int } type Tree struct { numbersVertex int root int MAXLOG int depth []int dad []int jump [][]int edges [][]int } func (tree *Tree) addEdge(u, v int) { tree.edges[u] = append(tree.edges[u], v) tree.edges[v] = append(tree.edges[v], u) } func (tree *Tree) dfs(u, par int) { tree.jump[0][u] = par tree.dad[u] = par for _, v := range tree.edges[u] { if v != par { tree.depth[v] = tree.depth[u] + 1 tree.dfs(v, u) } } } func (tree *Tree) GetDepth(u int) int { return tree.depth[u] } func (tree *Tree) GetDad(u int) int { return tree.dad[u] } func (tree *Tree) GetLCA(u, v int) int { if tree.GetDepth(u) < tree.GetDepth(v) { u, v = v, u } for j := tree.MAXLOG - 1; j >= 0; j-- { if tree.GetDepth(tree.jump[j][u]) >= tree.GetDepth(v) { u = tree.jump[j][u] } } if u == v { return u } for j := tree.MAXLOG - 1; j >= 0; j-- { if tree.jump[j][u] != tree.jump[j][v] { u = tree.jump[j][u] v = tree.jump[j][v] } } return tree.jump[0][u] } func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) { tree = new(Tree) tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0 tree.depth = make([]int, numbersVertex) tree.dad = make([]int, numbersVertex) for (1 << tree.MAXLOG) <= numbersVertex { (tree.MAXLOG) += 1 } (tree.MAXLOG) += 1 tree.jump = make([][]int, tree.MAXLOG) for j := 0; j < tree.MAXLOG; j++ { tree.jump[j] = make([]int, numbersVertex) } tree.edges = make([][]int, numbersVertex) for _, e := range edges { tree.addEdge(e.from, e.to) } return tree } // For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. // Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. // These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time. func LowestCommonAncestor(tree *Tree) { // call dfs to compute depth from the root to each node and the parent of each node. tree.dfs(tree.root, tree.root) // compute jump[j][u] for j := 1; j < tree.MAXLOG; j++ { for u := 0; u < tree.numbersVertex; u++ { tree.jump[j][u] = tree.jump[j-1][tree.jump[j-1][u]] } } }
graph
{ "name": "Sign", "signature": "func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int)", "argument_definitions": [ { "name": "x", "type": "big.Int", "definitions": [ { "type_definition": "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs nat // absolute value of the integer\n}", "definition_location": { "uri": "file:///usr/lib/go-1.22/src/math/big/int.go", "range": { "start": { "line": 32, "character": 5 }, "end": { "line": 32, "character": 8 } } } } ] } ], "start_line": 124, "end_line": 148 }
Sign
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) { // 1. Choose a random integer k from the range [1, q-1] k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1))) if err != nil { panic(err) } // 2. Compute r = (g^k mod p) mod q r = new(big.Int).Exp(g, k, p) r.Mod(r, q) // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message s = new(big.Int).ModInverse(k, q) // k^-1 mod q s.Mul( s, new(big.Int).Add( // (H(m) + x*r) h, new(big.Int).Mul(x, r), ), ) s.Mod(s, q) // mod q return r, s }
Go-master/cipher/dsa/dsa.go
/* dsa.go description: DSA encryption and decryption including key generation details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm) author(s): [ddaniel27](https://github.com/ddaniel27) */ package dsa import ( "crypto/rand" "io" "math/big" ) const ( numMRTests = 64 // Number of Miller-Rabin tests L = 1024 // Number of bits in p N = 160 // Number of bits in q ) type ( // parameters represents the DSA parameters parameters struct { P, Q, G *big.Int } // dsa represents the DSA dsa struct { parameters pubKey *big.Int // public key (y) privKey *big.Int // private key (x) } ) // New creates a new DSA instance func New() *dsa { d := new(dsa) d.dsaParameterGeneration() d.keyGen() return d } // Parameter generation for DSA // 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256) // 2. Choose a N-bit prime q // 3. Choose a L-bit prime p such that p-1 is a multiple of q // 4. Choose an integer h randomly from the range [2, p-2] // 5. Compute g = h^((p-1)/q) mod p // 6. Return (p, q, g) func (dsa *dsa) dsaParameterGeneration() { var err error p, q, bigInt := new(big.Int), new(big.Int), new(big.Int) one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2) pBytes := make([]byte, L/8) // GPLoop is a label for the loop // We use this loop to change the prime q if we don't find a prime p GPLoop: for { // 2. Choose a N-bit prime q q, err = rand.Prime(rand.Reader, N) if err != nil { panic(err) } for i := 0; i < 4*L; i++ { // 3. Choose a L-bit prime p such that p-1 is a multiple of q // In this case we generate a random number of L bits if _, err := io.ReadFull(rand.Reader, pBytes); err != nil { panic(err) } // This are the minimum conditions for p being a possible prime pBytes[len(pBytes)-1] |= 1 // p is odd pBytes[0] |= 0x80 // p has the highest bit set p.SetBytes(pBytes) // Instead of using (p-1)%q == 0 // We ensure that p-1 is a multiple of q and validates if p is prime bigInt.Mod(p, q) bigInt.Sub(bigInt, one) p.Sub(p, bigInt) if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits continue } dsa.P = p dsa.Q = q break GPLoop } } // 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2 // 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1 pm1 := new(big.Int).Sub(p, one) for g.Cmp(one) == 0 { g.Exp(h, new(big.Int).Div(pm1, q), p) h.Add(h, one) } dsa.G = g } // keyGen is key generation for DSA // 1. Choose a random integer x from the range [1, q-1] // 2. Compute y = g^x mod p func (dsa *dsa) keyGen() { // 1. Choose a random integer x from the range [1, q-1] x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1))) if err != nil { panic(err) } dsa.privKey = x // 2. Compute y = g^x mod p dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P) } // Sign is signature generation for DSA // 1. Choose a random integer k from the range [1, q-1] // 2. Compute r = (g^k mod p) mod q // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) { // 1. Choose a random integer k from the range [1, q-1] k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1))) if err != nil { panic(err) } // 2. Compute r = (g^k mod p) mod q r = new(big.Int).Exp(g, k, p) r.Mod(r, q) // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message s = new(big.Int).ModInverse(k, q) // k^-1 mod q s.Mul( s, new(big.Int).Add( // (H(m) + x*r) h, new(big.Int).Mul(x, r), ), ) s.Mod(s, q) // mod q return r, s } // Verify is signature verification for DSA // 1. Compute w = s^-1 mod q // 2. Compute u1 = (H(m) * w) mod q // 3. Compute u2 = (r * w) mod q // 4. Compute v = ((g^u1 * y^u2) mod p) mod q // 5. If v == r, the signature is valid func Verify(m []byte, r, s, p, q, g, y *big.Int) bool { // 1. Compute w = s^-1 mod q w := new(big.Int).ModInverse(s, q) // 2. Compute u1 = (H(m) * w) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message u1 := new(big.Int).Mul(h, w) u1.Mod(u1, q) // 3. Compute u2 = (r * w) mod q u2 := new(big.Int).Mul(r, w) u2.Mod(u2, q) // 4. Compute v = ((g^u1 * y^u2) mod p) mod q v := new(big.Int).Exp(g, u1, p) v.Mul( v, new(big.Int).Exp(y, u2, p), ) v.Mod(v, p) v.Mod(v, q) // 5. If v == r, the signature is valid return v.Cmp(r) == 0 } // GetPublicKey returns the public key (y) func (dsa *dsa) GetPublicKey() *big.Int { return dsa.pubKey } // GetParameters returns the DSA parameters (p, q, g) func (dsa *dsa) GetParameters() parameters { return dsa.parameters } // GetPrivateKey returns the private Key (x) func (dsa *dsa) GetPrivateKey() *big.Int { return dsa.privKey }
dsa
{ "name": "Verify", "signature": "func Verify(m []byte, r, s, p, q, g, y *big.Int) bool", "argument_definitions": [ { "name": "y", "type": "big.Int", "definitions": [ { "type_definition": "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs nat // absolute value of the integer\n}", "definition_location": { "uri": "file:///usr/lib/go-1.22/src/math/big/int.go", "range": { "start": { "line": 32, "character": 5 }, "end": { "line": 32, "character": 8 } } } } ] } ], "start_line": 156, "end_line": 180 }
Verify
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool { // 1. Compute w = s^-1 mod q w := new(big.Int).ModInverse(s, q) // 2. Compute u1 = (H(m) * w) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message u1 := new(big.Int).Mul(h, w) u1.Mod(u1, q) // 3. Compute u2 = (r * w) mod q u2 := new(big.Int).Mul(r, w) u2.Mod(u2, q) // 4. Compute v = ((g^u1 * y^u2) mod p) mod q v := new(big.Int).Exp(g, u1, p) v.Mul( v, new(big.Int).Exp(y, u2, p), ) v.Mod(v, p) v.Mod(v, q) // 5. If v == r, the signature is valid return v.Cmp(r) == 0 }
Go-master/cipher/dsa/dsa.go
/* dsa.go description: DSA encryption and decryption including key generation details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm) author(s): [ddaniel27](https://github.com/ddaniel27) */ package dsa import ( "crypto/rand" "io" "math/big" ) const ( numMRTests = 64 // Number of Miller-Rabin tests L = 1024 // Number of bits in p N = 160 // Number of bits in q ) type ( // parameters represents the DSA parameters parameters struct { P, Q, G *big.Int } // dsa represents the DSA dsa struct { parameters pubKey *big.Int // public key (y) privKey *big.Int // private key (x) } ) // New creates a new DSA instance func New() *dsa { d := new(dsa) d.dsaParameterGeneration() d.keyGen() return d } // Parameter generation for DSA // 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256) // 2. Choose a N-bit prime q // 3. Choose a L-bit prime p such that p-1 is a multiple of q // 4. Choose an integer h randomly from the range [2, p-2] // 5. Compute g = h^((p-1)/q) mod p // 6. Return (p, q, g) func (dsa *dsa) dsaParameterGeneration() { var err error p, q, bigInt := new(big.Int), new(big.Int), new(big.Int) one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2) pBytes := make([]byte, L/8) // GPLoop is a label for the loop // We use this loop to change the prime q if we don't find a prime p GPLoop: for { // 2. Choose a N-bit prime q q, err = rand.Prime(rand.Reader, N) if err != nil { panic(err) } for i := 0; i < 4*L; i++ { // 3. Choose a L-bit prime p such that p-1 is a multiple of q // In this case we generate a random number of L bits if _, err := io.ReadFull(rand.Reader, pBytes); err != nil { panic(err) } // This are the minimum conditions for p being a possible prime pBytes[len(pBytes)-1] |= 1 // p is odd pBytes[0] |= 0x80 // p has the highest bit set p.SetBytes(pBytes) // Instead of using (p-1)%q == 0 // We ensure that p-1 is a multiple of q and validates if p is prime bigInt.Mod(p, q) bigInt.Sub(bigInt, one) p.Sub(p, bigInt) if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits continue } dsa.P = p dsa.Q = q break GPLoop } } // 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2 // 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1 pm1 := new(big.Int).Sub(p, one) for g.Cmp(one) == 0 { g.Exp(h, new(big.Int).Div(pm1, q), p) h.Add(h, one) } dsa.G = g } // keyGen is key generation for DSA // 1. Choose a random integer x from the range [1, q-1] // 2. Compute y = g^x mod p func (dsa *dsa) keyGen() { // 1. Choose a random integer x from the range [1, q-1] x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1))) if err != nil { panic(err) } dsa.privKey = x // 2. Compute y = g^x mod p dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P) } // Sign is signature generation for DSA // 1. Choose a random integer k from the range [1, q-1] // 2. Compute r = (g^k mod p) mod q // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) { // 1. Choose a random integer k from the range [1, q-1] k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1))) if err != nil { panic(err) } // 2. Compute r = (g^k mod p) mod q r = new(big.Int).Exp(g, k, p) r.Mod(r, q) // 3. Compute s = (k^-1 * (H(m) + x*r)) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message s = new(big.Int).ModInverse(k, q) // k^-1 mod q s.Mul( s, new(big.Int).Add( // (H(m) + x*r) h, new(big.Int).Mul(x, r), ), ) s.Mod(s, q) // mod q return r, s } // Verify is signature verification for DSA // 1. Compute w = s^-1 mod q // 2. Compute u1 = (H(m) * w) mod q // 3. Compute u2 = (r * w) mod q // 4. Compute v = ((g^u1 * y^u2) mod p) mod q // 5. If v == r, the signature is valid func Verify(m []byte, r, s, p, q, g, y *big.Int) bool { // 1. Compute w = s^-1 mod q w := new(big.Int).ModInverse(s, q) // 2. Compute u1 = (H(m) * w) mod q h := new(big.Int).SetBytes(m) // This should be the hash of the message u1 := new(big.Int).Mul(h, w) u1.Mod(u1, q) // 3. Compute u2 = (r * w) mod q u2 := new(big.Int).Mul(r, w) u2.Mod(u2, q) // 4. Compute v = ((g^u1 * y^u2) mod p) mod q v := new(big.Int).Exp(g, u1, p) v.Mul( v, new(big.Int).Exp(y, u2, p), ) v.Mod(v, p) v.Mod(v, q) // 5. If v == r, the signature is valid return v.Cmp(r) == 0 } // GetPublicKey returns the public key (y) func (dsa *dsa) GetPublicKey() *big.Int { return dsa.pubKey } // GetParameters returns the DSA parameters (p, q, g) func (dsa *dsa) GetParameters() parameters { return dsa.parameters } // GetPrivateKey returns the private Key (x) func (dsa *dsa) GetPrivateKey() *big.Int { return dsa.privKey }
dsa
{ "name": "Encrypt", "signature": "func Encrypt(text string, rails int) string", "argument_definitions": [], "start_line": 12, "end_line": 48 }
Encrypt
func Encrypt(text string, rails int) string { if rails == 1 { return text } // Create a matrix for the rail fence pattern matrix := make([][]rune, rails) for i := range matrix { matrix[i] = make([]rune, len(text)) } // Fill the matrix dirDown := false row, col := 0, 0 for _, char := range text { if row == 0 || row == rails-1 { dirDown = !dirDown } matrix[row][col] = char col++ if dirDown { row++ } else { row-- } } var result strings.Builder for _, line := range matrix { for _, char := range line { if char != 0 { result.WriteRune(char) } } } return result.String() }
Go-master/cipher/railfence/railfence.go
// railfence.go // description: Rail Fence Cipher // details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext. // time complexity: O(n) // space complexity: O(n) // ref: https://en.wikipedia.org/wiki/Rail_fence_cipher package railfence import ( "strings" ) func Encrypt(text string, rails int) string { if rails == 1 { return text } // Create a matrix for the rail fence pattern matrix := make([][]rune, rails) for i := range matrix { matrix[i] = make([]rune, len(text)) } // Fill the matrix dirDown := false row, col := 0, 0 for _, char := range text { if row == 0 || row == rails-1 { dirDown = !dirDown } matrix[row][col] = char col++ if dirDown { row++ } else { row-- } } var result strings.Builder for _, line := range matrix { for _, char := range line { if char != 0 { result.WriteRune(char) } } } return result.String() } func Decrypt(cipherText string, rails int) string { if rails == 1 || rails >= len(cipherText) { return cipherText } // Placeholder for the decrypted message decrypted := make([]rune, len(cipherText)) // Calculate the zigzag pattern and place characters accordingly index := 0 for rail := 0; rail < rails; rail++ { position := rail down := true // Direction flag for position < len(cipherText) { decrypted[position] = rune(cipherText[index]) index++ // Determine the next position based on the current rail and direction if rail == 0 || rail == rails-1 { position += 2 * (rails - 1) } else if down { position += 2 * (rails - 1 - rail) down = false } else { position += 2 * rail down = true } } } return string(decrypted) }
railfence
{ "name": "Decrypt", "signature": "func Decrypt(cipherText string, rails int) string", "argument_definitions": [], "start_line": 49, "end_line": 80 }
Decrypt
func Decrypt(cipherText string, rails int) string { if rails == 1 || rails >= len(cipherText) { return cipherText } // Placeholder for the decrypted message decrypted := make([]rune, len(cipherText)) // Calculate the zigzag pattern and place characters accordingly index := 0 for rail := 0; rail < rails; rail++ { position := rail down := true // Direction flag for position < len(cipherText) { decrypted[position] = rune(cipherText[index]) index++ // Determine the next position based on the current rail and direction if rail == 0 || rail == rails-1 { position += 2 * (rails - 1) } else if down { position += 2 * (rails - 1 - rail) down = false } else { position += 2 * rail down = true } } } return string(decrypted) }
Go-master/cipher/railfence/railfence.go
// railfence.go // description: Rail Fence Cipher // details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext. // time complexity: O(n) // space complexity: O(n) // ref: https://en.wikipedia.org/wiki/Rail_fence_cipher package railfence import ( "strings" ) func Encrypt(text string, rails int) string { if rails == 1 { return text } // Create a matrix for the rail fence pattern matrix := make([][]rune, rails) for i := range matrix { matrix[i] = make([]rune, len(text)) } // Fill the matrix dirDown := false row, col := 0, 0 for _, char := range text { if row == 0 || row == rails-1 { dirDown = !dirDown } matrix[row][col] = char col++ if dirDown { row++ } else { row-- } } var result strings.Builder for _, line := range matrix { for _, char := range line { if char != 0 { result.WriteRune(char) } } } return result.String() } func Decrypt(cipherText string, rails int) string { if rails == 1 || rails >= len(cipherText) { return cipherText } // Placeholder for the decrypted message decrypted := make([]rune, len(cipherText)) // Calculate the zigzag pattern and place characters accordingly index := 0 for rail := 0; rail < rails; rail++ { position := rail down := true // Direction flag for position < len(cipherText) { decrypted[position] = rune(cipherText[index]) index++ // Determine the next position based on the current rail and direction if rail == 0 || rail == rails-1 { position += 2 * (rails - 1) } else if down { position += 2 * (rails - 1 - rail) down = false } else { position += 2 * rail down = true } } } return string(decrypted) }
railfence
{ "name": "Encrypt", "signature": "func Encrypt(text []rune, keyWord string) ([]rune, error)", "argument_definitions": [], "start_line": 52, "end_line": 80 }
Encrypt
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 encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder) } n := textLength % keyLength for i := 0; i < keyLength-n; i++ { text = append(text, placeholder) } textLength = len(text) var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[key[j]-1] = text[i+j] } result = append(result, transposition...) } return result, nil }
Go-master/cipher/transposition/transposition.go
// transposition.go // description: Transposition cipher // details: // Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes a permutation of the plaintext [Transposition cipher](https://en.wikipedia.org/wiki/Transposition_cipher) // time complexity: O(n) // space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see transposition_test.go package transposition import ( "errors" "fmt" "sort" "strings" ) var ErrNoTextToEncrypt = errors.New("no text to encrypt") var ErrKeyMissing = errors.New("missing Key") const placeholder = ' ' func getKey(keyWord string) []int { keyWord = strings.ToLower(keyWord) word := []rune(keyWord) var sortedWord = make([]rune, len(word)) copy(sortedWord, word) sort.Slice(sortedWord, func(i, j int) bool { return sortedWord[i] < sortedWord[j] }) usedLettersMap := make(map[rune]int) wordLength := len(word) resultKey := make([]int, wordLength) for i := 0; i < wordLength; i++ { char := word[i] numberOfUsage := usedLettersMap[char] resultKey[i] = getIndex(sortedWord, char) + numberOfUsage + 1 //+1 -so that indexing does not start at 0 numberOfUsage++ usedLettersMap[char] = numberOfUsage } return resultKey } func getIndex(wordSet []rune, subString rune) int { n := len(wordSet) for i := 0; i < n; i++ { if wordSet[i] == subString { return i } } return 0 } 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 encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder) } n := textLength % keyLength for i := 0; i < keyLength-n; i++ { text = append(text, placeholder) } textLength = len(text) var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[key[j]-1] = text[i+j] } result = append(result, transposition...) } return result, nil } 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 = append(text, placeholder) } var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[j] = text[i+key[j]-1] } result = append(result, transposition...) } result = []rune(strings.TrimRight(string(result), string(placeholder))) return result, nil }
transposition
{ "name": "Decrypt", "signature": "func Decrypt(text []rune, keyWord string) ([]rune, error)", "argument_definitions": [], "start_line": 82, "end_line": 106 }
Decrypt
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 = append(text, placeholder) } var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[j] = text[i+key[j]-1] } result = append(result, transposition...) } result = []rune(strings.TrimRight(string(result), string(placeholder))) return result, nil }
Go-master/cipher/transposition/transposition.go
// transposition.go // description: Transposition cipher // details: // Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes a permutation of the plaintext [Transposition cipher](https://en.wikipedia.org/wiki/Transposition_cipher) // time complexity: O(n) // space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see transposition_test.go package transposition import ( "errors" "fmt" "sort" "strings" ) var ErrNoTextToEncrypt = errors.New("no text to encrypt") var ErrKeyMissing = errors.New("missing Key") const placeholder = ' ' func getKey(keyWord string) []int { keyWord = strings.ToLower(keyWord) word := []rune(keyWord) var sortedWord = make([]rune, len(word)) copy(sortedWord, word) sort.Slice(sortedWord, func(i, j int) bool { return sortedWord[i] < sortedWord[j] }) usedLettersMap := make(map[rune]int) wordLength := len(word) resultKey := make([]int, wordLength) for i := 0; i < wordLength; i++ { char := word[i] numberOfUsage := usedLettersMap[char] resultKey[i] = getIndex(sortedWord, char) + numberOfUsage + 1 //+1 -so that indexing does not start at 0 numberOfUsage++ usedLettersMap[char] = numberOfUsage } return resultKey } func getIndex(wordSet []rune, subString rune) int { n := len(wordSet) for i := 0; i < n; i++ { if wordSet[i] == subString { return i } } return 0 } 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 encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder) } n := textLength % keyLength for i := 0; i < keyLength-n; i++ { text = append(text, placeholder) } textLength = len(text) var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[key[j]-1] = text[i+j] } result = append(result, transposition...) } return result, nil } 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 = append(text, placeholder) } var result []rune for i := 0; i < textLength; i += keyLength { transposition := make([]rune, keyLength) for j := 0; j < keyLength; j++ { transposition[j] = text[i+key[j]-1] } result = append(result, transposition...) } result = []rune(strings.TrimRight(string(result), string(placeholder))) return result, nil }
transposition
{ "name": "NewPolybius", "signature": "func NewPolybius(key string, size int, chars string) (*Polybius, error)", "argument_definitions": [], "start_line": 24, "end_line": 48 }
NewPolybius
func NewPolybius(key string, size int, chars string) (*Polybius, error) { if size < 0 { return nil, fmt.Errorf("provided size %d cannot be negative", size) } key = strings.ToUpper(key) if size > len(chars) { return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars)) } for _, r := range chars { if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') { return nil, fmt.Errorf("provided string %q should only contain latin characters", chars) } } chars = strings.ToUpper(chars)[:size] for i, r := range chars { if strings.ContainsRune(chars[i+1:], r) { return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r) } } if len(key) != size*size { return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size) } return &Polybius{size, chars, key}, nil }
Go-master/cipher/polybius/polybius.go
// Package polybius is encrypting method with polybius square // description: Polybius square // details : The Polybius algorithm is a simple algorithm that is used to encode a message by converting each letter to a pair of numbers. // time complexity: O(n) // space complexity: O(n) // ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher package polybius import ( "fmt" "math" "strings" ) // Polybius is struct having size, characters, and key type Polybius struct { size int characters string key string } // NewPolybius returns a pointer to object of Polybius. // If the size of "chars" is longer than "size", // "chars" are truncated to "size". func NewPolybius(key string, size int, chars string) (*Polybius, error) { if size < 0 { return nil, fmt.Errorf("provided size %d cannot be negative", size) } key = strings.ToUpper(key) if size > len(chars) { return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars)) } for _, r := range chars { if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') { return nil, fmt.Errorf("provided string %q should only contain latin characters", chars) } } chars = strings.ToUpper(chars)[:size] for i, r := range chars { if strings.ContainsRune(chars[i+1:], r) { return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r) } } if len(key) != size*size { return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size) } return &Polybius{size, chars, key}, nil } // Encrypt encrypts with polybius encryption func (p *Polybius) Encrypt(text string) (string, error) { encryptedText := "" for _, char := range strings.ToUpper(text) { encryptedChar, err := p.encipher(char) if err != nil { return "", fmt.Errorf("failed encipher: %w", err) } encryptedText += encryptedChar } return encryptedText, nil } // Decrypt decrypts with polybius encryption func (p *Polybius) Decrypt(text string) (string, error) { chars := []rune(strings.ToUpper(text)) decryptedText := "" for i := 0; i < len(chars); i += 2 { decryptedChar, err := p.decipher(chars[i:int(math.Min(float64(i+2), float64(len(chars))))]) if err != nil { return "", fmt.Errorf("failed decipher: %w", err) } decryptedText += decryptedChar } return decryptedText, nil } func (p *Polybius) encipher(char rune) (string, error) { index := strings.IndexRune(p.key, char) if index < 0 { return "", fmt.Errorf("%q does not exist in keys", char) } row := index / p.size col := index % p.size chars := []rune(p.characters) return string([]rune{chars[row], chars[col]}), nil } func (p *Polybius) decipher(chars []rune) (string, error) { if len(chars) != 2 { return "", fmt.Errorf("the size of \"chars\" must be even") } row := strings.IndexRune(p.characters, chars[0]) if row < 0 { return "", fmt.Errorf("%c does not exist in characters", chars[0]) } col := strings.IndexRune(p.characters, chars[1]) if col < 0 { return "", fmt.Errorf("%c does not exist in characters", chars[1]) } return string(p.key[row*p.size+col]), nil }
polybius
{ "name": "EggDropping", "signature": "func EggDropping(eggs, floors int) int", "argument_definitions": [], "start_line": 9, "end_line": 46 }
EggDropping
func EggDropping(eggs, floors int) int { // Edge case: If there are no floors, no attempts needed if floors == 0 { return 0 } // Edge case: If there is one floor, one attempt needed if floors == 1 { return 1 } // Edge case: If there is one egg, need to test all floors one by one if eggs == 1 { return floors } // Initialize DP table dp := make([][]int, eggs+1) for i := range dp { dp[i] = make([]int, floors+1) } // Fill the DP table for 1 egg for j := 1; j <= floors; j++ { dp[1][j] = j } // Fill the DP table for more than 1 egg for i := 2; i <= eggs; i++ { for j := 2; j <= floors; j++ { dp[i][j] = int(^uint(0) >> 1) // initialize with a large number for x := 1; x <= j; x++ { // Recurrence relation to fill the DP table res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1 dp[i][j] = min.Int(dp[i][j], res) } } } return dp[eggs][floors] }
Go-master/dynamic/eggdropping.go
package dynamic import ( "github.com/TheAlgorithms/Go/math/max" "github.com/TheAlgorithms/Go/math/min" ) // EggDropping finds the minimum number of attempts needed to find the critical floor // with `eggs` number of eggs and `floors` number of floors func EggDropping(eggs, floors int) int { // Edge case: If there are no floors, no attempts needed if floors == 0 { return 0 } // Edge case: If there is one floor, one attempt needed if floors == 1 { return 1 } // Edge case: If there is one egg, need to test all floors one by one if eggs == 1 { return floors } // Initialize DP table dp := make([][]int, eggs+1) for i := range dp { dp[i] = make([]int, floors+1) } // Fill the DP table for 1 egg for j := 1; j <= floors; j++ { dp[1][j] = j } // Fill the DP table for more than 1 egg for i := 2; i <= eggs; i++ { for j := 2; j <= floors; j++ { dp[i][j] = int(^uint(0) >> 1) // initialize with a large number for x := 1; x <= j; x++ { // Recurrence relation to fill the DP table res := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1 dp[i][j] = min.Int(dp[i][j], res) } } } return dp[eggs][floors] }
dynamic
{ "name": "MaxCoins", "signature": "func MaxCoins(nums []int) int", "argument_definitions": [], "start_line": 5, "end_line": 30 }
MaxCoins
func MaxCoins(nums []int) int { n := len(nums) if n == 0 { return 0 } nums = append([]int{1}, nums...) nums = append(nums, 1) dp := make([][]int, n+2) for i := range dp { dp[i] = make([]int, n+2) } for length := 1; length <= n; length++ { for left := 1; left+length-1 <= n; left++ { right := left + length - 1 for k := left; k <= right; k++ { coins := nums[left-1] * nums[k] * nums[right+1] dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins) } } } return dp[1][n] }
Go-master/dynamic/burstballoons.go
package dynamic import "github.com/TheAlgorithms/Go/math/max" // MaxCoins returns the maximum coins we can collect by bursting the balloons func MaxCoins(nums []int) int { n := len(nums) if n == 0 { return 0 } nums = append([]int{1}, nums...) nums = append(nums, 1) dp := make([][]int, n+2) for i := range dp { dp[i] = make([]int, n+2) } for length := 1; length <= n; length++ { for left := 1; left+length-1 <= n; left++ { right := left + length - 1 for k := left; k <= right; k++ { coins := nums[left-1] * nums[k] * nums[right+1] dp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins) } } } return dp[1][n] }
dynamic
{ "name": "MatrixChainDp", "signature": "func MatrixChainDp(D []int) int", "argument_definitions": [], "start_line": 25, "end_line": 47 }
MatrixChainDp
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 for k := i; k < j; k++ { prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j] dp[i][j] = min.Int(prod, dp[i][j]) } } } return dp[1][N-1] }
Go-master/dynamic/matrixmultiplication.go
// matrix chain multiplication problem // https://en.wikipedia.org/wiki/Matrix_chain_multiplication // www.geeksforgeeks.org/dynamic_programming-set-8-matrix-chain-multiplication/ // time complexity: O(n^3) // space complexity: O(n^2) package dynamic import "github.com/TheAlgorithms/Go/math/min" // MatrixChainRec function func MatrixChainRec(D []int, i, j int) int { // d[i-1] x d[i] : dimension of matrix i if i == j { return 0 } q := 1 << 32 for k := i; k < j; k++ { prod := MatrixChainRec(D, i, k) + MatrixChainRec(D, k+1, j) + D[i-1]*D[k]*D[j] q = min.Int(prod, q) } 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 } for l := 2; l < N; l++ { for i := 1; i < N-l+1; i++ { j := i + l - 1 dp[i][j] = 1 << 31 for k := i; k < j; k++ { prod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j] dp[i][j] = min.Int(prod, dp[i][j]) } } } return dp[1][N-1] } /* func main() { D := []int{2, 2, 2, 2, 2} // 4 matrices fmt.Print(matrixChainRec(D, 1, 4), "\n") fmt.Print(matrixChainDp(D), "\n") } */
dynamic
{ "name": "LongestPalindromicSubstring", "signature": "func LongestPalindromicSubstring(s string) string", "argument_definitions": [], "start_line": 9, "end_line": 42 }
LongestPalindromicSubstring
func LongestPalindromicSubstring(s string) string { n := len(s) if n == 0 { return "" } dp := make([][]bool, n) for i := range dp { dp[i] = make([]bool, n) } start := 0 maxLength := 1 for i := 0; i < n; i++ { dp[i][i] = true } for length := 2; length <= n; length++ { for i := 0; i < n-length+1; i++ { j := i + length - 1 if length == 2 { dp[i][j] = (s[i] == s[j]) } else { dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1] } if dp[i][j] && length > maxLength { maxLength = length start = i } } } return s[start : start+maxLength] }
Go-master/dynamic/longestpalindromicsubstring.go
// longestpalindromicsubstring.go // description: Implementation of finding the longest palindromic substring // reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring // time complexity: O(n^2) // space complexity: O(n^2) package dynamic // LongestPalindromicSubstring returns the longest palindromic substring in the input string func LongestPalindromicSubstring(s string) string { n := len(s) if n == 0 { return "" } dp := make([][]bool, n) for i := range dp { dp[i] = make([]bool, n) } start := 0 maxLength := 1 for i := 0; i < n; i++ { dp[i][i] = true } for length := 2; length <= n; length++ { for i := 0; i < n-length+1; i++ { j := i + length - 1 if length == 2 { dp[i][j] = (s[i] == s[j]) } else { dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1] } if dp[i][j] && length > maxLength { maxLength = length start = i } } } return s[start : start+maxLength] }
dynamic
{ "name": "PartitionProblem", "signature": "func PartitionProblem(nums []int) bool", "argument_definitions": [], "start_line": 10, "end_line": 29 }
PartitionProblem
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] }
Go-master/dynamic/partitionproblem.go
// partitionproblem.go // description: Solves the Partition Problem using dynamic programming // reference: https://en.wikipedia.org/wiki/Partition_problem // time complexity: O(n*sum) // space complexity: O(n*sum) package dynamic // PartitionProblem checks whether the given set can be partitioned into two subsets // such that the sum of the elements in both subsets is the same. func PartitionProblem(nums []int) bool { sum := 0 for _, num := range nums { sum += num } if sum%2 != 0 { return false } target := sum / 2 dp := make([]bool, target+1) dp[0] = true for _, num := range nums { for i := target; i >= num; i-- { dp[i] = dp[i] || dp[i-num] } } return dp[target] }
dynamic
{ "name": "LongestArithmeticSubsequence", "signature": "func LongestArithmeticSubsequence(nums []int) int", "argument_definitions": [], "start_line": 9, "end_line": 33 }
LongestArithmeticSubsequence
func LongestArithmeticSubsequence(nums []int) int { n := len(nums) if n <= 1 { return n } dp := make([]map[int]int, n) for i := range dp { dp[i] = make(map[int]int) } maxLength := 1 for i := 1; i < n; i++ { for j := 0; j < i; j++ { diff := nums[i] - nums[j] dp[i][diff] = dp[j][diff] + 1 if dp[i][diff]+1 > maxLength { maxLength = dp[i][diff] + 1 } } } return maxLength }
Go-master/dynamic/longestarithmeticsubsequence.go
// longestarithmeticsubsequence.go // description: Implementation of the Longest Arithmetic Subsequence problem // reference: https://en.wikipedia.org/wiki/Longest_arithmetic_progression // time complexity: O(n^2) // space complexity: O(n^2) package dynamic // LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence func LongestArithmeticSubsequence(nums []int) int { n := len(nums) if n <= 1 { return n } dp := make([]map[int]int, n) for i := range dp { dp[i] = make(map[int]int) } maxLength := 1 for i := 1; i < n; i++ { for j := 0; j < i; j++ { diff := nums[i] - nums[j] dp[i][diff] = dp[j][diff] + 1 if dp[i][diff]+1 > maxLength { maxLength = dp[i][diff] + 1 } } } return maxLength }
dynamic
{ "name": "IsInterleave", "signature": "func IsInterleave(s1, s2, s3 string) bool", "argument_definitions": [], "start_line": 9, "end_line": 35 }
IsInterleave
func IsInterleave(s1, s2, s3 string) bool { if len(s1)+len(s2) != len(s3) { return false } dp := make([][]bool, len(s1)+1) for i := range dp { dp[i] = make([]bool, len(s2)+1) } dp[0][0] = true for i := 1; i <= len(s1); i++ { dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1] } for j := 1; j <= len(s2); j++ { dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1] } for i := 1; i <= len(s1); i++ { for j := 1; j <= len(s2); j++ { dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]) } } return dp[len(s1)][len(s2)] }
Go-master/dynamic/interleavingstrings.go
// interleavingstrings.go // description: Solves the Interleaving Strings problem using dynamic programming // reference: https://en.wikipedia.org/wiki/Interleaving_strings // time complexity: O(m*n) // space complexity: O(m*n) package dynamic // IsInterleave checks if string `s1` and `s2` can be interleaved to form string `s3` func IsInterleave(s1, s2, s3 string) bool { if len(s1)+len(s2) != len(s3) { return false } dp := make([][]bool, len(s1)+1) for i := range dp { dp[i] = make([]bool, len(s2)+1) } dp[0][0] = true for i := 1; i <= len(s1); i++ { dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1] } for j := 1; j <= len(s2); j++ { dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1] } for i := 1; i <= len(s1); i++ { for j := 1; j <= len(s2); j++ { dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]) } } return dp[len(s1)][len(s2)] }
dynamic
{ "name": "OptimalBST", "signature": "func OptimalBST(keys []int, freq []int, n int) int", "argument_definitions": [], "start_line": 5, "end_line": 51 }
OptimalBST
func OptimalBST(keys []int, freq []int, n int) int { // Initialize DP table with size n x n dp := make([][]int, n) for i := range dp { dp[i] = make([]int, n) } // Base case: single key cost for i := 0; i < n; i++ { dp[i][i] = freq[i] } // Build the DP table for sequences of length 2 to n for length := 2; length <= n; length++ { for i := 0; i < n-length+1; i++ { j := i + length - 1 dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value sum := sum(freq, i, j) // Try every key as root and compute cost for k := i; k <= j; k++ { // Left cost: dp[i][k-1] is valid only if k > i var leftCost int if k > i { leftCost = dp[i][k-1] } else { leftCost = 0 } // Right cost: dp[k+1][j] is valid only if k < j var rightCost int if k < j { rightCost = dp[k+1][j] } else { rightCost = 0 } // Total cost for root k cost := sum + leftCost + rightCost // Update dp[i][j] with the minimum cost dp[i][j] = min.Int(dp[i][j], cost) } } } return dp[0][n-1] }
Go-master/dynamic/optimalbst.go
package dynamic import "github.com/TheAlgorithms/Go/math/min" // OptimalBST returns the minimum cost of constructing a Binary Search Tree func OptimalBST(keys []int, freq []int, n int) int { // Initialize DP table with size n x n dp := make([][]int, n) for i := range dp { dp[i] = make([]int, n) } // Base case: single key cost for i := 0; i < n; i++ { dp[i][i] = freq[i] } // Build the DP table for sequences of length 2 to n for length := 2; length <= n; length++ { for i := 0; i < n-length+1; i++ { j := i + length - 1 dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value sum := sum(freq, i, j) // Try every key as root and compute cost for k := i; k <= j; k++ { // Left cost: dp[i][k-1] is valid only if k > i var leftCost int if k > i { leftCost = dp[i][k-1] } else { leftCost = 0 } // Right cost: dp[k+1][j] is valid only if k < j var rightCost int if k < j { rightCost = dp[k+1][j] } else { rightCost = 0 } // Total cost for root k cost := sum + leftCost + rightCost // Update dp[i][j] with the minimum cost dp[i][j] = min.Int(dp[i][j], cost) } } } return dp[0][n-1] } // Helper function to sum the frequencies func sum(freq []int, i, j int) int { total := 0 for k := i; k <= j; k++ { total += freq[k] } return total }
dynamic
{ "name": "DiceThrow", "signature": "func DiceThrow(m, n, sum int) int", "argument_definitions": [], "start_line": 9, "end_line": 32 }
DiceThrow
func DiceThrow(m, n, sum int) int { dp := make([][]int, m+1) for i := range dp { dp[i] = make([]int, sum+1) } for i := 1; i <= n; i++ { if i <= sum { dp[1][i] = 1 } } for i := 2; i <= m; i++ { for j := 1; j <= sum; j++ { for k := 1; k <= n; k++ { if j-k >= 0 { dp[i][j] += dp[i-1][j-k] } } } } return dp[m][sum] }
Go-master/dynamic/dicethrow.go
// dicethrow.go // description: Solves the Dice Throw Problem using dynamic programming // reference: https://www.geeksforgeeks.org/dice-throw-problem/ // time complexity: O(m * n) // space complexity: O(m * n) package dynamic // DiceThrow returns the number of ways to get sum `sum` using `m` dice with `n` faces func DiceThrow(m, n, sum int) int { dp := make([][]int, m+1) for i := range dp { dp[i] = make([]int, sum+1) } for i := 1; i <= n; i++ { if i <= sum { dp[1][i] = 1 } } for i := 2; i <= m; i++ { for j := 1; j <= sum; j++ { for k := 1; k <= n; k++ { if j-k >= 0 { dp[i][j] += dp[i-1][j-k] } } } } return dp[m][sum] }
dynamic
{ "name": "LongestCommonSubsequence", "signature": "func LongestCommonSubsequence(a string, b string) int", "argument_definitions": [], "start_line": 15, "end_line": 39 }
LongestCommonSubsequence
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 := 0; i <= aLen; i++ { for j := 0; j <= bLen; j++ { if i == 0 || j == 0 { lcs[i][j] = 0 } else if aRunes[i-1] == bRunes[j-1] { lcs[i][j] = lcs[i-1][j-1] + 1 } else { lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1]) } } } // returning the length of longest common subsequence return lcs[aLen][bLen] }
Go-master/dynamic/longestcommonsubsequence.go
// LONGEST COMMON SUBSEQUENCE // DP - 4 // https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ // https://leetcode.com/problems/longest-common-subsequence/ // time complexity: O(m*n) where m and n are lengths of the strings // space complexity: O(m*n) where m and n are lengths of the strings package dynamic func strToRuneSlice(s string) (r []rune, size int) { r = []rune(s) return r, len(r) } // LongestCommonSubsequence function 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 := 0; i <= aLen; i++ { for j := 0; j <= bLen; j++ { if i == 0 || j == 0 { lcs[i][j] = 0 } else if aRunes[i-1] == bRunes[j-1] { lcs[i][j] = lcs[i-1][j-1] + 1 } else { lcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1]) } } } // returning the length of longest common subsequence return lcs[aLen][bLen] }
dynamic
{ "name": "EditDistanceRecursive", "signature": "func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int", "argument_definitions": [], "start_line": 11, "end_line": 30 }
EditDistanceRecursive
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] { return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1) } // We have three choices, all with cost of 1 unit return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace }
Go-master/dynamic/editdistance.go
// EDIT DISTANCE PROBLEM // time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. // space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. // https://www.geeksforgeeks.org/edit-distance-dp-5/ // https://leetcode.com/problems/edit-distance/ package dynamic import "github.com/TheAlgorithms/Go/math/min" // EditDistanceRecursive is a naive implementation with exponential time complexity. 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] { return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1) } // We have three choices, all with cost of 1 unit return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace } // EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. // We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value // of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, // first and second respectively. 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 { dp[i][j] = i continue } if first[i-1] == second[j-1] { dp[i][j] = dp[i-1][j-1] continue } dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) } } return dp[m][n] }
dynamic
{ "name": "EditDistanceDP", "signature": "func EditDistanceDP(first string, second string) int", "argument_definitions": [], "start_line": 36, "end_line": 70 }
EditDistanceDP
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 { dp[i][j] = i continue } if first[i-1] == second[j-1] { dp[i][j] = dp[i-1][j-1] continue } dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) } } return dp[m][n] }
Go-master/dynamic/editdistance.go
// EDIT DISTANCE PROBLEM // time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. // space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively. // https://www.geeksforgeeks.org/edit-distance-dp-5/ // https://leetcode.com/problems/edit-distance/ package dynamic import "github.com/TheAlgorithms/Go/math/min" // EditDistanceRecursive is a naive implementation with exponential time complexity. 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] { return EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1) } // We have three choices, all with cost of 1 unit return 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond), // Delete EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace } // EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. // We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value // of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, // first and second respectively. 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 { dp[i][j] = i continue } if first[i-1] == second[j-1] { dp[i][j] = dp[i-1][j-1] continue } dp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) } } return dp[m][n] }
dynamic
{ "name": "IsSubsetSum", "signature": "func IsSubsetSum(array []int, sum int) (bool, error)", "argument_definitions": [], "start_line": 14, "end_line": 55 }
IsSubsetSum
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; i++ { //sum 0 is always true subset[i][0] = true } for i := 1; i <= sum; i++ { //empty set is false when sum is not 0 subset[0][i] = false } for i := 1; i <= arraySize; i++ { for j := 1; j <= sum; j++ { if array[i-1] > j { subset[i][j] = subset[i-1][j] } if array[i-1] <= j { if j-array[i-1] < 0 || j-array[i-1] > sum { //out of bounds return false, ErrInvalidPosition } subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]] } } } return subset[arraySize][sum], nil }
Go-master/dynamic/subsetsum.go
//Given a set of non-negative integers, and a (positive) value sum, //determine if there is a subset of the given set with sum //equal to given sum. // time complexity: O(n*sum) // space complexity: O(n*sum) //references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ package dynamic import "fmt" var ErrInvalidPosition = fmt.Errorf("invalid position in subset") var ErrNegativeSum = fmt.Errorf("negative sum is not allowed") 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; i++ { //sum 0 is always true subset[i][0] = true } for i := 1; i <= sum; i++ { //empty set is false when sum is not 0 subset[0][i] = false } for i := 1; i <= arraySize; i++ { for j := 1; j <= sum; j++ { if array[i-1] > j { subset[i][j] = subset[i-1][j] } if array[i-1] <= j { if j-array[i-1] < 0 || j-array[i-1] > sum { //out of bounds return false, ErrInvalidPosition } subset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]] } } } return subset[arraySize][sum], nil }
dynamic
{ "name": "TrapRainWater", "signature": "func TrapRainWater(height []int) int", "argument_definitions": [], "start_line": 18, "end_line": 42 }
TrapRainWater
func TrapRainWater(height []int) int { if len(height) == 0 { return 0 } leftMax := make([]int, len(height)) rightMax := make([]int, len(height)) leftMax[0] = height[0] for i := 1; i < len(height); i++ { leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i]))) } rightMax[len(height)-1] = height[len(height)-1] for i := len(height) - 2; i >= 0; i-- { rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i]))) } trappedWater := 0 for i := 0; i < len(height); i++ { trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i] } return trappedWater }
Go-master/dynamic/traprainwater.go
// filename: traprainwater.go // description: Provides a function to calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming. // details: // The TrapRainWater function calculates the amount of trapped rainwater between the bars represented by the given elevation map. // It uses dynamic programming to precompute the maximum height of bars to the left and right of each position. // Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights. // Finally, it sums up the trapped rainwater for all positions and returns the total amount. // time complexity: O(n) // space complexity: O(n) // author(s) [TruongNhanNguyen (SOZEL)](https://github.com/TruongNhanNguyen) package dynamic import "math" // TrapRainWater calculates the amount of trapped rainwater between the bars represented by the given elevation map. // It uses dynamic programming to precompute the maximum height of bars to the left and right of each position. // Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights. // Finally, it sums up the trapped rainwater for all positions and returns the total amount. func TrapRainWater(height []int) int { if len(height) == 0 { return 0 } leftMax := make([]int, len(height)) rightMax := make([]int, len(height)) leftMax[0] = height[0] for i := 1; i < len(height); i++ { leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i]))) } rightMax[len(height)-1] = height[len(height)-1] for i := len(height) - 2; i >= 0; i-- { rightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i]))) } trappedWater := 0 for i := 0; i < len(height); i++ { trappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i] } return trappedWater }
dynamic
{ "name": "LpsDp", "signature": "func LpsDp(word string) int", "argument_definitions": [], "start_line": 26, "end_line": 52 }
LpsDp
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][j] = 2 + dp[i+1][j-1] } } else { dp[i][j] = Max(dp[i+1][j], dp[i][j-1]) } } } return dp[0][N-1] }
Go-master/dynamic/longestpalindromicsubsequence.go
// longest palindromic subsequence // time complexity: O(n^2) // space complexity: O(n^2) // http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/ package dynamic func lpsRec(word string, i, j int) int { if i == j { return 1 } if i > j { return 0 } if word[i] == word[j] { return 2 + lpsRec(word, i+1, j-1) } return Max(lpsRec(word, i, j-1), lpsRec(word, i+1, j)) } // LpsRec function func LpsRec(word string) int { return lpsRec(word, 0, len(word)-1) } // LpsDp function 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][j] = 2 + dp[i+1][j-1] } } else { dp[i][j] = Max(dp[i+1][j], dp[i][j-1]) } } } return dp[0][N-1] }
dynamic
{ "name": "UniquePaths", "signature": "func UniquePaths(m, n int) int", "argument_definitions": [], "start_line": 7, "end_line": 32 }
UniquePaths
func UniquePaths(m, n int) int { if m <= 0 || n <= 0 { return 0 } grid := make([][]int, m) for i := range grid { grid[i] = make([]int, n) } for i := 0; i < m; i++ { grid[i][0] = 1 } for j := 0; j < n; j++ { grid[0][j] = 1 } for i := 1; i < m; i++ { for j := 1; j < n; j++ { grid[i][j] = grid[i-1][j] + grid[i][j-1] } } return grid[m-1][n-1] }
Go-master/dynamic/uniquepaths.go
// See https://leetcode.com/problems/unique-paths/ // time complexity: O(m*n) where m and n are the dimensions of the grid // space complexity: O(m*n) where m and n are the dimensions of the grid // author: Rares Mateizer (https://github.com/rares985) package dynamic // UniquePaths implements the solution to the "Unique Paths" problem func UniquePaths(m, n int) int { if m <= 0 || n <= 0 { return 0 } grid := make([][]int, m) for i := range grid { grid[i] = make([]int, n) } for i := 0; i < m; i++ { grid[i][0] = 1 } for j := 0; j < n; j++ { grid[0][j] = 1 } for i := 1; i < m; i++ { for j := 1; j < n; j++ { grid[i][j] = grid[i-1][j] + grid[i][j-1] } } return grid[m-1][n-1] }
dynamic
{ "name": "Abbreviation", "signature": "func Abbreviation(a string, b string) bool", "argument_definitions": [], "start_line": 25, "end_line": 46 }
Abbreviation
func Abbreviation(a string, b string) bool { dp := make([][]bool, len(a)+1) for i := range dp { dp[i] = make([]bool, len(b)+1) } dp[0][0] = true for i := 0; i < len(a); i++ { for j := 0; j <= len(b); j++ { if dp[i][j] { if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) { dp[i+1][j+1] = true } if string(a[i]) == strings.ToLower(string(a[i])) { dp[i+1][j] = true } } } } return dp[len(a)][len(b)] }
Go-master/dynamic/abbreviation.go
// File: abbreviation.go // Description: Abbreviation problem // Details: // https://www.hackerrank.com/challenges/abbr/problem // Problem description (from hackerrank): // You can perform the following operations on the string, a: // 1. Capitalize zero or more of a's lowercase letters. // 2. Delete all of the remaining lowercase letters in a. // Given 2 strings a and b, determine if it's possible to make a equal to be using above operations. // Example: // Given a = "ABcde" and b = "ABCD" // We can capitalize "c" and "d" in a to get "ABCde" then delete all the lowercase letters (which is only "e") in a to get "ABCD" which equals b. // Author: [duongoku](https://github.com/duongoku) // Time Complexity: O(n*m) where n is the length of a and m is the length of b // Space Complexity: O(n*m) where n is the length of a and m is the length of b // See abbreviation_test.go for test cases package dynamic // strings for getting uppercases and lowercases import ( "strings" ) // Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise func Abbreviation(a string, b string) bool { dp := make([][]bool, len(a)+1) for i := range dp { dp[i] = make([]bool, len(b)+1) } dp[0][0] = true for i := 0; i < len(a); i++ { for j := 0; j <= len(b); j++ { if dp[i][j] { if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) { dp[i+1][j+1] = true } if string(a[i]) == strings.ToLower(string(a[i])) { dp[i+1][j] = true } } } } return dp[len(a)][len(b)] }
dynamic
{ "name": "IsMatch", "signature": "func IsMatch(s, p string) bool", "argument_definitions": [], "start_line": 9, "end_line": 32 }
IsMatch
func IsMatch(s, p string) bool { dp := make([][]bool, len(s)+1) for i := range dp { dp[i] = make([]bool, len(p)+1) } dp[0][0] = true for j := 1; j <= len(p); j++ { if p[j-1] == '*' { dp[0][j] = dp[0][j-1] } } for i := 1; i <= len(s); i++ { for j := 1; j <= len(p); j++ { if p[j-1] == s[i-1] || p[j-1] == '?' { dp[i][j] = dp[i-1][j-1] } else if p[j-1] == '*' { dp[i][j] = dp[i-1][j] || dp[i][j-1] } } } return dp[len(s)][len(p)] }
Go-master/dynamic/wildcardmatching.go
// wildcardmatching.go // description: Solves the Wildcard Matching problem using dynamic programming // reference: https://en.wikipedia.org/wiki/Wildcard_matching // time complexity: O(m*n) // space complexity: O(m*n) package dynamic // IsMatch checks if the string `s` matches the wildcard pattern `p` func IsMatch(s, p string) bool { dp := make([][]bool, len(s)+1) for i := range dp { dp[i] = make([]bool, len(p)+1) } dp[0][0] = true for j := 1; j <= len(p); j++ { if p[j-1] == '*' { dp[0][j] = dp[0][j-1] } } for i := 1; i <= len(s); i++ { for j := 1; j <= len(p); j++ { if p[j-1] == s[i-1] || p[j-1] == '?' { dp[i][j] = dp[i-1][j-1] } else if p[j-1] == '*' { dp[i][j] = dp[i-1][j] || dp[i][j-1] } } } return dp[len(s)][len(p)] }
dynamic
{ "name": "Generate", "signature": "func Generate(minLength int, maxLength int) string", "argument_definitions": [], "start_line": 17, "end_line": 48 }
Generate
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(length, big.NewInt(int64(minLength))) intLength := int(length.Int64()) newPassword := make([]byte, intLength) randomData := make([]byte, intLength+intLength/4) charLen := byte(len(chars)) maxrb := byte(256 - (256 % len(chars))) i := 0 for { if _, err := io.ReadFull(rand.Reader, randomData); err != nil { panic(err) } for _, c := range randomData { if c >= maxrb { continue } newPassword[i] = chars[c%charLen] i++ if i == intLength { return string(newPassword) } } } }
Go-master/other/password/generator.go
// This program generates a password from a list of possible chars // You must provide a minimum length and a maximum length // This length is not fixed if you generate multiple passwords for the same range // Package password contains functions to help generate random passwords // time complexity: O(n) // space complexity: O(n) package password import ( "crypto/rand" "io" "math/big" ) // Generate returns a newly generated password 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(length, big.NewInt(int64(minLength))) intLength := int(length.Int64()) newPassword := make([]byte, intLength) randomData := make([]byte, intLength+intLength/4) charLen := byte(len(chars)) maxrb := byte(256 - (256 % len(chars))) i := 0 for { if _, err := io.ReadFull(rand.Reader, randomData); err != nil { panic(err) } for _, c := range randomData { if c >= maxrb { continue } newPassword[i] = chars[c%charLen] i++ if i == intLength { return string(newPassword) } } } }
password
{ "name": "IsBalanced", "signature": "func IsBalanced(input string) bool", "argument_definitions": [], "start_line": 22, "end_line": 64 }
IsBalanced
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); i++ { if input[i] == '(' || input[i] == '{' || input[i] == '[' { stack = append(stack, input[i]) } else { if len(stack) > 0 { pair := string(stack[len(stack)-1]) + string(input[i]) stack = stack[:len(stack)-1] if pair != "[]" && pair != "{}" && pair != "()" { // This means that two types of brackets has // been mixed together, for example "([)]", // which makes seuqence invalid by definition. return false } } else { // This means that closing bracket is encountered // before opening one, which makes all sequence // invalid by definition. return false } } } // If sequence is properly nested, all elements in stack // has been paired with closing elements. If even one // element has not been paired with a closing bracket, // means that sequence is invalid by definition. return len(stack) == 0 }
Go-master/other/nested/nestedbrackets.go
// Package nested provides functions for testing // strings proper brackets nesting. package nested // IsBalanced returns true if provided input string is properly nested. // // Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. // // A sequence of brackets `s` is considered properly nested // if any of the following conditions are true: // - `s` is empty; // - `s` has the form (U) or [U] or {U} where U is a properly nested string; // - `s` has the form VW where V and W are properly nested strings. // // For example, the string "()()[()]" is properly nested but "[(()]" is not. // // **Note** Providing characters other then brackets would return false, // despite brackets sequence in the string. Make sure to filter // input before usage. // time complexity: O(n) // space complexity: O(n) 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); i++ { if input[i] == '(' || input[i] == '{' || input[i] == '[' { stack = append(stack, input[i]) } else { if len(stack) > 0 { pair := string(stack[len(stack)-1]) + string(input[i]) stack = stack[:len(stack)-1] if pair != "[]" && pair != "{}" && pair != "()" { // This means that two types of brackets has // been mixed together, for example "([)]", // which makes seuqence invalid by definition. return false } } else { // This means that closing bracket is encountered // before opening one, which makes all sequence // invalid by definition. return false } } } // If sequence is properly nested, all elements in stack // has been paired with closing elements. If even one // element has not been paired with a closing bracket, // means that sequence is invalid by definition. return len(stack) == 0 }
nested
{ "name": "hexToDecimal", "signature": "func hexToDecimal(hexStr string) (int64, error)", "argument_definitions": [], "start_line": 22, "end_line": 56 }
hexToDecimal
func hexToDecimal(hexStr string) (int64, error) { hexStr = strings.TrimSpace(hexStr) if len(hexStr) == 0 { return 0, fmt.Errorf("input string is empty") } // Check if the string has a valid hexadecimal prefix if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") { hexStr = hexStr[2:] } // Validate the hexadecimal string if !isValidHexadecimal(hexStr) { return 0, fmt.Errorf("invalid hexadecimal string") } var decimalValue int64 for _, char := range hexStr { var digit int64 if char >= '0' && char <= '9' { digit = int64(char - '0') } else if char >= 'A' && char <= 'F' { digit = int64(char - 'A' + 10) } else if char >= 'a' && char <= 'f' { digit = int64(char - 'a' + 10) } else { return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char) } decimalValue = decimalValue*16 + digit } return decimalValue, nil }
Go-master/conversion/hexadecimaltodecimal.go
/* Author: mapcrafter2048 GitHub: https://github.com/mapcrafter2048 */ // This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Decimal number(0-9). // https://en.wikipedia.org/wiki/Hexadecimal // https://en.wikipedia.org/wiki/Decimal // Function receives a Hexadecimal Number as string and returns the Decimal number as integer. // Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF. package conversion import ( "fmt" "regexp" "strings" ) var isValidHexadecimal = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString // hexToDecimal converts a hexadecimal string to a decimal integer. func hexToDecimal(hexStr string) (int64, error) { hexStr = strings.TrimSpace(hexStr) if len(hexStr) == 0 { return 0, fmt.Errorf("input string is empty") } // Check if the string has a valid hexadecimal prefix if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") { hexStr = hexStr[2:] } // Validate the hexadecimal string if !isValidHexadecimal(hexStr) { return 0, fmt.Errorf("invalid hexadecimal string") } var decimalValue int64 for _, char := range hexStr { var digit int64 if char >= '0' && char <= '9' { digit = int64(char - '0') } else if char >= 'A' && char <= 'F' { digit = int64(char - 'A' + 10) } else if char >= 'a' && char <= 'f' { digit = int64(char - 'a' + 10) } else { return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char) } decimalValue = decimalValue*16 + digit } return decimalValue, nil }
conversion
{ "name": "Base64Encode", "signature": "func Base64Encode(input []byte) string", "argument_definitions": [], "start_line": 20, "end_line": 53 }
Base64Encode
func Base64Encode(input []byte) string { var sb strings.Builder // If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output var padding string for i := len(input) % 3; i > 0 && i < 3; i++ { var zeroByte byte input = append(input, zeroByte) padding += "=" } // encode 24 bits per 24 bits (3 bytes per 3 bytes) for i := 0; i < len(input); i += 3 { // select 3 8-bit input groups, and re-arrange them into 4 6-bit groups // the literal 0x3F corresponds to the byte "0011 1111" // the operation "byte & 0x3F" masks the two left-most bits group := [4]byte{ input[i] >> 2, (input[i]<<4)&0x3F + input[i+1]>>4, (input[i+1]<<2)&0x3F + input[i+2]>>6, input[i+2] & 0x3F, } // translate each group into a char using the static map for _, b := range group { sb.WriteString(string(Alphabet[int(b)])) } } encoded := sb.String() // Apply the output padding encoded = encoded[:len(encoded)-len(padding)] + padding[:] return encoded }
Go-master/conversion/base64.go
// base64.go // description: The base64 encoding algorithm as defined in the RFC4648 standard. // author: [Paul Leydier] (https://github.com/paul-leydier) // time complexity: O(n) // space complexity: O(n) // ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4 // ref: https://en.wikipedia.org/wiki/Base64 // see base64_test.go package conversion import ( "strings" // Used for efficient string builder (more efficient than simply appending strings) ) const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" // Base64Encode encodes the received input bytes slice into a base64 string. // The implementation follows the RFC4648 standard, which is documented // at https://datatracker.ietf.org/doc/html/rfc4648#section-4 func Base64Encode(input []byte) string { var sb strings.Builder // If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output var padding string for i := len(input) % 3; i > 0 && i < 3; i++ { var zeroByte byte input = append(input, zeroByte) padding += "=" } // encode 24 bits per 24 bits (3 bytes per 3 bytes) for i := 0; i < len(input); i += 3 { // select 3 8-bit input groups, and re-arrange them into 4 6-bit groups // the literal 0x3F corresponds to the byte "0011 1111" // the operation "byte & 0x3F" masks the two left-most bits group := [4]byte{ input[i] >> 2, (input[i]<<4)&0x3F + input[i+1]>>4, (input[i+1]<<2)&0x3F + input[i+2]>>6, input[i+2] & 0x3F, } // translate each group into a char using the static map for _, b := range group { sb.WriteString(string(Alphabet[int(b)])) } } encoded := sb.String() // Apply the output padding encoded = encoded[:len(encoded)-len(padding)] + padding[:] return encoded } // Base64Decode decodes the received input base64 string into a byte slice. // The implementation follows the RFC4648 standard, which is documented // at https://datatracker.ietf.org/doc/html/rfc4648#section-4 func Base64Decode(input string) []byte { padding := strings.Count(input, "=") // Number of bytes which will be ignored var decoded []byte // select 4 6-bit input groups, and re-arrange them into 3 8-bit groups for i := 0; i < len(input); i += 4 { // translate each group into a byte using the static map byteInput := [4]byte{ byte(strings.IndexByte(Alphabet, input[i])), byte(strings.IndexByte(Alphabet, input[i+1])), byte(strings.IndexByte(Alphabet, input[i+2])), byte(strings.IndexByte(Alphabet, input[i+3])), } group := [3]byte{ byteInput[0]<<2 + byteInput[1]>>4, byteInput[1]<<4 + byteInput[2]>>2, byteInput[2]<<6 + byteInput[3], } decoded = append(decoded, group[:]...) } return decoded[:len(decoded)-padding] }
conversion
{ "name": "hexToBinary", "signature": "func hexToBinary(hex string) (string, error)", "argument_definitions": [], "start_line": 23, "end_line": 77 }
hexToBinary
func hexToBinary(hex string) (string, error) { // Trim any leading or trailing whitespace hex = strings.TrimSpace(hex) // Check if the hexadecimal string is empty if hex == "" { return "", errors.New("input string is empty") } // Check if the hexadecimal string is valid if !isValidHex(hex) { return "", errors.New("invalid hexadecimal string: " + hex) } // Parse the hexadecimal string to an integer var decimal int64 for i := 0; i < len(hex); i++ { char := hex[i] var value int64 if char >= '0' && char <= '9' { value = int64(char - '0') } else if char >= 'A' && char <= 'F' { value = int64(char - 'A' + 10) } else if char >= 'a' && char <= 'f' { value = int64(char - 'a' + 10) } else { return "", errors.New("invalid character in hexadecimal string: " + string(char)) } decimal = decimal*16 + value } // Convert the integer to a binary string without using predefined functions var binaryBuilder strings.Builder if decimal == 0 { binaryBuilder.WriteString("0") } else { for decimal > 0 { bit := decimal % 2 if bit == 0 { binaryBuilder.WriteString("0") } else { binaryBuilder.WriteString("1") } decimal = decimal / 2 } } // Reverse the binary string since the bits are added in reverse order binaryRunes := []rune(binaryBuilder.String()) for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 { binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i] } return string(binaryRunes), nil }
Go-master/conversion/hexadecimaltobinary.go
/* Author: mapcrafter2048 GitHub: https://github.com/mapcrafter2048 */ // This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1). // https://en.wikipedia.org/wiki/Hexadecimal // https://en.wikipedia.org/wiki/Binary_number // Function receives a Hexadecimal Number as string and returns the Binary number as string. // Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF. package conversion import ( "errors" "regexp" "strings" ) var isValidHex = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString // hexToBinary() function that will take Hexadecimal number as string, // and return its Binary equivalent as a string. func hexToBinary(hex string) (string, error) { // Trim any leading or trailing whitespace hex = strings.TrimSpace(hex) // Check if the hexadecimal string is empty if hex == "" { return "", errors.New("input string is empty") } // Check if the hexadecimal string is valid if !isValidHex(hex) { return "", errors.New("invalid hexadecimal string: " + hex) } // Parse the hexadecimal string to an integer var decimal int64 for i := 0; i < len(hex); i++ { char := hex[i] var value int64 if char >= '0' && char <= '9' { value = int64(char - '0') } else if char >= 'A' && char <= 'F' { value = int64(char - 'A' + 10) } else if char >= 'a' && char <= 'f' { value = int64(char - 'a' + 10) } else { return "", errors.New("invalid character in hexadecimal string: " + string(char)) } decimal = decimal*16 + value } // Convert the integer to a binary string without using predefined functions var binaryBuilder strings.Builder if decimal == 0 { binaryBuilder.WriteString("0") } else { for decimal > 0 { bit := decimal % 2 if bit == 0 { binaryBuilder.WriteString("0") } else { binaryBuilder.WriteString("1") } decimal = decimal / 2 } } // Reverse the binary string since the bits are added in reverse order binaryRunes := []rune(binaryBuilder.String()) for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 { binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i] } return string(binaryRunes), nil }
conversion
{ "name": "add", "signature": "func add(a, b string) string", "argument_definitions": [], "start_line": 123, "end_line": 149 }
add
func add(a, b string) string { if len(a) < len(b) { a, b = b, a } carry := 0 sum := make([]byte, len(a)+1) for i := 0; i < len(a); i++ { d := int(a[len(a)-1-i] - '0') if i < len(b) { d += int(b[len(b)-1-i] - '0') } d += carry sum[len(sum)-1-i] = byte(d%10) + '0' carry = d / 10 } if carry > 0 { sum[0] = byte(carry) + '0' } else { sum = sum[1:] } return string(sum) }
Go-master/project_euler/problem_13/problem13.go
/** * Problem 13 - Large sum * @see {@link https://projecteuler.net/problem=13} * * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. * * @author ddaniel27 */ package problem13 var numbers = [100]string{ "37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690", } func Problem13() string { sum := "0" for _, n := range numbers { sum = add(sum, n) } return sum[:10] } func add(a, b string) string { if len(a) < len(b) { a, b = b, a } carry := 0 sum := make([]byte, len(a)+1) for i := 0; i < len(a); i++ { d := int(a[len(a)-1-i] - '0') if i < len(b) { d += int(b[len(b)-1-i] - '0') } d += carry sum[len(sum)-1-i] = byte(d%10) + '0' carry = d / 10 } if carry > 0 { sum[0] = byte(carry) + '0' } else { sum = sum[1:] } return string(sum) }
problem13
{ "name": "Jump", "signature": "func Jump(array []int, target int) (int, error)", "argument_definitions": [], "start_line": 16, "end_line": 56 }
Jump
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 { prev = curr if prev >= len(array) { return -1, ErrNotFound } curr += step // prevent jumping over list range if curr > n { curr = n } } // perform linear search from index prev to index curr for array[prev] < target { prev++ // if reach end of range, indicate target not found if prev == curr { return -1, ErrNotFound } } if array[prev] == target { return prev, nil } return -1, ErrNotFound }
Go-master/search/jump.go
// jump.go // description: Implementation of jump search // details: // A search algorithm for ordered list that jump through the list to narrow down the range // before performing a linear search // reference: https://en.wikipedia.org/wiki/Jump_search // see jump_test.go for a test implementation, test function TestJump // time complexity: O(sqrt(n)) // space complexity: O(1) package search import "math" // Jump search works by jumping multiple steps ahead in sorted list until it find an item larger than target, // then create a sublist of item from the last searched item up to the current item and perform a linear search. 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 { prev = curr if prev >= len(array) { return -1, ErrNotFound } curr += step // prevent jumping over list range if curr > n { curr = n } } // perform linear search from index prev to index curr for array[prev] < target { prev++ // if reach end of range, indicate target not found if prev == curr { return -1, ErrNotFound } } if array[prev] == target { return prev, nil } return -1, ErrNotFound }
search
{ "name": "Interpolation", "signature": "func Interpolation(sortedData []int, guess int) (int, error)", "argument_definitions": [], "start_line": 14, "end_line": 50 }
Interpolation
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(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal))) // if guess is found, array can also have duplicate values, so scan backwards and find the first index if sortedData[mid] == guess { for mid > 0 && sortedData[mid-1] == guess { mid-- } return mid, nil } // adjust our guess and continue if sortedData[mid] > guess { high, highVal = mid-1, sortedData[high] } else { low, lowVal = mid+1, sortedData[low] } } if guess == lowVal { return low, nil } return -1, ErrNotFound }
Go-master/search/interpolation.go
package search // Interpolation searches for the entity in the given sortedData. // if the entity is present, it will return the index of the entity, if not -1 will be returned. // see: https://en.wikipedia.org/wiki/Interpolation_search // Complexity // // Worst: O(N) // Average: O(log(log(N)) if the elements are uniformly distributed // Best: O(1) // // Example // // fmt.Println(InterpolationSearch([]int{1, 2, 9, 20, 31, 45, 63, 70, 100},100)) func Interpolation(sortedData []int, guess int) (int, error) { if len(sortedData) == 0 { return -1, ErrNotFound } var ( low, high = 0, len(sortedData) - 1 lowVal, highVal = sortedData[low], sortedData[high] ) for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) { mid := low + int(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal))) // if guess is found, array can also have duplicate values, so scan backwards and find the first index if sortedData[mid] == guess { for mid > 0 && sortedData[mid-1] == guess { mid-- } return mid, nil } // adjust our guess and continue if sortedData[mid] > guess { high, highVal = mid-1, sortedData[high] } else { low, lowVal = mid+1, sortedData[low] } } if guess == lowVal { return low, nil } return -1, ErrNotFound }
search
{ "name": "Jump2", "signature": "func Jump2(arr []int, target int) (int, error)", "argument_definitions": [], "start_line": 4, "end_line": 23 }
Jump2
func Jump2(arr []int, target int) (int, error) { step := int(math.Round(math.Sqrt(float64(len(arr))))) rbound := len(arr) for i := step; i < len(arr); i += step { if arr[i] > target { rbound = i break } } for i := rbound - step; i < rbound; i++ { if arr[i] == target { return i, nil } if arr[i] > target { break } } return -1, ErrNotFound }
Go-master/search/jump2.go
package search import "math" func Jump2(arr []int, target int) (int, error) { step := int(math.Round(math.Sqrt(float64(len(arr))))) rbound := len(arr) for i := step; i < len(arr); i += step { if arr[i] > target { rbound = i break } } for i := rbound - step; i < rbound; i++ { if arr[i] == target { return i, nil } if arr[i] > target { break } } return -1, ErrNotFound }
search
{ "name": "doSort", "signature": "func doSort(arr []T, left, right int) bool", "argument_definitions": [], "start_line": 16, "end_line": 43 }
doSort
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], arr[high+1] = arr[high+1], arr[low] swapped = true } mid := left + (right-left)/2 leftHalf := doSort(arr, left, mid) rightHalf := doSort(arr, mid+1, right) return swapped || leftHalf || rightHalf }
Go-master/sort/circlesort.go
// Package sort implements various sorting algorithms. package sort import "github.com/TheAlgorithms/Go/constraints" // Circle sorts an array using the circle sort algorithm. func Circle[T constraints.Ordered](arr []T) []T { if len(arr) == 0 { return arr } for doSort(arr, 0, len(arr)-1) { } return arr } // doSort is the recursive function that implements the circle sort algorithm. func doSort[T constraints.Ordered](arr []T, left, right int) bool { if left == right { return false } swapped := false low := left high := right for low < high { if arr[low] > arr[high] { arr[low], arr[high] = arr[high], arr[low] swapped = true } low++ high-- } if low == high && arr[low] > arr[high+1] { arr[low], arr[high+1] = arr[high+1], arr[low] swapped = true } mid := left + (right-left)/2 leftHalf := doSort(arr, left, mid) rightHalf := doSort(arr, mid+1, right) return swapped || leftHalf || rightHalf }
sort
{ "name": "Mode", "signature": "func Mode(numbers []T) (T, error)", "argument_definitions": [], "start_line": 20, "end_line": 46 }
Mode
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 }
Go-master/math/mode.go
// mode.go // author(s): [CalvinNJK] (https://github.com/CalvinNJK) // time complexity: O(n) // space complexity: O(n) // description: Finding Mode Value In an Array // see mode.go package math import ( "errors" "github.com/TheAlgorithms/Go/constraints" ) // ErrEmptySlice is the error returned by functions in math package when // an empty slice is provided to it as argument when the function expects // a non-empty slice. var ErrEmptySlice = errors.New("empty slice provided") func Mode[T constraints.Number](numbers []T) (T, error) { countMap := make(map[T]int) n := len(numbers) if n == 0 { return 0, ErrEmptySlice } for _, number := range numbers { countMap[number]++ } var mode T count := 0 for k, v := range countMap { if v > count { count = v mode = k } } return mode, nil }
math
{ "name": "IsKrishnamurthyNumber", "signature": "func IsKrishnamurthyNumber(n T) bool", "argument_definitions": [], "start_line": 13, "end_line": 33 }
IsKrishnamurthyNumber
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 := n for n > 0 { nTemp -= digitFact[n%10] n /= 10 } return nTemp == 0 }
Go-master/math/krishnamurthy.go
// filename : krishnamurthy.go // description: A program which contains the function that returns true if a given number is Krishnamurthy number or not. // details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number. // Ex: 1! = 1, 145 = 1! + 4! + 5! // time complexity: O(log n) // space complexity: O(1) // author(s): [GooMonk](https://github.com/GooMonk) // see krishnamurthy_test.go package math import "github.com/TheAlgorithms/Go/constraints" // IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not. func IsKrishnamurthyNumber[T constraints.Integer](n T) bool { if n <= 0 { return false } // Preprocessing: Using a slice to store the digit Factorials digitFact := make([]T, 10) digitFact[0] = 1 // 0! = 1 for i := 1; i < 10; i++ { digitFact[i] = digitFact[i-1] * T(i) } // Subtract the digit Facotorial from the number nTemp := n for n > 0 { nTemp -= digitFact[n%10] n /= 10 } return nTemp == 0 }
math
{ "name": "Spigot", "signature": "func Spigot(n int) string", "argument_definitions": [], "start_line": 13, "end_line": 55 }
Spigot
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 quotient := sum / (j*2 + 1) remainders[j] = sum % (j*2 + 1) carriedOver = quotient * j } remainders[0] = sum % 10 q := sum / 10 switch q { case 9: digitsHeld++ case 10: q = 0 for k := 1; k <= digitsHeld; k++ { replaced, _ := strconv.Atoi(pi[i-k : i-k+1]) if replaced == 9 { replaced = 0 } else { replaced++ } pi = delChar(pi, i-k) pi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:] } digitsHeld = 1 default: digitsHeld = 1 } pi += strconv.Itoa(q) } return pi }
Go-master/math/pi/spigotpi.go
// spigotpi.go // description: A Spigot Algorithm for the Digits of Pi // details: // implementation of Spigot Algorithm for the Digits of Pi - [Spigot algorithm](https://en.wikipedia.org/wiki/Spigot_algorithm) // time complexity: O(n) // space complexity: O(n) // author(s) [red_byte](https://github.com/i-redbyte) // see spigotpi_test.go package pi import "strconv" 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 quotient := sum / (j*2 + 1) remainders[j] = sum % (j*2 + 1) carriedOver = quotient * j } remainders[0] = sum % 10 q := sum / 10 switch q { case 9: digitsHeld++ case 10: q = 0 for k := 1; k <= digitsHeld; k++ { replaced, _ := strconv.Atoi(pi[i-k : i-k+1]) if replaced == 9 { replaced = 0 } else { replaced++ } pi = delChar(pi, i-k) pi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:] } digitsHeld = 1 default: digitsHeld = 1 } pi += strconv.Itoa(q) } return pi } func delChar(s string, index int) string { tmp := []rune(s) return string(append(tmp[0:index], tmp[index+1:]...)) }
pi
{ "name": "MonteCarloPiConcurrent", "signature": "func MonteCarloPiConcurrent(n int) (float64, error)", "argument_definitions": [], "start_line": 37, "end_line": 56 }
MonteCarloPiConcurrent
func MonteCarloPiConcurrent(n int) (float64, error) { numCPU := runtime.GOMAXPROCS(0) c := make(chan int, numCPU) pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes if err != nil { return 0, err } // launch numCPU parallel tasks for _, p := range pointsToDraw { go drawPoints(p, c) } // collect the tasks results inside := 0 for i := 0; i < numCPU; i++ { inside += <-c } return float64(inside) / float64(n) * 4, nil }
Go-master/math/pi/montecarlopi.go
// montecarlopi.go // description: Calculating pi by the Monte Carlo method // details: // implementations of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method) // time complexity: O(n) // space complexity: O(1) // author(s): [red_byte](https://github.com/i-redbyte), [Paul Leydier] (https://github.com/paul-leydier) // see montecarlopi_test.go package pi import ( "fmt" // Used for error formatting "math/rand" // Used for random number generation in Monte Carlo method "runtime" // Used to get information on available CPUs "time" // Used for seeding the random number generation ) func MonteCarloPi(randomPoints int) float64 { rnd := rand.New(rand.NewSource(time.Now().UnixNano())) inside := 0 for i := 0; i < randomPoints; i++ { x := rnd.Float64() y := rnd.Float64() if x*x+y*y <= 1 { inside += 1 } } pi := float64(inside) / float64(randomPoints) * 4 return pi } // MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method. // Unlike the MonteCarloPi function (first version), this implementation uses // goroutines and channels to parallelize the computation. // More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method. // More details on goroutines parallelization available at https://go.dev/doc/effective_go#parallel. func MonteCarloPiConcurrent(n int) (float64, error) { numCPU := runtime.GOMAXPROCS(0) c := make(chan int, numCPU) pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes if err != nil { return 0, err } // launch numCPU parallel tasks for _, p := range pointsToDraw { go drawPoints(p, c) } // collect the tasks results inside := 0 for i := 0; i < numCPU; i++ { inside += <-c } return float64(inside) / float64(n) * 4, nil } // drawPoints draws n random two-dimensional points in the interval [0, 1), [0, 1) and sends through c // the number of points which where within the circle of center 0 and radius 1 (unit circle) func drawPoints(n int, c chan<- int) { rnd := rand.New(rand.NewSource(time.Now().UnixNano())) inside := 0 for i := 0; i < n; i++ { x, y := rnd.Float64(), rnd.Float64() if x*x+y*y <= 1 { inside++ } } c <- inside } // splitInt takes an integer x and splits it within an integer slice of length n in the most uniform // way possible. // For example, splitInt(10, 3) will return []int{4, 3, 3}, nil func splitInt(x int, n int) ([]int, error) { if x < n { return nil, fmt.Errorf("x must be < n - given values are x=%d, n=%d", x, n) } split := make([]int, n) if x%n == 0 { for i := 0; i < n; i++ { split[i] = x / n } } else { limit := x % n for i := 0; i < limit; i++ { split[i] = x/n + 1 } for i := limit; i < n; i++ { split[i] = x / n } } return split, nil }
pi
End of preview.

πŸ“š TestEval-LR: Unit Test Generation Benchmark for Low-Resource Languages

TestEval-LR is a validation benchmark designed to measure how well models can generate unit tests for Low-Resource Programming Languages (LRPLs) β€” specifically Rust, Go, and Julia.

πŸ“Œ Purpose

Evaluate how well a model can generate test code, given a focal function's source code and context.

πŸ“‚ Dataset Structure

Each example contains:

  • function_name: Name of the focal function.
  • focal_code: Raw source code of the function (used for context).
  • function_component: Detail information about the function like function signature,arguments definition,line range,...
  • file_content: Content of file have the focal function.
  • file_path: Relative path to the file in the repository.

Dataset Size

The dataset contains ~372–412 samples per language, depending on the source repository.

πŸ“ Prompt Example for Test Generation

Suffix syntax for each language: suffix syntax is to put in the end of the prompt ( after wrap in the chat template if need ) to generate the expected test function and avoid hallucination

    "Rust":  "#[test]\nfn test_{function_name}() {"

    "Julia": "@testset \"{function_name} Tests\" begin"

    "Go":    "func Test{function_name_with_uppercase_first_letter}("

This dataset uses a structured prompt format for three programming languages: Rust, Julia, and Go.
Each language has two variants:

  • instruct β†’ Full instruction prompt including explicit guidance to generate a unit test for a given function.
  • base β†’ Minimal version that only contains the function code and a short comment reminding to check correctness.

Structure

prompts = {
    "Rust": {
        "instruct": (
            "{function_code}\n"
            "Generate Rust unittest for {function_name} function in module {file_path}:\n"
        ),
        "base": (
            "{function_code}\n"
            "// Check the correctness for {function_name} function in Rust\n"
        ),
    },
    "Julia": {
        "instruct": (
            "{function_code}\n"
            "Generate Julia unittest for {function_name} function in module {file_path}:\n"
        ),
        "base": (
            "{function_code}\n"
            "# Check the correctness for {function_name} function in Julia\n"
        ),
    },
    "Go": {
        "instruct": (
            "{function_code}\n"
            "Generate Go unittest for {function_name} function in module {file_path}:\n"
        ),
        "base": (
            "{function_code}\n"
            "// Check the correctness for {function_name} function in Go\n"
        ),
    },
}

Downloads last month
35