repo
stringclasses 6
values | id
int64 0
371
| target_function_prompt
stringlengths 258
11.6k
| function_signature
stringlengths 258
11.6k
| focal_code
stringlengths 258
11.6k
| function_name
stringlengths 2
36
| start_line
int64 3
1.61k
| end_line
int64 23
1.64k
| file_path
stringlengths 7
56
| context
stringlengths 3.33k
9.15k
|
|---|---|---|---|---|---|---|---|---|---|
Go-master
| 0
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false
}
|
IsSubsequence
| 9
| 34
|
strings/issubsequence.go
|
#FILE: Go-master/structure/trie/trie.go
##CHUNK 1
}
return r
}
// remove lazily a word from the Trie node, no node is actually removed.
func (n *Node) remove(s string) {
if len(s) == 0 {
return
}
next, ok := n, false
for _, c := range s {
next, ok = next.children[c]
if !ok {
// word cannot be found - we're done !
return
}
}
next.isLeaf = false
}
#FILE: Go-master/structure/set/set.go
##CHUNK 1
return false
}
func (st *set[T]) IsSubsetOf(superSet Set[T]) bool {
if st.Len() > superSet.Len() {
return false
}
for _, item := range st.GetItems() {
if !superSet.In(item) {
return false
}
}
return true
}
func (st *set[T]) IsProperSubsetOf(superSet Set[T]) bool {
if st.Len() == superSet.Len() {
return false
}
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
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) {
#FILE: Go-master/structure/tree/btree.go
##CHUNK 1
}
}
func (node *BTreeNode[T]) IsFull(maxKeys int) bool {
return node.numKeys == maxKeys
}
func (node *BTreeNode[T]) Search(key T) bool {
i := 0
for ; i < node.numKeys; i++ {
if key == node.keys[i] {
return true
}
if key < node.keys[i] {
break
}
}
if node.isLeaf {
return false
}
##CHUNK 2
if key == node.keys[i] {
return true
}
if key < node.keys[i] {
break
}
}
if node.isLeaf {
return false
}
return node.children[i].Search(key)
}
func (tree *BTree[T]) Search(key T) bool {
if tree.root == nil {
return false
}
return tree.root.Search(key)
}
#FILE: Go-master/project_euler/problem_19/problem19.go
##CHUNK 1
return count
}
func IsLeapYear(year int) bool {
if year%4 == 0 {
if year%100 == 0 {
return year%400 == 0
}
return true
}
return false
}
#FILE: Go-master/graph/dijkstra.go
##CHUNK 1
pq.Update(*item)
}
}
}
for pq.Size() > 0 {
curr := pq.Pop().(Item)
if curr.node == end {
break
}
visit(curr)
}
item := nodes[end]
if item == nil {
return -1, false
}
return item.dist, true
}
#FILE: Go-master/math/prime/primecheck.go
##CHUNK 1
return false
}
// 2 and 3 are prime
if n < 4 {
return true
}
// all numbers divisible by 2 except 2 are not prime
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i++ {
j := i + length - 1
if length == 2 {
#FILE: Go-master/graph/floydwarshall_test.go
##CHUNK 1
for i := range *a {
if len((*a)[i]) != len(b[i]) {
return false
}
for j := range (*a)[i] {
if (*a)[i][j] == Inf && b[i][j] == Inf {
continue
}
if !almostEqual((*a)[i][j], b[i][j]) {
return false
}
}
}
return true
}
#CURRENT FILE: Go-master/strings/issubsequence.go
|
Go-master
| 1
|
func IsIsogram(text string, order IsogramOrder) (bool, error) {
if order < First || order > Third {
return false, errors.New("Invalid isogram order provided")
}
text = strings.ToLower(text)
text = strings.Join(strings.Fields(text), "")
if hasDigit(text) || hasSymbol(text) {
return false, errors.New("Cannot 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
}
|
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
}
|
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
}
|
IsIsogram
| 33
| 70
|
strings/isisogram.go
|
#FILE: Go-master/graph/cycle.go
##CHUNK 1
}
}
return allCycles
}
func (g Graph) findAllCyclesHelper(current int, all, visiting, visited map[int]struct{}) (bool, [][]int) {
parents := [][]int{}
delete(all, current)
visiting[current] = struct{}{}
neighbors := g.edges[current]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
##CHUNK 2
if g.hasCycleHelper(current, all, visiting, visited) {
return true
}
}
return false
}
func (g Graph) hasCycleHelper(v int, all, visiting, visited map[int]struct{}) bool {
delete(all, v)
visiting[v] = struct{}{}
neighbors := g.edges[v]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
return true
} else if g.hasCycleHelper(v, all, visiting, visited) {
##CHUNK 3
delete(all, v)
visiting[v] = struct{}{}
neighbors := g.edges[v]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
return true
} else if g.hasCycleHelper(v, all, visiting, visited) {
return true
}
}
delete(visiting, v)
visited[v] = struct{}{}
return false
}
// this function can do HasCycle() job but it is slower
func (g *Graph) FindAllCycles() []Graph {
##CHUNK 4
parents := [][]int{}
delete(all, current)
visiting[current] = struct{}{}
neighbors := g.edges[current]
for v := range neighbors {
if _, ok := visited[v]; ok {
continue
} else if _, ok := visiting[v]; ok {
parents = append(parents, []int{v, current})
return true, parents
} else if ok, savedParents := g.findAllCyclesHelper(v, all, visiting, visited); ok {
parents = append(parents, savedParents...)
parents = append(parents, []int{v, current})
return true, parents
}
}
delete(visiting, current)
visited[current] = struct{}{}
#FILE: Go-master/cipher/transposition/transposition_test.go
##CHUNK 1
return string(b)
}
func TestEncrypt(t *testing.T) {
fn := func(text string, keyWord string) (bool, error) {
encrypt, err := Encrypt([]rune(text), keyWord)
if err != nil && !errors.Is(err, ErrNoTextToEncrypt) && !errors.Is(err, ErrKeyMissing) {
t.Error("Unexpected error ", err)
}
return text == string(encrypt), err
}
for _, s := range texts {
if check, err := fn(s, getRandomString()); check || err != nil {
t.Error("String ", s, " not encrypted")
}
}
if _, err := fn(getRandomString(), ""); err == nil {
t.Error("Error! empty string encryption")
}
}
#FILE: Go-master/math/prime/millerrabintest.go
##CHUNK 1
}
// MillerTestMultiple is like MillerTest but runs the test for multiple
// witnesses.
func MillerTestMultiple(num int64, witnesses ...int64) (bool, error) {
for _, witness := range witnesses {
prime, err := MillerTest(num, witness)
if err != nil {
return false, err
}
if !prime {
return false, nil
}
}
return true, nil
}
// MillerRabinProbabilistic is a probabilistic test for primality
##CHUNK 2
d, _ := formatNum(num)
res, err := modular.Exponentiation(witness, d, num)
if err != nil {
return false, err
}
// miller conditions checks
if res == 1 || res == num-1 {
return true, nil
}
for d != num-1 {
res = (res * res) % num
d *= 2
if res == 1 {
return false, nil
}
if res == num-1 {
return true, nil
}
#FILE: Go-master/strings/isisogram_test.go
##CHUNK 1
{
"Not an isogram",
"Randomstring",
4,
false,
errors.New("Invalid isogram order provided"),
},
{
"Third order isogram checked as first order",
"Deeded",
1,
false,
nil,
},
}
func TestIsIsogram(t *testing.T) {
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
actualVal, actualErr := strings.IsIsogram(test.input, test.order)
#FILE: Go-master/structure/tree/tree_test.go
##CHUNK 1
if _, ok := tree.Min(); ok {
t.Errorf("Error with Min method.")
}
if _, ok := tree.Max(); ok {
t.Errorf("Error with Max method.")
}
tree.Push(nums...)
if min, ok := tree.Min(); !ok || min != nums[0] {
t.Errorf("Error with Min method.")
}
if max, ok := tree.Max(); !ok || max != nums[ll-1] {
t.Errorf("Error with Max method.")
}
}
lens := []int{500, 1_000, 10_000}
for _, ll := range lens {
nums := rand.Perm(ll)
sort.Ints(nums)
#FILE: Go-master/strings/charoccurrence.go
##CHUNK 1
// returns a map with `rune` as keys and the count as value.
func CountChars(text string) map[rune]int {
charMap := make(map[rune]int, 0)
for _, c := range text {
if _, ok := charMap[c]; !ok {
charMap[c] = 0
}
charMap[c]++
}
return charMap
}
#CURRENT FILE: Go-master/strings/isisogram.go
|
Go-master
| 2
|
func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {
populationNum := conf.PopulationNum
if populationNum == 0 {
populationNum = 200
}
selectionNum := conf.SelectionNum
if selectionNum == 0 {
selectionNum = 50
}
// Verify if 'populationNum' s bigger than 'selectionNum'
if 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
}
|
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
}
|
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
}
|
GeneticString
| 70
| 196
|
strings/genetic/genetic.go
|
#FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x 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++ {
##CHUNK 2
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)
##CHUNK 3
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
##CHUNK 4
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)
#FILE: Go-master/sort/countingsort.go
##CHUNK 1
import "github.com/TheAlgorithms/Go/constraints"
func Count[T constraints.Integer](data []T) []T {
if len(data) == 0 {
return data
}
var aMin, aMax = data[0], data[0]
for _, x := range data {
if x < aMin {
aMin = x
}
if x > aMax {
aMax = x
}
}
count := make([]int, aMax-aMin+1)
for _, x := range data {
count[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.
}
#FILE: Go-master/strings/search/boyermoore.go
##CHUNK 1
// using booyer moore horspool modification
// O(n) space instead of O(n**2)
bcr := make(map[byte]int)
for i := 0; i < n-1; i++ {
bcr[pattern[i]] = n - i - 1
}
// Apostolico–Giancarlo modification
// allow to skip patterns that we know matches
// let us do O(l) instead of O(ln)
skips := make(map[int]int)
for _, s := range bcr {
i := 0
for ; i < n-s; i++ {
if pattern[n-1-i] != pattern[n-1-s-i] {
break
}
}
skips[s] = i
}
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
// 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
}
#FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
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++ {
#FILE: Go-master/structure/tree/btree.go
##CHUNK 1
return node.children[node.numKeys].Max()
}
func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {
node.Verify(tree)
if node.isLeaf {
// Case 1: Node is a leaf. Directly delete the key.
for i := 0; i < node.numKeys; i++ {
if key == node.keys[i] {
node.DeleteIthKey(i)
return
}
}
return
}
minKeys := minKeys(tree.maxKeys)
i := 0
for ; i < node.numKeys; i++ {
if key == node.keys[i] {
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
#CURRENT FILE: Go-master/strings/genetic/genetic.go
|
Go-master
| 3
|
func Distance(str1, str2 string, icost, scost, dcost int) int {
row1 := make([]int, len(str2)+1)
row2 := make([]int, len(str2)+1)
for i := 1; i <= len(str2); i++ {
row1[i] = i * icost
}
for i := 1; i <= len(str1); i++ {
row2[0] = i * dcost
for j := 1; j <= len(str2); j++ {
if str1[i-1] == str2[j-1] {
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]
}
|
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]
}
|
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]
}
|
Distance
| 9
| 41
|
strings/levenshtein/levenshteindistance.go
|
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
##CHUNK 2
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]
}
#FILE: Go-master/dynamic/wildcardmatching.go
##CHUNK 1
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[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]
}
}
##CHUNK 2
}
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)]
}
#FILE: Go-master/dynamic/interleavingstrings.go
##CHUNK 1
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= 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++ {
##CHUNK 2
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)]
}
#FILE: Go-master/dynamic/longestpalindromicsubsequence.go
##CHUNK 1
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][j] = 2 + dp[i+1][j-1]
}
} else {
dp[i][j] = Max(dp[i+1][j], dp[i][j-1])
}
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
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]
}
}
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 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]
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#CURRENT FILE: Go-master/strings/levenshtein/levenshteindistance.go
|
Go-master
| 4
|
func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[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])
}
|
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])
}
|
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])
}
|
LongestPalindrome
| 36
| 62
|
strings/manacher/longestpalindrome.go
|
#FILE: Go-master/strings/search/boyermoore.go
##CHUNK 1
skip := 0
jump := n
for i := 0; i < l-n+1; {
skip = skips[jump]
for k := n - 1; k > -1; k-- {
if text[i+k] != pattern[k] {
jump, ok := bcr[text[i+k]]
if !ok {
jump = n
}
i += jump
break
}
if k == n-jump {
k -= skip
}
if k == 0 {
positions = append(positions, i)
jump = 1
##CHUNK 2
skips := make(map[int]int)
for _, s := range bcr {
i := 0
for ; i < n-s; i++ {
if pattern[n-1-i] != pattern[n-1-s-i] {
break
}
}
skips[s] = i
}
skip := 0
jump := n
for i := 0; i < l-n+1; {
skip = skips[jump]
for k := n - 1; k > -1; k-- {
if text[i+k] != pattern[k] {
jump, ok := bcr[text[i+k]]
if !ok {
jump = n
#FILE: Go-master/math/binomialcoefficient.go
##CHUNK 1
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
res *= (n - i)
res /= (i + 1)
}
return res, nil
}
##CHUNK 2
package math
import (
"errors"
)
var ErrPosArgsOnly error = errors.New("arguments must be positive")
// C is Binomial Coefficient function
// This function returns C(n, k) for given n and k
func Combinations(n int, k int) (int, error) {
if n < 0 || k < 0 {
return -1, ErrPosArgsOnly
}
if k > (n - k) {
k = n - k
}
res := 1
for i := 0; i < k; i++ {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/matrixmultiplication.go
##CHUNK 1
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]
}
/*
##CHUNK 2
}
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++ {
#FILE: Go-master/math/kthnumber.go
##CHUNK 1
return kthNumber(nums, index)
}
// kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).
func kthNumber(nums []int, k int) (int, error) {
if k < 0 || k >= len(nums) {
return -1, search.ErrNotFound
}
start := 0
end := len(nums) - 1
for start <= end {
pivot := sort.Partition(nums, start, end)
if k == pivot {
return nums[pivot], nil
}
if k > pivot {
start = pivot + 1
continue
}
end = pivot - 1
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
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
#FILE: Go-master/dynamic/longestpalindromicsubstring.go
##CHUNK 1
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
}
}
#CURRENT FILE: Go-master/strings/manacher/longestpalindrome.go
|
Go-master
| 5
|
func horspool(t, p []rune) (int, error) {
shiftMap := computeShiftMap(t, p)
pos := 0
for pos <= len(t)-len(p) {
if isMatch(pos, t, p) {
return pos, nil
}
if pos+len(p) >= len(t) {
// because the remaining length of the input string
// is the same as the length of the pattern
// and it does not 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
}
|
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
}
|
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
}
|
horspool
| 15
| 36
|
strings/horspool/horspool.go
|
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
// prettyPrint(current, j, n, pos, t, oracle)
// }
// current = getTransition(current, t[pos+j-1], oracle)
// j--
// }
// if stateExists(current, oracle) {
// if debugMode == true {
// fmt.Printf(" We got an occurrence!")
// }
// occurrences[currentOcc] = pos
##CHUNK 2
// prettyPrint(current, j, n, pos, t, oracle)
// }
// current = getTransition(current, t[pos+j-1], oracle)
// j--
// }
// if stateExists(current, oracle) {
// if debugMode == true {
// fmt.Printf(" We got an occurrence!")
// }
// occurrences[currentOcc] = pos
// currentOcc++
// }
// pos = pos + j + 1
// if pos+m-1 < len(t) {
// if debugMode == true {
// fmt.Printf("\n\nposition %d:\n", pos+m-1)
// }
// }
// }
// elapsed := time.Since(startTime)
##CHUNK 3
// // Function bom performing the Backward Oracle Matching algorithm.
// // Prints whether the word/pattern was found + positions of possible multiple occurrences
// // or that the word was not found.
// func bom(t, p string) {
// startTime := time.Now()
// n, m := len(t), len(p)
// var current, j, pos int
// oracle := oracleOnLine(reverse(p))
// occurrences := make([]int, len(t))
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
#FILE: Go-master/structure/queue/queuelinklistwithlist.go
##CHUNK 1
// Back it will return the back value
func (lq *LQueue) Back() (any, error) {
if !lq.Empty() {
val := lq.queue.Back().Value
return val, nil
}
return "", fmt.Errorf("error queue is empty")
}
// Len it will return the length of list
func (lq *LQueue) Len() int {
return lq.queue.Len()
}
// Empty is check our list is empty or not
func (lq *LQueue) Empty() bool {
return lq.queue.Len() == 0
}
#FILE: Go-master/search/jump.go
##CHUNK 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) {
##CHUNK 2
}
// 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
}
}
#FILE: Go-master/sort/cyclesort.go
##CHUNK 1
counter, cycle, len := 0, 0, len(arr)
// Early return if the array too small
if len <= 1 {
return arr
}
for cycle = 0; cycle < len-1; cycle++ {
elem := arr[cycle]
// Find total smaller elements to right
pos := cycle
for counter = cycle + 1; counter < len; counter++ {
if arr[counter] < elem {
pos++
}
}
// In case this element is already in correct position, let's skip processing
if pos == cycle {
continue
}
// In case we have same elements, we want to skip to the end of that list as well, ignoring order
#FILE: Go-master/structure/queue/queuelinkedlist.go
##CHUNK 1
if ll.head == nil {
ll.tail = nil
}
ll.length--
return data
}
// isEmpty it will check our list is empty or not
func (ll *Queue) isEmpty() bool {
return ll.length == 0
}
// len is return the length of queue
func (ll *Queue) len() int {
return ll.length
}
// frontQueue it will return the front data
func (ll *Queue) frontQueue() any {
#FILE: Go-master/strings/search/naive.go
##CHUNK 1
package search
// Implementation of naive string search
// O(n*m) where n=len(txt) and m=len(pattern)
func Naive(text string, pattern string) []int {
var positions []int
for i := 0; i <= len(text)-len(pattern); i++ {
var match bool = true
for j := 0; j < len(pattern); j++ {
if text[i+j] != pattern[j] {
match = false
break
}
}
if match {
positions = append(positions, i)
}
}
return positions
#CURRENT FILE: Go-master/strings/horspool/horspool.go
##CHUNK 1
// in order to handle multy-byte character properly
// the input is converted into rune arrays
return horspool([]rune(t), []rune(p))
}
}
// 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)
|
Go-master
| 6
|
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && 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
}
|
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
}
|
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
}
|
ConstructTrie
| 3
| 35
|
strings/ahocorasick/shared.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
stateIsTerminal[current] = true
f[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))
}
} else {
s[current] = i //initial state?
}
}
a := ComputeAlphabet(p) // concat of all patterns in 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)
}
}
}
##CHUNK 2
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 {
##CHUNK 3
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
}
}
}
##CHUNK 4
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
}
##CHUNK 5
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
}
##CHUNK 6
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]] {
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //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))
##CHUNK 2
}
// 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]
##CHUNK 3
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
}
}
}
}
##CHUNK 4
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
}
#CURRENT FILE: Go-master/strings/ahocorasick/shared.go
|
Go-master
| 7
|
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok := 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,
}
}
|
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,
}
}
|
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,
}
}
|
Advanced
| 9
| 42
|
strings/ahocorasick/advancedahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
if ok {
for i := range f[current] {
if p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match
newOccurrences := IntArrayCapUp(occurrences[f[current][i]])
occurrences[f[current][i]] = newOccurrences
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,
}
##CHUNK 2
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
}
}
}
}
##CHUNK 3
}
// 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]
##CHUNK 4
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++ {
##CHUNK 5
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++ {
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
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 {
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// currentOcc++
// }
// pos = pos + j + 1
// if pos+m-1 < len(t) {
// if debugMode == true {
// fmt.Printf("\n\nposition %d:\n", pos+m-1)
// }
// }
// }
// elapsed := time.Since(startTime)
// fmt.Printf("\n\nElapsed %f secs\n", elapsed.Seconds())
// fmt.Printf("\n\n")
// if currentOcc > 0 {
// fmt.Printf("Word %q was found %d times at positions: ", p, currentOcc)
// for k := 0; k < currentOcc-1; k++ {
// fmt.Printf("%d, ", occurrences[k])
// }
// fmt.Printf("%d", occurrences[currentOcc-1])
// fmt.Printf(".\n")
// }
##CHUNK 2
// // Function bom performing the Backward Oracle Matching algorithm.
// // Prints whether the word/pattern was found + positions of possible multiple occurrences
// // or that the word was not found.
// func bom(t, p string) {
// startTime := time.Now()
// n, m := len(t), len(p)
// var current, j, pos int
// oracle := oracleOnLine(reverse(p))
// occurrences := make([]int, len(t))
// currentOcc := 0
// pos = 0
// if debugMode == true {
// fmt.Printf("\n\nWe are reading backwards in %q, searching for %q\n\nat position %d:\n", t, p, pos+m-1)
// }
// for pos <= n-m {
// current = 0 //initial state of the oracle
// j = m
// for j > 0 && stateExists(current, oracle) {
// if debugMode == true {
#CURRENT FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
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
}
##CHUNK 2
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++ {
|
Go-master
| 8
|
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(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
}
|
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
}
|
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
}
|
BuildExtendedAc
| 45
| 81
|
strings/ahocorasick/advancedahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// Functions that builds Aho Corasick automaton.
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //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))
##CHUNK 2
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
}
##CHUNK 3
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++ {
##CHUNK 4
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
}
}
}
}
##CHUNK 5
}
// 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]
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
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 {
##CHUNK 2
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 {
##CHUNK 3
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
#CURRENT FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
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
}
}
}
##CHUNK 2
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
}
|
Go-master
| 9
|
func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac) != -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,
}
}
|
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,
}
}
|
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,
}
}
|
AhoCorasick
| 14
| 50
|
strings/ahocorasick/ahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
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
}
}
}
##CHUNK 2
_, 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{
##CHUNK 3
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
}
##CHUNK 4
}
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
##CHUNK 5
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)
}
}
}
##CHUNK 6
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 {
##CHUNK 7
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
}
##CHUNK 8
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]] {
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
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 {
#CURRENT FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
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
| 10
|
func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(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
}
|
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
}
|
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
}
|
BuildAc
| 53
| 76
|
strings/ahocorasick/ahocorasick.go
|
#FILE: Go-master/strings/ahocorasick/advancedahocorasick.go
##CHUNK 1
resultOccurrences,
}
}
// BuildExtendedAc Functions that builds extended Aho Corasick automaton.
func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]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]] {
##CHUNK 2
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 {
##CHUNK 3
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)
}
}
}
##CHUNK 4
}
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
##CHUNK 5
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
}
#FILE: Go-master/strings/ahocorasick/shared.go
##CHUNK 1
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 {
##CHUNK 2
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 {
#FILE: Go-master/strings/bom/bom.go
##CHUNK 1
// }
// // Adds one letter to the oracle.
// func oracleAddLetter(oracle map[int]map[uint8]int, supply []int, orP string, o uint8) (oracleToReturn map[int]map[uint8]int, orPToReturn string) {
// m := len(orP)
// var s int
// createNewState(m+1, oracle)
// createTransition(m, o, m+1, oracle)
// k := supply[m]
// for k > -1 && getTransition(k, o, oracle) == -1 {
// createTransition(k, o, m+1, oracle)
// k = supply[k]
// }
// if k == -1 {
// s = 0
// } else {
// s = getTransition(k, o, oracle)
// }
// supply[m+1] = s
// return oracle, orP + string(o)
#CURRENT FILE: Go-master/strings/ahocorasick/ahocorasick.go
##CHUNK 1
}
// 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]
##CHUNK 2
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
}
}
}
}
|
Go-master
| 11
|
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is 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
}
|
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
}
|
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
}
|
HuffTree
| 34
| 56
|
compression/huffmancoding.go
|
#FILE: Go-master/sqrt/sqrtdecomposition_test.go
##CHUNK 1
func(q1, q2 int) int { return q1 + q2 },
func(q, a, b int) int { return q - a + b },
)
for i := 0; i < len(test.updates); i++ {
s.Update(test.updates[i].index, test.updates[i].value)
}
for i := 0; i < len(test.queries); i++ {
result := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex)
if result != test.expected[i] {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expected result: %d\nFound: %d\n", test.expected[i], result)
}
}
})
}
}
##CHUNK 2
{index: 3, value: 3},
{index: 6, value: 6}},
queries: []query{{3, 5}, {7, 8}, {3, 7}, {0, 10}},
expected: []int{4, 1, 11, 18},
},
}
for _, test := range sqrtDecompositionTestData {
t.Run(test.description, func(t *testing.T) {
s := sqrt.NewSqrtDecomposition(test.array,
func(e int) int { return e },
func(q1, q2 int) int { return q1 + q2 },
func(q, a, b int) int { return q - a + b },
)
for i := 0; i < len(test.updates); i++ {
s.Update(test.updates[i].index, test.updates[i].value)
}
for i := 0; i < len(test.queries); i++ {
result := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex)
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
if pivot.LeftIsNil() {
pivotEnded = true
}
}
return maxPathValue
}
// PrintReport is a method that prints a report of the tree
// Node by node
func (t *Tree) PrintReport() {
t.Nodes = make(map[int]struct{})
if t.Root == nil {
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
head := 0
#FILE: Go-master/math/pi/montecarlopi.go
##CHUNK 1
}
// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform
// way possible.
// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil
func splitInt(x int, n int) ([]int, error) {
if x < n {
return nil, fmt.Errorf("x 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++ {
#FILE: Go-master/dynamic/longestincreasingsubsequence.go
##CHUNK 1
)
// LongestIncreasingSubsequence returns the longest increasing subsequence
// where all elements of the subsequence are sorted in increasing order
func LongestIncreasingSubsequence(elements []int) int {
n := len(elements)
lis := make([]int, n)
for i := range lis {
lis[i] = 1
}
for i := range lis {
for j := 0; j < i; j++ {
if elements[i] > elements[j] && lis[i] < lis[j]+1 {
lis[i] = lis[j] + 1
}
}
}
res := 0
for _, value := range lis {
res = max.Int(res, value)
#FILE: Go-master/structure/tree/rbtree.go
##CHUNK 1
type RB[T constraints.Ordered] struct {
Root *RBNode[T]
_NIL *RBNode[T] // a sentinel value for nil
}
// NewRB creates a new Red-Black Tree
func NewRB[T constraints.Ordered]() *RB[T] {
leaf := &RBNode[T]{color: Black, left: nil, right: nil}
leaf.parent = leaf
return &RB[T]{
Root: leaf,
_NIL: leaf,
}
}
// Empty determines the Red-Black tree is empty
func (t *RB[T]) Empty() bool {
return t.Root == t._NIL
}
#FILE: Go-master/graph/coloring/graph_test.go
##CHUNK 1
func getTestGraphsForNegativeTests() (list []*testGraph) {
list = getTestGraphs()
list[0].VertexColors = nil
list[1].VertexColors = map[int]coloring.Color{}
for v := range list[2].VertexColors {
in := len(list[2].VertexColors) - v - 1
list[2].VertexColors[v] = list[2].VertexColors[in]
}
for v := range list[3].VertexColors {
list[3].VertexColors[v] = 1
}
return list[:4]
}
func TestGraphValidateColorsOfVertex_Negative(t *testing.T) {
for i, tt := range getTestGraphsForNegativeTests() {
t.Run(strconv.Itoa(i), func(t *testing.T) {
if err := tt.Graph.ValidateColorsOfVertex(tt.VertexColors); err == nil {
t.Errorf("ValidateColorsOfVertex() error = nil, want some err")
}
#CURRENT FILE: Go-master/compression/huffmancoding.go
##CHUNK 1
// HuffTree returns the root Node of the Huffman tree by compressing listfreq.
// The compression produces the most optimal code lengths, provided listfreq is ordered,
}
// 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:]
}
##CHUNK 2
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,
}
// 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:]
##CHUNK 3
}
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
|
Go-master
| 12
|
func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
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 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 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
}
}
|
DepthFirstSearchHelper
| 26
| 56
|
graph/depthfirstsearch.go
|
#FILE: Go-master/structure/tree/tree.go
##CHUNK 1
return searchTreeHelper(node.Left(), nilNode, key)
}
return searchTreeHelper(node.Right(), nilNode, key)
}
func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {
var stack []Node[T]
var ret []T
for node != nilNode || len(stack) > 0 {
for node != nilNode {
stack = append(stack, node)
node = node.Left()
}
node = stack[len(stack)-1]
stack = stack[:len(stack)-1]
ret = append(ret, node.Key())
node = node.Right()
}
##CHUNK 2
func searchTreeHelper[T constraints.Ordered](node, nilNode Node[T], key T) (Node[T], bool) {
if node == nilNode {
return node, false
}
if key == node.Key() {
return node, true
}
if key < node.Key() {
return searchTreeHelper(node.Left(), nilNode, key)
}
return searchTreeHelper(node.Right(), nilNode, key)
}
func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {
var stack []Node[T]
var ret []T
for node != nilNode || len(stack) > 0 {
##CHUNK 3
for node != nilNode {
stack = append(stack, node)
node = node.Left()
}
node = stack[len(stack)-1]
stack = stack[:len(stack)-1]
ret = append(ret, node.Key())
node = node.Right()
}
return ret
}
func preOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) {
if n == nilNode {
return
}
*traversal = append(*traversal, n.Key())
#FILE: Go-master/graph/kosaraju.go
##CHUNK 1
var sccs [][]int
for len(stack) > 0 {
// Pop vertex from stack
v := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// Perform DFS if not already visited.
if !visited[v] {
scc := []int{}
transposed.dfs(v, visited, &scc)
sccs = append(sccs, scc)
}
}
return sccs
}
// Helper function to fill the stack with vertices in the order of their finish times.
func (g *Graph) fillOrder(v int, visited []bool, stack *[]int) {
#FILE: Go-master/other/nested/nestedbrackets.go
##CHUNK 1
// 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
}
##CHUNK 2
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
##CHUNK 3
// 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 {
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
for len(stack) > 0 {
current := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// If we run out of steps, we check the sum of the path,
// update the maxPathValue if necessary and continue
if current.StepsLeft == 0 {
if current.Sum > maxPathValue {
maxPathValue = current.Sum
pivot = current.Node
}
continue
}
if !current.Node.RightIsNil() {
stack = append(stack, DFSNode{
Node: current.Node.Right(),
StepsLeft: current.StepsLeft - 1,
Sum: current.Sum + int(current.Node.Right().Value()),
})
##CHUNK 2
var pivot Node = r.Root
pivotEnded := false
maxPathValue := int(pivot.Value())
stack := make([]DFSNode, 0)
for !pivotEnded {
stack = append(stack, DFSNode{Node: pivot, StepsLeft: deep, Sum: maxPathValue})
for len(stack) > 0 {
current := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// If we run out of steps, we check the sum of the path,
// update the maxPathValue if necessary and continue
if current.StepsLeft == 0 {
if current.Sum > maxPathValue {
maxPathValue = current.Sum
pivot = current.Node
#CURRENT FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
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 DepthFirstSearch(start, end int, nodes []int, edges [][]bool) ([]int, bool) {
return DepthFirstSearchHelper(start, end, nodes, edges, false)
}
|
Go-master
| 13
|
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
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
}
|
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
}
|
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
}
|
EdmondKarp
| 42
| 92
|
graph/edmondkarp.go
|
#FILE: Go-master/graph/floydwarshall.go
##CHUNK 1
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
numVertices := len(graph)
// Initializing result matrix and filling it up with same values as given 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]
}
}
##CHUNK 2
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)
##CHUNK 3
// 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]
}
}
#FILE: Go-master/sort/bucketsort.go
##CHUNK 1
}
// find the maximum and minimum elements in arr
max := arr[0]
min := arr[0]
for _, v := range arr {
if v > max {
max = v
}
if v < min {
min = v
}
}
// create an empty bucket for each element in arr
bucket := make([][]T, len(arr))
// put each element in the appropriate bucket
for _, v := range arr {
bucketIndex := int((v - min) / (max - min) * T(len(arr)-1))
##CHUNK 2
package sort
import "github.com/TheAlgorithms/Go/constraints"
// Bucket sorts a slice. It is mainly useful
// when input is uniformly distributed over a range.
func Bucket[T constraints.Number](arr []T) []T {
// early return if the array too small
if len(arr) <= 1 {
return arr
}
// find the maximum and minimum elements in arr
max := arr[0]
min := arr[0]
for _, v := range arr {
if v > max {
max = v
}
if v < min {
#FILE: Go-master/graph/coloring/bipartite.go
##CHUNK 1
}
}
for i := range g.edges {
if colors[i] == 0 {
colors[i] = 1
colorNode(i)
}
}
return colors
}
// basically tries to color the graph in two colors if each edge
// connects 2 differently colored nodes the graph can be considered bipartite
func BipartiteCheck(N int, edges [][]int) bool {
var graph Graph
for i := 0; i < N; i++ {
graph.AddVertex(i)
}
##CHUNK 2
return colors
}
// basically tries to color the graph in two colors if each edge
// connects 2 differently colored nodes the graph can be considered bipartite
func BipartiteCheck(N int, edges [][]int) bool {
var graph Graph
for i := 0; i < N; i++ {
graph.AddVertex(i)
}
for _, e := range edges {
graph.AddEdge(e[0], e[1])
}
return graph.ValidateColorsOfVertex(graph.TryBipartiteColoring()) == nil
}
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
// 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 {
#CURRENT FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
##CHUNK 2
"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
|
Go-master
| 14
|
func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
queue := make([]int, 0)
discovered := make([]int, nodes)
discovered[start] = 1
queue = append(queue, start)
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(edges[v]); i++ {
if 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
}
|
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
}
|
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
}
|
BreadthFirstSearch
| 8
| 27
|
graph/breadthfirstsearch.go
|
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
parent := make(map[int]int)
// BFS loop with saving the path found
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(rGraph[v]); i++ {
if !marked[i] && rGraph[v][i] > 0 {
parent[i] = v
// Terminate the BFS, if we reach to sink
if i == sink {
return parent
}
marked[i] = true
queue = append(queue, i)
}
}
}
// source and sink are not in the same connected component
return nil
##CHUNK 2
"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
##CHUNK 3
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++ {
#FILE: Go-master/graph/kahn.go
##CHUNK 1
queue := make([]int, 0, n)
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// order holds a valid topological order
order := make([]int, 0, n)
// process the dependency-free vertices
// every time we process a vertex, we "remove" it from the graph
for len(queue) > 0 {
// pop the first vertex from the queue
vtx := queue[0]
queue = queue[1:]
// add the vertex to the topological order
order = append(order, vtx)
// "remove" all the edges coming out of this vertex
##CHUNK 2
for _, d := range dependencies {
// make sure we don't add the same edge twice
if _, ok := g.edges[d[0]][d[1]]; !ok {
g.AddEdge(d[0], d[1])
inDegree[d[1]]++
}
}
// queue holds all vertices with in-degree 0
// these vertices have no dependency and thus can be ordered first
queue := make([]int, 0, n)
for i := 0; i < n; i++ {
if inDegree[i] == 0 {
queue = append(queue, i)
}
}
// order holds a valid topological order
order := make([]int, 0, n)
##CHUNK 3
// process the dependency-free vertices
// every time we process a vertex, we "remove" it from the graph
for len(queue) > 0 {
// pop the first vertex from the queue
vtx := queue[0]
queue = queue[1:]
// add the vertex to the topological order
order = append(order, vtx)
// "remove" all the edges coming out of this vertex
// every time we remove an edge, the corresponding in-degree reduces by 1
// if all dependencies on a vertex is removed, enqueue the vertex
for neighbour := range g.edges[vtx] {
inDegree[neighbour]--
if inDegree[neighbour] == 0 {
queue = append(queue, neighbour)
}
}
}
#FILE: Go-master/project_euler/problem_18/tree.go
##CHUNK 1
ID int
}
func (t *Tree) BFSInsert(value NodeValue) {
t.Nodes = make(map[int]struct{}) // Reset the nodes map
if t.Root == nil {
t.Root = &Root{NodeValue: value, ID: 0}
t.ID = 1
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
t.isInQueue(t.Root.GetID())
head := 0
for head < len(queue) {
current := queue[head]
##CHUNK 2
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
t.isInQueue(t.Root.GetID())
head := 0
for head < len(queue) {
current := queue[head]
head++
childNode := current.CreateChild(value, t.ID)
if current.HasSpace() {
current.Insert(childNode)
t.ID++
return
}
if !t.isInQueue(current.Left().GetID()) { // Avoid duplicates
##CHUNK 3
func (t *Tree) PrintReport() {
t.Nodes = make(map[int]struct{})
if t.Root == nil {
return
}
queue := make([]Node, 0)
queue = append(queue, t.Root)
head := 0
for head < len(queue) {
current := queue[head]
head++
print("ID:", current.GetID())
print(", Current node:", current.Value())
if !current.LeftIsNil() {
print(", Left Child:", current.Left().Value())
#FILE: Go-master/graph/depthfirstsearch.go
##CHUNK 1
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++ {
#CURRENT FILE: Go-master/graph/breadthfirstsearch.go
|
Go-master
| 15
|
func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
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
}
|
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
}
|
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
}
|
FloydWarshall
| 16
| 54
|
graph/floydwarshall.go
|
#FILE: Go-master/graph/edmondkarp.go
##CHUNK 1
}
func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
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
##CHUNK 2
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
##CHUNK 3
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++ {
#FILE: Go-master/math/matrix/strassenmatrixmultiply.go
##CHUNK 1
return Matrix[T]{}, err
}
C21, err := M2.Add(M4)
if err != nil {
return Matrix[T]{}, err
}
C22, err := A10.Subtract(M2)
if err != nil {
return Matrix[T]{}, err
}
// Combine subMatrices into the result matrix
var zeroVal T
C := New(n, n, zeroVal)
for i := 0; i < mid; i++ {
for j := 0; j < mid; j++ {
val, err := C11.Get(i, j)
if err != nil {
return Matrix[T]{}, err
##CHUNK 2
// Combine subMatrices into the result matrix
var zeroVal T
C := New(n, n, zeroVal)
for i := 0; i < mid; i++ {
for j := 0; j < mid; j++ {
val, err := C11.Get(i, j)
if err != nil {
return Matrix[T]{}, err
}
err = C.Set(i, j, val)
if err != nil {
return Matrix[T]{}, err
}
val, err = C12.Get(i, j)
if err != nil {
return Matrix[T]{}, err
#FILE: Go-master/math/matrix/strassenmatrixmultiply_test.go
##CHUNK 1
// Check the values in the result matrix
for i := 0; i < expectedRows; i++ {
for j := 0; j < expectedColumns; j++ {
val, err := resultMatrix.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
expVal, err := expectedData.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
if val != expVal {
t.Errorf("Expected value %d at (%d, %d) in result matrix, but got %d", expVal, i, j, val)
}
}
}
}
func TestMatrixMultiplication(t *testing.T) {
rand.New(rand.NewSource(time.Now().UnixNano()))
##CHUNK 2
// Generate random matrices for testing
size := 1 << (rand.Intn(8) + 1) // tests for matrix with n as power of 2
matrixA := MakeRandomMatrix[int](size, size)
matrixB := MakeRandomMatrix[int](size, size)
// Calculate the expected result using the standard multiplication
expected, err := matrixA.Multiply(matrixB)
if err != nil {
t.Error("copyMatrix.Set error: " + err.Error())
}
// Calculate the result using the Strassen algorithm
result, err := matrixA.StrassenMatrixMultiply(matrixB)
if err != nil {
t.Error("copyMatrix.Set error: " + err.Error())
}
// Check if the result matches the expected result
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
val, err := result.Get(i, j)
##CHUNK 3
columns := resultMatrix.Columns()
if rows != expectedRows {
t.Errorf("Expected %d rows in result matrix, but got %d", expectedRows, rows)
}
if columns != expectedColumns {
t.Errorf("Expected %d columns in result matrix, but got %d", expectedColumns, columns)
}
// Check the values in the result matrix
for i := 0; i < expectedRows; i++ {
for j := 0; j < expectedColumns; j++ {
val, err := resultMatrix.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
}
expVal, err := expectedData.Get(i, j)
if err != nil {
t.Fatalf("Failed to copy matrix: %v", err)
#FILE: Go-master/math/matrix/multiply.go
##CHUNK 1
for i := 0; i < m1.Rows(); i++ {
for j := 0; j < m2.Columns(); j++ {
i, j := i, j // Capture the loop variable for the goroutine
wg.Add(1)
go func() {
defer wg.Done()
// Compute the dot product of the row from the first matrix and the column from the second matrix.
dotProduct := zeroVal
for k := 0; k < m1.Columns(); k++ {
select {
case <-ctx.Done():
return // Context canceled; return without an error
default:
}
val1, err := m1.Get(i, k)
if err != nil {
cancel()
select {
case errCh <- err:
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
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
}
#CURRENT FILE: Go-master/graph/floydwarshall.go
|
Go-master
| 16
|
func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.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
}
|
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
}
|
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
}
|
KruskalMST
| 22
| 50
|
graph/kruskal.go
|
#FILE: Go-master/dynamic/optimalbst.go
##CHUNK 1
}
// Total cost for root k
cost := sum + leftCost + rightCost
// Update dp[i][j] with the minimum cost
dp[i][j] = min.Int(dp[i][j], cost)
}
}
}
return dp[0][n-1]
}
// Helper function to sum the frequencies
func sum(freq []int, i, j int) int {
total := 0
for k := i; k <= j; k++ {
total += freq[k]
}
return total
##CHUNK 2
} 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)
}
}
}
#FILE: Go-master/graph/prim.go
##CHUNK 1
var mst []Edge
marked := make([]bool, g.vertices)
h := &minEdge{}
// Pushing neighbors of the start node to the binary heap
for neighbor, weight := range g.edges[int(start)] {
heap.Push(h, Edge{start, Vertex(neighbor), weight})
}
marked[start] = true
cost := 0
for h.Len() > 0 {
e := heap.Pop(h).(Edge)
end := int(e.End)
// To avoid cycles
if marked[end] {
continue
}
marked[end] = true
cost += e.Weight
mst = append(mst, e)
// Check for neighbors of the newly added edge's End vertex
##CHUNK 2
e := heap.Pop(h).(Edge)
end := int(e.End)
// To avoid cycles
if marked[end] {
continue
}
marked[end] = true
cost += e.Weight
mst = append(mst, e)
// Check for neighbors of the newly added edge's End vertex
for neighbor, weight := range g.edges[end] {
if !marked[neighbor] {
heap.Push(h, Edge{e.End, Vertex(neighbor), weight})
}
}
}
return mst, cost
}
##CHUNK 3
// The Prim's algorithm computes the minimum spanning tree for a weighted undirected graph
// Worst Case Time Complexity: O(E log V) using Binary heap, where V is the number of vertices and E is the number of edges
// Space Complexity: O(V + E)
// Implementation is based on the book 'Introduction to Algorithms' (CLRS)
package graph
import (
"container/heap"
)
type minEdge []Edge
func (h minEdge) Len() int { return len(h) }
func (h minEdge) Less(i, j int) bool { return h[i].Weight < h[j].Weight }
func (h minEdge) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minEdge) Push(x interface{}) {
*h = append(*h, x.(Edge))
}
#FILE: Go-master/graph/graph.go
##CHUNK 1
g.edges[v] = make(map[int]int)
}
}
// AddEdge will add a new edge between the provided vertices in the graph
func (g *Graph) AddEdge(one, two int) {
// Add an edge with 0 weight
g.AddWeightedEdge(one, two, 0)
}
// AddWeightedEdge will add a new weighted edge between the provided vertices in the graph
func (g *Graph) AddWeightedEdge(one, two, weight int) {
// Add vertices: one and two to the graph if they are not present
g.AddVertex(one)
g.AddVertex(two)
// And finally add the edges
// one->two and two->one for undirected graph
// one->two for directed graphs
g.edges[one][two] = weight
##CHUNK 2
// AddWeightedEdge will add a new weighted edge between the provided vertices in the graph
func (g *Graph) AddWeightedEdge(one, two, weight int) {
// Add vertices: one and two to the graph if they are not present
g.AddVertex(one)
g.AddVertex(two)
// And finally add the edges
// one->two and two->one for undirected graph
// one->two for directed graphs
g.edges[one][two] = weight
if !g.Directed {
g.edges[two][one] = weight
}
}
##CHUNK 3
// AddVertex will add a new vertex in the graph.
// If the vertex already exists it will do nothing.
func (g *Graph) AddVertex(v int) {
if g.edges == nil {
g.edges = make(map[int]map[int]int)
}
// Check if vertex is present or not
if _, ok := g.edges[v]; !ok {
g.edges[v] = make(map[int]int)
}
}
// AddEdge will add a new edge between the provided vertices in the graph
func (g *Graph) AddEdge(one, two int) {
// Add an edge with 0 weight
g.AddWeightedEdge(one, two, 0)
}
##CHUNK 4
// This file contains the simple structural implementation of
// directed & undirected graphs used within the graph package
// Author(s): [Shivam](https://github.com/Shivam010), [Tahmeed](https://github.com/Tahmeed156)
package graph
// Graph provides a structure to store the graph.
// It is safe to use its empty object.
type Graph struct {
vertices int
edges map[int]map[int]int // Stores weight of an edge
Directed bool // Differentiate directed/undirected graphs
}
// Constructor functions for graphs (undirected by default)
func New(v int) *Graph {
return &Graph{
vertices: v,
}
}
#FILE: Go-master/graph/topological.go
##CHUNK 1
// topological.go
// description: Topological sort
// details: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph
// space complexity: O(V) where V is the number of vertices in the graph
// reference: https://en.wikipedia.org/wiki/Topological_sorting
package graph
// Topological assumes that graph given is valid and that its
// possible to get a topological ordering.
// constraints are array of []int{a, b}, representing
// an edge going from a to b
func Topological(N int, constraints [][]int) []int {
dependencies := make([]int, N)
nodes := make([]int, N)
for i := range nodes {
nodes[i] = i
}
edges := make([][]bool, N)
#CURRENT FILE: Go-master/graph/kruskal.go
|
Go-master
| 17
|
func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
tree = new(Tree)
tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0
tree.depth = make([]int, numbersVertex)
tree.dad = make([]int, numbersVertex)
for (1 << tree.MAXLOG) <= numbersVertex {
(tree.MAXLOG) += 1
}
(tree.MAXLOG) += 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
}
|
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
}
|
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
}
|
NewTree
| 85
| 107
|
graph/lowestcommonancestor.go
|
#FILE: Go-master/graph/lowestcommonancestor_test.go
##CHUNK 1
const MAXVERTEX int = 2000
var numbersVertex int = rnd.Intn(MAXVERTEX) + 1
var root int = rnd.Intn(numbersVertex)
var edges []TreeEdge
var fullGraph []TreeEdge
for u := 0; u < numbersVertex; u++ {
for v := 0; v < numbersVertex; v++ {
fullGraph = append(fullGraph, TreeEdge{
from: u,
to: v,
})
}
}
rnd.Shuffle(len(fullGraph), func(i, j int) {
fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i]
})
par := make([]int, numbersVertex)
##CHUNK 2
from: u,
to: v,
})
}
}
rnd.Shuffle(len(fullGraph), func(i, j int) {
fullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i]
})
par := make([]int, numbersVertex)
for u := 0; u < numbersVertex; u++ {
par[u] = u
}
var findp func(int) int
findp = func(u int) int {
if u == par[u] {
return u
} else {
par[u] = findp(par[u])
##CHUNK 3
return true
}
for _, e := range fullGraph {
if join(e.from, e.to) == true {
edges = append(edges, e)
}
}
return NewTree(numbersVertex, root, edges)
}
func generateQuery(tree *Tree) []Query {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
const MAXQUERY = 50
var queries []Query
bruteforceLCA := func(u, v int) int {
for u != v {
if tree.GetDepth(u) > tree.GetDepth(v) {
#FILE: Go-master/dynamic/dicethrow.go
##CHUNK 1
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
}
}
}
}
#FILE: Go-master/dynamic/uniquepaths.go
##CHUNK 1
}
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]
}
}
#FILE: Go-master/dynamic/binomialcoefficient.go
##CHUNK 1
// }
// }
// Bin2 function
func Bin2(n int, k int) int {
var i, j int
B := make([][]int, (n + 1))
for i := range B {
B[i] = make([]int, k+1)
}
for i = 0; i <= n; i++ {
for j = 0; j <= min.Int(i, k); j++ {
if j == 0 || j == i {
B[i][j] = 1
} else {
B[i][j] = B[i-1][j-1] + B[i-1][j]
}
}
#FILE: Go-master/dynamic/editdistance.go
##CHUNK 1
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 {
dp[i][j] = i
continue
}
#FILE: Go-master/dynamic/knapsack.go
##CHUNK 1
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
dp[i+1][j] = dp[i][j]
} else {
dp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])
}
}
}
return dp[n][m]
}
/*
##CHUNK 2
)
// Max function - possible duplicate
func Max(a, b int) int {
return int(math.Max(float64(a), float64(b)))
}
// Knapsack solves knapsack problem
// return maxProfit
func Knapsack(maxWeight int, weights, values []int) int {
n := len(weights)
m := maxWeight
// create dp data structure
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i < len(weights); i++ {
for j := 0; j <= maxWeight; j++ {
if weights[i] > j {
#FILE: Go-master/dynamic/longestcommonsubsequence.go
##CHUNK 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]
}
#CURRENT FILE: Go-master/graph/lowestcommonancestor.go
|
Go-master
| 18
|
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (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
}
|
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
}
|
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
}
|
Sign
| 124
| 148
|
cipher/dsa/dsa.go
|
#CURRENT FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
}
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * 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)
##CHUNK 2
// 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),
)
##CHUNK 3
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
}
// 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
##CHUNK 4
// 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
##CHUNK 5
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)
}
##CHUNK 6
}
// 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)))
##CHUNK 7
}
// 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
##CHUNK 8
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() {
##CHUNK 9
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)
##CHUNK 10
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)
}
|
Go-master
| 19
|
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := 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
}
|
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
}
|
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
}
|
Verify
| 156
| 180
|
cipher/dsa/dsa.go
|
#FILE: Go-master/cipher/rsa/rsa2.go
##CHUNK 1
// returns the RSA object
func New() *rsa {
// The following code generates keys for RSA encryption/decryption
// 1. Choose two large prime numbers, p and q and compute n = p * q
p, q := randomPrime() // p and q stands for prime numbers
modulus := p * q // n stands for common number
// 2. Compute the totient of n, lcm(p-1, q-1)
totient := uint64(lcm.Lcm(int64(p-1), int64(q-1)))
// 3. Choose an integer e such that 1 < e < totient(n) and gcd(e, totient(n)) = 1
publicKey := uint64(2) // e stands for encryption key (public key)
for publicKey < totient {
if gcd.Recursive(int64(publicKey), int64(totient)) == 1 {
break
}
publicKey++
}
// 4. Compute d such that d * e ≡ 1 (mod totient(n))
#CURRENT FILE: Go-master/cipher/dsa/dsa.go
##CHUNK 1
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
}
// GetPublicKey returns the public key (y)
func (dsa *dsa) GetPublicKey() *big.Int {
return dsa.pubKey
##CHUNK 2
// 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
}
// 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
##CHUNK 3
// 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
}
##CHUNK 4
// 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,
##CHUNK 5
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)
}
##CHUNK 6
}
// 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)))
##CHUNK 7
}
// 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
##CHUNK 8
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() {
##CHUNK 9
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)
}
|
Go-master
| 20
|
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if 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 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 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()
}
|
Encrypt
| 12
| 48
|
cipher/railfence/railfence.go
|
#FILE: Go-master/math/matrix/isvalid.go
##CHUNK 1
package matrix
import "github.com/TheAlgorithms/Go/constraints"
// IsValid checks if the input matrix has consistent row lengths.
func IsValid[T constraints.Integer](elements [][]T) bool {
if len(elements) == 0 {
return true
}
columns := len(elements[0])
for _, row := range elements {
if len(row) != columns {
return false
}
}
return true
}
#FILE: Go-master/conversion/hexadecimaltodecimal.go
##CHUNK 1
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid 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 {
##CHUNK 2
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
}
#FILE: Go-master/conversion/hexadecimaltobinary.go
##CHUNK 1
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 {
#FILE: Go-master/math/matrix/matrix.go
##CHUNK 1
columns := len(elements[0])
matrix := Matrix[T]{
elements: make([][]T, rows),
rows: rows, // Set the rows field
columns: columns, // Set the columns field
}
for i := range matrix.elements {
matrix.elements[i] = make([]T, columns)
copy(matrix.elements[i], elements[i])
}
return matrix, nil
}
func (m Matrix[T]) Get(row, col int) (T, error) {
if row < 0 || row >= m.rows || col < 0 || col >= m.columns {
var zeroVal T
return zeroVal, errors.New("index out of range")
}
#FILE: Go-master/math/matrix/isvalid_test.go
##CHUNK 1
// Test case 3: Invalid matrix with inconsistent row lengths
invalidMatrix := [][]int{
{1, 2, 3},
{4, 5},
{6, 7, 8},
}
result3 := matrix.IsValid(invalidMatrix)
if result3 {
t.Errorf("IsValid(invalidMatrix) returned true, expected false (invalid matrix with inconsistent row lengths)")
}
}
func BenchmarkIsValid(b *testing.B) {
// Create a sample matrix for benchmarking
rows := 100
columns := 100
elements := make([][]int, rows)
for i := range elements {
#FILE: Go-master/cipher/transposition/transposition.go
##CHUNK 1
}
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)
}
#FILE: Go-master/strings/manacher/longestpalindrome.go
##CHUNK 1
}
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
#FILE: Go-master/math/matrix/determinant_test.go
##CHUNK 1
if determinant != expectedValue {
t.Errorf("Determinant of the default matrix with an initial value 0 was %d; wanted %d.", initialValue, expectedValue)
}
}
// Benchmark a 3 by 3 matrix for computational throughput
func BenchmarkSmallMatrixDeterminant(b *testing.B) {
// Create a 3 by 3 matrix for benchmarking
rows := 3
columns := 3
initialValue := 0
matrix := matrix.New(rows, columns, initialValue)
for i := 0; i < b.N; i++ {
_, _ = matrix.Determinant()
}
}
// Benchmark a 10 by 10 matrix for computational throughput.
func BenchmarkMatrixDeterminant(b *testing.B) {
#CURRENT FILE: Go-master/cipher/railfence/railfence.go
##CHUNK 1
)
}
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
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 8