The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Error code: DatasetGenerationError
Exception: TypeError
Message: Couldn't cast array of type
struct<name: string, type: string, definition_content: string>
to
{'name': Value('string'), 'type': Value('string'), 'definitions': List({'type_definition': Value('string'), 'definition_location': {'uri': Value('string'), 'range': {'start': {'line': Value('int64'), 'character': Value('int64')}, 'end': {'line': Value('int64'), 'character': Value('int64')}}}})}
Traceback: Traceback (most recent call last):
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1831, in _prepare_split_single
writer.write_table(table)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 644, in write_table
pa_table = table_cast(pa_table, self._schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2272, in table_cast
return cast_table_to_schema(table, schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2223, in cast_table_to_schema
arrays = [
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2224, in <listcomp>
cast_array_to_feature(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1795, in wrapper
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1795, in <listcomp>
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2001, in cast_array_to_feature
arrays = [
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2002, in <listcomp>
_c(array.field(name) if name in array_fields else null_array, subfeature)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1797, in wrapper
return func(array, *args, **kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2052, in cast_array_to_feature
casted_array_values = _c(array.values, feature.feature)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1797, in wrapper
return func(array, *args, **kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2092, in cast_array_to_feature
raise TypeError(f"Couldn't cast array of type\n{_short_str(array.type)}\nto\n{_short_str(feature)}")
TypeError: Couldn't cast array of type
struct<name: string, type: string, definition_content: string>
to
{'name': Value('string'), 'type': Value('string'), 'definitions': List({'type_definition': Value('string'), 'definition_location': {'uri': Value('string'), 'range': {'start': {'line': Value('int64'), 'character': Value('int64')}, 'end': {'line': Value('int64'), 'character': Value('int64')}}}})}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1456, in compute_config_parquet_and_info_response
parquet_operations = convert_to_parquet(builder)
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1055, in convert_to_parquet
builder.download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 894, in download_and_prepare
self._download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 970, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1702, in _prepare_split
for job_id, done, content in self._prepare_split_single(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1858, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating the dataset") from e
datasets.exceptions.DatasetGenerationError: An error occurred while generating the datasetNeed help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
function_component dict | function_name string | focal_code string | file_path string | file_content string | wrap_class string | class_signature string | struct_class string | package_name string |
|---|---|---|---|---|---|---|---|---|
{
"name": "IsSubsequence",
"signature": "func IsSubsequence(s string, t string) bool",
"argument_definitions": [],
"start_line": 9,
"end_line": 34
} | IsSubsequence | func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}
if s == t {
return true
}
if len(s) == 0 {
return true
}
sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}
if sIndex == len(s) {
return true
}
}
return false... | Go-master/strings/issubsequence.go | // Checks if a given string is a subsequence of another string.
// A subsequence of a given string is a string that can be derived from the given
// string by deleting some or no characters without changing the order of the
// remaining characters. (i.e., "dpr" is a subsequence of "depqr" while "drp" is not).
// Author... | strings | |||
{
"name": "IsIsogram",
"signature": "func IsIsogram(text string, order IsogramOrder) (bool, error)",
"argument_definitions": [
{
"name": "order",
"type": "IsogramOrder",
"definitions": [
{
"type_definition": "type IsogramOrder int",
"definition_location": {
... | IsIsogram | func IsIsogram(text string, order IsogramOrder) (bool, error) {
if order < First || order > Third {
return false, errors.New("Invalid isogram order provided")
}
text = strings.ToLower(text)
text = strings.Join(strings.Fields(text), "")
if hasDigit(text) || hasSymbol(text) {
return false, errors.New("Cannot c... | Go-master/strings/isisogram.go | // Checks if a given string is an isogram.
// A first-order isogram is a word in which no letter of the alphabet occurs more than once.
// A second-order isogram is a word in which each letter appears twice.
// A third-order isogram is a word in which each letter appears three times.
// wiki: https://en.wikipedia.org/w... | strings | |||
{
"name": "GeneticString",
"signature": "func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error)",
"argument_definitions": [
{
"name": "conf",
"type": "Conf",
"definitions": [
{
"type_definition": "type Conf struct {\n\t// Maximum size of the populati... | GeneticString | func GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {
populationNum := conf.PopulationNum
if populationNum == 0 {
populationNum = 200
}
selectionNum := conf.SelectionNum
if selectionNum == 0 {
selectionNum = 50
}
// Verify if 'populationNum' s bigger than 'selectionNum'
if popul... | Go-master/strings/genetic/genetic.go | // Package genetic provides functions to work with strings
// using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm
//
// Author: D4rkia
package genetic
import (
"errors"
"fmt"
"math/rand"
"sort"
"strconv"
"time"
"unicode/utf8"
)
// Population item represent a single step in the evolution pr... | genetic | |||
{
"name": "Distance",
"signature": "func Distance(str1, str2 string, icost, scost, dcost int) int",
"argument_definitions": [],
"start_line": 9,
"end_line": 41
} | Distance | func Distance(str1, str2 string, icost, scost, dcost int) int {
row1 := make([]int, len(str2)+1)
row2 := make([]int, len(str2)+1)
for i := 1; i <= len(str2); i++ {
row1[i] = i * icost
}
for i := 1; i <= len(str1); i++ {
row2[0] = i * dcost
for j := 1; j <= len(str2); j++ {
if str1[i-1] == str2[j-1] {
... | Go-master/strings/levenshtein/levenshteindistance.go | /*
This algorithm calculates the distance between two strings.
Parameters: two strings to compare and weights of insertion, substitution and deletion.
Output: distance between both strings
*/
package levenshtein
// Distance Function that gives Levenshtein Distance
func Distance(str1, str2 string, icost, scost, dcost ... | levenshtein | |||
{
"name": "LongestPalindrome",
"signature": "func LongestPalindrome(s string) string",
"argument_definitions": [],
"start_line": 36,
"end_line": 62
} | LongestPalindrome | func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[... | Go-master/strings/manacher/longestpalindrome.go | // longestpalindrome.go
// description: Manacher's algorithm (Longest palindromic substring)
// details:
// An algorithm with linear running time that allows you to get compressed information about all palindromic substrings of a given string. - [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_s... | manacher | |||
{
"name": "horspool",
"signature": "func horspool(t, p []rune) (int, error)",
"argument_definitions": [],
"start_line": 15,
"end_line": 36
} | horspool | func horspool(t, p []rune) (int, error) {
shiftMap := computeShiftMap(t, p)
pos := 0
for pos <= len(t)-len(p) {
if isMatch(pos, t, p) {
return pos, nil
}
if pos+len(p) >= len(t) {
// because the remaining length of the input string
// is the same as the length of the pattern
// and it does not matc... | Go-master/strings/horspool/horspool.go | // Implementation of the
// [BoyerβMooreβHorspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm)
package horspool
import "errors"
var ErrNotFound = errors.New("pattern was not found in the input string")
func Horspool(t, p string) (int, error) {
// in order to handle multy... | horspool | |||
{
"name": "ConstructTrie",
"signature": "func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int)",
"argument_definitions": [],
"start_line": 3,
"end_line": 35
} | ConstructTrie | func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]int)
state := 1
CreateNewState(0, trie)
for i := 0; i < len(p); i++ {
current := 0
j := 0
for j < len(p[i]) && GetTra... | Go-master/strings/ahocorasick/shared.go | package ahocorasick
// ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings.
func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {
trie = make(map[int]map[uint8]int)
stateIsTerminal = make([]bool, 1)
f = make(map[int][]i... | ahocorasick | |||
{
"name": "Advanced",
"signature": "func Advanced(t string, p []string) Result",
"argument_definitions": [],
"start_line": 9,
"end_line": 42
} | Advanced | func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
if GetTransition(current, t[pos], ac) != -1 {
current = GetTransition(current, t[pos], ac)
} else {
current = 0
}
_, ok ... | Go-master/strings/ahocorasick/advancedahocorasick.go | package ahocorasick
import (
"fmt"
"time"
)
// Advanced Function performing the Advanced Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for ... | ahocorasick | |||
{
"name": "BuildExtendedAc",
"signature": "func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int)",
"argument_definitions": [],
"start_line": 45,
"end_line": 81
} | BuildExtendedAc | func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s := make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(state... | Go-master/strings/ahocorasick/advancedahocorasick.go | package ahocorasick
import (
"fmt"
"time"
)
// Advanced Function performing the Advanced Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func Advanced(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f := BuildExtendedAc(p)
current := 0
for ... | ahocorasick | |||
{
"name": "AhoCorasick",
"signature": "func AhoCorasick(t string, p []string) Result",
"argument_definitions": [],
"start_line": 14,
"end_line": 50
} | AhoCorasick | func AhoCorasick(t string, p []string) Result {
startTime := time.Now()
occurrences := make(map[int][]int)
ac, f, s := BuildAc(p)
current := 0
for pos := 0; pos < len(t); pos++ {
for GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {
current = s[current]
}
if GetTransition(current, t[pos], ac)... | Go-master/strings/ahocorasick/ahocorasick.go | package ahocorasick
import (
"fmt"
"time"
)
// Result structure to hold occurrences
type Result struct {
occurrences map[string][]int
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime :... | ahocorasick | |||
{
"name": "BuildAc",
"signature": "func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int)",
"argument_definitions": [],
"start_line": 53,
"end_line": 76
} | BuildAc | func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {
acTrie, stateIsTerminal, f := ConstructTrie(p)
s = make([]int, len(stateIsTerminal)) //supply function
i := 0 //root of acTrie
acToReturn = acTrie
s[i] = -1
for current := 1; current < len(stateI... | Go-master/strings/ahocorasick/ahocorasick.go | package ahocorasick
import (
"fmt"
"time"
)
// Result structure to hold occurrences
type Result struct {
occurrences map[string][]int
}
// AhoCorasick Function performing the Basic Aho-Corasick algorithm.
// Finds and prints occurrences of each pattern.
func AhoCorasick(t string, p []string) Result {
startTime :... | ahocorasick | |||
{
"name": "HuffTree",
"signature": "func HuffTree(listfreq []SymbolFreq) (*Node, error)",
"argument_definitions": [
{
"name": "listfreq",
"type": "[]SymbolFreq",
"definitions": [
{
"type_definition": "type SymbolFreq struct {\n\tSymbol rune\ntype SymbolFreq struct {\n\tSymb... | HuffTree | func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is... | Go-master/compression/huffmancoding.go | // huffman.go
// description: Implements Huffman compression, encoding and decoding
// details:
// We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding.
// It assumes that the list of symbol-frequencies is sorted.
// time complexity: O(n)
// space complexity: O(n)
// a... | compression | |||
{
"name": "DepthFirstSearchHelper",
"signature": "func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool)",
"argument_definitions": [],
"start_line": 26,
"end_line": 56
} | DepthFirstSearchHelper | func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {
var route []int
var stack []int
startIdx := GetIdx(start, nodes)
stack = append(stack, startIdx)
for len(stack) > 0 {
now := stack[len(stack)-1]
route = append(route, nodes[now])
if len(stack) > 1 {
st... | Go-master/graph/depthfirstsearch.go | // depthfirstsearch.go
// description: this file contains the implementation of the depth first search algorithm
// details: Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before ... | graph | |||
{
"name": "EdmondKarp",
"signature": "func EdmondKarp(graph WeightedGraph, source int, sink int) float64",
"argument_definitions": [
{
"name": "graph",
"type": "WeightedGraph",
"definitions": [
{
"type_definition": "type WeightedGraph [][]float64",
"definition_loc... | EdmondKarp | func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
// Check graph emptiness
if len(graph) == 0 {
return 0.0
}
// Check correct dimensions of the graph slice
for i := 0; i < len(graph); i++ {
if len(graph[i]) != len(graph) {
return 0.0
}
}
rGraph := make(WeightedGraph, len(graph))
fo... | Go-master/graph/edmondkarp.go | // Edmond-Karp algorithm is an implementation of the Ford-Fulkerson method
// to compute max-flow between a pair of source-sink vertices in a weighted graph
// It uses BFS (Breadth First Search) to find the residual paths
// Time Complexity: O(V * E^2) where V is the number of vertices and E is the number of edges
// S... | graph | |||
{
"name": "BreadthFirstSearch",
"signature": "func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int)",
"argument_definitions": [],
"start_line": 8,
"end_line": 27
} | BreadthFirstSearch | func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {
queue := make([]int, 0)
discovered := make([]int, nodes)
discovered[start] = 1
queue = append(queue, start)
for len(queue) > 0 {
v := queue[0]
queue = queue[1:]
for i := 0; i < len(edges[v]); i++ {
if discover... | Go-master/graph/breadthfirstsearch.go | package graph
// BreadthFirstSearch is an algorithm for traversing and searching graph data structures.
// It starts at an arbitrary node of a graph, and explores all of the neighbor nodes
// at the present depth prior to moving on to the nodes at the next depth level.
// Worst-case performance O(|V|+|E|)=O(b^{d})}... | graph | |||
{
"name": "FloydWarshall",
"signature": "func FloydWarshall(graph WeightedGraph) WeightedGraph",
"argument_definitions": [
{
"name": "graph",
"type": "WeightedGraph",
"definitions": [
{
"type_definition": "type WeightedGraph [][]float64",
"definition_location": {
... | FloydWarshall | func FloydWarshall(graph WeightedGraph) WeightedGraph {
// If graph is empty, returns nil
if len(graph) == 0 || len(graph) != len(graph[0]) {
return nil
}
for i := 0; i < len(graph); i++ {
//If graph matrix width is different than the height, returns nil
if len(graph[i]) != len(graph) {
return nil
}
}
... | Go-master/graph/floydwarshall.go | // Floyd-Warshall algorithm
// time complexity: O(V^3) where V is the number of vertices in the graph
// space complexity: O(V^2) where V is the number of vertices in the graph
// https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
package graph
import "math"
// WeightedGraph defining matrix to use 2d arr... | graph | |||
{
"name": "KruskalMST",
"signature": "func KruskalMST(n int, edges []Edge) ([]Edge, int)",
"argument_definitions": [
{
"name": "edges",
"type": "[]Edge",
"definitions": [
{
"type_definition": "type Edge struct {\n\tStart Vertex\n\tEnd Vertex\ntype Edge struct {\n\tStart... | KruskalMST | func KruskalMST(n int, edges []Edge) ([]Edge, int) {
// Initialize variables to store the minimum spanning tree and its total cost
var mst []Edge
var cost int
// Create a new UnionFind data structure with 'n' nodes
u := NewUnionFind(n)
// Sort the edges in non-decreasing order based on their weights
sort.Slice... | Go-master/graph/kruskal.go | // KRUSKAL'S ALGORITHM
// Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorithm/
// Reference: Union Find Algorithm: https://www.scaler.com/topics/data-structures/disjoint-set/
// Author: Author: Mugdha Behere[https://github.com/MugdhaBehere]
// Worst Case Time Complexity: O(E ... | graph | |||
{
"name": "NewTree",
"signature": "func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree)",
"argument_definitions": [
{
"name": "edges",
"type": "[]TreeEdge",
"definitions": [
{
"type_definition": "type TreeEdge struct {\n\tfrom int\ntype TreeEdge struct {\n\t... | NewTree | func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
tree = new(Tree)
tree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0
tree.depth = make([]int, numbersVertex)
tree.dad = make([]int, numbersVertex)
for (1 << tree.MAXLOG) <= numbersVertex {
(tree.MAXLOG) += 1
}
(tree.MAXLOG)... | Go-master/graph/lowestcommonancestor.go | // lowestcommonancestor.go
// description: Implementation of Lowest common ancestor (LCA) algorithm.
// detail:
// Let `T` be a tree. The LCA of `u` and `v` in T is the shared ancestor of `u` and `v`
// that is located farthest from the root.
// time complexity: O(n log n) where n is the number of vertices in the tree
... | graph | |||
{
"name": "Sign",
"signature": "func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int)",
"argument_definitions": [
{
"name": "x",
"type": "big.Int",
"definitions": [
{
"type_definition": "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs ... | Sign | func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = ... | Go-master/cipher/dsa/dsa.go | /*
dsa.go
description: DSA encryption and decryption including key generation
details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm)
author(s): [ddaniel27](https://github.com/ddaniel27)
*/
package dsa
import (
"crypto/rand"
"io"
"math/big"
)
const (
numMRTests = 64 // Number of Miller-Ra... | dsa | |||
{
"name": "Verify",
"signature": "func Verify(m []byte, r, s, p, q, g, y *big.Int) bool",
"argument_definitions": [
{
"name": "y",
"type": "big.Int",
"definitions": [
{
"type_definition": "type Int struct {\n\tneg bool // sign\ntype Int struct {\n\tneg bool // sign\n\tabs n... | Verify | func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := ... | Go-master/cipher/dsa/dsa.go | /*
dsa.go
description: DSA encryption and decryption including key generation
details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm)
author(s): [ddaniel27](https://github.com/ddaniel27)
*/
package dsa
import (
"crypto/rand"
"io"
"math/big"
)
const (
numMRTests = 64 // Number of Miller-Ra... | dsa | |||
{
"name": "Encrypt",
"signature": "func Encrypt(text string, rails int) string",
"argument_definitions": [],
"start_line": 12,
"end_line": 48
} | Encrypt | func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if ro... | Go-master/cipher/railfence/railfence.go | // railfence.go
// description: Rail Fence Cipher
// details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext.
// time complexity: O(n)
// space complexity: ... | railfence | |||
{
"name": "Decrypt",
"signature": "func Decrypt(cipherText string, rails int) string",
"argument_definitions": [],
"start_line": 49,
"end_line": 80
} | Decrypt | func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail... | Go-master/cipher/railfence/railfence.go | // railfence.go
// description: Rail Fence Cipher
// details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext.
// time complexity: O(n)
// space complexity: ... | railfence | |||
{
"name": "Encrypt",
"signature": "func Encrypt(text []rune, keyWord string) ([]rune, error)",
"argument_definitions": [],
"start_line": 52,
"end_line": 80
} | Encrypt | func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot en... | Go-master/cipher/transposition/transposition.go | // transposition.go
// description: Transposition cipher
// details:
// Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes ... | transposition | |||
{
"name": "Decrypt",
"signature": "func Decrypt(text []rune, keyWord string) ([]rune, error)",
"argument_definitions": [],
"start_line": 82,
"end_line": 106
} | Decrypt | func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = appe... | Go-master/cipher/transposition/transposition.go | // transposition.go
// description: Transposition cipher
// details:
// Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes ... | transposition | |||
{
"name": "NewPolybius",
"signature": "func NewPolybius(key string, size int, chars string) (*Polybius, error)",
"argument_definitions": [],
"start_line": 24,
"end_line": 48
} | NewPolybius | func NewPolybius(key string, size int, chars string) (*Polybius, error) {
if size < 0 {
return nil, fmt.Errorf("provided size %d cannot be negative", size)
}
key = strings.ToUpper(key)
if size > len(chars) {
return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars,... | Go-master/cipher/polybius/polybius.go | // Package polybius is encrypting method with polybius square
// description: Polybius square
// details : The Polybius algorithm is a simple algorithm that is used to encode a message by converting each letter to a pair of numbers.
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wik... | polybius | |||
{
"name": "EggDropping",
"signature": "func EggDropping(eggs, floors int) int",
"argument_definitions": [],
"start_line": 9,
"end_line": 46
} | EggDropping | func EggDropping(eggs, floors int) int {
// Edge case: If there are no floors, no attempts needed
if floors == 0 {
return 0
}
// Edge case: If there is one floor, one attempt needed
if floors == 1 {
return 1
}
// Edge case: If there is one egg, need to test all floors one by one
if eggs == 1 {
return floo... | Go-master/dynamic/eggdropping.go | package dynamic
import (
"github.com/TheAlgorithms/Go/math/max"
"github.com/TheAlgorithms/Go/math/min"
)
// EggDropping finds the minimum number of attempts needed to find the critical floor
// with `eggs` number of eggs and `floors` number of floors
func EggDropping(eggs, floors int) int {
// Edge case: If there ... | dynamic | |||
{
"name": "MaxCoins",
"signature": "func MaxCoins(nums []int) int",
"argument_definitions": [],
"start_line": 5,
"end_line": 30
} | MaxCoins | func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range dp {
dp[i] = make([]int, n+2)
}
for length := 1; length <= n; length++ {
for left := 1; left+length-1 <= n; left++ {
right := left + ... | Go-master/dynamic/burstballoons.go | package dynamic
import "github.com/TheAlgorithms/Go/math/max"
// MaxCoins returns the maximum coins we can collect by bursting the balloons
func MaxCoins(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
nums = append([]int{1}, nums...)
nums = append(nums, 1)
dp := make([][]int, n+2)
for i := range d... | dynamic | |||
{
"name": "MatrixChainDp",
"signature": "func MatrixChainDp(D []int) int",
"argument_definitions": [],
"start_line": 25,
"end_line": 47
} | MatrixChainDp | func MatrixChainDp(D []int) int {
// d[i-1] x d[i] : dimension of matrix i
N := len(D)
dp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 0
}
for l := 2; l < N; l++ {
for i := 1; i < N-l+1; i++ {
j := i + l - 1
dp[i][j] = 1 << 31
... | Go-master/dynamic/matrixmultiplication.go | // matrix chain multiplication problem
// https://en.wikipedia.org/wiki/Matrix_chain_multiplication
// www.geeksforgeeks.org/dynamic_programming-set-8-matrix-chain-multiplication/
// time complexity: O(n^3)
// space complexity: O(n^2)
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// MatrixChainRec fu... | dynamic | |||
{
"name": "LongestPalindromicSubstring",
"signature": "func LongestPalindromicSubstring(s string) string",
"argument_definitions": [],
"start_line": 9,
"end_line": 42
} | LongestPalindromicSubstring | func LongestPalindromicSubstring(s string) string {
n := len(s)
if n == 0 {
return ""
}
dp := make([][]bool, n)
for i := range dp {
dp[i] = make([]bool, n)
}
start := 0
maxLength := 1
for i := 0; i < n; i++ {
dp[i][i] = true
}
for length := 2; length <= n; length++ {
for i := 0; i < n-length+1; i+... | Go-master/dynamic/longestpalindromicsubstring.go | // longestpalindromicsubstring.go
// description: Implementation of finding the longest palindromic substring
// reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring
// time complexity: O(n^2)
// space complexity: O(n^2)
package dynamic
// LongestPalindromicSubstring returns the longest palindromic ... | dynamic | |||
{
"name": "PartitionProblem",
"signature": "func PartitionProblem(nums []int) bool",
"argument_definitions": [],
"start_line": 10,
"end_line": 29
} | PartitionProblem | func PartitionProblem(nums []int) bool {
sum := 0
for _, num := range nums {
sum += num
}
if sum%2 != 0 {
return false
}
target := sum / 2
dp := make([]bool, target+1)
dp[0] = true
for _, num := range nums {
for i := target; i >= num; i-- {
dp[i] = dp[i] || dp[i-num]
}
}
return dp[target]
} | Go-master/dynamic/partitionproblem.go | // partitionproblem.go
// description: Solves the Partition Problem using dynamic programming
// reference: https://en.wikipedia.org/wiki/Partition_problem
// time complexity: O(n*sum)
// space complexity: O(n*sum)
package dynamic
// PartitionProblem checks whether the given set can be partitioned into two subsets
//... | dynamic | |||
{
"name": "LongestArithmeticSubsequence",
"signature": "func LongestArithmeticSubsequence(nums []int) int",
"argument_definitions": [],
"start_line": 9,
"end_line": 33
} | LongestArithmeticSubsequence | func LongestArithmeticSubsequence(nums []int) int {
n := len(nums)
if n <= 1 {
return n
}
dp := make([]map[int]int, n)
for i := range dp {
dp[i] = make(map[int]int)
}
maxLength := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
diff := nums[i] - nums[j]
dp[i][diff] = dp[j][diff] + 1
if dp[... | Go-master/dynamic/longestarithmeticsubsequence.go | // longestarithmeticsubsequence.go
// description: Implementation of the Longest Arithmetic Subsequence problem
// reference: https://en.wikipedia.org/wiki/Longest_arithmetic_progression
// time complexity: O(n^2)
// space complexity: O(n^2)
package dynamic
// LongestArithmeticSubsequence returns the length of the lo... | dynamic | |||
{
"name": "IsInterleave",
"signature": "func IsInterleave(s1, s2, s3 string) bool",
"argument_definitions": [],
"start_line": 9,
"end_line": 35
} | IsInterleave | func IsInterleave(s1, s2, s3 string) bool {
if len(s1)+len(s2) != len(s3) {
return false
}
dp := make([][]bool, len(s1)+1)
for i := range dp {
dp[i] = make([]bool, len(s2)+1)
}
dp[0][0] = true
for i := 1; i <= len(s1); i++ {
dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]
}
for j := 1; j <= len(s2); j++ {... | Go-master/dynamic/interleavingstrings.go | // interleavingstrings.go
// description: Solves the Interleaving Strings problem using dynamic programming
// reference: https://en.wikipedia.org/wiki/Interleaving_strings
// time complexity: O(m*n)
// space complexity: O(m*n)
package dynamic
// IsInterleave checks if string `s1` and `s2` can be interleaved to form ... | dynamic | |||
{
"name": "OptimalBST",
"signature": "func OptimalBST(keys []int, freq []int, n int) int",
"argument_definitions": [],
"start_line": 5,
"end_line": 51
} | OptimalBST | func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case: single key cost
for i := 0; i < n; i++ {
dp[i][i] = freq[i]
}
// Build the DP table for sequences of length 2 to n
for length := 2;... | Go-master/dynamic/optimalbst.go | package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// OptimalBST returns the minimum cost of constructing a Binary Search Tree
func OptimalBST(keys []int, freq []int, n int) int {
// Initialize DP table with size n x n
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
// Base case... | dynamic | |||
{
"name": "DiceThrow",
"signature": "func DiceThrow(m, n, sum int) int",
"argument_definitions": [],
"start_line": 9,
"end_line": 32
} | DiceThrow | func DiceThrow(m, n, sum int) int {
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, sum+1)
}
for i := 1; i <= n; i++ {
if i <= sum {
dp[1][i] = 1
}
}
for i := 2; i <= m; i++ {
for j := 1; j <= sum; j++ {
for k := 1; k <= n; k++ {
if j-k >= 0 {
dp[i][j] += dp[i-1][j-k]
... | Go-master/dynamic/dicethrow.go | // dicethrow.go
// description: Solves the Dice Throw Problem using dynamic programming
// reference: https://www.geeksforgeeks.org/dice-throw-problem/
// time complexity: O(m * n)
// space complexity: O(m * n)
package dynamic
// DiceThrow returns the number of ways to get sum `sum` using `m` dice with `n` faces
func... | dynamic | |||
{
"name": "LongestCommonSubsequence",
"signature": "func LongestCommonSubsequence(a string, b string) int",
"argument_definitions": [],
"start_line": 15,
"end_line": 39
} | LongestCommonSubsequence | func LongestCommonSubsequence(a string, b string) int {
aRunes, aLen := strToRuneSlice(a)
bRunes, bLen := strToRuneSlice(b)
// here we are making a 2d slice of size (aLen+1)*(bLen+1)
lcs := make([][]int, aLen+1)
for i := 0; i <= aLen; i++ {
lcs[i] = make([]int, bLen+1)
}
// block that implements LCS
for i :... | Go-master/dynamic/longestcommonsubsequence.go | // LONGEST COMMON SUBSEQUENCE
// DP - 4
// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
// https://leetcode.com/problems/longest-common-subsequence/
// time complexity: O(m*n) where m and n are lengths of the strings
// space complexity: O(m*n) where m and n are lengths of the strings
package dynamic... | dynamic | |||
{
"name": "EditDistanceRecursive",
"signature": "func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int",
"argument_definitions": [],
"start_line": 11,
"end_line": 30
} | EditDistanceRecursive | func EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int {
if pointerFirst == 0 {
return pointerSecond
}
if pointerSecond == 0 {
return pointerFirst
}
// Characters match, so we recur for the remaining portions
if first[pointerFirst-1] == second[pointerSecond-1] {
... | Go-master/dynamic/editdistance.go | // EDIT DISTANCE PROBLEM
// time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.
// space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.
// https://www.geeksforgeeks.org/edit-distance-dp-5/
// https://leetcode.com/problems/edit... | dynamic | |||
{
"name": "EditDistanceDP",
"signature": "func EditDistanceDP(first string, second string) int",
"argument_definitions": [],
"start_line": 36,
"end_line": 70
} | EditDistanceDP | func EditDistanceDP(first string, second string) int {
m := len(first)
n := len(second)
// Create the DP table
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
dp[i][j] = j
continue
}
if j == 0 ... | Go-master/dynamic/editdistance.go | // EDIT DISTANCE PROBLEM
// time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.
// space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.
// https://www.geeksforgeeks.org/edit-distance-dp-5/
// https://leetcode.com/problems/edit... | dynamic | |||
{
"name": "IsSubsetSum",
"signature": "func IsSubsetSum(array []int, sum int) (bool, error)",
"argument_definitions": [],
"start_line": 14,
"end_line": 55
} | IsSubsetSum | func IsSubsetSum(array []int, sum int) (bool, error) {
if sum < 0 {
//not allow negative sum
return false, ErrNegativeSum
}
//create subset matrix
arraySize := len(array)
subset := make([][]bool, arraySize+1)
for i := 0; i <= arraySize; i++ {
subset[i] = make([]bool, sum+1)
}
for i := 0; i <= arraySize;... | Go-master/dynamic/subsetsum.go | //Given a set of non-negative integers, and a (positive) value sum,
//determine if there is a subset of the given set with sum
//equal to given sum.
// time complexity: O(n*sum)
// space complexity: O(n*sum)
//references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
package dynamic
import "fmt"
var ErrInv... | dynamic | |||
{
"name": "TrapRainWater",
"signature": "func TrapRainWater(height []int) int",
"argument_definitions": [],
"start_line": 18,
"end_line": 42
} | TrapRainWater | func TrapRainWater(height []int) int {
if len(height) == 0 {
return 0
}
leftMax := make([]int, len(height))
rightMax := make([]int, len(height))
leftMax[0] = height[0]
for i := 1; i < len(height); i++ {
leftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i])))
}
rightMax[len(height)-1] = heig... | Go-master/dynamic/traprainwater.go | // filename: traprainwater.go
// description: Provides a function to calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming.
// details:
// The TrapRainWater function calculates the amount of trapped rainwater between the bars represented by the given elevation ... | dynamic | |||
{
"name": "LpsDp",
"signature": "func LpsDp(word string) int",
"argument_definitions": [],
"start_line": 26,
"end_line": 52
} | LpsDp | func LpsDp(word string) int {
N := len(word)
dp := make([][]int, N)
for i := 0; i < N; i++ {
dp[i] = make([]int, N)
dp[i][i] = 1
}
for l := 2; l <= N; l++ {
// for length l
for i := 0; i < N-l+1; i++ {
j := i + l - 1
if word[i] == word[j] {
if l == 2 {
dp[i][j] = 2
} else {
dp[i][... | Go-master/dynamic/longestpalindromicsubsequence.go | // longest palindromic subsequence
// time complexity: O(n^2)
// space complexity: O(n^2)
// http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
package dynamic
func lpsRec(word string, i, j int) int {
if i == j {
return 1
}
if i > j {
return 0
}
if word[i] == word[j] {
... | dynamic | |||
{
"name": "UniquePaths",
"signature": "func UniquePaths(m, n int) int",
"argument_definitions": [],
"start_line": 7,
"end_line": 32
} | UniquePaths | func UniquePaths(m, n int) int {
if m <= 0 || n <= 0 {
return 0
}
grid := make([][]int, m)
for i := range grid {
grid[i] = make([]int, n)
}
for i := 0; i < m; i++ {
grid[i][0] = 1
}
for j := 0; j < n; j++ {
grid[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
grid[i][j] = grid[i... | Go-master/dynamic/uniquepaths.go | // See https://leetcode.com/problems/unique-paths/
// time complexity: O(m*n) where m and n are the dimensions of the grid
// space complexity: O(m*n) where m and n are the dimensions of the grid
// author: Rares Mateizer (https://github.com/rares985)
package dynamic
// UniquePaths implements the solution to the "Uniq... | dynamic | |||
{
"name": "Abbreviation",
"signature": "func Abbreviation(a string, b string) bool",
"argument_definitions": [],
"start_line": 25,
"end_line": 46
} | Abbreviation | func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] ... | Go-master/dynamic/abbreviation.go | // File: abbreviation.go
// Description: Abbreviation problem
// Details:
// https://www.hackerrank.com/challenges/abbr/problem
// Problem description (from hackerrank):
// You can perform the following operations on the string, a:
// 1. Capitalize zero or more of a's lowercase letters.
// 2. Delete all of the ... | dynamic | |||
{
"name": "IsMatch",
"signature": "func IsMatch(s, p string) bool",
"argument_definitions": [],
"start_line": 9,
"end_line": 32
} | IsMatch | func IsMatch(s, p string) bool {
dp := make([][]bool, len(s)+1)
for i := range dp {
dp[i] = make([]bool, len(p)+1)
}
dp[0][0] = true
for j := 1; j <= len(p); j++ {
if p[j-1] == '*' {
dp[0][j] = dp[0][j-1]
}
}
for i := 1; i <= len(s); i++ {
for j := 1; j <= len(p); j++ {
if p[j-1] == s[i-1] || p[j... | Go-master/dynamic/wildcardmatching.go | // wildcardmatching.go
// description: Solves the Wildcard Matching problem using dynamic programming
// reference: https://en.wikipedia.org/wiki/Wildcard_matching
// time complexity: O(m*n)
// space complexity: O(m*n)
package dynamic
// IsMatch checks if the string `s` matches the wildcard pattern `p`
func IsMatch(s... | dynamic | |||
{
"name": "Generate",
"signature": "func Generate(minLength int, maxLength int) string",
"argument_definitions": [],
"start_line": 17,
"end_line": 48
} | Generate | func Generate(minLength int, maxLength int) string {
var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~")
length, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
panic(err) // handle this gracefully
}
length.Add(lengt... | Go-master/other/password/generator.go | // This program generates a password from a list of possible chars
// You must provide a minimum length and a maximum length
// This length is not fixed if you generate multiple passwords for the same range
// Package password contains functions to help generate random passwords
// time complexity: O(n)
// space compl... | password | |||
{
"name": "IsBalanced",
"signature": "func IsBalanced(input string) bool",
"argument_definitions": [],
"start_line": 22,
"end_line": 64
} | IsBalanced | func IsBalanced(input string) bool {
if len(input) == 0 {
return true
}
if len(input)%2 != 0 {
return false
}
// Brackets such as '{', '[', '(' are valid UTF-8 characters,
// which means that only one byte is required to code them,
// so can be stored as bytes.
var stack []byte
for i := 0; i < len(input... | Go-master/other/nested/nestedbrackets.go | // Package nested provides functions for testing
// strings proper brackets nesting.
package nested
// IsBalanced returns true if provided input string is properly nested.
//
// Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'.
//
// A sequence of brackets `s` is considered properly nested
// if any of th... | nested | |||
{
"name": "hexToDecimal",
"signature": "func hexToDecimal(hexStr string) (int64, error)",
"argument_definitions": [],
"start_line": 22,
"end_line": 56
} | hexToDecimal | func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Vali... | Go-master/conversion/hexadecimaltodecimal.go | /*
Author: mapcrafter2048
GitHub: https://github.com/mapcrafter2048
*/
// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Decimal number(0-9).
// https://en.wikipedia.org/wiki/Hexadecimal
// https://en.wikipedia.org/wiki/Decimal
// Function receives a Hexadecimal Number as string and returns the D... | conversion | |||
{
"name": "Base64Encode",
"signature": "func Base64Encode(input []byte) string",
"argument_definitions": [],
"start_line": 20,
"end_line": 53
} | Base64Encode | func Base64Encode(input []byte) string {
var sb strings.Builder
// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output
var padding string
for i := len(input) % 3; i > 0 && i < 3; i++ {
var zeroByte byte
input = append(input, zeroByte)
padding += "="
}
// encode 24 bits pe... | Go-master/conversion/base64.go | // base64.go
// description: The base64 encoding algorithm as defined in the RFC4648 standard.
// author: [Paul Leydier] (https://github.com/paul-leydier)
// time complexity: O(n)
// space complexity: O(n)
// ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4
// ref: https://en.wikipedia.org/wiki/Base64
// se... | conversion | |||
{
"name": "hexToBinary",
"signature": "func hexToBinary(hex string) (string, error)",
"argument_definitions": [],
"start_line": 23,
"end_line": 77
} | hexToBinary | func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", err... | Go-master/conversion/hexadecimaltobinary.go | /*
Author: mapcrafter2048
GitHub: https://github.com/mapcrafter2048
*/
// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1).
// https://en.wikipedia.org/wiki/Hexadecimal
// https://en.wikipedia.org/wiki/Binary_number
// Function receives a Hexadecimal Number as string and retur... | conversion | |||
{
"name": "add",
"signature": "func add(a, b string) string",
"argument_definitions": [],
"start_line": 123,
"end_line": 149
} | add | func add(a, b string) string {
if len(a) < len(b) {
a, b = b, a
}
carry := 0
sum := make([]byte, len(a)+1)
for i := 0; i < len(a); i++ {
d := int(a[len(a)-1-i] - '0')
if i < len(b) {
d += int(b[len(b)-1-i] - '0')
}
d += carry
sum[len(sum)-1-i] = byte(d%10) + '0'
carry = d / 10
}
if carry > 0... | Go-master/project_euler/problem_13/problem13.go | /**
* Problem 13 - Large sum
* @see {@link https://projecteuler.net/problem=13}
*
* Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
*
* @author ddaniel27
*/
package problem13
var numbers = [100]string{
"37107287533902102798797998220837590246510135740250",
"4637693767749000971... | problem13 | |||
{
"name": "Jump",
"signature": "func Jump(array []int, target int) (int, error)",
"argument_definitions": [],
"start_line": 16,
"end_line": 56
} | Jump | func Jump(array []int, target int) (int, error) {
n := len(array)
if n == 0 {
return -1, ErrNotFound
}
// the optimal value of step is square root of the length of list
step := int(math.Round(math.Sqrt(float64(n))))
prev := 0 // previous index
curr := step // current index
for array[curr-1] < target {
... | Go-master/search/jump.go | // jump.go
// description: Implementation of jump search
// details:
// A search algorithm for ordered list that jump through the list to narrow down the range
// before performing a linear search
// reference: https://en.wikipedia.org/wiki/Jump_search
// see jump_test.go for a test implementation, test function TestJu... | search | |||
{
"name": "Interpolation",
"signature": "func Interpolation(sortedData []int, guess int) (int, error)",
"argument_definitions": [],
"start_line": 14,
"end_line": 50
} | Interpolation | func Interpolation(sortedData []int, guess int) (int, error) {
if len(sortedData) == 0 {
return -1, ErrNotFound
}
var (
low, high = 0, len(sortedData) - 1
lowVal, highVal = sortedData[low], sortedData[high]
)
for lowVal != highVal && (lowVal <= guess) && (guess <= highVal) {
mid := low + int(float6... | Go-master/search/interpolation.go | package search
// Interpolation searches for the entity in the given sortedData.
// if the entity is present, it will return the index of the entity, if not -1 will be returned.
// see: https://en.wikipedia.org/wiki/Interpolation_search
// Complexity
//
// Worst: O(N)
// Average: O(log(log(N)) if the elements are uni... | search | |||
{
"name": "Jump2",
"signature": "func Jump2(arr []int, target int) (int, error)",
"argument_definitions": [],
"start_line": 4,
"end_line": 23
} | Jump2 | func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
return i, nil
}
if arr[i] ... | Go-master/search/jump2.go | package search
import "math"
func Jump2(arr []int, target int) (int, error) {
step := int(math.Round(math.Sqrt(float64(len(arr)))))
rbound := len(arr)
for i := step; i < len(arr); i += step {
if arr[i] > target {
rbound = i
break
}
}
for i := rbound - step; i < rbound; i++ {
if arr[i] == target {
... | search | |||
{
"name": "doSort",
"signature": "func doSort(arr []T, left, right int) bool",
"argument_definitions": [],
"start_line": 16,
"end_line": 43
} | doSort | func doSort(arr []T, left, right int) bool {
if left == right {
return false
}
swapped := false
low := left
high := right
for low < high {
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
swapped = true
}
low++
high--
}
if low == high && arr[low] > arr[high+1] {
arr[low], ... | Go-master/sort/circlesort.go | // Package sort implements various sorting algorithms.
package sort
import "github.com/TheAlgorithms/Go/constraints"
// Circle sorts an array using the circle sort algorithm.
func Circle[T constraints.Ordered](arr []T) []T {
if len(arr) == 0 {
return arr
}
for doSort(arr, 0, len(arr)-1) {
}
return arr
}
// do... | sort | |||
{
"name": "Mode",
"signature": "func Mode(numbers []T) (T, error)",
"argument_definitions": [],
"start_line": 20,
"end_line": 46
} | Mode | func Mode(numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
} | Go-master/math/mode.go | // mode.go
// author(s): [CalvinNJK] (https://github.com/CalvinNJK)
// time complexity: O(n)
// space complexity: O(n)
// description: Finding Mode Value In an Array
// see mode.go
package math
import (
"errors"
"github.com/TheAlgorithms/Go/constraints"
)
// ErrEmptySlice is the error returned by functions in mat... | math | |||
{
"name": "IsKrishnamurthyNumber",
"signature": "func IsKrishnamurthyNumber(n T) bool",
"argument_definitions": [],
"start_line": 13,
"end_line": 33
} | IsKrishnamurthyNumber | func IsKrishnamurthyNumber(n T) bool {
if n <= 0 {
return false
}
// Preprocessing: Using a slice to store the digit Factorials
digitFact := make([]T, 10)
digitFact[0] = 1 // 0! = 1
for i := 1; i < 10; i++ {
digitFact[i] = digitFact[i-1] * T(i)
}
// Subtract the digit Facotorial from the number
nTemp :=... | Go-master/math/krishnamurthy.go | // filename : krishnamurthy.go
// description: A program which contains the function that returns true if a given number is Krishnamurthy number or not.
// details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number.
// Ex: 1! = 1, 145 = 1! + 4! + 5!
// time complex... | math | |||
{
"name": "Spigot",
"signature": "func Spigot(n int) string",
"argument_definitions": [],
"start_line": 13,
"end_line": 55
} | Spigot | func Spigot(n int) string {
pi := ""
boxes := n * 10 / 3
remainders := make([]int, boxes)
for i := 0; i < boxes; i++ {
remainders[i] = 2
}
digitsHeld := 0
for i := 0; i < n; i++ {
carriedOver := 0
sum := 0
for j := boxes - 1; j >= 0; j-- {
remainders[j] *= 10
sum = remainders[j] + carriedOver
qu... | Go-master/math/pi/spigotpi.go | // spigotpi.go
// description: A Spigot Algorithm for the Digits of Pi
// details:
// implementation of Spigot Algorithm for the Digits of Pi - [Spigot algorithm](https://en.wikipedia.org/wiki/Spigot_algorithm)
// time complexity: O(n)
// space complexity: O(n)
// author(s) [red_byte](https://github.com/i-redbyte)
// s... | pi | |||
{
"name": "MonteCarloPiConcurrent",
"signature": "func MonteCarloPiConcurrent(n int) (float64, error)",
"argument_definitions": [],
"start_line": 37,
"end_line": 56
} | MonteCarloPiConcurrent | func MonteCarloPiConcurrent(n int) (float64, error) {
numCPU := runtime.GOMAXPROCS(0)
c := make(chan int, numCPU)
pointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes
if err != nil {
return 0, err
}
// launch numCPU parallel tasks
for _, p := range pointsToDraw ... | Go-master/math/pi/montecarlopi.go | // montecarlopi.go
// description: Calculating pi by the Monte Carlo method
// details:
// implementations of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method)
// time complexity: O(n)
// space complexity: O(1)
// author(s): [red_byte](https://githu... | pi |
π TestEval-LR: Unit Test Generation Benchmark for Low-Resource Languages
TestEval-LR is a validation benchmark designed to measure how well models can generate unit tests for Low-Resource Programming Languages (LRPLs) β specifically Rust, Go, and Julia.
π Purpose
Evaluate how well a model can generate test code, given a focal function's source code and context.
π Dataset Structure
Each example contains:
- function_name: Name of the focal function.
- focal_code: Raw source code of the function (used for context).
- function_component: Detail information about the function like function signature,arguments definition,line range,...
- file_content: Content of file have the focal function.
- file_path: Relative path to the file in the repository.
Dataset Size
The dataset contains ~372β412 samples per language, depending on the source repository.
π Prompt Example for Test Generation
Suffix syntax for each language: suffix syntax is to put in the end of the prompt ( after wrap in the chat template if need ) to generate the expected test function and avoid hallucination
"Rust": "#[test]\nfn test_{function_name}() {"
"Julia": "@testset \"{function_name} Tests\" begin"
"Go": "func Test{function_name_with_uppercase_first_letter}("
This dataset uses a structured prompt format for three programming languages: Rust, Julia, and Go.
Each language has two variants:
instructβ Full instruction prompt including explicit guidance to generate a unit test for a given function.baseβ Minimal version that only contains the function code and a short comment reminding to check correctness.
Structure
prompts = {
"Rust": {
"instruct": (
"{function_code}\n"
"Generate Rust unittest for {function_name} function in module {file_path}:\n"
),
"base": (
"{function_code}\n"
"// Check the correctness for {function_name} function in Rust\n"
),
},
"Julia": {
"instruct": (
"{function_code}\n"
"Generate Julia unittest for {function_name} function in module {file_path}:\n"
),
"base": (
"{function_code}\n"
"# Check the correctness for {function_name} function in Julia\n"
),
},
"Go": {
"instruct": (
"{function_code}\n"
"Generate Go unittest for {function_name} function in module {file_path}:\n"
),
"base": (
"{function_code}\n"
"// Check the correctness for {function_name} function in Go\n"
),
},
}
- Downloads last month
- 24