Showing preview only (982K chars total). Download the full file or copy to clipboard to get everything.
Repository: TheAlgorithms/Go
Branch: master
Commit: 5ba447ec5ff3
Files: 519
Total size: 876.1 KB
Directory structure:
gitextract_m9961ttm/
├── .github/
│ ├── CODEOWNERS
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ ├── config.yml
│ │ ├── new_implementation.yml
│ │ └── other.yml
│ ├── PULL_REQUEST_TEMPLATE/
│ │ └── pull_request.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── ci.yml
│ ├── citk.yml
│ ├── godocmd.yml
│ ├── stale.yml
│ └── upload_coverage_report.yml
├── .gitignore
├── .gitpod.dockerfile
├── .gitpod.yml
├── .golangci.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── STYLE.md
├── cache/
│ ├── lfu.go
│ ├── lfu_test.go
│ ├── lru.go
│ └── lru_test.go
├── checksum/
│ ├── crc8.go
│ ├── crc8_test.go
│ ├── luhn.go
│ └── luhn_test.go
├── cipher/
│ ├── caesar/
│ │ ├── caesar.go
│ │ └── caesar_test.go
│ ├── cipher_test.go
│ ├── diffiehellman/
│ │ ├── diffiehellmankeyexchange.go
│ │ └── diffiehellmankeyexchange_test.go
│ ├── doc.go
│ ├── dsa/
│ │ ├── dsa.go
│ │ └── dsa_test.go
│ ├── polybius/
│ │ ├── polybius.go
│ │ └── polybius_test.go
│ ├── railfence/
│ │ ├── railfence.go
│ │ └── railfence_test.go
│ ├── rot13/
│ │ ├── rot13.go
│ │ └── rot13_test.go
│ ├── rsa/
│ │ ├── rsa.go
│ │ ├── rsa2.go
│ │ ├── rsa2_test.go
│ │ └── rsa_test.go
│ ├── transposition/
│ │ ├── transposition.go
│ │ └── transposition_test.go
│ └── xor/
│ ├── xor.go
│ └── xor_test.go
├── compression/
│ ├── huffmancoding.go
│ ├── huffmancoding_test.go
│ ├── rlecoding.go
│ └── rlecoding_test.go
├── constraints/
│ └── constraints.go
├── conversion/
│ ├── base64.go
│ ├── base64_test.go
│ ├── binarytodecimal.go
│ ├── binarytodecimal_test.go
│ ├── conversion_test.go
│ ├── decimaltobinary.go
│ ├── decimaltobinary_test.go
│ ├── doc.go
│ ├── hexadecimaltobinary.go
│ ├── hexadecimaltobinary_test.go
│ ├── hexadecimaltodecimal.go
│ ├── hexadecimaltodecimal_test.go
│ ├── inttoroman.go
│ ├── inttoroman_test.go
│ ├── rgbhex.go
│ ├── rgbhex_test.go
│ ├── romantoint.go
│ └── romantoint_test.go
├── dynamic/
│ ├── abbreviation.go
│ ├── abbreviation_test.go
│ ├── binomialcoefficient.go
│ ├── binomialcoefficient_test.go
│ ├── burstballoons.go
│ ├── burstballoons_test.go
│ ├── catalan.go
│ ├── catalan_test.go
│ ├── coinchange.go
│ ├── coinchange_test.go
│ ├── dicethrow.go
│ ├── dicethrow_test.go
│ ├── doc.go
│ ├── dynamic_test.go
│ ├── editdistance.go
│ ├── editdistance_test.go
│ ├── eggdropping.go
│ ├── eggdropping_test.go
│ ├── fibonacci.go
│ ├── fibonacci_test.go
│ ├── interleavingstrings.go
│ ├── interleavingstrings_test.go
│ ├── knapsack.go
│ ├── knapsack_test.go
│ ├── longestarithmeticsubsequence.go
│ ├── longestarithmeticsubsequence_test.go
│ ├── longestcommonsubsequence.go
│ ├── longestcommonsubsequence_test.go
│ ├── longestincreasingsubsequence.go
│ ├── longestincreasingsubsequence_test.go
│ ├── longestincreasingsubsequencegreedy.go
│ ├── longestpalindromicsubsequence.go
│ ├── longestpalindromicsubsequence_test.go
│ ├── longestpalindromicsubstring.go
│ ├── longestpalindromicsubstring_test.go
│ ├── matrixmultiplication.go
│ ├── maxsubarraysum.go
│ ├── maxsubarraysum_test.go
│ ├── optimalbst.go
│ ├── optimalbst_test.go
│ ├── partitionproblem.go
│ ├── partitionproblem_test.go
│ ├── rodcutting.go
│ ├── rodcutting_test.go
│ ├── subsetsum.go
│ ├── subsetsum_test.go
│ ├── tilingproblem.go
│ ├── tilingproblem_test.go
│ ├── traprainwater.go
│ ├── traprainwater_test.go
│ ├── uniquepaths.go
│ ├── uniquepaths_test.go
│ ├── wildcardmatching.go
│ ├── wildcardmatching_test.go
│ ├── wordbreak.go
│ └── wordbreak_test.go
├── go.mod
├── go.sum
├── graph/
│ ├── articulationpoints.go
│ ├── articulationpoints_test.go
│ ├── bellmanford.go
│ ├── bellmanford_test.go
│ ├── breadthfirstsearch.go
│ ├── breadthfirstsearch_test.go
│ ├── coloring/
│ │ ├── backtracking.go
│ │ ├── backtracking_test.go
│ │ ├── bfs.go
│ │ ├── bfs_test.go
│ │ ├── bipartite.go
│ │ ├── bipartite_test.go
│ │ ├── doc.go
│ │ ├── graph.go
│ │ ├── graph_test.go
│ │ ├── greedy.go
│ │ └── greedy_test.go
│ ├── cycle.go
│ ├── cycle_test.go
│ ├── depthfirstsearch.go
│ ├── depthfirstsearch_test.go
│ ├── dijkstra.go
│ ├── dijkstra_test.go
│ ├── doc.go
│ ├── edmondkarp.go
│ ├── edmondkarp_test.go
│ ├── floydwarshall.go
│ ├── floydwarshall_test.go
│ ├── graph.go
│ ├── graph_test.go
│ ├── kahn.go
│ ├── kahn_test.go
│ ├── kosaraju.go
│ ├── kosaraju_test.go
│ ├── kruskal.go
│ ├── kruskal_test.go
│ ├── lowestcommonancestor.go
│ ├── lowestcommonancestor_test.go
│ ├── prim.go
│ ├── prim_test.go
│ ├── topological.go
│ ├── topological_test.go
│ ├── unionfind.go
│ └── unionfind_test.go
├── hashing/
│ ├── doc.go
│ ├── hashing_test.go
│ ├── md5/
│ │ ├── md5.go
│ │ └── md5_test.go
│ ├── sha1/
│ │ ├── sha1.go
│ │ └── sha1_test.go
│ └── sha256/
│ ├── sha256.go
│ └── sha256_test.go
├── math/
│ ├── abs.go
│ ├── abs_test.go
│ ├── aliquot_test.go
│ ├── aliquotsum.go
│ ├── armstrong/
│ │ ├── isarmstrong.go
│ │ └── isarmstrong_test.go
│ ├── binary/
│ │ ├── abs.go
│ │ ├── abs_test.go
│ │ ├── arithmeticmean.go
│ │ ├── arithmeticmean_test.go
│ │ ├── bitcounter.go
│ │ ├── bitcounter_test.go
│ │ ├── checkisnumberpoweroftwo.go
│ │ ├── checkisnumberpoweroftwo_test.go
│ │ ├── fast_inverse_sqrt.go
│ │ ├── logarithm.go
│ │ ├── logarithm_test.go
│ │ ├── rbc.go
│ │ ├── rbc_test.go
│ │ ├── reversebits.go
│ │ ├── reversebits_test.go
│ │ ├── sqrt.go
│ │ ├── sqrt_test.go
│ │ ├── xorsearch.go
│ │ └── xorsearch_test.go
│ ├── binomialcoefficient.go
│ ├── binomialcoefficient_test.go
│ ├── catalan/
│ │ ├── catalannumber.go
│ │ └── catalannumber_test.go
│ ├── checkisnumberpoweroftwo.go
│ ├── checkisnumberpoweroftwo_test.go
│ ├── cos.go
│ ├── cos_test.go
│ ├── doc.go
│ ├── eulertotient.go
│ ├── eulertotient_test.go
│ ├── factorial/
│ │ ├── factorial.go
│ │ └── factorial_test.go
│ ├── fibonacci/
│ │ ├── fibonacci.go
│ │ └── fibonacci_test.go
│ ├── gcd/
│ │ ├── extended.go
│ │ ├── extended_test.go
│ │ ├── extendedgcd.go
│ │ ├── extendedgcd_test.go
│ │ ├── extendedgcditerative.go
│ │ ├── gcd.go
│ │ ├── gcd_test.go
│ │ └── gcditerative.go
│ ├── geometry/
│ │ ├── distance.go
│ │ ├── distance_test.go
│ │ ├── straightlines.go
│ │ └── straightlines_test.go
│ ├── isautomorphic.go
│ ├── isautomorphic_test.go
│ ├── krishnamurthy.go
│ ├── krishnamurthy_test.go
│ ├── kthnumber.go
│ ├── kthnumber_test.go
│ ├── lcm/
│ │ ├── lcm.go
│ │ └── lcm_test.go
│ ├── lerp.go
│ ├── lerp_test.go
│ ├── liouville.go
│ ├── liouville_test.go
│ ├── math_test.go
│ ├── matrix/
│ │ ├── add.go
│ │ ├── add_test.go
│ │ ├── checkequal.go
│ │ ├── checkequal_test.go
│ │ ├── copy.go
│ │ ├── copy_test.go
│ │ ├── determinant.go
│ │ ├── determinant_test.go
│ │ ├── isvalid.go
│ │ ├── isvalid_test.go
│ │ ├── matchdimensions.go
│ │ ├── matchdimensions_test.go
│ │ ├── matrix.go
│ │ ├── matrix_test.go
│ │ ├── multiply.go
│ │ ├── multiply_test.go
│ │ ├── strassenmatrixmultiply.go
│ │ ├── strassenmatrixmultiply_test.go
│ │ ├── string.go
│ │ ├── string_test.go
│ │ ├── submatrix.go
│ │ ├── submatrix_test.go
│ │ ├── subtract.go
│ │ └── subtract_test.go
│ ├── max/
│ │ ├── bitwisemax.go
│ │ ├── bitwisemax_test.go
│ │ ├── max.go
│ │ └── max_test.go
│ ├── mean.go
│ ├── mean_test.go
│ ├── median.go
│ ├── median_test.go
│ ├── min/
│ │ ├── bitwisemin.go
│ │ ├── min.go
│ │ └── min_test.go
│ ├── mobius.go
│ ├── mobius_test.go
│ ├── mode.go
│ ├── mode_test.go
│ ├── modular/
│ │ ├── exponentiation.go
│ │ ├── exponentiation_test.go
│ │ ├── inverse.go
│ │ └── inverse_test.go
│ ├── moserdebruijnsequence/
│ │ ├── sequence.go
│ │ └── sequence_test.go
│ ├── pascal/
│ │ ├── pascaltriangle.go
│ │ └── pascaltriangle_test.go
│ ├── perfectnumber.go
│ ├── perfectnumber_test.go
│ ├── permutation/
│ │ ├── heaps.go
│ │ ├── heaps_test.go
│ │ ├── next_permutation.go
│ │ └── next_permutation_test.go
│ ├── pi/
│ │ ├── montecarlopi.go
│ │ ├── montecarlopi_test.go
│ │ ├── spigotpi.go
│ │ └── spigotpi_test.go
│ ├── pollard.go
│ ├── pollard_test.go
│ ├── power/
│ │ ├── fastexponent.go
│ │ ├── fastexponent_test.go
│ │ ├── powvialogarithm.go
│ │ └── powvialogarithm_test.go
│ ├── prime/
│ │ ├── millerrabintest.go
│ │ ├── prime_test.go
│ │ ├── primecheck.go
│ │ ├── primefactorization.go
│ │ ├── primefactorization_test.go
│ │ ├── sieve.go
│ │ ├── sieve2.go
│ │ ├── sieve2_test.go
│ │ ├── sieve_test.go
│ │ ├── twin.go
│ │ └── twin_test.go
│ ├── pronicnumber.go
│ ├── pronicnumber_test.go
│ ├── pythagoras/
│ │ ├── pythagoras.go
│ │ └── pythagoras_test.go
│ ├── sin.go
│ └── sin_test.go
├── other/
│ ├── doc.go
│ ├── maxsubarraysum/
│ │ ├── maxsubarraysum.go
│ │ └── maxsubarraysum_test.go
│ ├── nested/
│ │ ├── nestedbrackets.go
│ │ └── nestedbrackets_test.go
│ ├── other_test.go
│ └── password/
│ └── generator.go
├── project_euler/
│ ├── problem_1/
│ │ ├── problem1.go
│ │ └── problem1_test.go
│ ├── problem_10/
│ │ ├── problem10.go
│ │ └── problem10_test.go
│ ├── problem_11/
│ │ ├── problem11.go
│ │ └── problem11_test.go
│ ├── problem_12/
│ │ ├── problem12.go
│ │ └── problem12_test.go
│ ├── problem_13/
│ │ ├── problem13.go
│ │ └── problem13_test.go
│ ├── problem_14/
│ │ ├── problem14.go
│ │ └── problem14_test.go
│ ├── problem_15/
│ │ ├── problem15.go
│ │ └── problem15_test.go
│ ├── problem_16/
│ │ ├── problem16.go
│ │ └── problem16_test.go
│ ├── problem_17/
│ │ ├── input.go
│ │ ├── problem17.go
│ │ └── problem17_test.go
│ ├── problem_18/
│ │ ├── edge.go
│ │ ├── input.go
│ │ ├── leaf.go
│ │ ├── problem18.go
│ │ ├── problem18_test.go
│ │ ├── root.go
│ │ └── tree.go
│ ├── problem_19/
│ │ ├── problem19.go
│ │ └── problem19_test.go
│ ├── problem_2/
│ │ ├── problem2.go
│ │ └── problem2_test.go
│ ├── problem_20/
│ │ ├── problem20.go
│ │ └── problem20_test.go
│ ├── problem_3/
│ │ ├── problem3.go
│ │ └── problem3_test.go
│ ├── problem_4/
│ │ ├── problem4.go
│ │ └── problem4_test.go
│ ├── problem_5/
│ │ ├── problem5.go
│ │ └── problem5_test.go
│ ├── problem_6/
│ │ ├── problem6.go
│ │ └── problem6_test.go
│ ├── problem_7/
│ │ ├── problem7.go
│ │ └── problem7_test.go
│ ├── problem_8/
│ │ ├── problem8.go
│ │ └── problem8_test.go
│ └── problem_9/
│ ├── problem9.go
│ └── problem9_test.go
├── search/
│ ├── binary.go
│ ├── binary_test.go
│ ├── doc.go
│ ├── errors.go
│ ├── interpolation.go
│ ├── interpolation_test.go
│ ├── jump.go
│ ├── jump2.go
│ ├── jump2_test.go
│ ├── jump_test.go
│ ├── linear.go
│ ├── linear_test.go
│ ├── selectk.go
│ ├── selectk_test.go
│ ├── ternary.go
│ ├── ternary_test.go
│ └── testcases.go
├── sort/
│ ├── binaryinsertionsort.go
│ ├── bogosort.go
│ ├── bubblesort.go
│ ├── bucketsort.go
│ ├── circlesort.go
│ ├── cocktailsort.go
│ ├── combSort.go
│ ├── countingsort.go
│ ├── cyclesort.go
│ ├── doc.go
│ ├── exchangesort.go
│ ├── heapsort.go
│ ├── insertionsort.go
│ ├── mergesort.go
│ ├── oddevensort.go
│ ├── pancakesort.go
│ ├── patiencesort.go
│ ├── pigeonholesort.go
│ ├── quicksort.go
│ ├── radixsort.go
│ ├── selectionsort.go
│ ├── shellsort.go
│ ├── simplesort.go
│ ├── sorts_test.go
│ ├── stooge_sort.go
│ └── timsort.go
├── sqrt/
│ ├── sqrtdecomposition.go
│ └── sqrtdecomposition_test.go
├── strings/
│ ├── ahocorasick/
│ │ ├── advancedahocorasick.go
│ │ ├── advancedahocorasick_test.go
│ │ ├── ahocorasick.go
│ │ ├── ahocorasick_test.go
│ │ ├── patterns.txt
│ │ ├── shared.go
│ │ └── text.txt
│ ├── bom/
│ │ └── bom.go
│ ├── charoccurrence.go
│ ├── charoccurrence_test.go
│ ├── combination/
│ │ └── combination.go
│ ├── doc.go
│ ├── generateparentheses/
│ │ ├── generateparentheses.go
│ │ └── generateparentheses_test.go
│ ├── genetic/
│ │ ├── genetic.go
│ │ └── geneticalgorithm_test.go
│ ├── guid/
│ │ ├── guid.go
│ │ └── guid_test.go
│ ├── hamming/
│ │ ├── hammingdistance.go
│ │ └── hammingdistance_test.go
│ ├── horspool/
│ │ ├── horspool.go
│ │ └── horspool_test.go
│ ├── isisogram.go
│ ├── isisogram_test.go
│ ├── issubsequence.go
│ ├── issubsequence_test.go
│ ├── kmp/
│ │ ├── kmp.go
│ │ └── kmp_test.go
│ ├── levenshtein/
│ │ ├── levenshteindistance.go
│ │ └── levenshteindistance_test.go
│ ├── manacher/
│ │ ├── longestpalindrome.go
│ │ └── longestpalindrome_test.go
│ ├── palindrome/
│ │ ├── ispalindrome.go
│ │ └── ispalindrome_test.go
│ ├── pangram/
│ │ ├── ispangram.go
│ │ └── ispangram_test.go
│ ├── parenthesis/
│ │ ├── parenthesis.go
│ │ └── parenthesis_test.go
│ ├── search/
│ │ ├── boyermoore.go
│ │ ├── naive.go
│ │ └── patternsearch_test.go
│ └── strings_test.go
└── structure/
├── circularqueue/
│ ├── circularqueue_test.go
│ └── circularqueuearray.go
├── deque/
│ ├── deque.go
│ └── deque_test.go
├── doc.go
├── dynamicarray/
│ ├── dynamicarray.go
│ └── dynamicarray_test.go
├── fenwicktree/
│ ├── fenwicktree.go
│ └── fenwicktree_test.go
├── hashmap/
│ ├── hashmap.go
│ └── hashmap_test.go
├── heap/
│ ├── heap.go
│ └── heap_test.go
├── linkedlist/
│ ├── Readme.md
│ ├── cyclic.go
│ ├── cyclic_test.go
│ ├── doc.go
│ ├── doubly.go
│ ├── doubly_test.go
│ ├── shared.go
│ ├── singlylinkedlist.go
│ └── singlylinkedlist_test.go
├── queue/
│ ├── queue_test.go
│ ├── queuearray.go
│ ├── queuelinkedlist.go
│ └── queuelinklistwithlist.go
├── segmenttree/
│ ├── segmenttree.go
│ └── segmenttree_test.go
├── set/
│ ├── set.go
│ ├── set_test.go
│ └── setexample_test.go
├── stack/
│ ├── stack_test.go
│ ├── stackarray.go
│ ├── stacklinkedlist.go
│ └── stacklinkedlistwithlist.go
├── structure_test.go
├── tree/
│ ├── avl.go
│ ├── avl_test.go
│ ├── bstree.go
│ ├── bstree_test.go
│ ├── btree.go
│ ├── btree_test.go
│ ├── example_test.go
│ ├── rbtree.go
│ ├── rbtree_test.go
│ ├── tree.go
│ └── tree_test.go
└── trie/
├── trie.go
├── trie_bench_test.go
├── trie_test.go
└── trieexample_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/CODEOWNERS
================================================
# This is a comment.
# Each line is a file pattern followed by one or more owners.
# More details are here: https://help.github.com/articles/about-codeowners/
# The '*' pattern is global owners.
# Order is important. The last matching pattern has the most precedence.
* @raklaptudirm @yanglbme
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: "Bug report"
description: "Create a report to help us improve"
title: "[BUG]"
labels: ["bug"]
body:
- type: textarea
id: description
attributes:
label: "Description"
description: "A clear and concise description of what the bug is."
validations:
required: true
- type: textarea
id: steps
attributes:
label: "Steps to reproduce"
description: "Steps to reproduce the behavior (if applicable)"
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: false
- type: textarea
id: exceptedbhv
attributes:
label: "Excepted behavior"
description: "A clear and concise description of what you expected to happen."
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: "Screenshots"
description: "If applicable, add screenshots to help explain your problem."
validations:
required: false
- type: textarea
id: context
attributes:
label: "Additional context"
description: "Add any other context about the problem here."
validations:
required: false
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
================================================
FILE: .github/ISSUE_TEMPLATE/new_implementation.yml
================================================
name: "New or optimize implementation"
description: "Propose an enhancement or a new algorithm implementation."
title: "[ENHANCEMENT]"
labels: ["enhancement"]
body:
- type: textarea
id: description
attributes:
label: What would you like to share?
description: Provide a clear and concise explanation of your issue.
validations:
required: true
- type: markdown
attributes:
value: |
For new implementations, please specify the name and problem statement for the algorithm.
For algorithm enhancements, specify what needs to be changed and why. For example:
- Adding tests.
- Optimizing logic.
- Refactoring the file and folders for better structure.
- type: textarea
id: issuedetails
attributes:
label: "Extra issue details"
description: "Write down all the issue/algorithm details mentioned above."
validations:
required: true
- type: textarea
id: extrainfo
attributes:
label: Additional information
description: Is there anything else we should know about this issue?
validations:
required: false
================================================
FILE: .github/ISSUE_TEMPLATE/other.yml
================================================
name: Other
description: Use this for any other issues. Do NOT create blank issues
title: "[OTHER]"
labels: ["awaiting triage"]
body:
- type: markdown
attributes:
value: "# Other issue"
- type: textarea
id: issuedescription
attributes:
label: What would you like to share?
description: Provide a clear and concise explanation of your issue.
validations:
required: true
- type: textarea
id: extrainfo
attributes:
label: Additional information
description: Is there anything else we should know about this issue?
validations:
required: false
================================================
FILE: .github/PULL_REQUEST_TEMPLATE/pull_request.md
================================================
#### Description of Change
<!--
Thank you for your Pull Request. Please provide a description above and review
the requirements below.
Contributors guide: https://github.com/TheAlgorithms/Go/CONTRIBUTING.md
-->
#### Checklist
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
- [ ] Added description of change
- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/Go/blob/master/CONTRIBUTING.md#New-File-Name-guidelines)
- [ ] Added tests and example, test must pass
- [ ] Added documentation so that the program is self-explanatory and educational - [GoDoc guidelines](https://blog.golang.org/godoc)
- [ ] Relevant documentation/comments is changed or added
- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/Go/blob/master/CONTRIBUTING.md#Commit-Guidelines)
- [ ] Search previous suggestions before making a new one, as yours may be a duplicate.
- [ ] I acknowledge that all my contributions will be made under the project's license.
Notes: <!-- Please add a one-line description for developers or pull request viewers -->
================================================
FILE: .github/dependabot.yml
================================================
# Keep GitHub Actions up to date with GitHub's Dependabot...
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
version: 2
updates:
- package-ecosystem: github-actions
directory: /
groups:
github-actions:
patterns:
- "*" # Group all Actions updates into a single larger pull request
schedule:
interval: weekly
================================================
FILE: .github/workflows/ci.yml
================================================
# https://github.com/golangci/golangci-lint
name: Continuous Integration
on:
push:
# prevent duplication of tests with
# `pull_request` event
branches:
- master
pull_request:
jobs:
golang_lint_and_test:
name: Code style and tests
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '^1.18'
- name: Run Golang CI Lint
uses: golangci/golangci-lint-action@v6
with:
version: latest
args: -E gofmt
- name: Run tests
run: go test ./...
codespell:
name: Check for spelling errors
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: codespell-project/actions-codespell@master
with:
ignore_words_list: "actualy,nwe"
skip: "go.mod,go.sum"
================================================
FILE: .github/workflows/citk.yml
================================================
# https://github.com/golangci/golangci-lint
name: CI tool kit
on:
pull_request:
jobs:
CITK:
name: Code style and tests
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "^1.18"
- name: Checkout branch
run: |
git fetch origin master:master
- name: Install citk tool
run: |
go install github.com/tjgurwara99/citk@latest
- name: Run citk tool
run: |
citk check -l go -b master
================================================
FILE: .github/workflows/godocmd.yml
================================================
name: Generate Documentation
on:
push:
branches:
- master
jobs:
generate_readme:
name: Markdown Generation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: '^1.18'
- name: Install GoDocMD
run: |
go install github.com/tjgurwara99/godocmd@v0.1.3
- name: Configure Github Action
run: |
git config --global user.name "$GITHUB_ACTOR"
git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com"
- name: Update README.md file
run: |
godocmd -r -module ./ -w
- name: Commit changes if README.md is different
run: |
if [[ `git status --porcelain` ]]; then
git commit -am "Updated Documentation in README.md"
git push
else
echo "NO CHANGES DETECTED"
fi
================================================
FILE: .github/workflows/stale.yml
================================================
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '0 0 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.'
close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.'
stale-pr-message: 'This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.'
close-pr-message: 'This PR was closed because it has been stalled for 7 days with no activity.'
exempt-issue-labels: 'dont-close'
exempt-pr-labels: 'dont-close'
days-before-stale: 30
days-before-close: 7
================================================
FILE: .github/workflows/upload_coverage_report.yml
================================================
---
name: upload_coverage_report
on:
workflow_dispatch:
push:
branches:
- master
pull_request:
env:
REPORT_NAME: "coverage.out"
jobs:
upload_coverage_report:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '^1.18'
- name: Generate code coverage
run: |
go test -coverprofile="${{ env.REPORT_NAME }}" ./...
- name: Upload coverage to codecov (tokenless)
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
uses: codecov/codecov-action@v5
with:
files: "${{ env.REPORT_NAME }}"
fail_ci_if_error: true
- name: Upload coverage to codecov (with token)
if: "! github.event.pull_request.head.repo.fork "
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: "${{ env.REPORT_NAME }}"
fail_ci_if_error: true
...
================================================
FILE: .gitignore
================================================
.idea/
.vscode/
coverage.out
================================================
FILE: .gitpod.dockerfile
================================================
FROM gitpod/workspace-go
================================================
FILE: .gitpod.yml
================================================
---
image:
file: .gitpod.dockerfile
tasks:
- init: |
echo "Welcome to TheAlgorithms/Go"
================================================
FILE: .golangci.yml
================================================
run:
go: 1.19
================================================
FILE: CONTRIBUTING.md
================================================
# CONTRIBUTION GUIDELINES
## Before contributing
Welcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/Go/issues/new/choose) or ask in our [Discord server](https://the-algorithms.com/discord/) / [Gitter](https://gitter.im/TheAlgorithms), and clearly state your concerns.
## Contributing
### Maintainers
---
Please check the [`CODEOWNERS`](https://github.com/TheAlgorithms/Go/blob/master/.github/CODEOWNERS) file for a list of repository maintainers.
### Contributor
---
Being a contributor at The Algorithms, we request you to follow the points mentioned below:
- You did your own work.
- No plagiarism is allowed. Any plagiarized work will not be merged.
- Your work will be distributed under the [MIT License](https://github.com/TheAlgorithms/Go/blob/master/LICENSE) once your pull request has been merged.
- Please follow the repository guidelines and standards mentioned below.
#### New implementation
- New implementations are welcome!
- You can add new algorithms or data structures that are **not present in the repository** or that can **improve** the old implementations (**documentation**, **improving test cases**, **removing bugs**, or in any other reasonable sense)
#### Issues
- Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request, and it will be evaluated by project maintainers.
### Making Changes
---
#### Code
- Please use the directory structure of the repository.
- Make sure the file extensions should be `*.go`.
- Use meaningful variable names.
- Use standard library inside your code and avoid to import packages from other repositories
- If an implementation of the algorithm already exists, please refer to the [filename section below](#new-file-name-guidelines).
- You can suggest reasonable changes to existing algorithms.
- Strictly use snake_case (underscore_separated) in filenames.
- If you have added or modified code, please make sure the code compiles before submitting.
- Our automated testing runs [LGTM](https://lgtm.com/projects/g/TheAlgorithms/Go/) on all the pull requests, so please be sure that your code passes before submitting.
- Please conform to [GoDoc](https://blog.golang.org/godoc) standard and document the code as much as possible. This not only facilitates the readers but also generates the correct info on the website.
- **Be consistent in the use of these guidelines.**
#### Documentation
- Make sure you put useful comments in your code. Do not comment on obvious things.
- Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. If you want to create a new directory, then please check if a similar category has been recently suggested or created by other pull requests.
- If you have modified/added documentation, please ensure that your language is concise and must not contain grammatical errors.
- Do not update [`README.md`](https://github.com/TheAlgorithms/Go/blob/master/README.md) along with other changes. First, create an issue and then link to that issue in your pull request to suggest specific changes required to [`README.md`](https://github.com/TheAlgorithms/Go/blob/master/README.md).
- The repository follows [GoDoc](https://blog.golang.org/godoc) standards and auto-generates the [repository website](https://thealgorithms.github.io/). Please ensure the code is documented in this structure. A sample implementation is given below.
#### Test
- Make sure to add examples and test cases in your `filename_test.go` file.
- If you find an algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes.
- Please try to add one or more `Test` functions that will invoke the algorithm implementation on random test data with the expected output.
### Benchmark
---
- Make sure to add examples and benchmark cases in your `filename_test.go` or `filename_bench.go` if you want separated test and benchmark files.
- If you find an algorithm or document without benchmarks, please feel free to create a pull request or issue describing suggested changes.
- Please try to add one or more `Benchmark` functions that will invoke the algorithm implementation.
- For running the benchmark, you could use this command `go test -bench=.` for more details, read this article [Using Subtests and Sub-benchmarks](https://go.dev/blog/subtests)
#### Typical structure of a program
```go
// filename
// description: Add one line description here
// details:
// This is a multi-line
// description containing links, references,
// math equations, etc.
// author(s) [Name](https://github.com/handle), [Name](https://github.com/handle)
// see relatedfile.go, anotherfile.go, file_test.go
// ** Is just an example of how to write description for package and function and other stuff ... **
// Package sort provides primitives for sorting slices and user-defined
// collections.
package sort
// Reasons why you used those packages
// name package : Add one line description here
// name2 package : Add one line description here
// ...
import (
...
)
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written, and any write error encountered.
func Fprint(w io.Writer, a ...any) (n int, err error) {
...
}
```
#### New File Name guidelines
- Use lowercase words without ``"_"`` for the file name
- Use ``"_"`` as a separator only for `_test.go` or `_bench.go`
- For instance
```markdown
MyNewGoFile.GO is incorrect
my_new_go_file.go is incorrect
mynewgofile.go is the correct format
mynewgofile_test.go is the correct format
```
- It will be used to dynamically create a directory of files and implementation.
- File name validation will run on Docker to ensure validity.
- If an implementation of the algorithm already exists and your version is different from that implemented, please use incremental numeric digit as a suffix. For example: if `binarysearch.go` already exists in the `search` folder, and you are contributing a new implementation, the filename should be `binarysearch2.go` and for a third implementation, `binarysearch3.go`.
- Check out `Go` [Package names](https://go.dev/blog/package-names) roles
#### New Directory guidelines
- We recommend adding files to existing directories as much as possible.
- Use lowercase words with ``"_"`` as separator ( no spaces or ```"-"``` allowed )
- For instance
```markdown
SomeNew Fancy-Category is incorrect
some_new_fancy_category is correct
```
- Filepaths will be used to dynamically create a directory of our algorithms.
- Filepath validation will run on GitHub Actions to ensure compliance.
#### Commit Guidelines
- It is recommended to keep your changes grouped logically within individual commits. Maintainers find it easier to understand changes that are logically spilled across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected.
```bash
git add filexyz.go
git commit -m "your message"
```
Examples of commit messages with semantic prefixes:
```markdown
fix: XYZ algorithm bug
feat: add XYZ algorithm
test: add test for XYZ algorithm
docs: add comments and explanation to XYZ algorithm
```
Common prefixes:
- fix: A bug fix
- feat: A new feature
- docs: Documentation changes
- test: Correct existing tests or add new ones
### For New Gophers
---
#### Installing Go
- Installation (only needs to be installed once.)
- Mac (using home-brew): `brew install go`
- Windows (MSYS2 64-bit): `choco install golang` [Chocolatey Package Manager](https://chocolatey.org/)
- Linux (Debian): `sudo apt-get install golang`
- Manual Installation: [Downloads - The Go Programming Language](https://golang.org/dl/)
- Running (all platforms): `go run filexyz.go`
> Note: New packages should not be `main`, and never implement `main` functions for any package.
#### Code formatter
To format your code, you can use the gofmt tool directly:
```bash
gofmt -w filexyz.go
```
Or you can use the "go fmt" command:
```bash
go fmt path/to/your/package
```
#### Building
To build you code locally, simply run:
```bash
go build .
```
### Pull Requests
---
- Check out our [pull request template](https://github.com/TheAlgorithms/Go/blob/master/.github/PULL_REQUEST_TEMPLATE/pull_request.md
)
#### Building Locally
Before submitting a pull request, [build the code locally](#building) or using the convenient [](https://gitpod.io/#https://github.com/TheAlgorithms/Go) service.
#### GitHub Actions
- Enable GitHub Actions on your fork of the repository.
After enabling, it will execute `golang_lint_and_test` after every push (not a commit).
- The result can create another commit if the actions made any changes on your behalf.
- Hence, it is better to wait and check the results of GitHub Actions after every push.
- Run `git pull` in your local clone if these actions made many changes to avoid merge conflicts.
Most importantly,
- Happy coding!
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 The Algorithms and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# The Algorithms - Go
[](https://gitpod.io/#https://github.com/TheAlgorithms/Go)
[](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml)
[](https://codecov.io/gh/TheAlgorithms/Go)



[](https://the-algorithms.com/discord/)
### Algorithms implemented in Go (for education)
The repository is a collection of open-source implementation of a variety of algorithms implemented in Go and licensed under [MIT License](LICENSE).
Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
## List of Algorithms
<!--- AUTOGENERATED --->
<!--- GODOCMD BEGIN --->
# Packages:
<details>
<summary> <strong> ahocorasick </strong> </summary>
---
##### Functions:
1. [`Advanced`](./strings/ahocorasick/advancedahocorasick.go#L10): Advanced Function performing the Advanced Aho-Corasick algorithm. Finds and prints occurrences of each pattern.
2. [`AhoCorasick`](./strings/ahocorasick/ahocorasick.go#L15): AhoCorasick Function performing the Basic Aho-Corasick algorithm. Finds and prints occurrences of each pattern.
3. [`ArrayUnion`](./strings/ahocorasick/shared.go#L86): ArrayUnion Concats two arrays of int's into one.
4. [`BoolArrayCapUp`](./strings/ahocorasick/shared.go#L78): BoolArrayCapUp Dynamically increases an array size of bool's by 1.
5. [`BuildAc`](./strings/ahocorasick/ahocorasick.go#L54): Functions that builds Aho Corasick automaton.
6. [`BuildExtendedAc`](./strings/ahocorasick/advancedahocorasick.go#L46): BuildExtendedAc Functions that builds extended Aho Corasick automaton.
7. [`ComputeAlphabet`](./strings/ahocorasick/shared.go#L61): ComputeAlphabet Function that returns string of all the possible characters in given patterns.
8. [`ConstructTrie`](./strings/ahocorasick/shared.go#L4): ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings.
9. [`Contains`](./strings/ahocorasick/shared.go#L39): Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.
10. [`CreateNewState`](./strings/ahocorasick/shared.go#L111): CreateNewState Automaton function for creating a new state 'state'.
11. [`CreateTransition`](./strings/ahocorasick/shared.go#L116): CreateTransition Creates a transition for function σ(state,letter) = end.
12. [`GetParent`](./strings/ahocorasick/shared.go#L99): GetParent Function that finds the first previous state of a state and returns it. Used for trie where there is only one parent.
13. [`GetTransition`](./strings/ahocorasick/shared.go#L121): GetTransition Returns ending state for transition σ(fromState,overChar), '-1' if there is none.
14. [`GetWord`](./strings/ahocorasick/shared.go#L49): GetWord Function that returns word found in text 't' at position range 'begin' to 'end'.
15. [`IntArrayCapUp`](./strings/ahocorasick/shared.go#L70): IntArrayCapUp Dynamically increases an array size of int's by 1.
16. [`StateExists`](./strings/ahocorasick/shared.go#L133): StateExists Checks if state 'state' exists. Returns 'true' if it does, 'false' otherwise.
---
##### Types
1. [`Result`](./strings/ahocorasick/ahocorasick.go#L9): No description provided.
---
</details><details>
<summary> <strong> armstrong </strong> </summary>
---
##### Functions:
1. [`IsArmstrong`](./math/armstrong/isarmstrong.go#L14): No description provided.
---
</details><details>
<summary> <strong> binary </strong> </summary>
---
##### Package binary describes algorithms that use binary operations for different calculations.
---
##### Functions:
1. [`Abs`](./math/binary/abs.go#L10): Abs returns absolute value using binary operation Principle of operation: 1) Get the mask by right shift by the base 2) Base is the size of an integer variable in bits, for example, for int32 it will be 32, for int64 it will be 64 3) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. 4) Add the mask to the given number. 5) XOR of mask + n and mask gives the absolute value.
2. [`BitCounter`](./math/binary/bitcounter.go#L11): BitCounter - The function returns the number of set bits for an unsigned integer number
3. [`FastInverseSqrt`](./math/binary/fast_inverse_sqrt.go#L15): FastInverseSqrt assumes that argument is always positive, and it does not deal with negative numbers. The "magic" number 0x5f3759df is hex for 1597463007 in decimals. The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)).
4. [`IsPowerOfTwo`](./math/binary/checkisnumberpoweroftwo.go#L21): IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which we have to add and extra condition.
5. [`IsPowerOfTwoLeftShift`](./math/binary/checkisnumberpoweroftwo.go#L28): IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000, which in decimal system is 8 or = 2 * 2 * 2
6. [`LogBase2`](./math/binary/logarithm.go#L7): LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm)
7. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12): MeanUsingAndXor This function finds arithmetic mean using "AND" and "XOR" operations
8. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17): MeanUsingRightShift This function finds arithmetic mean using right shift
9. [`ReverseBits`](./math/binary/reversebits.go#L14): ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed.
10. [`SequenceGrayCode`](./math/binary/rbc.go#L11): SequenceGrayCode The function generates an "Gray code" sequence of length n
11. [`Sqrt`](./math/binary/sqrt.go#L10): No description provided.
12. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11): XorSearchMissingNumber This function finds a missing number in a sequence
---
</details><details>
<summary> <strong> cache </strong> </summary>
---
##### Functions:
1. [`NewLRU`](./cache/lru.go#L22): NewLRU represent initiate lru cache with capacity
2. [`NewLFU`](./cache/lfu.go#L33): NewLFU represent initiate lfu cache with capacity
3. [`Get`](./cache/lfu.go#L52): Get the value by key from LFU cache
4. [`Put`](./cache/lfu.go#L66): Put the key and value in LFU cache
---
##### Types
1. [`LRU`](./cache/lru.go#L15): Default the struct of lru cache algorithm.
2. [`LFU`](./cache/lfu.go#L19): Default the struct of lfu cache algorithm.
---
</details><details>
<summary> <strong> caesar </strong> </summary>
---
##### Package caesar is the shift cipher ref: https://en.wikipedia.org/wiki/Caesar_cipher
---
##### Functions:
1. [`Decrypt`](./cipher/caesar/caesar.go#L27): Decrypt decrypts by left shift of "key" each character of "input"
2. [`Encrypt`](./cipher/caesar/caesar.go#L6): Encrypt encrypts by right shift of "key" each character of "input"
3. [`FuzzCaesar`](./cipher/caesar/caesar_test.go#L158): No description provided.
---
</details><details>
<summary> <strong> catalan </strong> </summary>
---
##### Functions:
1. [`CatalanNumber`](./math/catalan/catalannumber.go#L16): CatalanNumber This function returns the `nth` Catalan number
---
</details><details>
<summary> <strong> checksum </strong> </summary>
---
##### Package checksum describes algorithms for finding various checksums
---
##### Functions:
1. [`CRC8`](./checksum/crc8.go#L25): CRC8 calculates CRC8 checksum of the given data.
2. [`Luhn`](./checksum/luhn.go#L11): Luhn validates the provided data using the Luhn algorithm.
---
##### Types
1. [`CRCModel`](./checksum/crc8.go#L15): No description provided.
---
</details><details>
<summary> <strong> coloring </strong> </summary>
---
##### Package coloring provides implementation of different graph coloring algorithms, e.g. coloring using BFS, using Backtracking, using greedy approach. Author(s): [Shivam](https://github.com/Shivam010)
---
##### Functions:
1. [`BipartiteCheck`](./graph/coloring/bipartite.go#L40): basically tries to color the graph in two colors if each edge connects 2 differently colored nodes the graph can be considered bipartite
---
##### Types
1. [`Graph`](./graph/coloring/graph.go#L14): No description provided.
---
</details><details>
<summary> <strong> combination </strong> </summary>
---
##### Package combination ...
---
##### Functions:
1. [`Start`](./strings/combination/combination.go#L13): Start ...
---
##### Types
1. [`Combinations`](./strings/combination/combination.go#L7): No description provided.
---
</details><details>
<summary> <strong> compression </strong> </summary>
---
##### Functions:
1. [`HuffDecode`](./compression/huffmancoding.go#L104): HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root. current stores the current node of the traversing algorithm. out stores the current decoded string.
2. [`HuffEncode`](./compression/huffmancoding.go#L93): HuffEncode encodes the string in by applying the mapping defined by codes.
3. [`HuffEncoding`](./compression/huffmancoding.go#L76): 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.
4. [`HuffTree`](./compression/huffmancoding.go#L33): HuffTree returns the root Node of the Huffman tree by compressing listfreq. The compression produces the most optimal code lengths, provided listfreq is ordered, i.e.: listfreq[i] <= listfreq[j], whenever i < j.
---
##### Types
1. [`Node`](./compression/huffmancoding.go#L17): No description provided.
2. [`SymbolFreq`](./compression/huffmancoding.go#L25): No description provided.
---
</details><details>
<summary> <strong> compression_test </strong> </summary>
---
##### Functions:
1. [`SymbolCountOrd`](./compression/huffmancoding_test.go#L16): SymbolCountOrd computes sorted symbol-frequency list of input message
---
</details><details>
<summary> <strong> conversion </strong> </summary>
---
##### Package conversion is a package of implementations which converts one data structure to another.
---
##### Functions:
1. [`Base64Decode`](./conversion/base64.go#L57): Base64Decode decodes the received input base64 string into a byte slice. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4
2. [`Base64Encode`](./conversion/base64.go#L19): Base64Encode encodes the received input bytes slice into a base64 string. The implementation follows the RFC4648 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc4648#section-4
3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25): BinaryToDecimal() function that will take Binary number as string, and return its Decimal equivalent as integer.
4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32): DecimalToBinary() function that will take Decimal number as int, and return its Binary equivalent as string.
5. [`FuzzBase64Encode`](./conversion/base64_test.go#L113): No description provided.
6. [`HEXToRGB`](./conversion/rgbhex.go#L10): HEXToRGB splits an RGB input (e.g. a color in hex format; 0x<color-code>) into the individual components: red, green and blue
7. [`IntToRoman`](./conversion/inttoroman.go#L17): IntToRoman converts an integer value to a roman numeral string. An error is returned if the integer is not between 1 and 3999.
8. [`RGBToHEX`](./conversion/rgbhex.go#L41): RGBToHEX does exactly the opposite of HEXToRGB: it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex
9. [`Reverse`](./conversion/decimaltobinary.go#L22): Reverse() function that will take string, and returns the reverse of that string.
10. [`RomanToInt`](./conversion/romantoint.go#L40): RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers outside the range 1 to 3,999 will return an error. Nil or empty string return 0 with no error thrown.
---
</details><details>
<summary> <strong> deque </strong> </summary>
---
##### Package deque implements a Double Ended Queue data structure.
---
##### Functions:
1. [`New`](./structure/deque/deque.go#L22): New returns a new DoublyEndedQueue.
---
##### Types
1. [`DoublyEndedQueue`](./structure/deque/deque.go#L17): No description provided.
---
</details><details>
<summary> <strong> deque_test </strong> </summary>
---
##### Types
1. [`QueryStructure`](./structure/deque/deque_test.go#L20): No description provided.
2. [`TestCaseData`](./structure/deque/deque_test.go#L27): No description provided.
---
</details><details>
<summary> <strong> diffiehellman </strong> </summary>
---
##### Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI
---
##### Functions:
1. [`GenerateMutualKey`](./cipher/diffiehellman/diffiehellmankeyexchange.go#L19): GenerateMutualKey : generates a mutual key that can be used by only alice and bob mutualKey = (shareKey^prvKey)%primeNumber
2. [`GenerateShareKey`](./cipher/diffiehellman/diffiehellmankeyexchange.go#L13): GenerateShareKey : generates a key using client private key , generator and primeNumber this key can be made public shareKey = (g^key)%primeNumber
---
</details><details>
<summary> <strong> dynamic </strong> </summary>
---
##### Package dynamic is a package of certain implementations of dynamically run algorithms.
---
##### Functions:
1. [`Abbreviation`](./dynamic/abbreviation.go#L24): Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise
2. [`Bin2`](./dynamic/binomialcoefficient.go#L21): Bin2 function
3. [`CoinChange`](./dynamic/coinchange.go#L5): CoinChange finds the number of possible combinations of coins of different values which can get to the target amount.
4. [`CutRodDp`](./dynamic/rodcutting.go#L21): CutRodDp solve the same problem using dynamic programming
5. [`CutRodRec`](./dynamic/rodcutting.go#L8): CutRodRec solve the problem recursively: initial approach
6. [`EditDistanceDP`](./dynamic/editdistance.go#L35): EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation. We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value of first[0..i-1] and second[0..j-1]. Time complexity is O(m * n) where m and n are lengths of the strings, first and second respectively.
7. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10): EditDistanceRecursive is a naive implementation with exponential time complexity.
8. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided.
9. [`Knapsack`](./dynamic/knapsack.go#L17): Knapsack solves knapsack problem return maxProfit
10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L13): LongestCommonSubsequence function
11. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9): LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order
12. [`LongestIncreasingSubsequenceGreedy`](./dynamic/longestincreasingsubsequencegreedy.go#L9): LongestIncreasingSubsequenceGreedy is a function to find the longest increasing subsequence in a given array using a greedy approach. The dynamic programming approach is implemented alongside this one. Worst Case Time Complexity: O(nlogn) Auxiliary Space: O(n), where n is the length of the array(slice). Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/
13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L25): LpsDp function
14. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L20): LpsRec function
15. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24): MatrixChainDp function
16. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10): MatrixChainRec function
17. [`Max`](./dynamic/knapsack.go#L11): Max function - possible duplicate
18. [`NthCatalanNumber`](./dynamic/catalan.go#L13): NthCatalan returns the n-th Catalan Number Complexity: O(n²)
19. [`NthFibonacci`](./dynamic/fibonacci.go#L6): NthFibonacci returns the nth Fibonacci Number
20. [`TrapRainWater`](./dynamic/traprainwater.go#L17): Calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming.
---
</details><details>
<summary> <strong> dynamicarray </strong> </summary>
---
##### Package dynamicarray A dynamic array is quite similar to a regular array, but its Size is modifiable during program runtime, very similar to how a slice in Go works. The implementation is for educational purposes and explains how one might go about implementing their own version of slices. For more details check out those links below here: GeeksForGeeks article : https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/ Go blog: https://blog.golang.org/slices-intro Go blog: https://blog.golang.org/slices authors [Wesllhey Holanda](https://github.com/wesllhey), [Milad](https://github.com/miraddo) see dynamicarray.go, dynamicarray_test.go
---
##### Types
1. [`DynamicArray`](./structure/dynamicarray/dynamicarray.go#L21): No description provided.
---
</details><details>
<summary> <strong> factorial </strong> </summary>
---
##### Package factorial describes algorithms Factorials calculations.
---
##### Functions:
1. [`Iterative`](./math/factorial/factorial.go#L12): Iterative returns the iteratively brute forced factorial of n
2. [`Recursive`](./math/factorial/factorial.go#L21): Recursive This function recursively computes the factorial of a number
3. [`UsingTree`](./math/factorial/factorial.go#L30): UsingTree This function finds the factorial of a number using a binary tree
---
</details><details>
<summary> <strong> fibonacci </strong> </summary>
---
##### Functions:
1. [`Formula`](./math/fibonacci/fibonacci.go#L42): Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio) Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers
2. [`Matrix`](./math/fibonacci/fibonacci.go#L15): Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form)
3. [`Recursive`](./math/fibonacci/fibonacci.go#L51): Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers. This algorithm is extremely slow for bigger numbers, but provides a simpler implementation.
---
</details><details>
<summary> <strong> gcd </strong> </summary>
---
##### Functions:
1. [`Extended`](./math/gcd/extended.go#L12): Extended simple extended gcd
2. [`ExtendedIterative`](./math/gcd/extendedgcditerative.go#L4): ExtendedIterative finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).
3. [`ExtendedRecursive`](./math/gcd/extendedgcd.go#L4): ExtendedRecursive finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).
4. [`Iterative`](./math/gcd/gcditerative.go#L4): Iterative Faster iterative version of GcdRecursive without holding up too much of the stack
5. [`Recursive`](./math/gcd/gcd.go#L4): Recursive finds and returns the greatest common divisor of a given integer.
6. [`TemplateBenchmarkExtendedGCD`](./math/gcd/extendedgcd_test.go#L44): No description provided.
7. [`TemplateBenchmarkGCD`](./math/gcd/gcd_test.go#L37): No description provided.
8. [`TemplateTestExtendedGCD`](./math/gcd/extendedgcd_test.go#L7): No description provided.
9. [`TemplateTestGCD`](./math/gcd/gcd_test.go#L18): No description provided.
---
</details><details>
<summary> <strong> generateparentheses </strong> </summary>
---
##### Functions:
1. [`GenerateParenthesis`](./strings/generateparentheses/generateparentheses.go#L12): No description provided.
---
</details><details>
<summary> <strong> genetic </strong> </summary>
---
##### Package genetic provides functions to work with strings using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia
---
##### Functions:
1. [`GeneticString`](./strings/genetic/genetic.go#L71): GeneticString generates PopulationItem based on the imputed target string, and a set of possible runes to build a string with. In order to optimise string generation additional configurations can be provided with Conf instance. Empty instance of Conf (&Conf{}) can be provided, then default values would be set. Link to the same algorithm implemented in python: https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py
---
##### Types
1. [`Conf`](./strings/genetic/genetic.go#L32): No description provided.
2. [`PopulationItem`](./strings/genetic/genetic.go#L26): No description provided.
3. [`Result`](./strings/genetic/genetic.go#L52): No description provided.
---
</details><details>
<summary> <strong> geometry </strong> </summary>
---
##### Package geometry contains geometric algorithms Package geometry contains geometric algorithms
---
##### Functions:
1. [`Distance`](./math/geometry/straightlines.go#L18): Distance calculates the shortest distance between two points.
2. [`EuclideanDistance`](./math/geometry/distance.go#L20): EuclideanDistance returns the Euclidean distance between points in any `n` dimensional Euclidean space.
3. [`IsParallel`](./math/geometry/straightlines.go#L42): IsParallel checks if two lines are parallel or not.
4. [`IsPerpendicular`](./math/geometry/straightlines.go#L47): IsPerpendicular checks if two lines are perpendicular or not.
5. [`PointDistance`](./math/geometry/straightlines.go#L53): PointDistance calculates the distance of a given Point from a given line. The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order.
6. [`Section`](./math/geometry/straightlines.go#L24): Section calculates the Point that divides a line in specific ratio. DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n.
7. [`Slope`](./math/geometry/straightlines.go#L32): Slope calculates the slope (gradient) of a line.
8. [`YIntercept`](./math/geometry/straightlines.go#L37): YIntercept calculates the Y-Intercept of a line from a specific Point.
---
##### Types
1. [`EuclideanPoint`](./math/geometry/distance.go#L14): No description provided.
2. [`Line`](./math/geometry/straightlines.go#L13): No description provided.
3. [`Point`](./math/geometry/straightlines.go#L9): No description provided.
---
</details><details>
<summary> <strong> graph </strong> </summary>
---
##### Package graph demonstrates Graph search algorithms reference: https://en.wikipedia.org/wiki/Tree_traversal
---
##### Functions:
1. [`ArticulationPoint`](./graph/articulationpoints.go#L19): ArticulationPoint is a function to identify articulation points in a graph. The function takes the graph as an argument and returns a boolean slice which indicates whether a vertex is an articulation point or not. Worst Case Time Complexity: O(|V| + |E|) Auxiliary Space: O(|V|) reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point
2. [`BreadthFirstSearch`](./graph/breadthfirstsearch.go#L9): BreadthFirstSearch is an algorithm for traversing and searching graph data structures. It starts at an arbitrary node of a graph, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. Worst-case performance O(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) Worst-case space complexity O(|V|)=O(b^{d})}O(|V|)=O(b^{d}) reference: https://en.wikipedia.org/wiki/Breadth-first_search
3. [`DepthFirstSearch`](./graph/depthfirstsearch.go#L53): No description provided.
4. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided.
5. [`FloydWarshall`](./graph/floydwarshall.go#L15): FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm
6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided.
7. [`KruskalMST`](./graph/kruskal.go#L23): No description provided.
8. [`PrimMST`](./graph/prim.go#30): Computes the minimum spanning tree of a weighted undirected graph
9. [`LowestCommonAncestor`](./graph/lowestcommonancestor.go#L111): For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time.
10. [`New`](./graph/graph.go#L16): Constructor functions for graphs (undirected by default)
11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided.
12. [`NewUnionFind`](./graph/unionfind.go#L24): Initialise a new union find data structure with s nodes
13. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided.
14. [`Topological`](./graph/topological.go#L7): 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
15. [`Edmond-Karp`](./graph/edmondkarp.go#L43): Computes the maximum possible flow between a pair of s-t vertices in a weighted graph
---
##### Types
1. [`Edge`](./graph/kruskal.go#L17): No description provided.
2. [`Graph`](./graph/graph.go#L9): No description provided.
3. [`Item`](./graph/dijkstra.go#L5): No description provided.
4. [`Query`](./graph/lowestcommonancestor_test.go#L9): No description provided.
5. [`Tree`](./graph/lowestcommonancestor.go#L25): No description provided.
6. [`TreeEdge`](./graph/lowestcommonancestor.go#L12): No description provided.
7. [`UnionFind`](./graph/unionfind.go#L18): No description provided.
8. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided.
---
</details><details>
<summary> <strong> guid </strong> </summary>
---
##### Package guid provides facilities for generating random globally unique identifiers.
---
##### Functions:
1. [`New`](./strings/guid/guid.go#L28): New returns a randomly generated global unique identifier.
---
</details><details>
<summary> <strong> hashmap </strong> </summary>
---
##### Functions:
1. [`Make`](./structure/hashmap/hashmap.go#L32): Make creates a new HashMap instance with input size and capacity
2. [`New`](./structure/hashmap/hashmap.go#L24): New return new HashMap instance
---
##### Types
1. [`HashMap`](./structure/hashmap/hashmap.go#L17): No description provided.
---
</details><details>
<summary> <strong> heap </strong> </summary>
---
##### Functions:
1. [`New`](./structure/heap/heap.go#L15): New gives a new heap object.
2. [`NewAny`](./structure/heap/heap.go#L24): NewAny gives a new heap object. element can be anything, but must provide less function.
---
##### Types
1. [`Heap`](./structure/heap/heap.go#L9): No description provided.
---
</details><details>
<summary> <strong> heap_test </strong> </summary>
---
##### Types
1. [`testInt`](#L0):
Methods:
1. [`Less`](./structure/heap/heap_test.go#L11): No description provided.
2. [`testStudent`](#L0):
Methods:
1. [`Less`](./structure/heap/heap_test.go#L20): No description provided.
---
</details><details>
<summary> <strong> horspool </strong> </summary>
---
##### Functions:
1. [`Horspool`](./strings/horspool/horspool.go#L10): No description provided.
---
</details><details>
<summary> <strong> kmp </strong> </summary>
---
##### Functions:
1. [`Kmp`](./strings/kmp/kmp.go#L4): Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
---
##### Types
1. [`args`](./strings/kmp/kmp_test.go#L39): No description provided.
---
</details><details>
<summary> <strong> lcm </strong> </summary>
---
##### Functions:
1. [`Lcm`](./math/lcm/lcm.go#L10): Lcm returns the lcm of two numbers using the fact that lcm(a,b) * gcd(a,b) = | a * b |
---
</details><details>
<summary> <strong> levenshtein </strong> </summary>
---
##### Functions:
1. [`Distance`](./strings/levenshtein/levenshteindistance.go#L10): Distance Function that gives Levenshtein Distance
---
</details><details>
<summary> <strong> linkedlist </strong> </summary>
---
##### Package linkedlist demonstrates different implementations on linkedlists.
---
##### Functions:
1. [`JosephusProblem`](./structure/linkedlist/cyclic.go#L120): https://en.wikipedia.org/wiki/Josephus_problem This is a struct-based solution for Josephus problem.
2. [`NewCyclic`](./structure/linkedlist/cyclic.go#L12): Create new list.
3. [`NewDoubly`](./structure/linkedlist/doubly.go#L31): No description provided.
4. [`NewNode`](./structure/linkedlist/shared.go#L12): Create new node.
5. [`NewSingly`](./structure/linkedlist/singlylinkedlist.go#L19): NewSingly returns a new instance of a linked list
---
##### Types
1. [`Cyclic`](./structure/linkedlist/cyclic.go#L6): No description provided.
2. [`Doubly`](./structure/linkedlist/doubly.go#L18): No description provided.
3. [`Node`](./structure/linkedlist/shared.go#L5): No description provided.
4. [`Singly`](./structure/linkedlist/singlylinkedlist.go#L10): No description provided.
5. [`testCase`](./structure/linkedlist/cyclic_test.go#L105): No description provided.
---
</details><details>
<summary> <strong> manacher </strong> </summary>
---
##### Functions:
1. [`LongestPalindrome`](./strings/manacher/longestpalindrome.go#L37): No description provided.
---
</details><details>
<summary> <strong> math </strong> </summary>
---
##### Package math is a package that contains mathematical algorithms and its different implementations. 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! author(s): [GooMonk](https://github.com/GooMonk) see krishnamurthy_test.go
---
##### Functions:
1. [`Abs`](./math/abs.go#L11): Abs returns absolute value
2. [`AliquotSum`](./math/aliquotsum.go#L14): This function returns s(n) for given number
3. [`Combinations`](./math/binomialcoefficient.go#L20): C is Binomial Coefficient function This function returns C(n, k) for given n and k
4. [`Cos`](./math/cos.go#L10): Cos returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine) [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx)
5. [`DefaultPolynomial`](./math/pollard.go#L16): DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n
6. [`FindKthMax`](./math/kthnumber.go#L11): FindKthMax returns the kth large element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process.
7. [`FindKthMin`](./math/kthnumber.go#L19): FindKthMin returns kth small element given an integer slice with nil `error` if found and returns -1 with `error` `search.ErrNotFound` if not found. NOTE: The `nums` slice gets mutated in the process.
8. [`IsAutomorphic`](./math/isautomorphic.go#L16): No description provided.
9. [`IsKrishnamurthyNumber`](./math/krishnamurthy.go#L12): IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not.
10. [`IsPerfectNumber`](./math/perfectnumber.go#L34): Checks if inNumber is a perfect number
11. [`IsPowOfTwoUseLog`](./math/checkisnumberpoweroftwo.go#L10): IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm. The limiting degree can be from 0 to 63. See alternatives in the binary package.
12. [`Lerp`](./math/lerp.go#L5): Lerp or Linear interpolation This function will return new value in 't' percentage between 'v0' and 'v1'
13. [`LiouvilleLambda`](./math/liouville.go#L24): Lambda is the liouville function This function returns λ(n) for given number
14. [`Mean`](./math/mean.go#L7): No description provided.
15. [`Median`](./math/median.go#L12): No description provided.
16. [`Mode`](./math/mode.go#L19): No description provided.
17. [`Mu`](./math/mobius.go#L21): Mu is the Mobius function This function returns μ(n) for given number
18. [`Phi`](./math/eulertotient.go#L5): Phi is the Euler totient function. This function computes the number of numbers less then n that are coprime with n.
19. [`PollardsRhoFactorization`](./math/pollard.go#L29): PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2
20. [`PronicNumber`](./math/pronicnumber.go#L15): PronicNumber returns true if argument passed to the function is pronic and false otherwise.
21. [`Sin`](./math/sin.go#L9): Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine)
22. [`SumOfProperDivisors`](./math/perfectnumber.go#L17): Returns the sum of proper divisors of inNumber.
---
</details><details>
<summary> <strong> matrix </strong> </summary>
---
##### filename: strassenmatrixmultiply.go description: Implements matrix multiplication using the Strassen algorithm. details: This program takes two matrices as input and performs matrix multiplication using the Strassen algorithm, which is an optimized divide-and-conquer approach. It allows for efficient multiplication of large matrices. author(s): Mohit Raghav(https://github.com/mohit07raghav19) See strassenmatrixmultiply_test.go for test cases
---
##### Functions:
1. [`IsValid`](./math/matrix/isvalid.go#L6): IsValid checks if the input matrix has consistent row lengths.
2. [`New`](./math/matrix/matrix.go#L17): NewMatrix creates a new Matrix based on the provided arguments.
3. [`NewFromElements`](./math/matrix/matrix.go#L43): NewFromElements creates a new Matrix from the given elements.
---
##### Types
1. [`Matrix`](./math/matrix/matrix.go#L10): No description provided.
---
</details><details>
<summary> <strong> matrix_test </strong> </summary>
---
##### Functions:
1. [`MakeRandomMatrix`](./math/matrix/strassenmatrixmultiply_test.go#L105): No description provided.
---
</details><details>
<summary> <strong> max </strong> </summary>
---
##### Functions:
1. [`Bitwise`](./math/max/bitwisemax.go#L11): Bitwise computes using bitwise operator the maximum of all the integer input and returns it
2. [`Int`](./math/max/max.go#L6): Int is a function which returns the maximum of all the integers provided as arguments.
---
</details><details>
<summary> <strong> maxsubarraysum </strong> </summary>
---
##### Package maxsubarraysum is a package containing a solution to a common problem of finding max contiguous sum within a array of ints.
---
##### Functions:
1. [`MaxSubarraySum`](./other/maxsubarraysum/maxsubarraysum.go#L13): MaxSubarraySum returns the maximum subarray sum
---
</details><details>
<summary> <strong> min </strong> </summary>
---
##### Functions:
1. [`Bitwise`](./math/min/bitwisemin.go#L11): Bitwise This function returns the minimum integer using bit operations
2. [`Int`](./math/min/min.go#L6): Int is a function which returns the minimum of all the integers provided as arguments.
---
</details><details>
<summary> <strong> modular </strong> </summary>
---
##### Functions:
1. [`Exponentiation`](./math/modular/exponentiation.go#L22): Exponentiation returns base^exponent % mod
2. [`Inverse`](./math/modular/inverse.go#L19): Inverse Modular function
3. [`Multiply64BitInt`](./math/modular/exponentiation.go#L51): Multiply64BitInt Checking if the integer multiplication overflows
---
</details><details>
<summary> <strong> moserdebruijnsequence </strong> </summary>
---
##### Functions:
1. [`MoserDeBruijnSequence`](./math/moserdebruijnsequence/sequence.go#L7): No description provided.
---
</details><details>
<summary> <strong> nested </strong> </summary>
---
##### Package nested provides functions for testing strings proper brackets nesting.
---
##### Functions:
1. [`IsBalanced`](./other/nested/nestedbrackets.go#L20): IsBalanced returns true if provided input string is properly nested. Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. A sequence of brackets `s` is considered properly nested if any of the following conditions are true: - `s` is empty; - `s` has the form (U) or [U] or {U} where U is a properly nested string; - `s` has the form VW where V and W are properly nested strings. For example, the string "()()[()]" is properly nested but "[(()]" is not. **Note** Providing characters other then brackets would return false, despite brackets sequence in the string. Make sure to filter input before usage.
---
</details><details>
<summary> <strong> palindrome </strong> </summary>
---
##### Functions:
1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided.
2. [`IsPalindromeRecursive`](./strings/palindrome/ispalindrome.go#L39): No description provided.
---
</details><details>
<summary> <strong> pangram </strong> </summary>
---
##### Functions:
1. [`IsPangram`](./strings/pangram/ispangram.go#L21): No description provided.
---
</details><details>
<summary> <strong> parenthesis </strong> </summary>
---
##### Functions:
1. [`Parenthesis`](./strings/parenthesis/parenthesis.go#L8): Parenthesis algorithm checks if every opened parenthesis is closed correctly. When parcounter is less than 0 when a closing parenthesis is detected without an opening parenthesis that surrounds it and parcounter will be 0 if all open parenthesis are closed correctly.
---
</details><details>
<summary> <strong> pascal </strong> </summary>
---
##### Functions:
1. [`GenerateTriangle`](./math/pascal/pascaltriangle.go#L24): GenerateTriangle This function generates a Pascal's triangle of n lines
---
</details><details>
<summary> <strong> password </strong> </summary>
---
##### Package password contains functions to help generate random passwords
---
##### Functions:
1. [`Generate`](./other/password/generator.go#L15): Generate returns a newly generated password
---
</details><details>
<summary> <strong> permutation </strong> </summary>
---
##### Functions:
1. [`GenerateElementSet`](./math/permutation/heaps.go#L37): No description provided.
2. [`Heaps`](./math/permutation/heaps.go#L8): Heap's Algorithm for generating all permutations of n objects
3. [`NextPermutation`](./math/permutation/next_permutation.go#8): A solution to find next permutation of an integer array in constant memory
---
</details><details>
<summary> <strong> pi </strong> </summary>
---
##### spigotpi_test.go description: Test for Spigot Algorithm for the Digits of Pi author(s) [red_byte](https://github.com/i-redbyte) see spigotpi.go
---
##### Functions:
1. [`MonteCarloPi`](./math/pi/montecarlopi.go#L17): No description provided.
2. [`MonteCarloPiConcurrent`](./math/pi/montecarlopi.go#L36): 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.
3. [`Spigot`](./math/pi/spigotpi.go#L12): No description provided.
---
</details><details>
<summary> <strong> polybius </strong> </summary>
---
##### Package polybius is encrypting method with polybius square ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher
---
##### Functions:
1. [`FuzzPolybius`](./cipher/polybius/polybius_test.go#L154): No description provided.
2. [`NewPolybius`](./cipher/polybius/polybius.go#L21): NewPolybius returns a pointer to object of Polybius. If the size of "chars" is longer than "size", "chars" are truncated to "size".
---
##### Types
1. [`Polybius`](./cipher/polybius/polybius.go#L12): No description provided.
---
</details><details>
<summary> <strong> power </strong> </summary>
---
##### Functions:
1. [`IterativePower`](./math/power/fastexponent.go#L4): IterativePower is iterative O(logn) function for pow(x, y)
2. [`RecursivePower`](./math/power/fastexponent.go#L18): RecursivePower is recursive O(logn) function for pow(x, y)
3. [`RecursivePower1`](./math/power/fastexponent.go#L30): RecursivePower1 is recursive O(n) function for pow(x, y)
4. [`UsingLog`](./math/power/powvialogarithm.go#L14): No description provided.
---
</details><details>
<summary> <strong> prime </strong> </summary>
---
##### Functions:
1. [`Factorize`](./math/prime/primefactorization.go#L5): Factorize is a function that computes the exponents of each prime in the prime factorization of n
2. [`Generate`](./math/prime/sieve.go#L26): Generate returns a int slice of prime numbers up to the limit
3. [`GenerateChannel`](./math/prime/sieve.go#L9): Generate generates the sequence of integers starting at 2 and sends it to the channel `ch`
4. [`MillerRabinDeterministic`](./math/prime/millerrabintest.go#L121): MillerRabinDeterministic is a Deterministic version of the Miller-Rabin test, which returns correct results for all valid int64 numbers.
5. [`MillerRabinProbabilistic`](./math/prime/millerrabintest.go#L101): MillerRabinProbabilistic is a probabilistic test for primality of an integer based of the algorithm devised by Miller and Rabin.
6. [`MillerRandomTest`](./math/prime/millerrabintest.go#L77): MillerRandomTest This is the intermediate step that repeats within the miller rabin primality test for better probabilitic chances of receiving the correct result with random witnesses.
7. [`MillerTest`](./math/prime/millerrabintest.go#L49): MillerTest tests whether num is a strong probable prime to a witness. Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s
8. [`MillerTestMultiple`](./math/prime/millerrabintest.go#L84): MillerTestMultiple is like MillerTest but runs the test for multiple witnesses.
9. [`OptimizedTrialDivision`](./math/prime/primecheck.go#L26): OptimizedTrialDivision checks primality of an integer using an optimized trial division method. The optimizations include not checking divisibility by the even numbers and only checking up to the square root of the given number.
10. [`Sieve`](./math/prime/sieve.go#L16): Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels
11. [`TrialDivision`](./math/prime/primecheck.go#L9): TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it.
12. [`Twin`](./math/prime/twin.go#L15): This function returns twin prime for given number returns (n + 2) if both n and (n + 2) are prime -1 otherwise
---
</details><details>
<summary> <strong> pythagoras </strong> </summary>
---
##### Functions:
1. [`Distance`](./math/pythagoras/pythagoras.go#L15): Distance calculates the distance between to vectors with the Pythagoras theorem
---
##### Types
1. [`Vector`](./math/pythagoras/pythagoras.go#L8): No description provided.
---
</details><details>
<summary> <strong> queue </strong> </summary>
---
##### Functions:
1. [`BackQueue`](./structure/queue/queuearray.go#L32): BackQueue return the Back value
2. [`DeQueue`](./structure/queue/queuearray.go#L20): DeQueue it will be removed the first value that added into the list
3. [`EnQueue`](./structure/queue/queuearray.go#L15): EnQueue it will be added new value into our list
4. [`FrontQueue`](./structure/queue/queuearray.go#L27): FrontQueue return the Front value
5. [`IsEmptyQueue`](./structure/queue/queuearray.go#L42): IsEmptyQueue check our list is empty or not
6. [`LenQueue`](./structure/queue/queuearray.go#L37): LenQueue will return the length of the queue list
---
##### Types
1. [`LQueue`](./structure/queue/queuelinklistwithlist.go#L20): No description provided.
2. [`Node`](./structure/queue/queuelinkedlist.go#L13): No description provided.
3. [`Queue`](./structure/queue/queuelinkedlist.go#L19): No description provided.
---
</details><details>
<summary> <strong> rot13 </strong> </summary>
---
##### Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ref: https://en.wikipedia.org/wiki/ROT13
---
##### Functions:
1. [`FuzzRot13`](./cipher/rot13/rot13_test.go#L72): No description provided.
---
</details><details>
<summary> <strong> rsa </strong> </summary>
---
##### Package rsa shows a simple implementation of RSA algorithm
---
##### Functions:
1. [`Decrypt`](./cipher/rsa/rsa.go#L43): Decrypt decrypts encrypted rune slice based on the RSA algorithm
2. [`Encrypt`](./cipher/rsa/rsa.go#L28): Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory
3. [`FuzzRsa`](./cipher/rsa/rsa_test.go#L79): No description provided.
---
</details><details>
<summary> <strong> search </strong> </summary>
---
##### Functions:
1. [`BoyerMoore`](./strings/search/boyermoore.go#L5): Implementation of boyer moore string search O(l) where l=len(text)
2. [`Naive`](./strings/search/naive.go#L5): Implementation of naive string search O(n*m) where n=len(txt) and m=len(pattern)
---
</details><details>
<summary> <strong> segmenttree </strong> </summary>
---
##### Functions:
1. [`NewSegmentTree`](./structure/segmenttree/segmenttree.go#L116): No description provided.
---
##### Types
1. [`SegmentTree`](./structure/segmenttree/segmenttree.go#L17): No description provided.
---
</details><details>
<summary> <strong> set </strong> </summary>
---
##### package set implements a Set using a golang map. This implies that only the types that are accepted as valid map keys can be used as set elements. For instance, do not try to Add a slice, or the program will panic.
---
##### Functions:
1. [`New`](./structure/set/set.go#L7): New gives new set.
---
</details><details>
<summary> <strong> sha256 </strong> </summary>
---
##### Functions:
1. [`Hash`](./hashing/sha256/sha256.go#L50): Hash hashes the input message using the sha256 hashing function, and return a 32 byte array. The implementation follows the RGC6234 standard, which is documented at https://datatracker.ietf.org/doc/html/rfc6234
---
</details><details>
<summary> <strong> sort </strong> </summary>
---
##### Package sort a package for demonstrating sorting algorithms in Go
---
##### Functions:
1. [`BinaryInsertion`](./sort/binaryinsertionsort.go#L13): No description provided.
2. [`Bogo`](./sort/bogosort.go#L32): No description provided.
3. [`Bubble`](./sort/bubblesort.go#L9): Bubble is a simple generic definition of Bubble sort algorithm.
4. [`Bucket`](./sort/bucketsort.go#L7): Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range.
5. [`Cocktail`](./sort/cocktailsort.go#L9): Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)
6. [`Comb`](./sort/combSort.go#L17): Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm.
7. [`Count`](./sort/countingsort.go#L11): No description provided.
8. [`Cycle`](./sort/cyclesort.go#L10): Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It is theoretically optimal in terms of the total number of writes to the original array.
9. [`Exchange`](./sort/exchangesort.go#L8): No description provided.
10. [`HeapSort`](./sort/heapsort.go#L116): No description provided.
11. [`ImprovedSimple`](./sort/simplesort.go#L27): ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last. This improved version is more similar to implementation of insertion sort
12. [`Insertion`](./sort/insertionsort.go#L5): No description provided.
13. [`Merge`](./sort/mergesort.go#L41): Merge Perform merge sort on a slice
14. [`MergeIter`](./sort/mergesort.go#L55): No description provided.
15. [`Pancake`](./sort/pancakesort.go#L8): Pancake sorts a slice using flip operations, where flip refers to the idea of reversing the slice from index `0` to `i`.
16. [`ParallelMerge`](./sort/mergesort.go#L66): ParallelMerge Perform merge sort on a slice using goroutines
17. [`Partition`](./sort/quicksort.go#L12): No description provided.
18. [`Patience`](./sort/patiencesort.go#L13): No description provided.
19. [`Pigeonhole`](./sort/pigeonholesort.go#L15): Pigeonhole sorts a slice using pigeonhole sorting algorithm. NOTE: To maintain time complexity O(n + N), this is the reason for having only Integer constraint instead of Ordered.
20. [`Quicksort`](./sort/quicksort.go#L39): Quicksort Sorts the entire array
21. [`QuicksortRange`](./sort/quicksort.go#L26): QuicksortRange Sorts the specified range within the array
22. [`RadixSort`](./sort/radixsort.go#L43): No description provided.
23. [`Selection`](./sort/selectionsort.go#L5): No description provided.
24. [`Shell`](./sort/shellsort.go#L5): No description provided.
25. [`Simple`](./sort/simplesort.go#L13): No description provided.
---
##### Types
1. [`MaxHeap`](./sort/heapsort.go#L5): No description provided.
---
</details><details>
<summary> <strong> sqrt </strong> </summary>
---
##### Package sqrt contains algorithms and data structures that contains a √n in their complexity
---
##### Functions:
1. [`NewSqrtDecomposition`](./sqrt/sqrtdecomposition.go#L34): Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment Assumptions: - len(elements) > 0
---
##### Types
1. [`SqrtDecomposition`](./sqrt/sqrtdecomposition.go#L21): No description provided.
---
</details><details>
<summary> <strong> stack </strong> </summary>
---
##### Functions:
1. [`NewStack`](./structure/stack/stackarray.go#L17): NewStack creates and returns a new stack.
---
##### Types
1. [`Array`](./structure/stack/stackarray.go#L12): No description provided.
2. [`Node`](./structure/stack/stacklinkedlist.go#L13): No description provided.
3. [`SList`](./structure/stack/stacklinkedlistwithlist.go#L18): No description provided.
4. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided.
---
</details><details>
<summary> <strong> strings </strong> </summary>
---
##### Package strings is a package that contains all algorithms that are used to analyse and manipulate strings.
---
##### Functions:
1. [`CountChars`](./strings/charoccurrence.go#L12): CountChars counts the number of a times a character has occurred in the provided string argument and returns a map with `rune` as keys and the count as value.
2. [`IsIsogram`](./strings/isisogram.go#L34): No description provided.
3. [`IsSubsequence`](./strings/issubsequence.go#L10): Returns true if s is subsequence of t, otherwise return false.
---
</details><details>
<summary> <strong> transposition </strong> </summary>
---
##### Functions:
1. [`Decrypt`](./cipher/transposition/transposition.go#L81): No description provided.
2. [`Encrypt`](./cipher/transposition/transposition.go#L51): No description provided.
3. [`FuzzTransposition`](./cipher/transposition/transposition_test.go#L103): No description provided.
---
</details><details>
<summary> <strong> tree </strong> </summary>
---
##### For more details check out those links below here: Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree authors [guuzaa](https://github.com/guuzaa)
---
##### Functions:
1. [`NewAVL`](./structure/tree/avl.go#L54): NewAVL creates a novel AVL tree
2. [`NewBinarySearch`](./structure/tree/bstree.go#L46): NewBinarySearch creates a novel Binary-Search tree
3. [`NewRB`](./structure/tree/rbtree.go#L57): NewRB creates a new Red-Black Tree
---
##### Types
1. [`AVL`](./structure/tree/avl.go#L48): No description provided.
2. [`AVLNode`](./structure/tree/avl.go#L18): No description provided.
3. [`BSNode`](./structure/tree/bstree.go#L15): No description provided.
4. [`BinarySearch`](./structure/tree/bstree.go#L40): No description provided.
5. [`RB`](./structure/tree/rbtree.go#L51): No description provided.
6. [`RBNode`](./structure/tree/rbtree.go#L25): No description provided.
---
</details><details>
<summary> <strong> trie </strong> </summary>
---
##### Package trie provides Trie data structures in golang. Wikipedia: https://en.wikipedia.org/wiki/Trie
---
##### Functions:
1. [`NewNode`](./structure/trie/trie.go#L14): NewNode creates a new Trie node with initialized children map.
---
##### Types
1. [`Node`](./structure/trie/trie.go#L7): No description provided.
---
</details><details>
<summary> <strong> xor </strong> </summary>
---
##### Package xor is an encryption algorithm that operates the exclusive disjunction(XOR) ref: https://en.wikipedia.org/wiki/XOR_cipher
---
##### Functions:
1. [`Decrypt`](./cipher/xor/xor.go#L19): Decrypt decrypts with Xor encryption
2. [`Encrypt`](./cipher/xor/xor.go#L10): Encrypt encrypts with Xor encryption after converting each character to byte The returned value might not be readable because there is no guarantee which is within the ASCII range If using other type such as string, []int, or some other types, add the statements for converting the type to []byte.
3. [`FuzzXOR`](./cipher/xor/xor_test.go#L108): No description provided.
---
</details>
##### Package rail fence is a classical type of transposition cipher ref : https://en.wikipedia.org/wiki/Rail_fence_cipher
---
##### Functions:
1. [`Encrypt`](.cipher/railfence/railfence.go#L7): Encrypt encrypts a message using rail fence cipher
2. [`Decrypt`](.cipher/railfence/railfence.go#L44): decrypt decrypts a message using rail fence cipher
3. [`TestEncrypt`](.cipher/railfence/railfence_test.go#L7) Test function for Encrypt
4. [`TestDecrypt`](.cipher/railfence/railfence_test.go#L50) Test function for Decrypt
---
</details>
<!--- GODOCMD END --->
================================================
FILE: STYLE.md
================================================
# The Algorithms Go Repository Style Guide
This guide contains a set of go idioms and best practices which should be followed while writing
code whenever they are applicable. The instructions in this document should be given precedence
if there is a conflict between this document and [contribution guidelines](./CONTRIBUTING.md). If you find any issue or ambiguity in
this document, the maintainers of this repository should be consulted.
## Table of Contents
- [Formatting](#formatting)
- [Commenting](#commenting)
- [Package Comments](#package-comments)
- [Documentation Comments](#documentation-comments)
- [Author Comments](#author-comments)
- [Naming](#naming)
- [Package Naming](#package-naming)
- [Symbol Naming](#symbol-naming)
- [Function Naming](#function-naming)
- [Constructor Naming](#constructor-naming)
- [Getter Naming](#getter-naming)
- [Setter Naming](#setter-naming)
- [Interface Naming](#interface-naming)
## Formatting
All go code should be formatted with the official formatting tool `gofmt`. This requirement is
verified by the repository workflows.
## Commenting
All exported symbols should be commented with documentation, so that their motivation and use is
clear. All documentation should record any nuances of the symbol so that users are well aware of
them.
C++ style line comments should be preferred over C-style block comments.
<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>
```go
/*
Unmarshal converts a JSON string into a go interface
...
*/
```
</td><td>
```go
// Unmarshal converts a JSON string into a go interface
// ...
```
</td></tr>
</tbody></table>
### Package Comments
Package comments should start with the word "Package" followed by the package name. For packages
spanning multiple files or with a need for a large documentation, use a separate `doc.go` file for package level documentation comment.
<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>
```go
// sort is a package which implements sorting functions.
```
</td><td>
```go
// Package sort implements sorting functions.
```
</td></tr>
</tbody></table>
### Documentation Comments
All doc comments for symbols should start with the symbol name.
<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>
```go
// Function Quick is an implementation
// of the Quicksort algorithm.
```
</td><td>
```go
// Quick is an implementation
// of the Quicksort algorithm.
```
</td></tr>
</tbody></table>
### Author Comments
A comment recording the author of a particular file may also be added. This comment should be
written at the top of the file and it should not be a part of the package documentation.
<table>
<thead><tr><th>Bad</th><th>Good</th></tr></thead>
<tbody>
<tr><td>
```go
// author: Rak Laptudirm (@raklaptudirm)
package sort
```
Comment is a part of the package documentation.
</td><td>
```go
// author: Rak Laptudirm (@raklaptudirm)
package sort
```
Comment is not a part of the package documentation.
</td></tr>
</tbody></table>
## Naming
### Package Naming
Package names should be short and to the point. Keep in mind that this identifier will be used to
refer to your package, so make it easy to remember. It should be only composed of lower case
letters. Prefer `json` to `JSON` or `Json`. If your package name has two words, merge them
together. Prefer `jsonencoding` to `jsonEncoding` or `json_encoding`. Although, there is almost always a word to succinctly describe the package with an appropriate name. So if you have a name that describes the package nicely, please use that.
Add the `_test` suffix to your package name to implement black-box testing for your package in the test files.
### Symbol Naming
Go symbols should be named in the `camelCase` or `PascalCase`, depending of whether the symbol
is exported or not. The case when using acronyms in names should be consistent. Use `json` or
`JSON` instead of `Json`.
For exported symbols, use the package name to your advantage to write concise symbol names. For
example, if you have a package `png`, instead of defining a `png.PNGFile`, define a `png.File`.
It is much clearer and avoids repetition.
### Function Naming
#### Constructor Naming
Constructors should use the naming format `New<Type>()` for constructors which return pointers and
`Make<Type>()` for constructors which return values in accordance with the Go Programming Language's
`new` and `make` functions. If the package only exports a single constructor, use the name `New()`.
Some valid names are `reader.New()`, `metainfo.NewFile()`.
#### Getter Naming
Usage of Getters and Setters are discouraged. Use exported variables instead.
Getters should use the name of the field that is being fetched. For example, prefer a getter
name like `user.Name()` to `user.GetName()`.
#### Setter Naming
Setters should use names in the format `Set<Field>`. For example, `user.SetName()`.
### Interface Naming
Interfaces should use names in the format of `<Method>er` or `<Method>`. For example, some
valid interface names are:
```go
type Node interface {
Node()
}
type Writer interface {
Write()
}
```
================================================
FILE: cache/lfu.go
================================================
// lfu.go
// description: a type of cache algorithm used to manage memory within a computer.
// details:
// The standard characteristics of this method involve the system keeping track of the number of times a block is referenced in memory.
// When the cache is full and requires more room the system will purge the item with the lowest reference frequency.
// ref: (https://en.wikipedia.org/wiki/Least_frequently_used)
// time complexity: O(N)
// space complexity: O(1)
// author: [CocaineCong](https://github.com/CocaineCong)
package cache
import (
"container/list"
"math"
)
// LFU the Least Frequently Used (LFU) page-replacement algorithm
type LFU struct {
len int // length
cap int // capacity
minFreq int // The element that operates least frequently in LFU
// key: key of element, value: value of element
itemMap map[string]*list.Element
// key: frequency of possible occurrences of all elements in the itemMap
// value: elements with the same frequency
freqMap map[int]*list.List
}
// NewLFU init the LFU cache with capacity
func NewLFU(capacity int) LFU {
return LFU{
len: 0,
cap: capacity,
minFreq: math.MaxInt,
itemMap: make(map[string]*list.Element),
freqMap: make(map[int]*list.List),
}
}
// initItem to init item for LFU
func initItem(k string, v any, f int) item {
return item{
key: k,
value: v,
freq: f,
}
}
// Get the key in cache by LFU
func (c *LFU) Get(key string) any {
// if existed, will return value
if e, ok := c.itemMap[key]; ok {
// the frequency of e +1 and change freqMap
c.increaseFreq(e)
obj := e.Value.(item)
return obj.value
}
// if not existed, return nil
return nil
}
// Put the key in LFU cache
func (c *LFU) Put(key string, value any) {
if e, ok := c.itemMap[key]; ok {
// if key existed, update the value
obj := e.Value.(item)
obj.value = value
c.increaseFreq(e)
} else {
// if key not existed
obj := initItem(key, value, 1)
// if the length of item gets to the top line
// remove the least frequently operated element
if c.len == c.cap {
c.eliminate()
c.len--
}
// insert in freqMap and itemMap
c.insertMap(obj)
// change minFreq to 1 because insert the newest one
c.minFreq = 1
// length++
c.len++
}
}
// increaseFreq increase the frequency if element
func (c *LFU) increaseFreq(e *list.Element) {
obj := e.Value.(item)
// remove from low frequency first
oldLost := c.freqMap[obj.freq]
oldLost.Remove(e)
// change the value of minFreq
if c.minFreq == obj.freq && oldLost.Len() == 0 {
// if it is the last node of the minimum frequency that is removed
c.minFreq++
}
// add to high frequency list
c.insertMap(obj)
}
// insertMap insert item in map
func (c *LFU) insertMap(obj item) {
// add in freqMap
l, ok := c.freqMap[obj.freq]
if !ok {
l = list.New()
c.freqMap[obj.freq] = l
}
e := l.PushFront(obj)
// update or add the value of itemMap key to e
c.itemMap[obj.key] = e
}
// eliminate clear the least frequently operated element
func (c *LFU) eliminate() {
l := c.freqMap[c.minFreq]
e := l.Back()
obj := e.Value.(item)
l.Remove(e)
delete(c.itemMap, obj.key)
}
================================================
FILE: cache/lfu_test.go
================================================
package cache_test
import (
"testing"
"github.com/TheAlgorithms/Go/cache"
)
func TestLFU(t *testing.T) {
lfuCache := cache.NewLFU(3)
t.Run("Test 1: Put number and Get is correct", func(t *testing.T) {
key, value := "1", 1
lfuCache.Put(key, value)
got := lfuCache.Get(key)
if got != value {
t.Errorf("expected: %v, got: %v", value, got)
}
})
t.Run("Test 2: Get data not stored in cache should return nil", func(t *testing.T) {
got := lfuCache.Get("2")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
})
t.Run("Test 3: Put data over capacity and Get should return nil", func(t *testing.T) {
lfuCache.Put("2", 2)
lfuCache.Put("3", 3)
lfuCache.Put("4", 4)
got := lfuCache.Get("1")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
})
t.Run("test 4: Put key over capacity but recent key exists", func(t *testing.T) {
lfuCache.Put("4", 4)
lfuCache.Put("3", 3)
lfuCache.Put("2", 2)
lfuCache.Put("1", 1)
got := lfuCache.Get("4")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
expected := 3
got = lfuCache.Get("3")
if got != expected {
t.Errorf("expected: %v, got: %v", expected, got)
}
})
}
================================================
FILE: cache/lru.go
================================================
// lru.go
// description : Least Recently Used (LRU) cache
// details : A Least Recently Used (LRU) cache is a type of cache algorithm used to manage memory within a computer. The LRU algorithm is designed to remove the least recently used items first when the cache reaches its limit.
// time complexity : O(1)
// space complexity : O(n)
// ref : https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
package cache
import (
"github.com/TheAlgorithms/Go/structure/linkedlist"
)
type item struct {
key string
value any
// the frequency of key
freq int
}
type LRU struct {
dl *linkedlist.Doubly[any]
size int
capacity int
storage map[string]*linkedlist.Node[any]
}
// NewLRU represent initiate lru cache with capacity
func NewLRU(capacity int) LRU {
return LRU{
dl: linkedlist.NewDoubly[any](),
storage: make(map[string]*linkedlist.Node[any], capacity),
size: 0,
capacity: capacity,
}
}
// Get value from lru
// if not found, return nil
func (c *LRU) Get(key string) any {
v, ok := c.storage[key]
if ok {
c.dl.MoveToBack(v)
return v.Val.(item).value
}
return nil
}
// Put cache with key and value to lru
func (c *LRU) Put(key string, value any) {
e, ok := c.storage[key]
if ok {
n := e.Val.(item)
n.value = value
e.Val = n
c.dl.MoveToBack(e)
return
}
if c.size >= c.capacity {
e := c.dl.Front()
dk := e.Val.(item).key
c.dl.Remove(e)
delete(c.storage, dk)
c.size--
}
n := item{key: key, value: value}
c.dl.AddAtEnd(n)
ne := c.dl.Back()
c.storage[key] = ne
c.size++
}
================================================
FILE: cache/lru_test.go
================================================
package cache_test
import (
"testing"
"github.com/TheAlgorithms/Go/cache"
)
func TestLRU(t *testing.T) {
cache := cache.NewLRU(3)
t.Run("Test 1: Put number and Get is correct", func(t *testing.T) {
key, value := "1", 1
cache.Put(key, value)
got := cache.Get(key)
if got != value {
t.Errorf("expected: %v, got: %v", value, got)
}
})
t.Run("Test 2: Get data not stored in cache should return nil", func(t *testing.T) {
got := cache.Get("2")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
})
t.Run("Test 3: Put data over capacity and Get should return nil", func(t *testing.T) {
cache.Put("2", 2)
cache.Put("3", 3)
cache.Put("4", 4)
got := cache.Get("1")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
})
t.Run("test 4: Put key over capacity but recent key exists", func(t *testing.T) {
cache.Put("4", 4)
cache.Put("3", 3)
cache.Put("2", 2)
cache.Put("1", 1)
got := cache.Get("4")
if got != nil {
t.Errorf("expected: nil, got: %v", got)
}
expected := 3
got = cache.Get("3")
if got != expected {
t.Errorf("expected: %v, got: %v", expected, got)
}
})
}
================================================
FILE: checksum/crc8.go
================================================
// crc8.go
// description: Calculate CRC8
// details:
// A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks
// and storage devices to detect accidental changes to raw data.
// time complexity: O(n)
// space complexity: O(1)
// See more [CRC](https://en.wikipedia.org/wiki/Cyclic_redundancy_check)
// author(s) [red_byte](https://github.com/i-redbyte)
// see crc8_test.go
package checksum
import "math/bits"
// CRCModel contains the necessary parameters for calculating the DRC algorithm
type CRCModel struct {
Poly uint8
Init uint8
RefIn bool
RefOut bool
XorOut uint8
Name string
}
// CRC8 calculates CRC8 checksum of the given data.
func CRC8(data []byte, model CRCModel) uint8 {
table := getTable(model)
crcResult := model.Init
crcResult = addBytes(data, model, crcResult, table)
if model.RefOut {
crcResult = bits.Reverse8(crcResult)
}
return crcResult ^ model.XorOut
}
// This function get the result of adding the bytes in data to the crc
func addBytes(data []byte, model CRCModel, crcResult uint8, table []uint8) uint8 {
if model.RefIn {
for _, d := range data {
d = bits.Reverse8(d)
crcResult = table[crcResult^d]
}
return crcResult
}
for _, d := range data {
crcResult = table[crcResult^d]
}
return crcResult
}
// This function get 256-byte (256x8) table for efficient processing.
func getTable(model CRCModel) []uint8 {
table := make([]uint8, 256)
for i := 0; i < 256; i++ {
crc := uint8(i)
for j := 0; j < 8; j++ {
isSetBit := (crc & 0x80) != 0
crc <<= 1
if isSetBit {
crc ^= model.Poly
}
}
table[i] = crc
}
return table
}
================================================
FILE: checksum/crc8_test.go
================================================
// crc8_test.go
// description: Test for calculate crc8
// author(s) [red_byte](https://github.com/i-redbyte)
// see crc8.go
package checksum_test
import (
"fmt"
"testing"
"github.com/TheAlgorithms/Go/checksum"
)
var (
CRC8 = checksum.CRCModel{0x07, 0x00, false, false, 0x00, "CRC-8"}
CRC8CDMA2000 = checksum.CRCModel{0x9B, 0xFF, false, false, 0x00, "CRC-8/CDMA2000"}
CRC8DARC = checksum.CRCModel{0x39, 0x00, true, true, 0x00, "CRC-8/DARC"}
CRC8DVBS2 = checksum.CRCModel{0xD5, 0x00, false, false, 0x00, "CRC-8/DVB-S2"}
CRC8EBU = checksum.CRCModel{0x1D, 0xFF, true, true, 0x00, "CRC-8/EBU"}
CRC8ICODE = checksum.CRCModel{0x1D, 0xFD, false, false, 0x00, "CRC-8/I-CODE"}
CRC8ITU = checksum.CRCModel{0x07, 0x00, false, false, 0x55, "CRC-8/ITU"}
CRC8MAXIM = checksum.CRCModel{0x31, 0x00, true, true, 0x00, "CRC-8/MAXIM"}
CRC8ROHC = checksum.CRCModel{0x07, 0xFF, true, true, 0x00, "CRC-8/ROHC"}
CRC8WCDMA = checksum.CRCModel{0x9B, 0x00, true, true, 0x00, "CRC-8/WCDMA"}
)
func TestCalculateCRC8(t *testing.T) {
data := []byte("123456789")
tests := []struct {
name string
data []byte
model checksum.CRCModel
want uint8
}{
{CRC8.Name, data, CRC8, 0xF4},
{CRC8CDMA2000.Name, data, CRC8CDMA2000, 0xDA},
{CRC8DARC.Name, data, CRC8DARC, 0x15},
{CRC8DVBS2.Name, data, CRC8DVBS2, 0xBC},
{CRC8EBU.Name, data, CRC8EBU, 0x97},
{CRC8ICODE.Name, data, CRC8ICODE, 0x7E},
{CRC8ITU.Name, data, CRC8ITU, 0xA1},
{CRC8MAXIM.Name, data, CRC8MAXIM, 0xA1},
{CRC8ROHC.Name, data, CRC8ROHC, 0xD0},
{CRC8WCDMA.Name, data, CRC8WCDMA, 0x25},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fmt.Println(checksum.CRC8(test.data, test.model))
if got := checksum.CRC8(test.data, test.model); got != test.want {
t.Errorf("CalculateCRC8() = %v, want %v", got, test.want)
}
})
}
}
func BenchmarkCalculateCRC8(b *testing.B) {
for i := 0; i < b.N; i++ {
checksum.CRC8([]byte("123456789"), CRC8)
}
}
================================================
FILE: checksum/luhn.go
================================================
// lunh.go
// description: Luhn algorithm
// details: is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, etc [Lunh](https://en.wikipedia.org/wiki/Luhn_algorithm)
// time complexity: O(n)
// space complexity: O(1)
// author(s) [red_byte](https://github.com/i-redbyte)
// see lunh_test.go
// Package checksum describes algorithms for finding various checksums
package checksum
// Luhn validates the provided data using the Luhn algorithm.
func Luhn(s []byte) bool {
n := len(s)
number := 0
result := 0
for i := 0; i < n; i++ {
number = int(s[i]) - '0'
if i%2 != 0 {
result += number
continue
}
number *= 2
if number > 9 {
number -= 9
}
result += number
}
return result%10 == 0
}
================================================
FILE: checksum/luhn_test.go
================================================
// luhn_test.go
// description: Test for Luhn algorithm
// author(s) [red_byte](https://github.com/i-redbyte)
// see luhn.go
package checksum_test
import (
"testing"
"github.com/TheAlgorithms/Go/checksum"
)
func TestLuhn(t *testing.T) {
tests := []struct {
name string
s []byte
want bool
}{
{"check 4242424242424242", []byte("4242424242424242"), true},
{"check 6200000000000005", []byte("6200000000000005"), true},
{"check 5534200028533164", []byte("5534200028533164"), true},
{"check 36227206271667", []byte("36227206271667"), true},
{"check 471629309440", []byte("471629309440"), false},
{"check 1111", []byte("1111"), false},
{"check 12345674", []byte("12345674"), true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := checksum.Luhn(test.s); got != test.want {
t.Errorf("LuhnAlgorithm() = %v, want %v", got, test.want)
}
})
}
}
func BenchmarkBruteForceFactorial(b *testing.B) {
for i := 0; i < b.N; i++ {
checksum.Luhn([]byte("4242424242424242"))
}
}
================================================
FILE: cipher/caesar/caesar.go
================================================
// Package caesar is the shift cipher
// description: Caesar cipher
// details : Caesar cipher is a type of substitution cipher in which each letter in the plaintext is shifted a certain number of places down the alphabet.
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/Caesar_cipher
package caesar
// Encrypt encrypts by right shift of "key" each character of "input"
func Encrypt(input string, key int) string {
// if key is negative value,
// updates "key" the number which congruents to "key" modulo 26
key8 := byte(key%26+26) % 26
var outputBuffer []byte
// b is a byte, which is the equivalent of uint8.
for _, b := range []byte(input) {
newByte := b
if 'A' <= b && b <= 'Z' {
outputBuffer = append(outputBuffer, 'A'+(newByte-'A'+key8)%26)
} else if 'a' <= b && b <= 'z' {
outputBuffer = append(outputBuffer, 'a'+(newByte-'a'+key8)%26)
} else {
outputBuffer = append(outputBuffer, newByte)
}
}
return string(outputBuffer)
}
// Decrypt decrypts by left shift of "key" each character of "input"
func Decrypt(input string, key int) string {
// left shift of "key" is same as right shift of 26-"key"
return Encrypt(input, 26-key)
}
================================================
FILE: cipher/caesar/caesar_test.go
================================================
package caesar
import (
"fmt"
"math/rand"
"testing"
"time"
)
func TestEncrypt(t *testing.T) {
var caesarTestData = []struct {
description string
input string
key int
expected string
}{
{
"Basic caesar encryption with letter 'a'",
"a",
3,
"d",
},
{
"Basic caesar encryption wrap around alphabet on letter 'z'",
"z",
3,
"c",
},
{
"Encrypt a simple string with caesar encryiption",
"hello",
3,
"khoor",
},
{
"Encrypt a simple string with key 13",
"hello",
13,
"uryyb",
},
{
"Encrypt a simple string with key -13",
"hello",
-13,
"uryyb",
},
{
"With key of 26 output should be the same as the input",
"no change",
26,
"no change",
},
{
"Encrypt sentence with key 10",
"the quick brown fox jumps over the lazy dog.",
10,
"dro aesmu lbygx pyh tewzc yfob dro vkji nyq.",
},
{
"Encrypt sentence with key 10",
"The Quick Brown Fox Jumps over the Lazy Dog.",
10,
"Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.",
},
}
for _, test := range caesarTestData {
t.Run(test.description, func(t *testing.T) {
actual := Encrypt(test.input, test.key)
if actual != test.expected {
t.Logf("FAIL: %s", test.description)
t.Fatalf("With input string '%s' and key '%d' was expecting '%s' but actual was '%s'",
test.input, test.key, test.expected, actual)
}
})
}
}
func TestDecrypt(t *testing.T) {
var caesarTestData = []struct {
description string
input string
key int
expected string
}{
{
"Basic caesar decryption with letter 'a'",
"a",
3,
"x",
},
{
"Basic caesar decryption wrap around alphabet on letter 'z'",
"z",
3,
"w",
},
{
"Decrypt a simple string with caesar encryiption",
"hello",
3,
"ebiil",
},
{
"Decrypt a simple string with key 13",
"hello",
13,
"uryyb",
},
{
"Decrypt a simple string with key -13",
"hello",
-13,
"uryyb",
},
{
"With key of 26 output should be the same as the input",
"no change",
26,
"no change",
},
{
"Decrypt sentence with key 10",
"Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.",
10,
"The Quick Brown Fox Jumps over the Lazy Dog.",
},
}
for _, test := range caesarTestData {
t.Run(test.description, func(t *testing.T) {
actual := Decrypt(test.input, test.key)
if actual != test.expected {
t.Logf("FAIL: %s", test.description)
t.Fatalf("With input string '%s' and key '%d' was expecting '%s' but actual was '%s'",
test.input, test.key, test.expected, actual)
}
})
}
}
func Example() {
const (
key = 10
input = "The Quick Brown Fox Jumps over the Lazy Dog."
)
encryptedText := Encrypt(input, key)
fmt.Printf("Encrypt=> key: %d, input: %s, encryptedText: %s\n", key, input, encryptedText)
decryptedText := Decrypt(encryptedText, key)
fmt.Printf("Decrypt=> key: %d, input: %s, decryptedText: %s\n", key, encryptedText, decryptedText)
// Output:
// Encrypt=> key: 10, input: The Quick Brown Fox Jumps over the Lazy Dog., encryptedText: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.
// Decrypt=> key: 10, input: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq., decryptedText: The Quick Brown Fox Jumps over the Lazy Dog.
}
func FuzzCaesar(f *testing.F) {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
f.Add("The Quick Brown Fox Jumps over the Lazy Dog.")
f.Fuzz(func(t *testing.T, input string) {
key := rnd.Intn(26)
if result := Decrypt(Encrypt(input, key), key); result != input {
t.Fatalf("With input: '%s' and key: %d\n\tExpected: '%s'\n\tGot: '%s'", input, key, input, result)
}
})
}
================================================
FILE: cipher/cipher_test.go
================================================
// Empty test file to keep track of all the tests for the algorithms.
package cipher
================================================
FILE: cipher/diffiehellman/diffiehellmankeyexchange.go
================================================
// Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm
// description: Diffie-Hellman key exchange
// details : Diffie-Hellman key exchange is a method of securely exchanging cryptographic keys over a public channel by combining private keys of two parties to generate a shared secret key.
// time complexity: O(log(n))
// space complexity: O(1)
// for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI
package diffiehellman
const (
generator = 3
primeNumber int64 = 6700417 // prime number discovered by Leonhard Euler
)
// GenerateShareKey : generates a key using client private key , generator and primeNumber
// this key can be made public
// shareKey = (g^key)%primeNumber
func GenerateShareKey(prvKey int64) int64 {
return modularExponentiation(generator, prvKey, primeNumber)
}
// GenerateMutualKey : generates a mutual key that can be used by only alice and bob
// mutualKey = (shareKey^prvKey)%primeNumber
func GenerateMutualKey(prvKey, shareKey int64) int64 {
return modularExponentiation(shareKey, prvKey, primeNumber)
}
// r = (b^e)%mod
func modularExponentiation(b, e, mod int64) int64 {
//runs in O(log(n)) where n = e
//uses exponentiation by squaring to speed up the process
if mod == 1 {
return 0
}
var r int64 = 1
b = b % mod
for e > 0 {
if e&1 == 1 {
r = (r * b) % mod
}
e = e >> 1
b = (b * b) % mod
}
return r
}
================================================
FILE: cipher/diffiehellman/diffiehellmankeyexchange_test.go
================================================
package diffiehellman
import (
"crypto/rand"
"crypto/rsa"
"testing"
)
func TestDiffieHellmanKeyExchange(t *testing.T) {
t.Run("Test 1: modularExponentiation", func(t *testing.T) {
var want int64 = 9 // (3^5)mod13 = 243mod13 = 9
var prvKey int64 = 5
var generator int64 = 3
var primeNumber int64 = 13
got := modularExponentiation(generator, prvKey, primeNumber)
if got != want {
t.Errorf(`with privateKey=%d, generator=%d and primeNumber=%d
modularExponentiation should result=%d, but resulted=%d`, prvKey, generator, primeNumber, want, got)
}
})
t.Run("Test 2: Key Exchange", func(t *testing.T) {
// generating a small sized rsa_cipher key for testing
alicePrvKey, _ := rsa.GenerateKey(rand.Reader, 31)
bobPrvKey, _ := rsa.GenerateKey(rand.Reader, 31)
// alice and bob generates their respective share key with their privateKey
shareKeyByAlice := GenerateShareKey(alicePrvKey.D.Int64())
shareKeyByBob := GenerateShareKey(bobPrvKey.D.Int64())
// generated share key now can be exchanged even via insecure channel
// mutualKey can be computed using shared key
mutualKeyComputedByAlice := GenerateMutualKey(alicePrvKey.D.Int64(), shareKeyByBob)
mutualKeyComputedByBob := GenerateMutualKey(bobPrvKey.D.Int64(), shareKeyByAlice)
if mutualKeyComputedByAlice != mutualKeyComputedByBob {
t.Errorf("mutual key computed by alice and bob should be same, but got un-equal")
}
})
}
================================================
FILE: cipher/doc.go
================================================
// Package cipher is a package containing different implementations of certain ciphers
package cipher
================================================
FILE: cipher/dsa/dsa.go
================================================
/*
dsa.go
description: DSA encryption and decryption including key generation
details: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm)
author(s): [ddaniel27](https://github.com/ddaniel27)
*/
package dsa
import (
"crypto/rand"
"io"
"math/big"
)
const (
numMRTests = 64 // Number of Miller-Rabin tests
L = 1024 // Number of bits in p
N = 160 // Number of bits in q
)
type (
// parameters represents the DSA parameters
parameters struct {
P, Q, G *big.Int
}
// dsa represents the DSA
dsa struct {
parameters
pubKey *big.Int // public key (y)
privKey *big.Int // private key (x)
}
)
// New creates a new DSA instance
func New() *dsa {
d := new(dsa)
d.dsaParameterGeneration()
d.keyGen()
return d
}
// Parameter generation for DSA
// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)
// 2. Choose a N-bit prime q
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// 4. Choose an integer h randomly from the range [2, p-2]
// 5. Compute g = h^((p-1)/q) mod p
// 6. Return (p, q, g)
func (dsa *dsa) dsaParameterGeneration() {
var err error
p, q, bigInt := new(big.Int), new(big.Int), new(big.Int)
one, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)
pBytes := make([]byte, L/8)
// GPLoop is a label for the loop
// We use this loop to change the prime q if we don't find a prime p
GPLoop:
for {
// 2. Choose a N-bit prime q
q, err = rand.Prime(rand.Reader, N)
if err != nil {
panic(err)
}
for i := 0; i < 4*L; i++ {
// 3. Choose a L-bit prime p such that p-1 is a multiple of q
// In this case we generate a random number of L bits
if _, err := io.ReadFull(rand.Reader, pBytes); err != nil {
panic(err)
}
// This are the minimum conditions for p being a possible prime
pBytes[len(pBytes)-1] |= 1 // p is odd
pBytes[0] |= 0x80 // p has the highest bit set
p.SetBytes(pBytes)
// Instead of using (p-1)%q == 0
// We ensure that p-1 is a multiple of q and validates if p is prime
bigInt.Mod(p, q)
bigInt.Sub(bigInt, one)
p.Sub(p, bigInt)
if p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits
continue
}
dsa.P = p
dsa.Q = q
break GPLoop
}
}
// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2
// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1
pm1 := new(big.Int).Sub(p, one)
for g.Cmp(one) == 0 {
g.Exp(h, new(big.Int).Div(pm1, q), p)
h.Add(h, one)
}
dsa.G = g
}
// keyGen is key generation for DSA
// 1. Choose a random integer x from the range [1, q-1]
// 2. Compute y = g^x mod p
func (dsa *dsa) keyGen() {
// 1. Choose a random integer x from the range [1, q-1]
x, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1)))
if err != nil {
panic(err)
}
dsa.privKey = x
// 2. Compute y = g^x mod p
dsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)
}
// Sign is signature generation for DSA
// 1. Choose a random integer k from the range [1, q-1]
// 2. Compute r = (g^k mod p) mod q
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
// 1. Choose a random integer k from the range [1, q-1]
k, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))
if err != nil {
panic(err)
}
// 2. Compute r = (g^k mod p) mod q
r = new(big.Int).Exp(g, k, p)
r.Mod(r, q)
// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
s = new(big.Int).ModInverse(k, q) // k^-1 mod q
s.Mul(
s,
new(big.Int).Add( // (H(m) + x*r)
h,
new(big.Int).Mul(x, r),
),
)
s.Mod(s, q) // mod q
return r, s
}
// Verify is signature verification for DSA
// 1. Compute w = s^-1 mod q
// 2. Compute u1 = (H(m) * w) mod q
// 3. Compute u2 = (r * w) mod q
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
// 5. If v == r, the signature is valid
func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
// 1. Compute w = s^-1 mod q
w := new(big.Int).ModInverse(s, q)
// 2. Compute u1 = (H(m) * w) mod q
h := new(big.Int).SetBytes(m) // This should be the hash of the message
u1 := new(big.Int).Mul(h, w)
u1.Mod(u1, q)
// 3. Compute u2 = (r * w) mod q
u2 := new(big.Int).Mul(r, w)
u2.Mod(u2, q)
// 4. Compute v = ((g^u1 * y^u2) mod p) mod q
v := new(big.Int).Exp(g, u1, p)
v.Mul(
v,
new(big.Int).Exp(y, u2, p),
)
v.Mod(v, p)
v.Mod(v, q)
// 5. If v == r, the signature is valid
return v.Cmp(r) == 0
}
// GetPublicKey returns the public key (y)
func (dsa *dsa) GetPublicKey() *big.Int {
return dsa.pubKey
}
// GetParameters returns the DSA parameters (p, q, g)
func (dsa *dsa) GetParameters() parameters {
return dsa.parameters
}
// GetPrivateKey returns the private Key (x)
func (dsa *dsa) GetPrivateKey() *big.Int {
return dsa.privKey
}
================================================
FILE: cipher/dsa/dsa_test.go
================================================
package dsa_test
import (
"math/big"
"testing"
"github.com/TheAlgorithms/Go/cipher/dsa"
)
func TestDSA(t *testing.T) {
tests := []struct {
name string
message string
alter bool
want bool
}{
{
name: "valid signature",
message: "Hello, world!",
alter: false,
want: true,
},
{
name: "invalid signature",
message: "Hello, world!",
alter: true,
want: false,
},
}
// Generate a DSA key pair
dsaInstance := dsa.New()
pubKey := dsaInstance.GetPublicKey()
params := dsaInstance.GetParameters()
privKey := dsaInstance.GetPrivateKey()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Sign the message
r, s := dsa.Sign(
[]byte(tt.message),
params.P,
params.Q,
params.G,
privKey,
)
if tt.alter {
// Alter the signature
r.Add(r, big.NewInt(1))
}
// Verify the signature
if got := dsa.Verify(
[]byte(tt.message),
r,
s,
params.P,
params.Q,
params.G,
pubKey,
); got != tt.want {
t.Errorf("got %v, want %v", got, tt.want)
}
})
}
}
/* ------------------- BENCHMARKS ------------------- */
func BenchmarkDSANew(b *testing.B) {
for i := 0; i < b.N; i++ {
dsa.New()
}
}
func BenchmarkDSASign(b *testing.B) {
dsaInstance := dsa.New()
params := dsaInstance.GetParameters()
privKey := dsaInstance.GetPrivateKey()
for i := 0; i < b.N; i++ {
dsa.Sign(
[]byte("Hello, World!"),
params.P,
params.Q,
params.G,
privKey,
)
}
}
func BenchmarkDSAVerify(b *testing.B) {
dsaInstance := dsa.New()
pubKey := dsaInstance.GetPublicKey()
params := dsaInstance.GetParameters()
privKey := dsaInstance.GetPrivateKey()
r, s := dsa.Sign(
[]byte("Hello, World!"),
params.P,
params.Q,
params.G,
privKey,
)
for i := 0; i < b.N; i++ {
dsa.Verify(
[]byte("Hello, World!"),
r,
s,
params.P,
params.Q,
params.G,
pubKey,
)
}
}
================================================
FILE: cipher/polybius/polybius.go
================================================
// Package polybius is encrypting method with polybius square
// description: Polybius square
// details : The Polybius algorithm is a simple algorithm that is used to encode a message by converting each letter to a pair of numbers.
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher
package polybius
import (
"fmt"
"math"
"strings"
)
// Polybius is struct having size, characters, and key
type Polybius struct {
size int
characters string
key string
}
// NewPolybius returns a pointer to object of Polybius.
// If the size of "chars" is longer than "size",
// "chars" are truncated to "size".
func NewPolybius(key string, size int, chars string) (*Polybius, error) {
if size < 0 {
return nil, fmt.Errorf("provided size %d cannot be negative", size)
}
key = strings.ToUpper(key)
if size > len(chars) {
return nil, fmt.Errorf("provided size %d is too small to use to slice string %q of len %d", size, chars, len(chars))
}
for _, r := range chars {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
return nil, fmt.Errorf("provided string %q should only contain latin characters", chars)
}
}
chars = strings.ToUpper(chars)[:size]
for i, r := range chars {
if strings.ContainsRune(chars[i+1:], r) {
return nil, fmt.Errorf("%q contains same character %q", chars[i+1:], r)
}
}
if len(key) != size*size {
return nil, fmt.Errorf("len(key): %d must be as long as size squared: %d", len(key), size*size)
}
return &Polybius{size, chars, key}, nil
}
// Encrypt encrypts with polybius encryption
func (p *Polybius) Encrypt(text string) (string, error) {
encryptedText := ""
for _, char := range strings.ToUpper(text) {
encryptedChar, err := p.encipher(char)
if err != nil {
return "", fmt.Errorf("failed encipher: %w", err)
}
encryptedText += encryptedChar
}
return encryptedText, nil
}
// Decrypt decrypts with polybius encryption
func (p *Polybius) Decrypt(text string) (string, error) {
chars := []rune(strings.ToUpper(text))
decryptedText := ""
for i := 0; i < len(chars); i += 2 {
decryptedChar, err := p.decipher(chars[i:int(math.Min(float64(i+2), float64(len(chars))))])
if err != nil {
return "", fmt.Errorf("failed decipher: %w", err)
}
decryptedText += decryptedChar
}
return decryptedText, nil
}
func (p *Polybius) encipher(char rune) (string, error) {
index := strings.IndexRune(p.key, char)
if index < 0 {
return "", fmt.Errorf("%q does not exist in keys", char)
}
row := index / p.size
col := index % p.size
chars := []rune(p.characters)
return string([]rune{chars[row], chars[col]}), nil
}
func (p *Polybius) decipher(chars []rune) (string, error) {
if len(chars) != 2 {
return "", fmt.Errorf("the size of \"chars\" must be even")
}
row := strings.IndexRune(p.characters, chars[0])
if row < 0 {
return "", fmt.Errorf("%c does not exist in characters", chars[0])
}
col := strings.IndexRune(p.characters, chars[1])
if col < 0 {
return "", fmt.Errorf("%c does not exist in characters", chars[1])
}
return string(p.key[row*p.size+col]), nil
}
================================================
FILE: cipher/polybius/polybius_test.go
================================================
package polybius
import (
"fmt"
"log"
"strings"
"testing"
)
func ExampleNewPolybius() {
// initialize
const (
plainText = "HogeFugaPiyoSpam"
size = 5
characters = "HogeF"
key = "abcdefghijklmnopqrstuvwxy"
)
p, err := NewPolybius(key, size, characters)
if err != nil {
log.Fatalf("failed NewPolybius: %v", err)
}
encryptedText, err := p.Encrypt(plainText)
if err != nil {
log.Fatalf("failed Encrypt: %v", err)
}
fmt.Printf("Encrypt=> plainText: %s, encryptedText: %s\n", plainText, encryptedText)
decryptedText, err := p.Decrypt(encryptedText)
if err != nil {
log.Fatalf("failed Decrypt: %v", err)
}
fmt.Printf("Decrypt=> encryptedText: %s, decryptedText: %s\n", encryptedText, decryptedText)
// Output:
// Encrypt=> plainText: HogeFugaPiyoSpam, encryptedText: OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG
// Decrypt=> encryptedText: OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG, decryptedText: HOGEFUGAPIYOSPAM
}
func TestNewPolybius(t *testing.T) {
t.Parallel()
cases := []struct {
name string
size int
characters string
key string
wantErr string
}{
{
name: "correct initialization", size: 5, characters: "HogeF", key: "abcdefghijklmnopqrstuvwxy", wantErr: "",
},
{
name: "truncate characters", size: 5, characters: "HogeFuga", key: "abcdefghijklmnopqrstuvwxy", wantErr: "",
},
{
name: "invalid key", size: 5, characters: "HogeFuga", key: "abcdefghi", wantErr: "len(key): 9 must be as long as size squared: 25",
},
{
name: "invalid characters", size: 5, characters: "HogeH", key: "abcdefghijklmnopqrstuvwxy", wantErr: "\"OGEH\" contains same character 'H'",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := NewPolybius(tc.key, tc.size, tc.characters)
if err != nil && err.Error() != tc.wantErr {
t.Errorf("failed NewPolybius: %v", err)
}
})
}
}
func TestPolybiusEncrypt(t *testing.T) {
t.Parallel()
cases := []struct {
name string
text string
want string
}{
{
name: "correct encryption", text: "HogeFugaPiyoSpam", want: "OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG",
},
{
name: "invalid encryption", text: "hogz", want: "failed encipher: 'Z' does not exist in keys",
},
}
// initialize
const (
size = 5
characters = "HogeF"
key = "abcdefghijklmnopqrstuvwxy"
)
p, err := NewPolybius(key, size, characters)
if err != nil {
t.Fatalf("failed NewPolybius: %v", err)
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
encrypted, err := p.Encrypt(tc.text)
if err != nil {
if err.Error() != tc.want {
t.Errorf("failed Encrypt: %v", err)
}
} else if encrypted != tc.want {
t.Errorf("Encrypt: %v, want: %v", encrypted, tc.want)
}
})
}
}
func TestPolybiusDecrypt(t *testing.T) {
t.Parallel()
cases := []struct {
name string
text string
want string
}{
{
name: "correct decryption", text: "OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG", want: "HOGEFUGAPIYOSPAM",
},
{
name: "invalid decryption(position of even number)", text: "hogz", want: "failed decipher: Z does not exist in characters",
},
{
name: "invalid decryption(position of odd number)", text: "hode", want: "failed decipher: D does not exist in characters",
},
{
name: "invalid text size which is odd", text: "hog", want: "failed decipher: the size of \"chars\" must be even",
},
}
// initialize
const (
size = 5
characters = "HogeF"
key = "abcdefghijklmnopqrstuvwxy"
)
p, err := NewPolybius(key, size, characters)
if err != nil {
t.Fatalf("failed NewPolybius: %v", err)
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
encrypted, err := p.Decrypt(tc.text)
if err != nil {
if err.Error() != tc.want {
t.Errorf("failed Encrypt: %v", err)
}
} else if encrypted != tc.want {
t.Errorf("Encrypt: %v, want: %v", encrypted, tc.want)
}
})
}
}
func FuzzPolybius(f *testing.F) {
const (
size = 5
characters = "HogeF"
key = "abcdefghijklmnopqrstuvwxy"
)
f.Add(size, characters, key)
f.Fuzz(func(t *testing.T, size int, characters, key string) {
p, err := NewPolybius(key, size, characters)
switch {
case err == nil:
case strings.Contains(err.Error(), "cannot be negative"),
strings.Contains(err.Error(), "is too small"),
strings.Contains(err.Error(), "should only contain latin characters"),
strings.Contains(err.Error(), "contains same character"),
strings.Contains(err.Error(), "must be as long as size squared"):
return
default:
t.Fatalf("unexpected error when creating a new polybius variable: %v", err)
}
encrypted, err := p.Encrypt(characters)
switch {
case err == nil:
case strings.Contains(err.Error(), "does not exist in keys"):
return
default:
t.Fatalf("unexpected error during encryption: %v", err)
}
decrypted, err := p.Decrypt(encrypted)
if err != nil {
t.Fatalf("unexpected error during decryption: %v", err)
}
if decrypted != strings.ToUpper(characters) {
t.Errorf("Expecting output to match with %q but was %q", characters, decrypted)
}
})
}
================================================
FILE: cipher/railfence/railfence.go
================================================
// railfence.go
// description: Rail Fence Cipher
// details: The rail fence cipher is a an encryption algorithm that uses a rail fence pattern to encode a message. it is a type of transposition cipher that rearranges the characters of the plaintext to form the ciphertext.
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/Rail_fence_cipher
package railfence
import (
"strings"
)
func Encrypt(text string, rails int) string {
if rails == 1 {
return text
}
// Create a matrix for the rail fence pattern
matrix := make([][]rune, rails)
for i := range matrix {
matrix[i] = make([]rune, len(text))
}
// Fill the matrix
dirDown := false
row, col := 0, 0
for _, char := range text {
if row == 0 || row == rails-1 {
dirDown = !dirDown
}
matrix[row][col] = char
col++
if dirDown {
row++
} else {
row--
}
}
var result strings.Builder
for _, line := range matrix {
for _, char := range line {
if char != 0 {
result.WriteRune(char)
}
}
}
return result.String()
}
func Decrypt(cipherText string, rails int) string {
if rails == 1 || rails >= len(cipherText) {
return cipherText
}
// Placeholder for the decrypted message
decrypted := make([]rune, len(cipherText))
// Calculate the zigzag pattern and place characters accordingly
index := 0
for rail := 0; rail < rails; rail++ {
position := rail
down := true // Direction flag
for position < len(cipherText) {
decrypted[position] = rune(cipherText[index])
index++
// Determine the next position based on the current rail and direction
if rail == 0 || rail == rails-1 {
position += 2 * (rails - 1)
} else if down {
position += 2 * (rails - 1 - rail)
down = false
} else {
position += 2 * rail
down = true
}
}
}
return string(decrypted)
}
================================================
FILE: cipher/railfence/railfence_test.go
================================================
package railfence
import (
"testing"
)
func TestEncrypt(t *testing.T) {
var railFenceTestData = []struct {
description string
input string
rails int
expected string
}{
{
"Encrypt with 2 rails",
"hello",
2,
"hloel",
},
{
"Encrypt with 3 rails",
"hello world",
3,
"horel ollwd",
},
{
"Encrypt with edge case: 1 rail",
"hello",
1,
"hello",
},
{
"Encrypt with more rails than letters",
"hi",
100,
"hi",
},
}
for _, test := range railFenceTestData {
t.Run(test.description, func(t *testing.T) {
actual := Encrypt(test.input, test.rails)
if actual != test.expected {
t.Errorf("FAIL: %s - Encrypt(%s, %d) = %s, want %s", test.description, test.input, test.rails, actual, test.expected)
}
})
}
}
func TestDecrypt(t *testing.T) {
var railFenceTestData = []struct {
description string
input string
rails int
expected string
}{
{
"Decrypt with 2 rails",
"hloel",
2,
"hello",
},
{
"Decrypt with 3 rails",
"ho l lewrdlo",
3,
"hld olle wor",
},
{
"Decrypt with edge case: 1 rail",
"hello",
1,
"hello",
},
{
"Decrypt with more rails than letters",
"hi",
100,
"hi",
},
}
for _, test := range railFenceTestData {
t.Run(test.description, func(t *testing.T) {
actual := Decrypt(test.input, test.rails)
if actual != test.expected {
t.Errorf("FAIL: %s - Decrypt(%s, %d) = %s, want %s", test.description, test.input, test.rails, actual, test.expected)
}
})
}
}
================================================
FILE: cipher/rot13/rot13.go
================================================
// Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet.
// description: ROT13
// details: ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. it is a special case of the Caesar cipher
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/ROT13
package rot13
import (
"github.com/TheAlgorithms/Go/cipher/caesar"
)
// rot13 is a special case, which is fixed the shift of 13, of the Caesar cipher
func rot13(input string) string {
return caesar.Encrypt(input, 13)
}
================================================
FILE: cipher/rot13/rot13_test.go
================================================
package rot13
import (
"testing"
)
var rot13TestData = []struct {
description string
input string
expected string
}{
{
"Basic rotation with letter 'a' gives 'n",
"a",
"n",
},
{
"Rotation with wrapping around alphabet on letter 'z' gives 'm'",
"z",
"m",
},
{
"Rotation on 'hello world'",
"hello world",
"uryyb jbeyq",
},
{
"Rotation on the rotation of 'hello world' gives 'hello world' back",
"uryyb jbeyq",
"hello world",
},
{
"Full sentence rotation",
"the quick brown fox jumps over the lazy dog.",
"gur dhvpx oebja sbk whzcf bire gur ynml qbt.",
},
{
"Sentence from Rot13.go main function",
"we'll just make him an offer he can't refuse... tell me you get the pop culture reference",
"jr'yy whfg znxr uvz na bssre ur pna'g ershfr... gryy zr lbh trg gur cbc phygher ersrerapr",
},
}
func TestRot13Encrypt(t *testing.T) {
for _, test := range rot13TestData {
t.Run(test.description, func(t *testing.T) {
input := test.input
expected := test.expected
assertRot13Output(t, input, expected)
})
}
}
func TestRot13Decrypt(t *testing.T) {
for _, test := range rot13TestData {
t.Run(test.description, func(t *testing.T) {
input := test.expected
expected := test.input
assertRot13Output(t, input, expected)
})
}
}
func assertRot13Output(t *testing.T, input, expected string) {
actual := rot13(input)
if actual != expected {
t.Fatalf("With input string %q was expecting %q but actual was %q",
input, expected, actual)
}
}
func FuzzRot13(f *testing.F) {
for _, rot13TestInput := range rot13TestData {
f.Add(rot13TestInput.input)
}
f.Fuzz(func(t *testing.T, input string) {
if result := rot13(rot13(input)); result != input {
t.Fatalf("With input string %q was expecting %q but actual was %q",
input, input, result)
}
})
}
================================================
FILE: cipher/rsa/rsa.go
================================================
// rsa.go
// description: Simple RSA algorithm implementation
// details:
// A simple RSA Encryption and Decryption algorithm.
// It uses prime numbers that fit in int64 datatypes and
// thus both the Encrypt and Decrypt are not a production
// ready implementation. The OpenSSL implementation of RSA
// also adds a padding which is not present in this algorithm.
// time complexity: O(n)
// space complexity: O(n)
// author(s) [Taj](https://github.com/tjgurwara99)
// see rsa_test.go
// Package rsa shows a simple implementation of RSA algorithm
package rsa
import (
"errors"
modular "github.com/TheAlgorithms/Go/math/modular"
)
// ErrorFailedToEncrypt Raised when Encrypt function fails to encrypt the message
var ErrorFailedToEncrypt = errors.New("failed to Encrypt")
// ErrorFailedToDecrypt Raised when Decrypt function fails to decrypt the encrypted message
var ErrorFailedToDecrypt = errors.New("failed to Decrypt")
// Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory
func Encrypt(message []rune, publicExponent, modulus int64) ([]rune, error) {
var encrypted []rune
for _, letter := range message {
encryptedLetter, err := modular.Exponentiation(int64(letter), publicExponent, modulus)
if err != nil {
return nil, ErrorFailedToEncrypt
}
encrypted = append(encrypted, rune(encryptedLetter))
}
return encrypted, nil
}
// Decrypt decrypts encrypted rune slice based on the RSA algorithm
func Decrypt(encrypted []rune, privateExponent, modulus int64) (string, error) {
var decrypted []rune
for _, letter := range encrypted {
decryptedLetter, err := modular.Exponentiation(int64(letter), privateExponent, modulus)
if err != nil {
return "", ErrorFailedToDecrypt
}
decrypted = append(decrypted, rune(decryptedLetter))
}
return string(decrypted), nil
}
================================================
FILE: cipher/rsa/rsa2.go
================================================
/*
rsa2.go
description: RSA encryption and decryption including key generation
details: [RSA wiki](https://en.wikipedia.org/wiki/RSA_(cryptosystem))
time complexity: O(n)
space complexity: O(1)
author(s): [ddaniel27](https://github.com/ddaniel27)
*/
package rsa
import (
"encoding/binary"
"fmt"
"math/big"
"math/rand"
"github.com/TheAlgorithms/Go/math/gcd"
"github.com/TheAlgorithms/Go/math/lcm"
"github.com/TheAlgorithms/Go/math/modular"
"github.com/TheAlgorithms/Go/math/prime"
)
// rsa struct contains the public key, private key and modulus
type rsa struct {
publicKey uint64
privateKey uint64
modulus uint64
}
// New initializes the RSA algorithm
// 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))
inv, _ := modular.Inverse(int64(publicKey), int64(totient))
privateKey := uint64(inv)
return &rsa{
publicKey: publicKey,
privateKey: privateKey,
modulus: modulus,
}
}
// EncryptString encrypts the data using RSA algorithm
// returns the encrypted string
func (rsa *rsa) EncryptString(data string) string {
var nums []byte
for _, char := range data {
slice := make([]byte, 8)
binary.BigEndian.PutUint64( // convert uint64 to byte slice
slice,
encryptDecryptInt(rsa.publicKey, rsa.modulus, uint64(char)), // encrypt each character
)
nums = append(nums, slice...)
}
return string(nums)
}
// DecryptString decrypts the data using RSA algorithm
// returns the decrypted string
func (rsa *rsa) DecryptString(data string) string {
result := ""
middle := []byte(data)
for i := 0; i < len(middle); i += 8 {
if i+8 > len(middle) {
break
}
slice := middle[i : i+8]
num := binary.BigEndian.Uint64(slice) // convert byte slice to uint64
result += fmt.Sprintf("%c", encryptDecryptInt(rsa.privateKey, rsa.modulus, num))
}
return result
}
// GetPublicKey returns the public key and modulus
func (rsa *rsa) GetPublicKey() (uint64, uint64) {
return rsa.publicKey, rsa.modulus
}
// GetPrivateKey returns the private key
func (rsa *rsa) GetPrivateKey() uint64 {
return rsa.privateKey
}
// encryptDecryptInt encrypts or decrypts the data using RSA algorithm
func encryptDecryptInt(e, n, data uint64) uint64 {
pow := new(big.Int).Exp(big.NewInt(int64(data)), big.NewInt(int64(e)), big.NewInt(int64(n)))
return pow.Uint64()
}
// randomPrime returns two random prime numbers
func randomPrime() (uint64, uint64) {
sieve := prime.SieveEratosthenes(1000)
sieve = sieve[10:] // remove first 10 prime numbers (small numbers)
index1 := rand.Intn(len(sieve))
index2 := rand.Intn(len(sieve))
for index1 == index2 {
index2 = rand.Intn(len(sieve))
}
return uint64(sieve[index1]), uint64(sieve[index2])
}
================================================
FILE: cipher/rsa/rsa2_test.go
================================================
package rsa_test
import (
"testing"
"github.com/TheAlgorithms/Go/cipher/rsa"
)
func TestRSA(t *testing.T) {
tests := []struct {
name string
message string
}{
{
name: "Encrypt letter 'a' and decrypt it back",
message: "a",
},
{
name: "Encrypt 'Hello, World!' and decrypt it back",
message: "Hello, World!",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rsa := rsa.New()
encrypted := rsa.EncryptString(tt.message)
decrypted := rsa.DecryptString(encrypted)
if decrypted != tt.message {
t.Errorf("expected %s, got %s", tt.message, decrypted)
}
})
}
}
func BenchmarkRSAEncryption(b *testing.B) {
rsa := rsa.New()
for i := 0; i < b.N; i++ {
rsa.EncryptString("Hello, World!")
}
}
func BenchmarkRSADecryption(b *testing.B) {
rsa := rsa.New()
encrypted := rsa.EncryptString("Hello, World!")
for i := 0; i < b.N; i++ {
rsa.DecryptString(encrypted)
}
}
================================================
FILE: cipher/rsa/rsa_test.go
================================================
// rsa_test.go
// description: Test for RSA Encrypt and Decrypt algorithms
// author(s) [Taj](https://github.com/tjgurwara99)
// see rsa.go
package rsa
import (
"testing"
"github.com/TheAlgorithms/Go/math/gcd"
"github.com/TheAlgorithms/Go/math/lcm"
"github.com/TheAlgorithms/Go/math/modular"
)
var rsaTestData = []struct {
description string
input string
}{
{
"Encrypt letter 'a'",
"a",
},
{
"Encrypt 'hello world'",
"hello world",
},
{
"Encrypt full sentence",
"the quick brown fox jumps over the lazy dog.",
},
{
"Encrypt full sentence from rsacipher.go main function",
"I think RSA is really great",
},
}
func testPrecondition(t *testing.T) (int64, int64, int64) {
// Both prime numbers
t.Helper()
p := int64(61)
q := int64(53)
n := p * q
delta := lcm.Lcm(p-1, q-1)
e := int64(17) // Coprime with delta
if gcd.Recursive(e, delta) != 1 {
t.Fatal("something went wrong: prime numbers are chosen statically and it shouldn't fail at this stage")
}
d, err := modular.Inverse(e, delta)
if err != nil {
t.Fatalf("something went wrong: problem with %q: %v", "modular.Inverse", err)
}
return e, d, n
}
func TestEncryptDecrypt(t *testing.T) {
for _, test := range rsaTestData {
t.Run(test.description, func(t *testing.T) {
e, d, n := testPrecondition(t)
message := []rune(test.input)
encrypted, err := Encrypt(message, e, n)
if err != nil {
t.Fatalf("Failed to Encrypt test string:\n\tDescription: %v\n\tErrMessage: %v", test.description, err)
}
decrypted, err := Decrypt(encrypted, d, n)
if err != nil {
t.Fatalf("Failed to Decrypt test message:\n\tDescription: %v\n\tErrMessage: %v", test.description, err)
}
if actual := test.input; actual != decrypted {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expecting %v, actual %v", decrypted, actual)
}
})
}
}
func FuzzRsa(f *testing.F) {
for _, rsaTestInput := range rsaTestData {
f.Add(rsaTestInput.input)
}
f.Fuzz(func(t *testing.T, input string) {
e, d, n := testPrecondition(t)
encrypted, err := Encrypt([]rune(input), e, n)
if err != nil {
t.Fatalf("failed to encrypt string: %v", err)
}
decrypted, err := Decrypt(encrypted, d, n)
if err != nil {
t.Fatalf("failed to decrypt string: %v", err)
}
if decrypted != input {
t.Fatalf("expected: %q, got: %q", input, decrypted)
}
})
}
================================================
FILE: cipher/transposition/transposition.go
================================================
// transposition.go
// description: Transposition cipher
// details:
// Implementation "Transposition cipher" is a method of encryption by which the positions held by units of plaintext (which are commonly characters or groups of characters) are shifted according to a regular system, so that the ciphertext constitutes a permutation of the plaintext [Transposition cipher](https://en.wikipedia.org/wiki/Transposition_cipher)
// time complexity: O(n)
// space complexity: O(n)
// author(s) [red_byte](https://github.com/i-redbyte)
// see transposition_test.go
package transposition
import (
"errors"
"fmt"
"sort"
"strings"
)
var ErrNoTextToEncrypt = errors.New("no text to encrypt")
var ErrKeyMissing = errors.New("missing Key")
const placeholder = ' '
func getKey(keyWord string) []int {
keyWord = strings.ToLower(keyWord)
word := []rune(keyWord)
var sortedWord = make([]rune, len(word))
copy(sortedWord, word)
sort.Slice(sortedWord, func(i, j int) bool { return sortedWord[i] < sortedWord[j] })
usedLettersMap := make(map[rune]int)
wordLength := len(word)
resultKey := make([]int, wordLength)
for i := 0; i < wordLength; i++ {
char := word[i]
numberOfUsage := usedLettersMap[char]
resultKey[i] = getIndex(sortedWord, char) + numberOfUsage + 1 //+1 -so that indexing does not start at 0
numberOfUsage++
usedLettersMap[char] = numberOfUsage
}
return resultKey
}
func getIndex(wordSet []rune, subString rune) int {
n := len(wordSet)
for i := 0; i < n; i++ {
if wordSet[i] == subString {
return i
}
}
return 0
}
func Encrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
keyLength := len(key)
textLength := len(text)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
if text[len(text)-1] == placeholder {
return nil, fmt.Errorf("%w: cannot encrypt a text, %q, ending with the placeholder char %q", ErrNoTextToEncrypt, text, placeholder)
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
textLength = len(text)
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[key[j]-1] = text[i+j]
}
result = append(result, transposition...)
}
return result, nil
}
func Decrypt(text []rune, keyWord string) ([]rune, error) {
key := getKey(keyWord)
textLength := len(text)
if textLength <= 0 {
return nil, ErrNoTextToEncrypt
}
keyLength := len(key)
if keyLength <= 0 {
return nil, ErrKeyMissing
}
n := textLength % keyLength
for i := 0; i < keyLength-n; i++ {
text = append(text, placeholder)
}
var result []rune
for i := 0; i < textLength; i += keyLength {
transposition := make([]rune, keyLength)
for j := 0; j < keyLength; j++ {
transposition[j] = text[i+key[j]-1]
}
result = append(result, transposition...)
}
result = []rune(strings.TrimRight(string(result), string(placeholder)))
return result, nil
}
================================================
FILE: cipher/transposition/transposition_test.go
================================================
// transposition_test.go
// description: Transposition cipher
// author(s) [red_byte](https://github.com/i-redbyte)
// see transposition.go
package transposition
import (
"errors"
"math/rand"
"reflect"
"testing"
)
const enAlphabet = "abcdefghijklmnopqrstuvwxyz"
var texts = []string{
"Ilya Sokolov",
"A slice literal is declared just like an array literal, except you leave out the element count",
"Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.",
"Go’s treatment of errors as values has served us well over the last decade. Although the standard library’s support for errors has been minimal—just the errors.New and fmt.Errorf functions, which produce errors that contain only a message—the built-in error interface allows Go programmers to add whatever information they desire. All it requires is a type that implements an Error method:",
"А тут для примера русский текст",
}
func getRandomString() string {
enRunes := []rune(enAlphabet)
b := make([]rune, rand.Intn(100))
for i := range b {
b[i] = enRunes[rand.Intn(len(enRunes))]
}
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")
}
}
func TestDecrypt(t *testing.T) {
for _, s := range texts {
keyWord := getRandomString()
encrypt, errEncrypt := Encrypt([]rune(s), keyWord)
if errEncrypt != nil &&
!errors.Is(errEncrypt, ErrNoTextToEncrypt) &&
!errors.Is(errEncrypt, ErrKeyMissing) {
t.Error("Unexpected error ", errEncrypt)
}
if errEncrypt != nil {
t.Error(errEncrypt)
}
decrypt, errDecrypt := Decrypt([]rune(encrypt), keyWord)
if errDecrypt != nil &&
!errors.Is(errDecrypt, ErrNoTextToEncrypt) &&
!errors.Is(errDecrypt, ErrKeyMissing) {
t.Error("Unexpected error ", errDecrypt)
}
if errDecrypt != nil {
t.Error(errDecrypt)
}
if reflect.DeepEqual(encrypt, decrypt) {
t.Error("String ", s, " not encrypted")
}
if reflect.DeepEqual(encrypt, s) {
t.Error("String ", s, " not encrypted")
}
}
}
func TestEncryptDecrypt(t *testing.T) {
text := []rune("Test text for checking the algorithm")
key1 := "testKey"
key2 := "Test Key2"
encrypt, errEncrypt := Encrypt(text, key1)
if errEncrypt != nil {
t.Error(errEncrypt)
}
decrypt, errDecrypt := Decrypt(encrypt, key1)
if errDecrypt != nil {
t.Error(errDecrypt)
}
if !reflect.DeepEqual(decrypt, text) {
t.Errorf("The string was not decrypted correctly %q %q", decrypt, text)
}
decrypt, _ = Decrypt([]rune(encrypt), key2)
if reflect.DeepEqual(decrypt, text) {
t.Errorf("The string was decrypted with a different key: %q %q", decrypt, text)
}
}
func FuzzTransposition(f *testing.F) {
for _, transpositionTestInput := range texts {
f.Add(transpositionTestInput)
}
f.Fuzz(func(t *testing.T, input string) {
keyword := getRandomString()
message := []rune(input)
encrypted, err := Encrypt(message, keyword)
switch {
case err == nil:
case errors.Is(err, ErrKeyMissing),
errors.Is(err, ErrNoTextToEncrypt):
return
default:
t.Fatalf("unexpected error when encrypting string %q: %v", input, err)
}
decrypted, err := Decrypt([]rune(encrypted), keyword)
switch {
case err == nil:
case errors.Is(err, ErrKeyMissing),
errors.Is(err, ErrNoTextToEncrypt):
return
default:
t.Fatalf("unexpected error when decrypting string %q: %v", encrypted, err)
}
if !reflect.DeepEqual(message, decrypted) {
t.Fatalf("expected: %+v, got: %+v", message, []rune(decrypted))
}
})
}
================================================
FILE: cipher/xor/xor.go
================================================
// Package xor is an encryption algorithm that operates the exclusive disjunction(XOR)
// description: XOR encryption
// details: The XOR encryption is an algorithm that operates the exclusive disjunction(XOR) on each character of the plaintext with a given key
// time complexity: O(n)
// space complexity: O(n)
// ref: https://en.wikipedia.org/wiki/XOR_cipher
package xor
// Encrypt encrypts with Xor encryption after converting each character to byte
// The returned value might not be readable because there is no guarantee
// which is within the ASCII range
// If using other type such as string, []int, or some other types,
// add the statements for converting the type to []byte.
func Encrypt(key byte, plaintext []byte) []byte {
cipherText := []byte{}
for _, ch := range plaintext {
cipherText = append(cipherText, key^ch)
}
return cipherText
}
// Decrypt decrypts with Xor encryption
func Decrypt(key byte, cipherText []byte) []byte {
plainText := []byte{}
for _, ch := range cipherText {
plainText = append(plainText, key^ch)
}
return plainText
}
================================================
FILE: cipher/xor/xor_test.go
================================================
package xor
import (
"bytes"
"fmt"
"reflect"
"testing"
)
func Example() {
const (
seed = "Hello World"
key = 97
)
encrypted := Encrypt(byte(key), []byte(seed))
fmt.Printf("Encrypt=> key: %d, seed: %s, encryptedText: %v\n", key, seed, encrypted)
decrypted := Decrypt(byte(key), encrypted)
fmt.Printf("Decrypt=> key: %d, encryptedText: %v, DecryptedText: %s\n", key, encrypted, string(decrypted))
// Output:
// Encrypt=> key: 97, seed: Hello World, encryptedText: [41 4 13 13 14 65 54 14 19 13 5]
// Decrypt=> key: 97, encryptedText: [41 4 13 13 14 65 54 14 19 13 5], DecryptedText: Hello World
}
var xorTestData = []struct {
description string
input string
key int
encrypted string
}{
{
"Encrypt letter 'a' with key 0 makes no changes",
"a",
0,
"a",
},
{
"Encrypt letter 'a' with key 1",
"a",
1,
"`",
},
{
"Encrypt letter 'a' with key 10",
"a",
10,
"k",
},
{
"Encrypt 'hello world' with key 0 makes no changes",
"hello world",
0,
"hello world",
},
{
"Encrypt 'hello world' with key 1",
"hello world",
1,
"idmmn!vnsme",
},
{
"Encrypt 'hello world' with key 10",
"hello world",
10,
"boffe*}exfn",
},
{
"Encrypt full sentence with key 64",
"the quick brown fox jumps over the lazy dog.",
64,
"4(%`15)#+`\"2/7.`&/8`*5-03`/6%2`4(%`,!:9`$/'n",
},
{
"Encrypt a word with key 32 make the case swap",
"abcdefghijklmNOPQRSTUVWXYZ",
32,
"ABCDEFGHIJKLMnopqrstuvwxyz",
},
}
func TestXorCipherEncrypt(t *testing.T) {
for _, test := range xorTestData {
t.Run(test.description, func(t *testing.T) {
encrypted := Encrypt(byte(test.key), []byte(test.input))
if !reflect.DeepEqual(string(encrypted), test.encrypted) {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expecting %s, actual %s", test.encrypted, string(encrypted))
}
})
}
}
func TestXorCipherDecrypt(t *testing.T) {
for _, test := range xorTestData {
t.Run(test.description, func(t *testing.T) {
decrypted := Decrypt(byte(test.key), []byte(test.encrypted))
if !reflect.DeepEqual(string(decrypted), test.input) {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expecting %s, actual %s", test.input, string(decrypted))
}
})
}
}
func FuzzXOR(f *testing.F) {
f.Add([]byte("The Quick Brown Fox Jumps over the Lazy Dog."), byte('X'))
f.Fuzz(func(t *testing.T, input []byte, key byte) {
cipherText := Encrypt(key, input)
result := Decrypt(key, cipherText)
if !bytes.Equal(input, result) {
t.Errorf("Before: %s, after: %s, key: %d", input, result, key)
}
})
}
================================================
FILE: compression/huffmancoding.go
================================================
// huffman.go
// description: Implements Huffman compression, encoding and decoding
// details:
// We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding.
// It assumes that the list of symbol-frequencies is sorted.
// time complexity: O(n)
// space complexity: O(n)
// author(s) [pedromsrocha](https://github.com/pedromsrocha)
// see also huffmancoding_test.go
package compression
import "fmt"
// A Node of an Huffman tree, which can either be a leaf or an internal node.
// Each node has a weight.
// A leaf node has an associated symbol, but no children (i.e., left == right == nil).
// A parent node has a left and right child and no symbol (i.e., symbol == -1).
type Node struct {
left *Node
right *Node
symbol rune
weight int
}
// A SymbolFreq is a pair of a symbol and its associated frequency.
type SymbolFreq struct {
Symbol rune
Freq int
}
// HuffTree returns the root Node of the Huffman tree by compressing listfreq.
// The compression produces the most optimal code lengths, provided listfreq is ordered,
// i.e.: listfreq[i] <= listfreq[j], whenever i < j.
func HuffTree(listfreq []SymbolFreq) (*Node, error) {
if len(listfreq) < 1 {
return nil, fmt.Errorf("huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs")
}
q1 := make([]Node, len(listfreq))
q2 := make([]Node, 0, len(listfreq))
for i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq
q1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}
}
//loop invariant: q1, q2 are ordered by increasing weights
for len(q1)+len(q2) > 1 {
var node1, node2 Node
node1, q1, q2 = least(q1, q2)
node2, q1, q2 = least(q1, q2)
node := Node{left: &node1, right: &node2,
symbol: -1, weight: node1.weight + node2.weight}
q2 = append(q2, node)
}
if len(q1) == 1 { // returns the remaining node in q1, q2
return &q1[0], nil
}
return &q2[0], nil
}
// least removes the node with lowest weight from q1, q2.
// It returns the node with lowest weight and the slices q1, q2 after the update.
func least(q1 []Node, q2 []Node) (Node, []Node, []Node) {
if len(q1) == 0 {
return q2[0], q1, q2[1:]
}
if len(q2) == 0 {
return q1[0], q1[1:], q2
}
if q1[0].weight <= q2[0].weight {
return q1[0], q1[1:], q2
}
return q2[0], q1, q2[1:]
}
// HuffEncoding recursively traverses the Huffman tree pointed by node to obtain
// the map codes, that associates a rune with a slice of booleans.
// Each code is prefixed by prefix and left and right children are labelled with
// the booleans false and true, respectively.
func HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) {
if node.symbol != -1 { //base case
codes[node.symbol] = prefix
return
}
// inductive step
prefixLeft := make([]bool, len(prefix))
copy(prefixLeft, prefix)
prefixLeft = append(prefixLeft, false)
HuffEncoding(node.left, prefixLeft, codes)
prefixRight := make([]bool, len(prefix))
copy(prefixRight, prefix)
prefixRight = append(prefixRight, true)
HuffEncoding(node.right, prefixRight, codes)
}
// HuffEncode encodes the string in by applying the mapping defined by codes.
func HuffEncode(codes map[rune][]bool, in string) []bool {
out := make([]bool, 0)
for _, s := range in {
out = append(out, codes[s]...)
}
return out
}
// HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root.
// current stores the current node of the traversing algorithm.
// out stores the current decoded string.
func HuffDecode(root, current *Node, in []bool, out string) string {
if current.symbol != -1 {
out += string(current.symbol)
return HuffDecode(root, root, in, out)
}
if len(in) == 0 {
return out
}
if in[0] {
return HuffDecode(root, current.right, in[1:], out)
}
return HuffDecode(root, current.left, in[1:], out)
}
================================================
FILE: compression/huffmancoding_test.go
================================================
// huffmancoding_test.go
// description: Tests the compression, encoding and decoding algorithms of huffmancoding.go.
// author(s) [pedromsrocha](https://github.com/pedromsrocha)
// see huffmancoding.go
package compression_test
import (
"sort"
"testing"
"github.com/TheAlgorithms/Go/compression"
)
// SymbolCountOrd computes sorted symbol-frequency list of input message
func SymbolCountOrd(message string) []compression.SymbolFreq {
runeCount := make(map[rune]int)
for _, s := range message {
runeCount[s]++
}
listfreq := make([]compression.SymbolFreq, len(runeCount))
i := 0
for s, n := range runeCount {
listfreq[i] = compression.SymbolFreq{Symbol: s, Freq: n}
i++
}
sort.Slice(listfreq, func(i, j int) bool { return listfreq[i].Freq < listfreq[j].Freq })
return listfreq
}
func TestHuffman(t *testing.T) {
messages := []string{
"hello world \U0001F600",
"colorless green ideas sleep furiously",
"the quick brown fox jumps over the lazy dog",
`Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.`,
}
for _, message := range messages {
t.Run("huffman: "+message, func(t *testing.T) {
tree, _ := compression.HuffTree(SymbolCountOrd(message))
codes := make(map[rune][]bool)
compression.HuffEncoding(tree, nil, codes)
messageCoded := compression.HuffEncode(codes, message)
messageHuffDecoded := compression.HuffDecode(tree, tree, messageCoded, "")
if messageHuffDecoded != message {
t.Errorf("got: %q\nbut expected: %q", messageHuffDecoded, message)
}
})
}
}
================================================
FILE: compression/rlecoding.go
================================================
/*
rlecoding.go
description: run length encoding and decoding
details:
Run-length encoding (RLE) is a simple form of data compression in which runs of data are stored as a single data value and count, rather than as the original run. This is useful when the data contains many repeated values. For example, the data "WWWWWWWWWWWWBWWWWWWWWWWWWBBB" can be compressed to "12W1B12W3B". The algorithm is simple and can be implemented in a few lines of code.
time complexity: O(n)
space complexity: O(n)
ref: https://en.wikipedia.org/wiki/Run-length_encoding
author(s) [ddaniel27](https://github.com/ddaniel27)
*/
package compression
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
)
// RLEncode takes a string and returns its run-length encoding
func RLEncode(data string) string {
var result string
count := 1
for i := 0; i < len(data); i++ {
if i+1 < len(data) && data[i] == data[i+1] {
count++
continue
}
result += fmt.Sprintf("%d%c", count, data[i])
count = 1
}
return result
}
// RLEdecode takes a run-length encoded string and returns the original string
func RLEdecode(data string) string {
var result string
regex := regexp.MustCompile(`(\d+)(\w)`)
for _, match := range regex.FindAllStringSubmatch(data, -1) {
num, _ := strconv.Atoi(match[1])
result += strings.Repeat(match[2], num)
}
return result
}
// RLEncodebytes takes a byte slice and returns its run-length encoding as a byte slice
func RLEncodebytes(data []byte) []byte {
var result []byte
var count byte = 1
for i := 0; i < len(data); i++ {
if i+1 < len(data) && data[i] == data[i+1] {
count++
continue
}
result = append(result, count, data[i])
count = 1
}
return result
}
// RLEdecodebytes takes a run-length encoded byte slice and returns the original byte slice
func RLEdecodebytes(data []byte) []byte {
var result []byte
for i := 0; i < len(data); i += 2 {
count := int(data[i])
result = append(result, bytes.Repeat([]byte{data[i+1]}, count)...)
}
return result
}
================================================
FILE: compression/rlecoding_test.go
================================================
package compression_test
import (
"bytes"
"testing"
"github.com/TheAlgorithms/Go/compression"
)
func TestCompressionRLEncode(t *testing.T) {
tests := []struct {
name string
data string
want string
}{
{
name: "test 1",
data: "WWWWWWWWWWWWBWWWWWWWWWWWWBBB",
want: "12W1B12W3B",
},
{
name: "test 2",
data: "AABCCCDEEEE",
want: "2A1B3C1D4E",
},
{
name: "test 3",
data: "AAAABBBCCDA",
want: "4A3B2C1D1A",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := compression.RLEncode(tt.data); got != tt.want {
t.Errorf("RLEncode() = %v, want %v", got, tt.want)
}
})
}
}
func TestCompressionRLEDecode(t *testing.T) {
tests := []struct {
name string
data string
want string
}{
{
name: "test 1",
data: "12W1B12W3B",
want: "WWWWWWWWWWWWBWWWWWWWWWWWWBBB",
},
{
name: "test 2",
data: "2A1B3C1D4E",
want: "AABCCCDEEEE",
},
{
name: "test 3",
data: "4A3B2C1D1A",
want: "AAAABBBCCDA",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := compression.RLEdecode(tt.data); got != tt.want {
t.Errorf("RLEdecode() = %v, want %v", got, tt.want)
}
})
}
}
func TestCompressionRLEncodeBytes(t *testing.T) {
tests := []struct {
name string
data []byte
want []byte
}{
{
name: "test 1",
data: []byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB"),
want: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'},
},
{
name: "test 2",
data: []byte("AABCCCDEEEE"),
want: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'},
},
{
name: "test 3",
data: []byte("AAAABBBCCDA"),
want: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := compression.RLEncodebytes(tt.data); !bytes.Equal(got, tt.want) {
t.Errorf("RLEncodebytes() = %v, want %v", got, tt.want)
}
})
}
}
func TestCompressionRLEDecodeBytes(t *testing.T) {
tests := []struct {
name string
data []byte
want []byte
}{
{
name: "test 1",
data: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'},
want: []byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB"),
},
{
name: "test 2",
data: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'},
want: []byte("AABCCCDEEEE"),
},
{
name: "test 3",
data: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'},
want: []byte("AAAABBBCCDA"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := compression.RLEdecodebytes(tt.data); !bytes.Equal(got, tt.want) {
t.Errorf("RLEdecodebytes() = %v, want %v", got, tt.want)
}
})
}
}
/* --- BENCHMARKS --- */
func BenchmarkRLEncode(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = compression.RLEncode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB")
}
}
func BenchmarkRLEDecode(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = compression.RLEdecode("12W1B12W3B")
}
}
func BenchmarkRLEncodeBytes(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = compression.RLEncodebytes([]byte("WWWWWWWWWWWWBWWWWWWWWWWWWBBB"))
}
}
func BenchmarkRLEDecodeBytes(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = compression.RLEdecodebytes([]byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'})
}
}
================================================
FILE: constraints/constraints.go
================================================
// Package constraints has some useful generic type constraints defined which is very similar to
// [golang.org/x/exp/constraints](https://pkg.go.dev/golang.org/x/exp/constraints) package.
// We refrained from using that until it gets placed into the standard library - currently
// there are some questions regarding this package [ref](https://github.com/golang/go/issues/50792).
package constraints
// Signed is a generic type constraint for all signed integers.
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
// Unsigned is a generic type constraint for all unsigned integers.
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}
// Integer is a generic type constraint for all integers (signed and unsigned.)
type Integer interface {
Signed | Unsigned
}
// Float is a generic type constraint for all floating point types.
type Float interface {
~float32 | ~float64
}
// Number is a generic type constraint for all numeric types in Go except Complex types.
type Number interface {
Integer | Float
}
// Ordered is a generic type constraint for all ordered data types in Go.
// Loosely speaking, in mathematics a field is an ordered field if there is a "total
// order" (a binary relation - in this case `<` symbol) such that we will always have
// if a < b then a + c < b + c and if 0 < a, 0 < b then 0 < a.b
// The idea in Go is quite similar, though only limited to Go standard types
// not user defined types.
type Ordered interface {
Integer | ~string | Float
}
================================================
FILE: conversion/base64.go
================================================
// base64.go
// description: The base64 encoding algorithm as defined in the RFC4648 standard.
// author: [Paul Leydier] (https://github.com/paul-leydier)
// time complexity: O(n)
// space complexity: O(n)
// ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4
// ref: https://en.wikipedia.org/wiki/Base64
// see base64_test.go
package conversion
import (
"strings" // Used for efficient string builder (more efficient than simply appending strings)
)
const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
// Base64Encode encodes the received input bytes slice into a base64 string.
// The implementation follows the RFC4648 standard, which is documented
// at https://datatracker.ietf.org/doc/html/rfc4648#section-4
func Base64Encode(input []byte) string {
var sb strings.Builder
// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output
var padding string
for i := len(input) % 3; i > 0 && i < 3; i++ {
var zeroByte byte
input = append(input, zeroByte)
padding += "="
}
// encode 24 bits per 24 bits (3 bytes per 3 bytes)
for i := 0; i < len(input); i += 3 {
// select 3 8-bit input groups, and re-arrange them into 4 6-bit groups
// the literal 0x3F corresponds to the byte "0011 1111"
// the operation "byte & 0x3F" masks the two left-most bits
group := [4]byte{
input[i] >> 2,
(input[i]<<4)&0x3F + input[i+1]>>4,
(input[i+1]<<2)&0x3F + input[i+2]>>6,
input[i+2] & 0x3F,
}
// translate each group into a char using the static map
for _, b := range group {
sb.WriteString(string(Alphabet[int(b)]))
}
}
encoded := sb.String()
// Apply the output padding
encoded = encoded[:len(encoded)-len(padding)] + padding[:]
return encoded
}
// Base64Decode decodes the received input base64 string into a byte slice.
// The implementation follows the RFC4648 standard, which is documented
// at https://datatracker.ietf.org/doc/html/rfc4648#section-4
func Base64Decode(input string) []byte {
padding := strings.Count(input, "=") // Number of bytes which will be ignored
var decoded []byte
// select 4 6-bit input groups, and re-arrange them into 3 8-bit groups
for i := 0; i < len(input); i += 4 {
// translate each group into a byte using the static map
byteInput := [4]byte{
byte(strings.IndexByte(Alphabet, input[i])),
byte(strings.IndexByte(Alphabet, input[i+1])),
byte(strings.IndexByte(Alphabet, input[i+2])),
byte(strings.IndexByte(Alphabet, input[i+3])),
}
group := [3]byte{
byteInput[0]<<2 + byteInput[1]>>4,
byteInput[1]<<4 + byteInput[2]>>2,
byteInput[2]<<6 + byteInput[3],
}
decoded = append(decoded, group[:]...)
}
return decoded[:len(decoded)-padding]
}
================================================
FILE: conversion/base64_test.go
================================================
package conversion
import "testing"
func TestBase64Encode(t *testing.T) {
testCases := []struct {
in string
expected string
}{
{"Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits)
{"Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1
{"Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2
{"", ""}, // empty byte slice
{"6", "Ng=="}, // short text
{"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text
}
for _, tc := range testCases {
result := Base64Encode([]byte(tc.in))
if result != tc.expected {
t.Fatalf("Base64Encode(%s) = %s, want %s", tc.in, result, tc.expected)
}
}
}
func BenchmarkBase64Encode(b *testing.B) {
benchmarks := []struct {
name string
in string
expected string
}{
{"Hello World!", "Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits)
{"Hello World!a", "Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1
{"Hello World!ab", "Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2
{"Empty", "", ""}, // empty byte slice
{"6", "6", "Ng=="}, // short text
{"Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text
}
for _, bm := range benchmarks {
b.Run(bm.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
Base64Encode([]byte(bm.in))
}
})
}
}
func TestBase64Decode(t *testing.T) {
testCases := []struct {
expected string
in string
}{
{"Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits)
{"Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1
{"Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2
{"", ""}, // empty byte slice
{"6", "Ng=="}, // short text
{"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text
}
for _, tc := range testCases {
result := string(Base64Decode(tc.in))
if result != tc.expected {
t.Fatalf("Base64Decode(%s) = %s, want %s", tc.in, result, tc.expected)
}
}
}
func BenchmarkBase64Decode(b *testing.B) {
benchmarks := []struct {
name string
expected string
in string
}{
{"Hello World!", "Hello World!", "SGVsbG8gV29ybGQh"}, // multiple of 3 byte length (multiple of 24-bits)
{"Hello World!a", "Hello World!a", "SGVsbG8gV29ybGQhYQ=="}, // multiple of 3 byte length + 1
{"Hello World!ab", "Hello World!ab", "SGVsbG8gV29ybGQhYWI="}, // multiple of 3 byte length + 2
{"Empty", "", ""}, // empty byte slice
{"6", "6", "Ng=="}, // short text
{"Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uIHVsbGFtY28gbGFib3JpcyBuaXNpIHV0IGFsaXF1aXAgZXggZWEgY29tbW9kbyBjb25zZXF1YXQuIER1aXMgYXV0ZSBpcnVyZSBkb2xvciBpbiByZXByZWhlbmRlcml0IGluIHZvbHVwdGF0ZSB2ZWxpdCBlc3NlIGNpbGx1bSBkb2xvcmUgZXUgZnVnaWF0IG51bGxhIHBhcmlhdHVyLiBFeGNlcHRldXIgc2ludCBvY2NhZWNhdCBjdXBpZGF0YXQgbm9uIHByb2lkZW50LCBzdW50IGluIGN1bHBhIHF1aSBvZmZpY2lhIGRlc2VydW50IG1vbGxpdCBhbmltIGlkIGVzdCBsYWJvcnVtLg=="}, // Long text
}
for _, bm := range benchmarks {
b.Run(bm.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
Base64Decode(bm.in)
}
})
}
}
func TestBase64EncodeDecodeInverse(t *testing.T) {
testCases := []struct {
in string
}{
{"Hello World!"}, // multiple of 3 byte length (multiple of 24-bits)
{"Hello World!a"}, // multiple of 3 byte length + 1
{"Hello World!ab"}, // multiple of 3 byte length + 2
{""}, // empty byte slice
{"6"}, // short text
{"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}, // Long text
}
for _, tc := range testCases {
result := string(Base64Decode(Base64Encode([]byte(tc.in))))
if result != tc.in {
t.Fatalf("Base64Decode(Base64Encode(%s)) = %s, want %s", tc.in, result, tc.in)
}
}
}
func FuzzBase64Encode(f *testing.F) {
f.Add([]byte("hello"))
f.Fuzz(func(t *testing.T, input []byte) {
result := Base64Decode(Base64Encode(input))
for i := 0; i < len(input); i++ {
if result[i] != input[i] {
t.Fatalf("with input '%s' - expected '%s', got '%s' (mismatch at position %d)", input, input, result, i)
}
}
})
}
================================================
FILE: conversion/binarytodecimal.go
================================================
/*
Author: Motasim
GitHub: https://github.com/motasimmakki
Date: 19-Oct-2021
*/
// This algorithm will convert any Binary number(0 or 1) to Decimal number(+ve number).
// https://en.wikipedia.org/wiki/Binary_number
// https://en.wikipedia.org/wiki/Decimal
// Function receives a Binary Number as string and returns the Decimal number as integer.
// Supported Binary number range is 0 to 2^(31-1).
// time complexity: O(n)
// space complexity: O(1)
package conversion
// Importing necessary package.
import (
"errors"
"regexp"
)
var isValid = regexp.MustCompile("^[0-1]{1,}$").MatchString
// BinaryToDecimal() function that will take Binary number as string,
// and return its Decimal equivalent as an integer.
func BinaryToDecimal(binary string) (int, error) {
if !isValid(binary) {
return -1, errors.New("not a valid binary string")
}
if len(binary) > 32 {
return -1, errors.New("binary number must be in range 0 to 2^(31-1)")
}
var result, base int = 0, 1
for i := len(binary) - 1; i >= 0; i-- {
if binary[i] == '1' {
result += base
}
base *= 2
}
return result, nil
}
================================================
FILE: conversion/binarytodecimal_test.go
================================================
package conversion
import "testing"
var binaryTestCases = map[string]int{
"0": 0, "1": 1, "10": 2, "11": 3, "100": 4,
"101": 5, "110": 6, "111": 7, "1000": 8, "1001": 9,
"1010": 10, "1011": 11, "1100": 12, "1101": 13, "1110": 14,
"1111": 15, "10000": 16, "10001": 17, "10010": 18, "10011": 19,
"10100": 20, "10101": 21, "10110": 22, "10111": 23, "11000": 24,
"11001": 25, "11010": 26, "11011": 27, "11100": 28, "11101": 29,
"11110": 30, "11111": 31, "100000": 32, "100001": 33, "100010": 34,
"100011": 35, "100100": 36, "100101": 37, "100110": 38, "100111": 39,
"101000": 40, "101001": 41, "101010": 42, "101011": 43, "101100": 44,
"101101": 45, "101110": 46, "101111": 47, "110000": 48, "110001": 49,
"110010": 50, "110011": 51, "110100": 52, "110101": 53, "110110": 54,
"110111": 55, "111000": 56, "111001": 57, "111010": 58, "111011": 59,
"111100": 60, "111101": 61, "111110": 62, "111111": 63, "1000000": 64,
"1000001": 65, "1000010": 66, "1000011": 67, "1000100": 68, "1000101": 69,
"1000110": 70, "1000111": 71, "1001000": 72, "1001001": 73, "1001010": 74,
"1001011": 75, "1001100": 76, "1001101": 77, "1001110": 78, "1001111": 79,
"1010000": 80, "1010001": 81, "1010010": 82, "1010011": 83, "1010100": 84,
"1010101": 85, "1010110": 86, "1010111": 87, "1011000": 88, "1011001": 89,
"1011010": 90, "1011011": 91, "1011100": 92, "1011101": 93, "1011110": 94,
"1011111": 95, "1100000": 96, "1100001": 97, "1100010": 98, "1100011": 99,
"1100100": 100,
}
func TestBinaryToDecimal(t *testing.T) {
for input, expected := range binaryTestCases {
out, err := BinaryToDecimal(input)
if err != nil {
t.Errorf("BinaryToDecimal(%s) returned an error %s", input, err.Error())
}
if out != expected {
t.Errorf("BinaryToDecimal(%s) = %d; want %d", input, out, expected)
}
}
}
func BenchmarkBinaryToDecimal(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = BinaryToDecimal("1100100")
}
}
================================================
FILE: conversion/conversion_test.go
================================================
// Empty test file to keep track of all the tests for the algorithms.
package conversion
================================================
FILE: conversion/decimaltobinary.go
================================================
/*
Author: Motasim
GitHub: https://github.com/motasimmakki
Date: 14-Oct-2021
*/
// This algorithm will convert any Decimal (+ve integer) number to Binary number.
// https://en.wikipedia.org/wiki/Binary_number
// Function receives a integer as a Decimal number and returns the Binary number.
// Supported integer value range is 0 to 2^(31 -1).
// time complexity: O(log(n))
// space complexity: O(1)
package conversion
// Importing necessary package.
import (
"errors"
"strconv"
)
// Reverse() function that will take string,
// and returns the reverse of that string.
func Reverse(str string) string {
rStr := []rune(str)
for i, j := 0, len(rStr)-1; i < len(rStr)/2; i, j = i+1, j-1 {
rStr[i], rStr[j] = rStr[j], rStr[i]
}
return string(rStr)
}
// DecimalToBinary() function that will take Decimal number as int,
// and return its Binary equivalent as a string.
func DecimalToBinary(num int) (string, error) {
if num < 0 {
return "", errors.New("integer must have +ve value")
}
if num == 0 {
return "0", nil
}
var result string = ""
for num > 0 {
result += strconv.Itoa(num & 1)
num >>= 1
}
return Reverse(result), nil
}
================================================
FILE: conversion/decimaltobinary_test.go
================================================
package conversion
import "testing"
var decimalTestCases = map[int]string{
0: "0", 1: "1", 2: "10", 3: "11", 4: "100",
5: "101", 6: "110", 7: "111", 8: "1000", 9: "1001",
10: "1010", 11: "1011", 12: "1100", 13: "1101", 14: "1110",
15: "1111", 16: "10000", 17: "10001", 18: "10010", 19: "10011",
20: "10100", 21: "10101", 22: "10110", 23: "10111", 24: "11000",
25: "11001", 26: "11010", 27: "11011", 28: "11100", 29: "11101",
30: "11110", 31: "11111", 32: "100000", 33: "100001", 34: "100010",
35: "100011", 36: "100100", 37: "100101", 38: "100110", 39: "100111",
40: "101000", 41: "101001", 42: "101010", 43: "101011", 44: "101100",
45: "101101", 46: "101110", 47: "101111", 48: "110000", 49: "110001",
50: "110010", 51: "110011", 52: "110100", 53: "110101", 54: "110110",
55: "110111", 56: "111000", 57: "111001", 58: "111010", 59: "111011",
60: "111100", 61: "111101", 62: "111110", 63: "111111", 64: "1000000",
65: "1000001", 66: "1000010", 67: "1000011", 68: "1000100", 69: "1000101",
70: "1000110", 71: "1000111", 72: "1001000", 73: "1001001", 74: "1001010",
75: "1001011", 76: "1001100", 77: "1001101", 78: "1001110", 79: "1001111",
80: "1010000", 81: "1010001", 82: "1010010", 83: "1010011", 84: "1010100",
85: "1010101", 86: "1010110", 87: "1010111", 88: "1011000", 89: "1011001",
90: "1011010", 91: "1011011", 92: "1011100", 93: "1011101", 94: "1011110",
95: "1011111", 96: "1100000", 97: "1100001", 98: "1100010", 99: "1100011",
100: "1100100",
}
func TestDecimalToBinary(t *testing.T) {
for input, expected := range decimalTestCases {
out, err := DecimalToBinary(input)
if err != nil {
t.Errorf("DecimalToBinary(%d) returned an error %s", input, err.Error())
}
if out != expected {
t.Errorf("DecimalToBinary(%d) = %s; want %s", input, out, expected)
}
}
}
func BenchmarkDecimalToBinary(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = DecimalToBinary(100)
}
}
================================================
FILE: conversion/doc.go
================================================
// Package conversion is a package of implementations which converts one data structure to another.
package conversion
================================================
FILE: conversion/hexadecimaltobinary.go
================================================
/*
Author: mapcrafter2048
GitHub: https://github.com/mapcrafter2048
*/
// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1).
// https://en.wikipedia.org/wiki/Hexadecimal
// https://en.wikipedia.org/wiki/Binary_number
// Function receives a Hexadecimal Number as string and returns the Binary number as string.
// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF.
package conversion
import (
"errors"
"regexp"
"strings"
)
var isValidHex = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString
// hexToBinary() function that will take Hexadecimal number as string,
// and return its Binary equivalent as a string.
func hexToBinary(hex string) (string, error) {
// Trim any leading or trailing whitespace
hex = strings.TrimSpace(hex)
// Check if the hexadecimal string is empty
if hex == "" {
return "", errors.New("input string is empty")
}
// Check if the hexadecimal string is valid
if !isValidHex(hex) {
return "", errors.New("invalid hexadecimal string: " + hex)
}
// Parse the hexadecimal string to an integer
var decimal int64
for i := 0; i < len(hex); i++ {
char := hex[i]
var value int64
if char >= '0' && char <= '9' {
value = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
value = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
value = int64(char - 'a' + 10)
} else {
return "", errors.New("invalid character in hexadecimal string: " + string(char))
}
decimal = decimal*16 + value
}
// Convert the integer to a binary string without using predefined functions
var binaryBuilder strings.Builder
if decimal == 0 {
binaryBuilder.WriteString("0")
} else {
for decimal > 0 {
bit := decimal % 2
if bit == 0 {
binaryBuilder.WriteString("0")
} else {
binaryBuilder.WriteString("1")
}
decimal = decimal / 2
}
}
// Reverse the binary string since the bits are added in reverse order
binaryRunes := []rune(binaryBuilder.String())
for i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {
binaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]
}
return string(binaryRunes), nil
}
================================================
FILE: conversion/hexadecimaltobinary_test.go
================================================
package conversion
import (
"testing"
)
func TestHexToBinary(t *testing.T) {
tests := []struct {
hex string
want string
wantErr bool
}{
{"", "", true},
{"G123", "", true},
{"12XZ", "", true},
{"1", "1", false},
{"A", "1010", false},
{"10", "10000", false},
{"1A", "11010", false},
{"aB", "10101011", false},
{"0Ff", "11111111", false},
{" 1A ", "11010", false},
{"0001A", "11010", false},
{"7FFFFFFFFFFFFFFF", "111111111111111111111111111111111111111111111111111111111111111", false},
}
for _, tt := range tests {
t.Run(tt.hex, func(t *testing.T) {
got, err := hexToBinary(tt.hex)
if (err != nil) != tt.wantErr {
t.Errorf("hexToBinary(%q) error = %v, wantErr %v", tt.hex, err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("hexToBinary(%q) = %v, want %v", tt.hex, got, tt.want)
}
})
}
}
func BenchmarkHexToBinary(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = hexToBinary("7FFFFFFFFFFFFFFF")
}
}
================================================
FILE: conversion/hexadecimaltodecimal.go
================================================
/*
Author: mapcrafter2048
GitHub: https://github.com/mapcrafter2048
*/
// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Decimal number(0-9).
// https://en.wikipedia.org/wiki/Hexadecimal
// https://en.wikipedia.org/wiki/Decimal
// Function receives a Hexadecimal Number as string and returns the Decimal number as integer.
// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF.
package conversion
import (
"fmt"
"regexp"
"strings"
)
var isValidHexadecimal = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString
// hexToDecimal converts a hexadecimal string to a decimal integer.
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nil
}
================================================
FILE: conversion/hexadecimaltodecimal_test.go
================================================
package conversion
import (
"testing"
)
func TestHexToDecimal(t *testing.T) {
tests := []struct {
hex string
want int64
wantErr bool
}{
{"", 0, true},
{"G123", 0, true},
{"123Z", 0, true},
{"1", 1, false},
{"A", 10, false},
{"10", 16, false},
{"1A", 26, false},
{"aB", 171, false},
{"0Ff", 255, false},
{" 1A ", 26, false},
{"0x1A", 26, false},
{"0X1A", 26, false},
{"1A", 26, false},
{"7FFFFFFFFFFFFFFF", 9223372036854775807, false},
{"0001A", 26, false},
{"0000007F", 127, false},
{"0", 0, false},
{"0x0", 0, false},
}
for _, tt := range tests {
t.Run(tt.hex, func(t *testing.T) {
got, err := hexToDecimal(tt.hex)
if (err != nil) != tt.wantErr {
t.Errorf("hexToDecimal(%q) error = %v, wantErr %v", tt.hex, err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("hexToDecimal(%q) = %v, want %v", tt.hex, got, tt.want)
}
})
}
}
func BenchmarkHexToDecimal(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = hexToDecimal("7FFFFFFFFFFFFFFF")
}
}
================================================
FILE: conversion/inttoroman.go
================================================
// inttoroman.go
// description: Convert an integer to a roman numeral
// details: This program converts an integer to a roman numeral. The program uses a lookup array to convert the integer to a roman numeral.
// time complexity: O(1)
// space complexity: O(1)
package conversion
import (
"errors"
)
var (
// lookup arrays used for converting from an int to a roman numeral extremely quickly.
r0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"} // 1 - 9
r1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"} // 10 - 90
r2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"} // 100 - 900
r3 = []string{"", "M", "MM", "MMM"} // 1,000 - 3,000
)
// IntToRoman converts an integer value to a roman numeral string. An error is
// returned if the integer is not between 1 and 3999.
func IntToRoman(n int) (string, error) {
if n < 1 || n > 3999 {
return "", errors.New("integer must be between 1 and 3999")
}
// Concatenate strings for each of 4 lookup array categories.
//
// Key behavior to note here is how math with integers is handled. Values are floored to the
// nearest int, not rounded up. For example, 26/10 = 2 even though the actual result is 2.6.
//
// For example, lets use an input value of 126:
// `r3[n%1e4/1e3]` --> 126 % 10_000 = 126 --> 126 / 1_000 = 0.126 (0 as int) --> r3[0] = ""
// `r2[n%1e3/1e2]` --> 126 % 1_000 = 126 --> 126 / 100 = 1.26 (1 as int) --> r2[1] = "C"
// `r1[n%100/10]` --> 126 % 100 = 26 --> 26 / 10 = 2.6 (2 as int) --> r1[2] = "XX"
// `r0[n%10]` --> 126 % 10 = 6 --> r0[6] = "VI"
// FINAL --> "" + "C" + "XX" + "VI" = "CXXVI"
//
// This is efficient in Go. The 4 operands are evaluated,
// then a single allocation is made of the exact size needed for the result.
return r3[n%1e4/1e3] + r2[n%1e3/1e2] + r1[n%100/10] + r0[n%10], nil
}
================================================
FILE: conversion/inttoroman_test.go
================================================
package conversion
import "testing"
func TestIntToRoman(t *testing.T) {
for expected, input := range romanTestCases {
out, err := IntToRoman(input)
if err != nil {
t.Errorf("IntToRoman(%d) returned an error %s", input, err.Error())
}
if out != expected {
t.Errorf("IntToRoman(%d) = %s; want %s", input, out, expected)
}
}
_, err := IntToRoman(100000)
if err == nil {
t.Errorf("IntToRoman(%d) expected an error", 100000)
}
_, err = IntToRoman(0)
if err == nil {
t.Errorf("IntToRoman(%d) expected an error", 0)
}
}
func BenchmarkIntToRoman(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = IntToRoman(3999)
}
}
================================================
FILE: conversion/rgbhex.go
================================================
// rgbhex.go
// description: convert hex input to red, green and blue and vice versa
// time complexity: O(1)
// space complexity: O(1)
// author(s) [darmiel](https://github.com/darmiel)
// see rgbhex_test.go
package conversion
// HEXToRGB splits an RGB input (e.g. a color in hex format; 0x<color-code>)
// into the individual components: red, green and blue
func HEXToRGB(hex uint) (red, green, blue byte) {
// A hex code is structured like this:
// #3498db (light blue) - converted to binary:
// 00110100 10011000 11011011
// <red> <green> <blue>
// To get the blue value we use the bit operation AND with the bit mask 0xFF (in binary: 11111111)
// 00110100 10011000 <11011011> &
// 00000000 00000000 11111111 =
// 00000000 00000000 <11011011> =
blue = byte(hex & 0xFF)
// To get the green value, we first shift the value 8 bits to the right:
// 00110100 <10011000> 11011011 >> 8 =
// 00000000 00110100 <10011000> &
// 00000000 00000000 11111111 =
// 00000000 00000000 <10011000> =
green = byte((hex >> 8) & 0xFF)
// Same as green value, only this time shift 16 to the right
// Alternatively, you can apply a bitmask first and then shift it.
// <00110100> 10011000 11011011 &
// 11111111 00000000 00000000 =
// <00110100> 00000000 00000000 >> 16
// 00000000 00000000 <00110100> =
red = byte((hex >> 16) & 0xFF)
return
}
// RGBToHEX does exactly the opposite of HEXToRGB:
// it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex
func RGBToHEX(red, green, blue byte) (hex uint) {
// Sets the bits of blue in position 1-8, green in 9-16 and red in 17-24
// Red: 00110100
// Green: 10011000
// Blue: 11011011
// RGB:
// R << 16: [00110100] 00000000 00000000 |
// G << 8 : 00000000 {10011000} 00000000 |
// B : 00000000 00000000 <11011011> =
// [00110100] {10011000} <11011011>
return (uint(red) << 16) | (uint(green) << 8) | uint(blue)
}
================================================
FILE: conversion/rgbhex_test.go
================================================
package conversion
import "testing"
var HEX = []uint{
0x1abc9c,
0x3498db,
0x9b59b6,
}
var RGB = [][]byte{
{26, 188, 156},
{52, 152, 219},
{155, 89, 182},
}
func TestHEXToRGB(t *testing.T) {
for i := 0; i < len(HEX); i++ {
hex := HEX[i]
expected := RGB[i]
resultR, resultG, resultB := HEXToRGB(hex)
if resultR != expected[0] || resultG != expected[1] || resultB != expected[2] {
t.Errorf("HEXToRGB(%d) = %d,%d,%d; want %d,%d,%d",
hex, resultR, resultG, resultB, expected[0], expected[1], expected[2])
}
}
}
func BenchmarkHEXToRGB(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _, _ = HEXToRGB(0xdeadbe)
}
}
func TestRGBToHEX(t *testing.T) {
for i := 0; i < len(RGB); i++ {
args := RGB[i]
expected := HEX[i]
result := RGBToHEX(args[0], args[1], args[2])
if result != expected {
t.Errorf("RGBToHEX(%d,%d,%d) = %d; want %d",
args[0], args[1], args[2], result, expected)
}
}
}
func BenchmarkRGBToHEX(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = RGBToHEX(222, 173, 190)
}
}
================================================
FILE: conversion/romantoint.go
================================================
// This algorithm will convert a standard roman number to an integer
// https://en.wikipedia.org/wiki/Roman_numerals
// Function receives a string as a roman number and outputs an integer
// Maximum output will be 3999
// Only standard form is supported
// time complexity: O(n)
// space complexity: O(1)
package conversion
import (
"errors"
"strings"
)
// numeral describes the value and symbol of a single roman numeral
type numeral struct {
val int
sym string
}
// lookup array for numeral values sorted by largest to smallest
var nums = []numeral{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
}
// RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers
// outside the range 1 to 3,999 will return an error. Nil or empty string return 0
// with no error thrown.
func RomanToInt(input string) (int, error) {
if input == "" {
return 0, nil
}
var output int
for _, n := range nums {
for strings.HasPrefix(input, n.sym) {
output += n.val
input = input[len(n.sym):]
}
}
// if we are still left with input string values then the
// input was invalid and an error is returned.
if len(input) > 0 {
return 0, errors.New("invalid roman numeral")
}
return output, nil
}
================================================
FILE: conversion/romantoint_test.go
================================================
package conversion
import "testing"
var romanTestCases = map[string]int{
"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5, "VI": 6,
"VII": 7, "VIII": 8, "IX": 9, "X": 10, "XI": 11, "XII": 12,
"XIII": 13, "XIV": 14, "XV": 15, "XVI": 16, "XVII": 17,
"XVIII": 18, "XIX": 19, "XX": 20, "XXXI": 31, "XXXII": 32,
"XXXIII": 33, "XXXIV": 34, "XXXV": 35, "XXXVI": 36, "XXXVII": 37,
"XXXVIII": 38, "XXXIX": 39, "XL": 40, "XLI": 41, "XLII": 42,
"XLIII": 43, "XLIV": 44, "XLV": 45, "XLVI": 46, "XLVII": 47,
"XLVIII": 48, "XLIX": 49, "L": 50, "LXXXIX": 89, "XC": 90,
"XCI": 91, "XCII": 92, "XCIII": 93, "XCIV": 94, "XCV": 95,
"XCVI": 96, "XCVII": 97, "XCVIII": 98, "XCIX": 99, "C": 100,
"CI": 101, "CII": 102, "CIII": 103, "CIV": 104, "CV": 105,
"CVI": 106, "CVII": 107, "CVIII": 108, "CIX": 109, "CXLIX": 149,
"CCCXLIX": 349, "CDLVI": 456, "D": 500, "DCIV": 604, "DCCLXXXIX": 789,
"DCCCXLIX": 849, "CMIV": 904, "M": 1000, "MVII": 1007, "MLXVI": 1066,
"MCCXXXIV": 1234, "MDCCLXXVI": 1776, "MMXXI": 2021, "MMDCCCVI": 2806,
"MMCMXCIX": 2999, "MMM": 3000, "MMMCMLXXIX": 3979, "MMMCMXCIX": 3999,
}
func TestRomanToInt(t *testing.T) {
for input, expected := range romanTestCases {
out, err := RomanToInt(input)
if err != nil {
t.Errorf("RomanToInt(%s) returned an error %s", input, err.Error())
}
if out != expected {
t.Errorf("RomanToInt(%s) = %d; want %d", input, out, expected)
}
}
_, err := RomanToInt("IVCMXCIX")
if err == nil {
t.Error("RomanToInt(IVCMXCIX) expected an error")
}
val, err := RomanToInt("")
if val != 0 {
t.Errorf("RomanToInt(\"\") = %d; want 0", val)
}
if err != nil {
t.Errorf("RomanToInt(\"\") returned an error %s", err.Error())
}
}
func BenchmarkRomanToInt(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = RomanToInt("MMMCMXCIX")
}
}
================================================
FILE: dynamic/abbreviation.go
================================================
// File: abbreviation.go
// Description: Abbreviation problem
// Details:
// https://www.hackerrank.com/challenges/abbr/problem
// Problem description (from hackerrank):
// You can perform the following operations on the string, a:
// 1. Capitalize zero or more of a's lowercase letters.
// 2. Delete all of the remaining lowercase letters in a.
// Given 2 strings a and b, determine if it's possible to make a equal to be using above operations.
// Example:
// Given a = "ABcde" and b = "ABCD"
// We can capitalize "c" and "d" in a to get "ABCde" then delete all the lowercase letters (which is only "e") in a to get "ABCD" which equals b.
// Author: [duongoku](https://github.com/duongoku)
// Time Complexity: O(n*m) where n is the length of a and m is the length of b
// Space Complexity: O(n*m) where n is the length of a and m is the length of b
// See abbreviation_test.go for test cases
package dynamic
// strings for getting uppercases and lowercases
import (
"strings"
)
// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise
func Abbreviation(a string, b string) bool {
dp := make([][]bool, len(a)+1)
for i := range dp {
dp[i] = make([]bool, len(b)+1)
}
dp[0][0] = true
for i := 0; i < len(a); i++ {
for j := 0; j <= len(b); j++ {
if dp[i][j] {
if j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {
dp[i+1][j+1] = true
}
if string(a[i]) == strings.ToLower(string(a[i])) {
dp[i+1][j] = true
}
}
}
}
return dp[len(a)][len(b)]
}
================================================
FILE: dynamic/abbreviation_test.go
================================================
package dynamic
import (
"fmt"
"testing"
)
func TestAbbreviation(t *testing.T) {
tests := []struct {
a string
b string
expected bool
}{
{"uOHlGMdUBc", "uOalGMdUBCasdcavsdf", false},
{"kotgDIUagj", "DIU", true},
{"WPTffVkSNl", "WPTVSN", true},
{"CoJsPURrVX", "CPUVX", false},
{"xasreDHndqvCnFfX", "DHndqvCnFX", false},
{"XFEaWCxpeepGjOnCCsFh", "XFEAWCPEPGOCCSF", true},
{"", "", true},
{"a", "", true},
{"a", "b", false},
{"a", "a", false},
{"A", "A", true},
}
count := len(tests)
for i := 0; i < count; i++ {
name := fmt.Sprintf(
"Test case #%d: string a = \"%s\", string b = \"%s\"",
i+1,
tests[i].a,
tests[i].b,
)
t.Run(name, func(t *testing.T) {
result := Abbreviation(tests[i].a, tests[i].b)
if result != tests[i].expected {
t.Errorf("Expected the %t, got %t", tests[i].expected, result)
}
})
}
}
================================================
FILE: dynamic/binomialcoefficient.go
================================================
// binomialcoefficient.go
// description: Implementation of the binomial coefficient using dynamic programming
// details: The binomial coefficient C(n, k) is the number of ways to choose a subset of k elements from a set of n elements. The binomial coefficient is calculated using the formula C(n, k) = C(n-1, k-1) + C(n-1, k) with base cases C(n, 0) = C(n, n) = 1.
// time complexity: O(n*k) where n is the number of elements and k is the number of elements to choose
// space complexity: O(n*k) where n is the number of elements and k is the number of elements to choose
package dynamic
import "github.com/TheAlgorithms/Go/math/min"
// func main() {
// myArrayOfK := [4]int{5, 6, 7, 8}
// var x int
// fmt.Println("\nBinomial Coefficient Using Dynamic Programming:", bin2(50, 5))
// for _, element := range myArrayOfK {
// start := time.Now()
// x = bin2(50, element)
// elapsed := time.Since(start)
// fmt.Println("bin2 (50,", element, ") = ", x, " took ", elapsed)
// }
// }
// 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]
}
}
}
return B[n][k]
}
================================================
FILE: dynamic/binomialcoefficient_test.go
================================================
package dynamic_test
import (
"fmt"
gitextract_m9961ttm/
├── .github/
│ ├── CODEOWNERS
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ ├── config.yml
│ │ ├── new_implementation.yml
│ │ └── other.yml
│ ├── PULL_REQUEST_TEMPLATE/
│ │ └── pull_request.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── ci.yml
│ ├── citk.yml
│ ├── godocmd.yml
│ ├── stale.yml
│ └── upload_coverage_report.yml
├── .gitignore
├── .gitpod.dockerfile
├── .gitpod.yml
├── .golangci.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── STYLE.md
├── cache/
│ ├── lfu.go
│ ├── lfu_test.go
│ ├── lru.go
│ └── lru_test.go
├── checksum/
│ ├── crc8.go
│ ├── crc8_test.go
│ ├── luhn.go
│ └── luhn_test.go
├── cipher/
│ ├── caesar/
│ │ ├── caesar.go
│ │ └── caesar_test.go
│ ├── cipher_test.go
│ ├── diffiehellman/
│ │ ├── diffiehellmankeyexchange.go
│ │ └── diffiehellmankeyexchange_test.go
│ ├── doc.go
│ ├── dsa/
│ │ ├── dsa.go
│ │ └── dsa_test.go
│ ├── polybius/
│ │ ├── polybius.go
│ │ └── polybius_test.go
│ ├── railfence/
│ │ ├── railfence.go
│ │ └── railfence_test.go
│ ├── rot13/
│ │ ├── rot13.go
│ │ └── rot13_test.go
│ ├── rsa/
│ │ ├── rsa.go
│ │ ├── rsa2.go
│ │ ├── rsa2_test.go
│ │ └── rsa_test.go
│ ├── transposition/
│ │ ├── transposition.go
│ │ └── transposition_test.go
│ └── xor/
│ ├── xor.go
│ └── xor_test.go
├── compression/
│ ├── huffmancoding.go
│ ├── huffmancoding_test.go
│ ├── rlecoding.go
│ └── rlecoding_test.go
├── constraints/
│ └── constraints.go
├── conversion/
│ ├── base64.go
│ ├── base64_test.go
│ ├── binarytodecimal.go
│ ├── binarytodecimal_test.go
│ ├── conversion_test.go
│ ├── decimaltobinary.go
│ ├── decimaltobinary_test.go
│ ├── doc.go
│ ├── hexadecimaltobinary.go
│ ├── hexadecimaltobinary_test.go
│ ├── hexadecimaltodecimal.go
│ ├── hexadecimaltodecimal_test.go
│ ├── inttoroman.go
│ ├── inttoroman_test.go
│ ├── rgbhex.go
│ ├── rgbhex_test.go
│ ├── romantoint.go
│ └── romantoint_test.go
├── dynamic/
│ ├── abbreviation.go
│ ├── abbreviation_test.go
│ ├── binomialcoefficient.go
│ ├── binomialcoefficient_test.go
│ ├── burstballoons.go
│ ├── burstballoons_test.go
│ ├── catalan.go
│ ├── catalan_test.go
│ ├── coinchange.go
│ ├── coinchange_test.go
│ ├── dicethrow.go
│ ├── dicethrow_test.go
│ ├── doc.go
│ ├── dynamic_test.go
│ ├── editdistance.go
│ ├── editdistance_test.go
│ ├── eggdropping.go
│ ├── eggdropping_test.go
│ ├── fibonacci.go
│ ├── fibonacci_test.go
│ ├── interleavingstrings.go
│ ├── interleavingstrings_test.go
│ ├── knapsack.go
│ ├── knapsack_test.go
│ ├── longestarithmeticsubsequence.go
│ ├── longestarithmeticsubsequence_test.go
│ ├── longestcommonsubsequence.go
│ ├── longestcommonsubsequence_test.go
│ ├── longestincreasingsubsequence.go
│ ├── longestincreasingsubsequence_test.go
│ ├── longestincreasingsubsequencegreedy.go
│ ├── longestpalindromicsubsequence.go
│ ├── longestpalindromicsubsequence_test.go
│ ├── longestpalindromicsubstring.go
│ ├── longestpalindromicsubstring_test.go
│ ├── matrixmultiplication.go
│ ├── maxsubarraysum.go
│ ├── maxsubarraysum_test.go
│ ├── optimalbst.go
│ ├── optimalbst_test.go
│ ├── partitionproblem.go
│ ├── partitionproblem_test.go
│ ├── rodcutting.go
│ ├── rodcutting_test.go
│ ├── subsetsum.go
│ ├── subsetsum_test.go
│ ├── tilingproblem.go
│ ├── tilingproblem_test.go
│ ├── traprainwater.go
│ ├── traprainwater_test.go
│ ├── uniquepaths.go
│ ├── uniquepaths_test.go
│ ├── wildcardmatching.go
│ ├── wildcardmatching_test.go
│ ├── wordbreak.go
│ └── wordbreak_test.go
├── go.mod
├── go.sum
├── graph/
│ ├── articulationpoints.go
│ ├── articulationpoints_test.go
│ ├── bellmanford.go
│ ├── bellmanford_test.go
│ ├── breadthfirstsearch.go
│ ├── breadthfirstsearch_test.go
│ ├── coloring/
│ │ ├── backtracking.go
│ │ ├── backtracking_test.go
│ │ ├── bfs.go
│ │ ├── bfs_test.go
│ │ ├── bipartite.go
│ │ ├── bipartite_test.go
│ │ ├── doc.go
│ │ ├── graph.go
│ │ ├── graph_test.go
│ │ ├── greedy.go
│ │ └── greedy_test.go
│ ├── cycle.go
│ ├── cycle_test.go
│ ├── depthfirstsearch.go
│ ├── depthfirstsearch_test.go
│ ├── dijkstra.go
│ ├── dijkstra_test.go
│ ├── doc.go
│ ├── edmondkarp.go
│ ├── edmondkarp_test.go
│ ├── floydwarshall.go
│ ├── floydwarshall_test.go
│ ├── graph.go
│ ├── graph_test.go
│ ├── kahn.go
│ ├── kahn_test.go
│ ├── kosaraju.go
│ ├── kosaraju_test.go
│ ├── kruskal.go
│ ├── kruskal_test.go
│ ├── lowestcommonancestor.go
│ ├── lowestcommonancestor_test.go
│ ├── prim.go
│ ├── prim_test.go
│ ├── topological.go
│ ├── topological_test.go
│ ├── unionfind.go
│ └── unionfind_test.go
├── hashing/
│ ├── doc.go
│ ├── hashing_test.go
│ ├── md5/
│ │ ├── md5.go
│ │ └── md5_test.go
│ ├── sha1/
│ │ ├── sha1.go
│ │ └── sha1_test.go
│ └── sha256/
│ ├── sha256.go
│ └── sha256_test.go
├── math/
│ ├── abs.go
│ ├── abs_test.go
│ ├── aliquot_test.go
│ ├── aliquotsum.go
│ ├── armstrong/
│ │ ├── isarmstrong.go
│ │ └── isarmstrong_test.go
│ ├── binary/
│ │ ├── abs.go
│ │ ├── abs_test.go
│ │ ├── arithmeticmean.go
│ │ ├── arithmeticmean_test.go
│ │ ├── bitcounter.go
│ │ ├── bitcounter_test.go
│ │ ├── checkisnumberpoweroftwo.go
│ │ ├── checkisnumberpoweroftwo_test.go
│ │ ├── fast_inverse_sqrt.go
│ │ ├── logarithm.go
│ │ ├── logarithm_test.go
│ │ ├── rbc.go
│ │ ├── rbc_test.go
│ │ ├── reversebits.go
│ │ ├── reversebits_test.go
│ │ ├── sqrt.go
│ │ ├── sqrt_test.go
│ │ ├── xorsearch.go
│ │ └── xorsearch_test.go
│ ├── binomialcoefficient.go
│ ├── binomialcoefficient_test.go
│ ├── catalan/
│ │ ├── catalannumber.go
│ │ └── catalannumber_test.go
│ ├── checkisnumberpoweroftwo.go
│ ├── checkisnumberpoweroftwo_test.go
│ ├── cos.go
│ ├── cos_test.go
│ ├── doc.go
│ ├── eulertotient.go
│ ├── eulertotient_test.go
│ ├── factorial/
│ │ ├── factorial.go
│ │ └── factorial_test.go
│ ├── fibonacci/
│ │ ├── fibonacci.go
│ │ └── fibonacci_test.go
│ ├── gcd/
│ │ ├── extended.go
│ │ ├── extended_test.go
│ │ ├── extendedgcd.go
│ │ ├── extendedgcd_test.go
│ │ ├── extendedgcditerative.go
│ │ ├── gcd.go
│ │ ├── gcd_test.go
│ │ └── gcditerative.go
│ ├── geometry/
│ │ ├── distance.go
│ │ ├── distance_test.go
│ │ ├── straightlines.go
│ │ └── straightlines_test.go
│ ├── isautomorphic.go
│ ├── isautomorphic_test.go
│ ├── krishnamurthy.go
│ ├── krishnamurthy_test.go
│ ├── kthnumber.go
│ ├── kthnumber_test.go
│ ├── lcm/
│ │ ├── lcm.go
│ │ └── lcm_test.go
│ ├── lerp.go
│ ├── lerp_test.go
│ ├── liouville.go
│ ├── liouville_test.go
│ ├── math_test.go
│ ├── matrix/
│ │ ├── add.go
│ │ ├── add_test.go
│ │ ├── checkequal.go
│ │ ├── checkequal_test.go
│ │ ├── copy.go
│ │ ├── copy_test.go
│ │ ├── determinant.go
│ │ ├── determinant_test.go
│ │ ├── isvalid.go
│ │ ├── isvalid_test.go
│ │ ├── matchdimensions.go
│ │ ├── matchdimensions_test.go
│ │ ├── matrix.go
│ │ ├── matrix_test.go
│ │ ├── multiply.go
│ │ ├── multiply_test.go
│ │ ├── strassenmatrixmultiply.go
│ │ ├── strassenmatrixmultiply_test.go
│ │ ├── string.go
│ │ ├── string_test.go
│ │ ├── submatrix.go
│ │ ├── submatrix_test.go
│ │ ├── subtract.go
│ │ └── subtract_test.go
│ ├── max/
│ │ ├── bitwisemax.go
│ │ ├── bitwisemax_test.go
│ │ ├── max.go
│ │ └── max_test.go
│ ├── mean.go
│ ├── mean_test.go
│ ├── median.go
│ ├── median_test.go
│ ├── min/
│ │ ├── bitwisemin.go
│ │ ├── min.go
│ │ └── min_test.go
│ ├── mobius.go
│ ├── mobius_test.go
│ ├── mode.go
│ ├── mode_test.go
│ ├── modular/
│ │ ├── exponentiation.go
│ │ ├── exponentiation_test.go
│ │ ├── inverse.go
│ │ └── inverse_test.go
│ ├── moserdebruijnsequence/
│ │ ├── sequence.go
│ │ └── sequence_test.go
│ ├── pascal/
│ │ ├── pascaltriangle.go
│ │ └── pascaltriangle_test.go
│ ├── perfectnumber.go
│ ├── perfectnumber_test.go
│ ├── permutation/
│ │ ├── heaps.go
│ │ ├── heaps_test.go
│ │ ├── next_permutation.go
│ │ └── next_permutation_test.go
│ ├── pi/
│ │ ├── montecarlopi.go
│ │ ├── montecarlopi_test.go
│ │ ├── spigotpi.go
│ │ └── spigotpi_test.go
│ ├── pollard.go
│ ├── pollard_test.go
│ ├── power/
│ │ ├── fastexponent.go
│ │ ├── fastexponent_test.go
│ │ ├── powvialogarithm.go
│ │ └── powvialogarithm_test.go
│ ├── prime/
│ │ ├── millerrabintest.go
│ │ ├── prime_test.go
│ │ ├── primecheck.go
│ │ ├── primefactorization.go
│ │ ├── primefactorization_test.go
│ │ ├── sieve.go
│ │ ├── sieve2.go
│ │ ├── sieve2_test.go
│ │ ├── sieve_test.go
│ │ ├── twin.go
│ │ └── twin_test.go
│ ├── pronicnumber.go
│ ├── pronicnumber_test.go
│ ├── pythagoras/
│ │ ├── pythagoras.go
│ │ └── pythagoras_test.go
│ ├── sin.go
│ └── sin_test.go
├── other/
│ ├── doc.go
│ ├── maxsubarraysum/
│ │ ├── maxsubarraysum.go
│ │ └── maxsubarraysum_test.go
│ ├── nested/
│ │ ├── nestedbrackets.go
│ │ └── nestedbrackets_test.go
│ ├── other_test.go
│ └── password/
│ └── generator.go
├── project_euler/
│ ├── problem_1/
│ │ ├── problem1.go
│ │ └── problem1_test.go
│ ├── problem_10/
│ │ ├── problem10.go
│ │ └── problem10_test.go
│ ├── problem_11/
│ │ ├── problem11.go
│ │ └── problem11_test.go
│ ├── problem_12/
│ │ ├── problem12.go
│ │ └── problem12_test.go
│ ├── problem_13/
│ │ ├── problem13.go
│ │ └── problem13_test.go
│ ├── problem_14/
│ │ ├── problem14.go
│ │ └── problem14_test.go
│ ├── problem_15/
│ │ ├── problem15.go
│ │ └── problem15_test.go
│ ├── problem_16/
│ │ ├── problem16.go
│ │ └── problem16_test.go
│ ├── problem_17/
│ │ ├── input.go
│ │ ├── problem17.go
│ │ └── problem17_test.go
│ ├── problem_18/
│ │ ├── edge.go
│ │ ├── input.go
│ │ ├── leaf.go
│ │ ├── problem18.go
│ │ ├── problem18_test.go
│ │ ├── root.go
│ │ └── tree.go
│ ├── problem_19/
│ │ ├── problem19.go
│ │ └── problem19_test.go
│ ├── problem_2/
│ │ ├── problem2.go
│ │ └── problem2_test.go
│ ├── problem_20/
│ │ ├── problem20.go
│ │ └── problem20_test.go
│ ├── problem_3/
│ │ ├── problem3.go
│ │ └── problem3_test.go
│ ├── problem_4/
│ │ ├── problem4.go
│ │ └── problem4_test.go
│ ├── problem_5/
│ │ ├── problem5.go
│ │ └── problem5_test.go
│ ├── problem_6/
│ │ ├── problem6.go
│ │ └── problem6_test.go
│ ├── problem_7/
│ │ ├── problem7.go
│ │ └── problem7_test.go
│ ├── problem_8/
│ │ ├── problem8.go
│ │ └── problem8_test.go
│ └── problem_9/
│ ├── problem9.go
│ └── problem9_test.go
├── search/
│ ├── binary.go
│ ├── binary_test.go
│ ├── doc.go
│ ├── errors.go
│ ├── interpolation.go
│ ├── interpolation_test.go
│ ├── jump.go
│ ├── jump2.go
│ ├── jump2_test.go
│ ├── jump_test.go
│ ├── linear.go
│ ├── linear_test.go
│ ├── selectk.go
│ ├── selectk_test.go
│ ├── ternary.go
│ ├── ternary_test.go
│ └── testcases.go
├── sort/
│ ├── binaryinsertionsort.go
│ ├── bogosort.go
│ ├── bubblesort.go
│ ├── bucketsort.go
│ ├── circlesort.go
│ ├── cocktailsort.go
│ ├── combSort.go
│ ├── countingsort.go
│ ├── cyclesort.go
│ ├── doc.go
│ ├── exchangesort.go
│ ├── heapsort.go
│ ├── insertionsort.go
│ ├── mergesort.go
│ ├── oddevensort.go
│ ├── pancakesort.go
│ ├── patiencesort.go
│ ├── pigeonholesort.go
│ ├── quicksort.go
│ ├── radixsort.go
│ ├── selectionsort.go
│ ├── shellsort.go
│ ├── simplesort.go
│ ├── sorts_test.go
│ ├── stooge_sort.go
│ └── timsort.go
├── sqrt/
│ ├── sqrtdecomposition.go
│ └── sqrtdecomposition_test.go
├── strings/
│ ├── ahocorasick/
│ │ ├── advancedahocorasick.go
│ │ ├── advancedahocorasick_test.go
│ │ ├── ahocorasick.go
│ │ ├── ahocorasick_test.go
│ │ ├── patterns.txt
│ │ ├── shared.go
│ │ └── text.txt
│ ├── bom/
│ │ └── bom.go
│ ├── charoccurrence.go
│ ├── charoccurrence_test.go
│ ├── combination/
│ │ └── combination.go
│ ├── doc.go
│ ├── generateparentheses/
│ │ ├── generateparentheses.go
│ │ └── generateparentheses_test.go
│ ├── genetic/
│ │ ├── genetic.go
│ │ └── geneticalgorithm_test.go
│ ├── guid/
│ │ ├── guid.go
│ │ └── guid_test.go
│ ├── hamming/
│ │ ├── hammingdistance.go
│ │ └── hammingdistance_test.go
│ ├── horspool/
│ │ ├── horspool.go
│ │ └── horspool_test.go
│ ├── isisogram.go
│ ├── isisogram_test.go
│ ├── issubsequence.go
│ ├── issubsequence_test.go
│ ├── kmp/
│ │ ├── kmp.go
│ │ └── kmp_test.go
│ ├── levenshtein/
│ │ ├── levenshteindistance.go
│ │ └── levenshteindistance_test.go
│ ├── manacher/
│ │ ├── longestpalindrome.go
│ │ └── longestpalindrome_test.go
│ ├── palindrome/
│ │ ├── ispalindrome.go
│ │ └── ispalindrome_test.go
│ ├── pangram/
│ │ ├── ispangram.go
│ │ └── ispangram_test.go
│ ├── parenthesis/
│ │ ├── parenthesis.go
│ │ └── parenthesis_test.go
│ ├── search/
│ │ ├── boyermoore.go
│ │ ├── naive.go
│ │ └── patternsearch_test.go
│ └── strings_test.go
└── structure/
├── circularqueue/
│ ├── circularqueue_test.go
│ └── circularqueuearray.go
├── deque/
│ ├── deque.go
│ └── deque_test.go
├── doc.go
├── dynamicarray/
│ ├── dynamicarray.go
│ └── dynamicarray_test.go
├── fenwicktree/
│ ├── fenwicktree.go
│ └── fenwicktree_test.go
├── hashmap/
│ ├── hashmap.go
│ └── hashmap_test.go
├── heap/
│ ├── heap.go
│ └── heap_test.go
├── linkedlist/
│ ├── Readme.md
│ ├── cyclic.go
│ ├── cyclic_test.go
│ ├── doc.go
│ ├── doubly.go
│ ├── doubly_test.go
│ ├── shared.go
│ ├── singlylinkedlist.go
│ └── singlylinkedlist_test.go
├── queue/
│ ├── queue_test.go
│ ├── queuearray.go
│ ├── queuelinkedlist.go
│ └── queuelinklistwithlist.go
├── segmenttree/
│ ├── segmenttree.go
│ └── segmenttree_test.go
├── set/
│ ├── set.go
│ ├── set_test.go
│ └── setexample_test.go
├── stack/
│ ├── stack_test.go
│ ├── stackarray.go
│ ├── stacklinkedlist.go
│ └── stacklinkedlistwithlist.go
├── structure_test.go
├── tree/
│ ├── avl.go
│ ├── avl_test.go
│ ├── bstree.go
│ ├── bstree_test.go
│ ├── btree.go
│ ├── btree_test.go
│ ├── example_test.go
│ ├── rbtree.go
│ ├── rbtree_test.go
│ ├── tree.go
│ └── tree_test.go
└── trie/
├── trie.go
├── trie_bench_test.go
├── trie_test.go
└── trieexample_test.go
SYMBOL INDEX (1488 symbols across 471 files)
FILE: cache/lfu.go
type LFU (line 19) | type LFU struct
method Get (line 53) | func (c *LFU) Get(key string) any {
method Put (line 67) | func (c *LFU) Put(key string, value any) {
method increaseFreq (line 92) | func (c *LFU) increaseFreq(e *list.Element) {
method insertMap (line 107) | func (c *LFU) insertMap(obj item) {
method eliminate (line 120) | func (c *LFU) eliminate() {
function NewLFU (line 33) | func NewLFU(capacity int) LFU {
function initItem (line 44) | func initItem(k string, v any, f int) item {
FILE: cache/lfu_test.go
function TestLFU (line 9) | func TestLFU(t *testing.T) {
FILE: cache/lru.go
type item (line 14) | type item struct
type LRU (line 22) | type LRU struct
method Get (line 41) | func (c *LRU) Get(key string) any {
method Put (line 52) | func (c *LRU) Put(key string, value any) {
function NewLRU (line 30) | func NewLRU(capacity int) LRU {
FILE: cache/lru_test.go
function TestLRU (line 9) | func TestLRU(t *testing.T) {
FILE: checksum/crc8.go
type CRCModel (line 17) | type CRCModel struct
function CRC8 (line 27) | func CRC8(data []byte, model CRCModel) uint8 {
function addBytes (line 38) | func addBytes(data []byte, model CRCModel, crcResult uint8, table []uint...
function getTable (line 53) | func getTable(model CRCModel) []uint8 {
FILE: checksum/crc8_test.go
function TestCalculateCRC8 (line 28) | func TestCalculateCRC8(t *testing.T) {
function BenchmarkCalculateCRC8 (line 57) | func BenchmarkCalculateCRC8(b *testing.B) {
FILE: checksum/luhn.go
function Luhn (line 13) | func Luhn(s []byte) bool {
FILE: checksum/luhn_test.go
function TestLuhn (line 14) | func TestLuhn(t *testing.T) {
function BenchmarkBruteForceFactorial (line 37) | func BenchmarkBruteForceFactorial(b *testing.B) {
FILE: cipher/caesar/caesar.go
function Encrypt (line 10) | func Encrypt(input string, key int) string {
function Decrypt (line 31) | func Decrypt(input string, key int) string {
FILE: cipher/caesar/caesar_test.go
function TestEncrypt (line 10) | func TestEncrypt(t *testing.T) {
function TestDecrypt (line 78) | func TestDecrypt(t *testing.T) {
function Example (line 141) | func Example() {
function FuzzCaesar (line 158) | func FuzzCaesar(f *testing.F) {
FILE: cipher/diffiehellman/diffiehellmankeyexchange.go
constant generator (line 10) | generator = 3
constant primeNumber (line 11) | primeNumber int64 = 6700417
function GenerateShareKey (line 17) | func GenerateShareKey(prvKey int64) int64 {
function GenerateMutualKey (line 23) | func GenerateMutualKey(prvKey, shareKey int64) int64 {
function modularExponentiation (line 28) | func modularExponentiation(b, e, mod int64) int64 {
FILE: cipher/diffiehellman/diffiehellmankeyexchange_test.go
function TestDiffieHellmanKeyExchange (line 9) | func TestDiffieHellmanKeyExchange(t *testing.T) {
FILE: cipher/dsa/dsa.go
constant numMRTests (line 16) | numMRTests = 64
constant L (line 17) | L = 1024
constant N (line 18) | N = 160
type parameters (line 23) | type parameters struct
type dsa (line 28) | type dsa struct
method dsaParameterGeneration (line 50) | func (dsa *dsa) dsaParameterGeneration() {
method keyGen (line 108) | func (dsa *dsa) keyGen() {
method GetPublicKey (line 184) | func (dsa *dsa) GetPublicKey() *big.Int {
method GetParameters (line 189) | func (dsa *dsa) GetParameters() parameters {
method GetPrivateKey (line 194) | func (dsa *dsa) GetPrivateKey() *big.Int {
function New (line 36) | func New() *dsa {
function Sign (line 125) | func Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {
function Verify (line 157) | func Verify(m []byte, r, s, p, q, g, y *big.Int) bool {
FILE: cipher/dsa/dsa_test.go
function TestDSA (line 10) | func TestDSA(t *testing.T) {
function BenchmarkDSANew (line 70) | func BenchmarkDSANew(b *testing.B) {
function BenchmarkDSASign (line 76) | func BenchmarkDSASign(b *testing.B) {
function BenchmarkDSAVerify (line 91) | func BenchmarkDSAVerify(b *testing.B) {
FILE: cipher/polybius/polybius.go
type Polybius (line 16) | type Polybius struct
method Encrypt (line 52) | func (p *Polybius) Encrypt(text string) (string, error) {
method Decrypt (line 65) | func (p *Polybius) Decrypt(text string) (string, error) {
method encipher (line 78) | func (p *Polybius) encipher(char rune) (string, error) {
method decipher (line 89) | func (p *Polybius) decipher(chars []rune) (string, error) {
function NewPolybius (line 25) | func NewPolybius(key string, size int, chars string) (*Polybius, error) {
FILE: cipher/polybius/polybius_test.go
function ExampleNewPolybius (line 10) | func ExampleNewPolybius() {
function TestNewPolybius (line 39) | func TestNewPolybius(t *testing.T) {
function TestPolybiusEncrypt (line 72) | func TestPolybiusEncrypt(t *testing.T) {
function TestPolybiusDecrypt (line 110) | func TestPolybiusDecrypt(t *testing.T) {
function FuzzPolybius (line 154) | func FuzzPolybius(f *testing.F) {
FILE: cipher/railfence/railfence.go
function Encrypt (line 13) | func Encrypt(text string, rails int) string {
function Decrypt (line 50) | func Decrypt(cipherText string, rails int) string {
FILE: cipher/railfence/railfence_test.go
function TestEncrypt (line 7) | func TestEncrypt(t *testing.T) {
function TestDecrypt (line 50) | func TestDecrypt(t *testing.T) {
FILE: cipher/rot13/rot13.go
function rot13 (line 14) | func rot13(input string) string {
FILE: cipher/rot13/rot13_test.go
function TestRot13Encrypt (line 44) | func TestRot13Encrypt(t *testing.T) {
function TestRot13Decrypt (line 54) | func TestRot13Decrypt(t *testing.T) {
function assertRot13Output (line 64) | func assertRot13Output(t *testing.T, input, expected string) {
function FuzzRot13 (line 72) | func FuzzRot13(f *testing.F) {
FILE: cipher/rsa/rsa.go
function Encrypt (line 30) | func Encrypt(message []rune, publicExponent, modulus int64) ([]rune, err...
function Decrypt (line 45) | func Decrypt(encrypted []rune, privateExponent, modulus int64) (string, ...
FILE: cipher/rsa/rsa2.go
type rsa (line 24) | type rsa struct
method EncryptString (line 63) | func (rsa *rsa) EncryptString(data string) string {
method DecryptString (line 80) | func (rsa *rsa) DecryptString(data string) string {
method GetPublicKey (line 98) | func (rsa *rsa) GetPublicKey() (uint64, uint64) {
method GetPrivateKey (line 103) | func (rsa *rsa) GetPrivateKey() uint64 {
function New (line 32) | func New() *rsa {
function encryptDecryptInt (line 108) | func encryptDecryptInt(e, n, data uint64) uint64 {
function randomPrime (line 114) | func randomPrime() (uint64, uint64) {
FILE: cipher/rsa/rsa2_test.go
function TestRSA (line 9) | func TestRSA(t *testing.T) {
function BenchmarkRSAEncryption (line 36) | func BenchmarkRSAEncryption(b *testing.B) {
function BenchmarkRSADecryption (line 43) | func BenchmarkRSADecryption(b *testing.B) {
FILE: cipher/rsa/rsa_test.go
function testPrecondition (line 38) | func testPrecondition(t *testing.T) (int64, int64, int64) {
function TestEncryptDecrypt (line 56) | func TestEncryptDecrypt(t *testing.T) {
function FuzzRsa (line 79) | func FuzzRsa(f *testing.F) {
FILE: cipher/transposition/transposition.go
constant placeholder (line 22) | placeholder = ' '
function getKey (line 24) | func getKey(keyWord string) []int {
function getIndex (line 43) | func getIndex(wordSet []rune, subString rune) int {
function Encrypt (line 53) | func Encrypt(text []rune, keyWord string) ([]rune, error) {
function Decrypt (line 83) | func Decrypt(text []rune, keyWord string) ([]rune, error) {
FILE: cipher/transposition/transposition_test.go
constant enAlphabet (line 15) | enAlphabet = "abcdefghijklmnopqrstuvwxyz"
function getRandomString (line 25) | func getRandomString() string {
function TestEncrypt (line 34) | func TestEncrypt(t *testing.T) {
function TestDecrypt (line 52) | func TestDecrypt(t *testing.T) {
function TestEncryptDecrypt (line 82) | func TestEncryptDecrypt(t *testing.T) {
function FuzzTransposition (line 103) | func FuzzTransposition(f *testing.F) {
FILE: cipher/xor/xor.go
function Encrypt (line 14) | func Encrypt(key byte, plaintext []byte) []byte {
function Decrypt (line 23) | func Decrypt(key byte, cipherText []byte) []byte {
FILE: cipher/xor/xor_test.go
function Example (line 10) | func Example() {
function TestXorCipherEncrypt (line 83) | func TestXorCipherEncrypt(t *testing.T) {
function TestXorCipherDecrypt (line 95) | func TestXorCipherDecrypt(t *testing.T) {
function FuzzXOR (line 108) | func FuzzXOR(f *testing.F) {
FILE: compression/huffmancoding.go
type Node (line 19) | type Node struct
type SymbolFreq (line 27) | type SymbolFreq struct
function HuffTree (line 35) | func HuffTree(listfreq []SymbolFreq) (*Node, error) {
function least (line 61) | func least(q1 []Node, q2 []Node) (Node, []Node, []Node) {
function HuffEncoding (line 78) | func HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) {
function HuffEncode (line 95) | func HuffEncode(codes map[rune][]bool, in string) []bool {
function HuffDecode (line 106) | func HuffDecode(root, current *Node, in []bool, out string) string {
FILE: compression/huffmancoding_test.go
function SymbolCountOrd (line 16) | func SymbolCountOrd(message string) []compression.SymbolFreq {
function TestHuffman (line 31) | func TestHuffman(t *testing.T) {
FILE: compression/rlecoding.go
function RLEncode (line 22) | func RLEncode(data string) string {
function RLEdecode (line 37) | func RLEdecode(data string) string {
function RLEncodebytes (line 50) | func RLEncodebytes(data []byte) []byte {
function RLEdecodebytes (line 67) | func RLEdecodebytes(data []byte) []byte {
FILE: compression/rlecoding_test.go
function TestCompressionRLEncode (line 10) | func TestCompressionRLEncode(t *testing.T) {
function TestCompressionRLEDecode (line 42) | func TestCompressionRLEDecode(t *testing.T) {
function TestCompressionRLEncodeBytes (line 74) | func TestCompressionRLEncodeBytes(t *testing.T) {
function TestCompressionRLEDecodeBytes (line 106) | func TestCompressionRLEDecodeBytes(t *testing.T) {
function BenchmarkRLEncode (line 139) | func BenchmarkRLEncode(b *testing.B) {
function BenchmarkRLEDecode (line 145) | func BenchmarkRLEDecode(b *testing.B) {
function BenchmarkRLEncodeBytes (line 151) | func BenchmarkRLEncodeBytes(b *testing.B) {
function BenchmarkRLEDecodeBytes (line 157) | func BenchmarkRLEDecodeBytes(b *testing.B) {
FILE: constraints/constraints.go
type Signed (line 8) | type Signed interface
type Unsigned (line 13) | type Unsigned interface
type Integer (line 18) | type Integer interface
type Float (line 23) | type Float interface
type Number (line 28) | type Number interface
type Ordered (line 38) | type Ordered interface
FILE: conversion/base64.go
constant Alphabet (line 16) | Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567...
function Base64Encode (line 21) | func Base64Encode(input []byte) string {
function Base64Decode (line 59) | func Base64Decode(input string) []byte {
FILE: conversion/base64_test.go
function TestBase64Encode (line 5) | func TestBase64Encode(t *testing.T) {
function BenchmarkBase64Encode (line 26) | func BenchmarkBase64Encode(b *testing.B) {
function TestBase64Decode (line 49) | func TestBase64Decode(t *testing.T) {
function BenchmarkBase64Decode (line 70) | func BenchmarkBase64Decode(b *testing.B) {
function TestBase64EncodeDecodeInverse (line 93) | func TestBase64EncodeDecodeInverse(t *testing.T) {
function FuzzBase64Encode (line 113) | func FuzzBase64Encode(f *testing.F) {
FILE: conversion/binarytodecimal.go
function BinaryToDecimal (line 27) | func BinaryToDecimal(binary string) (int, error) {
FILE: conversion/binarytodecimal_test.go
function TestBinaryToDecimal (line 29) | func TestBinaryToDecimal(t *testing.T) {
function BenchmarkBinaryToDecimal (line 41) | func BenchmarkBinaryToDecimal(b *testing.B) {
FILE: conversion/decimaltobinary.go
function Reverse (line 24) | func Reverse(str string) string {
function DecimalToBinary (line 34) | func DecimalToBinary(num int) (string, error) {
FILE: conversion/decimaltobinary_test.go
function TestDecimalToBinary (line 29) | func TestDecimalToBinary(t *testing.T) {
function BenchmarkDecimalToBinary (line 41) | func BenchmarkDecimalToBinary(b *testing.B) {
FILE: conversion/hexadecimaltobinary.go
function hexToBinary (line 24) | func hexToBinary(hex string) (string, error) {
FILE: conversion/hexadecimaltobinary_test.go
function TestHexToBinary (line 7) | func TestHexToBinary(t *testing.T) {
function BenchmarkHexToBinary (line 41) | func BenchmarkHexToBinary(b *testing.B) {
FILE: conversion/hexadecimaltodecimal.go
function hexToDecimal (line 23) | func hexToDecimal(hexStr string) (int64, error) {
FILE: conversion/hexadecimaltodecimal_test.go
function TestHexToDecimal (line 7) | func TestHexToDecimal(t *testing.T) {
function BenchmarkHexToDecimal (line 47) | func BenchmarkHexToDecimal(b *testing.B) {
FILE: conversion/inttoroman.go
function IntToRoman (line 23) | func IntToRoman(n int) (string, error) {
FILE: conversion/inttoroman_test.go
function TestIntToRoman (line 5) | func TestIntToRoman(t *testing.T) {
function BenchmarkIntToRoman (line 25) | func BenchmarkIntToRoman(b *testing.B) {
FILE: conversion/rgbhex.go
function HEXToRGB (line 12) | func HEXToRGB(hex uint) (red, green, blue byte) {
function RGBToHEX (line 43) | func RGBToHEX(red, green, blue byte) (hex uint) {
FILE: conversion/rgbhex_test.go
function TestHEXToRGB (line 17) | func TestHEXToRGB(t *testing.T) {
function BenchmarkHEXToRGB (line 29) | func BenchmarkHEXToRGB(b *testing.B) {
function TestRGBToHEX (line 35) | func TestRGBToHEX(t *testing.T) {
function BenchmarkRGBToHEX (line 47) | func BenchmarkRGBToHEX(b *testing.B) {
FILE: conversion/romantoint.go
type numeral (line 17) | type numeral struct
function RomanToInt (line 42) | func RomanToInt(input string) (int, error) {
FILE: conversion/romantoint_test.go
function TestRomanToInt (line 24) | func TestRomanToInt(t *testing.T) {
function BenchmarkRomanToInt (line 48) | func BenchmarkRomanToInt(b *testing.B) {
FILE: dynamic/abbreviation.go
function Abbreviation (line 26) | func Abbreviation(a string, b string) bool {
FILE: dynamic/abbreviation_test.go
function TestAbbreviation (line 8) | func TestAbbreviation(t *testing.T) {
FILE: dynamic/binomialcoefficient.go
function Bin2 (line 26) | func Bin2(n int, k int) int {
FILE: dynamic/binomialcoefficient_test.go
function TestBin2 (line 10) | func TestBin2(t *testing.T) {
FILE: dynamic/burstballoons.go
function MaxCoins (line 6) | func MaxCoins(nums []int) int {
FILE: dynamic/burstballoons_test.go
type testCaseBurstBalloons (line 9) | type testCaseBurstBalloons struct
function getBurstBalloonsTestCases (line 14) | func getBurstBalloonsTestCases() []testCaseBurstBalloons {
function TestMaxCoins (line 24) | func TestMaxCoins(t *testing.T) {
FILE: dynamic/catalan.go
function NthCatalanNumber (line 15) | func NthCatalanNumber(n int) (int64, error) {
FILE: dynamic/catalan_test.go
function TestCatalanNumbers (line 8) | func TestCatalanNumbers(t *testing.T) {
FILE: dynamic/coinchange.go
function CoinChange (line 11) | func CoinChange(coins []int32, amount int32) int32 {
FILE: dynamic/coinchange_test.go
function TestCoinChange (line 9) | func TestCoinChange(t *testing.T) {
FILE: dynamic/dicethrow.go
function DiceThrow (line 10) | func DiceThrow(m, n, sum int) int {
FILE: dynamic/dicethrow_test.go
type testCaseDiceThrow (line 9) | type testCaseDiceThrow struct
function getDiceThrowTestCases (line 17) | func getDiceThrowTestCases() []testCaseDiceThrow {
function TestDiceThrow (line 33) | func TestDiceThrow(t *testing.T) {
FILE: dynamic/editdistance.go
function EditDistanceRecursive (line 12) | func EditDistanceRecursive(first string, second string, pointerFirst int...
function EditDistanceDP (line 37) | func EditDistanceDP(first string, second string) int {
FILE: dynamic/editdistance_test.go
function Test_EditDistance (line 8) | func Test_EditDistance(t *testing.T) {
FILE: dynamic/eggdropping.go
function EggDropping (line 10) | func EggDropping(eggs, floors int) int {
FILE: dynamic/eggdropping_test.go
type testCaseEggDropping (line 9) | type testCaseEggDropping struct
function getEggDroppingTestCases (line 15) | func getEggDroppingTestCases() []testCaseEggDropping {
function TestEggDropping (line 26) | func TestEggDropping(t *testing.T) {
FILE: dynamic/fibonacci.go
function NthFibonacci (line 10) | func NthFibonacci(n uint) uint {
FILE: dynamic/fibonacci_test.go
function Test_NthFibonacci (line 8) | func Test_NthFibonacci(t *testing.T) {
FILE: dynamic/interleavingstrings.go
function IsInterleave (line 10) | func IsInterleave(s1, s2, s3 string) bool {
FILE: dynamic/interleavingstrings_test.go
type testCaseInterleaving (line 9) | type testCaseInterleaving struct
function getInterleavingTestCases (line 14) | func getInterleavingTestCases() []testCaseInterleaving {
function TestIsInterleave (line 29) | func TestIsInterleave(t *testing.T) {
FILE: dynamic/knapsack.go
function Max (line 14) | func Max(a, b int) int {
function Knapsack (line 20) | func Knapsack(maxWeight int, weights, values []int) int {
FILE: dynamic/knapsack_test.go
function TestKnapsack (line 10) | func TestKnapsack(t *testing.T) {
function ExampleKnapsack (line 35) | func ExampleKnapsack() {
FILE: dynamic/longestarithmeticsubsequence.go
function LongestArithmeticSubsequence (line 10) | func LongestArithmeticSubsequence(nums []int) int {
FILE: dynamic/longestarithmeticsubsequence_test.go
type testCaseLongestArithmeticSubsequence (line 9) | type testCaseLongestArithmeticSubsequence struct
function getLongestArithmeticSubsequenceTestCases (line 14) | func getLongestArithmeticSubsequenceTestCases() []testCaseLongestArithme...
function TestLongestArithmeticSubsequence (line 29) | func TestLongestArithmeticSubsequence(t *testing.T) {
FILE: dynamic/longestcommonsubsequence.go
function strToRuneSlice (line 10) | func strToRuneSlice(s string) (r []rune, size int) {
function LongestCommonSubsequence (line 16) | func LongestCommonSubsequence(a string, b string) int {
FILE: dynamic/longestcommonsubsequence_test.go
type testCaseLCS (line 9) | type testCaseLCS struct
function getLCSTestCases (line 15) | func getLCSTestCases() []testCaseLCS {
function TestLongestCommonSubsequence (line 36) | func TestLongestCommonSubsequence(t *testing.T) {
FILE: dynamic/longestincreasingsubsequence.go
function LongestIncreasingSubsequence (line 15) | func LongestIncreasingSubsequence(elements []int) int {
FILE: dynamic/longestincreasingsubsequence_test.go
function longestIncreasingSubsequenceTest (line 10) | func longestIncreasingSubsequenceTest(t *testing.T, algorithm func(nums ...
function TestLongestIncreasingSubsequence (line 32) | func TestLongestIncreasingSubsequence(t *testing.T) {
function TestLongestIncreasingSubsequenceGreedy (line 36) | func TestLongestIncreasingSubsequenceGreedy(t *testing.T) {
FILE: dynamic/longestincreasingsubsequencegreedy.go
function LongestIncreasingSubsequenceGreedy (line 9) | func LongestIncreasingSubsequenceGreedy(nums []int) int {
function lowerBound (line 29) | func lowerBound(arr []int, val int) int {
FILE: dynamic/longestpalindromicsubsequence.go
function lpsRec (line 8) | func lpsRec(word string, i, j int) int {
function LpsRec (line 22) | func LpsRec(word string) int {
function LpsDp (line 27) | func LpsDp(word string) int {
FILE: dynamic/longestpalindromicsubsequence_test.go
function lpsTestTemplate (line 10) | func lpsTestTemplate(t *testing.T, algorithm func(input string) int) {
function TestLpsRec (line 34) | func TestLpsRec(t *testing.T) {
function TestLpsDp (line 38) | func TestLpsDp(t *testing.T) {
FILE: dynamic/longestpalindromicsubstring.go
function LongestPalindromicSubstring (line 10) | func LongestPalindromicSubstring(s string) string {
FILE: dynamic/longestpalindromicsubstring_test.go
type testCaseLongestPalindromicSubstring (line 9) | type testCaseLongestPalindromicSubstring struct
function getLongestPalindromicSubstringTestCases (line 14) | func getLongestPalindromicSubstringTestCases() []testCaseLongestPalindro...
function TestLongestPalindromicSubstring (line 28) | func TestLongestPalindromicSubstring(t *testing.T) {
FILE: dynamic/matrixmultiplication.go
function MatrixChainRec (line 12) | func MatrixChainRec(D []int, i, j int) int {
function MatrixChainDp (line 26) | func MatrixChainDp(D []int) int {
FILE: dynamic/maxsubarraysum.go
function MaxSubArraySum (line 12) | func MaxSubArraySum(nums []int) int {
FILE: dynamic/maxsubarraysum_test.go
type testCaseMaxSubArraySum (line 9) | type testCaseMaxSubArraySum struct
function getMaxSubArraySumTestCases (line 14) | func getMaxSubArraySumTestCases() []testCaseMaxSubArraySum {
function TestMaxSubArraySum (line 28) | func TestMaxSubArraySum(t *testing.T) {
FILE: dynamic/optimalbst.go
function OptimalBST (line 6) | func OptimalBST(keys []int, freq []int, n int) int {
function sum (line 55) | func sum(freq []int, i, j int) int {
FILE: dynamic/optimalbst_test.go
type testCaseOptimalBST (line 9) | type testCaseOptimalBST struct
function getOptimalBSTTestCases (line 16) | func getOptimalBSTTestCases() []testCaseOptimalBST {
function TestOptimalBST (line 24) | func TestOptimalBST(t *testing.T) {
FILE: dynamic/partitionproblem.go
function PartitionProblem (line 11) | func PartitionProblem(nums []int) bool {
FILE: dynamic/partitionproblem_test.go
type testCasePartitionProblem (line 10) | type testCasePartitionProblem struct
function getPartitionProblemTestCases (line 16) | func getPartitionProblemTestCases() []testCasePartitionProblem {
function TestPartitionProblem (line 30) | func TestPartitionProblem(t *testing.T) {
FILE: dynamic/rodcutting.go
function CutRodRec (line 10) | func CutRodRec(price []int, length int) int {
function CutRodDp (line 23) | func CutRodDp(price []int, length int) int {
FILE: dynamic/rodcutting_test.go
type rodCuttingTestCase (line 9) | type rodCuttingTestCase struct
function getRodCuttingTestCases (line 15) | func getRodCuttingTestCases() []rodCuttingTestCase {
function cutRodSolTestFunc (line 24) | func cutRodSolTestFunc(t *testing.T, cutRodSolFunc func([]int, int) int) {
function TestCutRodRec (line 33) | func TestCutRodRec(t *testing.T) {
function TestCutRodDp (line 37) | func TestCutRodDp(t *testing.T) {
FILE: dynamic/subsetsum.go
function IsSubsetSum (line 15) | func IsSubsetSum(array []int, sum int) (bool, error) {
FILE: dynamic/subsetsum_test.go
function TestSubsetSum (line 5) | func TestSubsetSum(t *testing.T) {
FILE: dynamic/tilingproblem.go
function TilingProblem (line 10) | func TilingProblem(n int) int {
FILE: dynamic/tilingproblem_test.go
type testCaseTilingProblem (line 9) | type testCaseTilingProblem struct
function getTilingProblemTestCases (line 14) | func getTilingProblemTestCases() []testCaseTilingProblem {
function TestTilingProblem (line 29) | func TestTilingProblem(t *testing.T) {
FILE: dynamic/traprainwater.go
function TrapRainWater (line 19) | func TrapRainWater(height []int) int {
FILE: dynamic/traprainwater_test.go
function TestTrapRainWater (line 10) | func TestTrapRainWater(t *testing.T) {
FILE: dynamic/uniquepaths.go
function UniquePaths (line 8) | func UniquePaths(m, n int) int {
FILE: dynamic/uniquepaths_test.go
function TestUniquePaths (line 7) | func TestUniquePaths(t *testing.T) {
FILE: dynamic/wildcardmatching.go
function IsMatch (line 10) | func IsMatch(s, p string) bool {
FILE: dynamic/wildcardmatching_test.go
type testCaseWildcardMatching (line 10) | type testCaseWildcardMatching struct
function getWildcardMatchingTestCases (line 17) | func getWildcardMatchingTestCases() []testCaseWildcardMatching {
function TestIsMatch (line 35) | func TestIsMatch(t *testing.T) {
FILE: dynamic/wordbreak.go
function WordBreak (line 10) | func WordBreak(s string, wordDict []string) bool {
FILE: dynamic/wordbreak_test.go
type testCaseWordBreak (line 9) | type testCaseWordBreak struct
function getWordBreakTestCases (line 15) | func getWordBreakTestCases() []testCaseWordBreak {
function TestWordBreak (line 31) | func TestWordBreak(t *testing.T) {
FILE: graph/articulationpoints.go
type apHelper (line 7) | type apHelper struct
function ArticulationPoint (line 20) | func ArticulationPoint(graph *Graph) []bool {
function articulationPointHelper (line 46) | func articulationPointHelper(
FILE: graph/articulationpoints_test.go
function TestArticulationPoints (line 8) | func TestArticulationPoints(t *testing.T) {
FILE: graph/bellmanford.go
method BellmanFord (line 16) | func (g *Graph) BellmanFord(start, end int) (isReachable bool, distance ...
FILE: graph/bellmanford_test.go
function TestBellmanford (line 10) | func TestBellmanford(t *testing.T) {
FILE: graph/breadthfirstsearch.go
function BreadthFirstSearch (line 9) | func BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnect...
FILE: graph/breadthfirstsearch_test.go
function TestBreadthFirstSearch (line 7) | func TestBreadthFirstSearch(t *testing.T) {
FILE: graph/coloring/backtracking.go
method ColorUsingBacktracking (line 10) | func (g *Graph) ColorUsingBacktracking() (map[int]Color, int) {
method colorVertex (line 24) | func (g *Graph) colorVertex(v int, color map[int]Color) bool {
FILE: graph/coloring/backtracking_test.go
function TestGraphColorUsingBacktracking (line 11) | func TestGraphColorUsingBacktracking(t *testing.T) {
FILE: graph/coloring/bfs.go
method ColorUsingBFS (line 12) | func (g *Graph) ColorUsingBFS() (map[int]Color, int) {
FILE: graph/coloring/bfs_test.go
function TestGraphColorUsingBFS (line 11) | func TestGraphColorUsingBFS(t *testing.T) {
FILE: graph/coloring/bipartite.go
method TryBipartiteColoring (line 9) | func (g *Graph) TryBipartiteColoring() map[int]Color {
function BipartiteCheck (line 46) | func BipartiteCheck(N int, edges [][]int) bool {
FILE: graph/coloring/bipartite_test.go
function TestBipartite (line 23) | func TestBipartite(t *testing.T) {
FILE: graph/coloring/graph.go
type Color (line 10) | type Color
type Graph (line 14) | type Graph struct
method AddVertex (line 21) | func (g *Graph) AddVertex(v int) {
method AddEdge (line 34) | func (g *Graph) AddEdge(one, two int) {
method ValidateColorsOfVertex (line 44) | func (g *Graph) ValidateColorsOfVertex(colors map[int]Color) error {
FILE: graph/coloring/graph_test.go
type testGraph (line 12) | type testGraph struct
function getTestGraphs (line 18) | func getTestGraphs() (list []*testGraph) {
function TestGraph_ValidateColorsOfVertex (line 121) | func TestGraph_ValidateColorsOfVertex(t *testing.T) {
function getTestGraphsForNegativeTests (line 131) | func getTestGraphsForNegativeTests() (list []*testGraph) {
function TestGraphValidateColorsOfVertex_Negative (line 145) | func TestGraphValidateColorsOfVertex_Negative(t *testing.T) {
FILE: graph/coloring/greedy.go
method ColorUsingGreedyApproach (line 13) | func (g *Graph) ColorUsingGreedyApproach() (map[int]Color, int) {
FILE: graph/coloring/greedy_test.go
function TestGraphColorUsingGreedyApproach (line 11) | func TestGraphColorUsingGreedyApproach(t *testing.T) {
FILE: graph/cycle.go
method HasCycle (line 10) | func (g *Graph) HasCycle() bool {
method hasCycleHelper (line 30) | func (g Graph) hasCycleHelper(v int, all, visiting, visited map[int]stru...
method FindAllCycles (line 50) | func (g *Graph) FindAllCycles() []Graph {
method findAllCyclesHelper (line 90) | func (g Graph) findAllCyclesHelper(current int, all, visiting, visited m...
FILE: graph/cycle_test.go
function TestHasCycle (line 7) | func TestHasCycle(t *testing.T) {
function TestFindAllCycles (line 27) | func TestFindAllCycles(t *testing.T) {
FILE: graph/depthfirstsearch.go
function GetIdx (line 9) | func GetIdx(target int, nodes []int) int {
function NotExist (line 18) | func NotExist(target int, slice []int) bool {
function DepthFirstSearchHelper (line 27) | func DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool,...
function DepthFirstSearch (line 59) | func DepthFirstSearch(start, end int, nodes []int, edges [][]bool) ([]in...
FILE: graph/depthfirstsearch_test.go
function TestDfsWhenPathIsFound (line 8) | func TestDfsWhenPathIsFound(t *testing.T) {
function TestDfsWhenPathIsNotFound (line 37) | func TestDfsWhenPathIsNotFound(t *testing.T) {
FILE: graph/dijkstra.go
type Item (line 12) | type Item struct
method More (line 17) | func (a Item) More(b any) bool {
method Idx (line 21) | func (a Item) Idx() int {
method Dijkstra (line 25) | func (g *Graph) Dijkstra(start, end int) (int, bool) {
FILE: graph/dijkstra_test.go
function TestDijkstra (line 36) | func TestDijkstra(t *testing.T) {
FILE: graph/edmondkarp.go
function FindPath (line 16) | func FindPath(rGraph WeightedGraph, source int, sink int) map[int]int {
function EdmondKarp (line 43) | func EdmondKarp(graph WeightedGraph, source int, sink int) float64 {
FILE: graph/edmondkarp_test.go
function TestEdmondKarp (line 7) | func TestEdmondKarp(t *testing.T) {
FILE: graph/floydwarshall.go
type WeightedGraph (line 11) | type WeightedGraph
function FloydWarshall (line 17) | func FloydWarshall(graph WeightedGraph) WeightedGraph {
FILE: graph/floydwarshall_test.go
constant float64EqualityThreshold (line 8) | float64EqualityThreshold = 1e-9
function almostEqual (line 12) | func almostEqual(a, b float64) bool {
method IsAlmostEqualTo (line 17) | func (a *WeightedGraph) IsAlmostEqualTo(b WeightedGraph) bool {
function TestFloydWarshall (line 41) | func TestFloydWarshall(t *testing.T) {
FILE: graph/graph.go
type Graph (line 9) | type Graph struct
method AddVertex (line 24) | func (g *Graph) AddVertex(v int) {
method AddEdge (line 36) | func (g *Graph) AddEdge(one, two int) {
method AddWeightedEdge (line 42) | func (g *Graph) AddWeightedEdge(one, two, weight int) {
function New (line 16) | func New(v int) *Graph {
FILE: graph/graph_test.go
function TestDirectedGraph (line 58) | func TestDirectedGraph(t *testing.T) {
function TestUndirectedGraph (line 104) | func TestUndirectedGraph(t *testing.T) {
FILE: graph/kahn.go
function Kahn (line 15) | func Kahn(n int, dependencies [][]int) []int {
FILE: graph/kahn_test.go
function TestKahn (line 7) | func TestKahn(t *testing.T) {
FILE: graph/kosaraju.go
method Kosaraju (line 15) | func (g *Graph) Kosaraju() [][]int {
method fillOrder (line 50) | func (g *Graph) fillOrder(v int, visited []bool, stack *[]int) {
method transpose (line 64) | func (g *Graph) transpose() *Graph {
method dfs (line 83) | func (g *Graph) dfs(v int, visited []bool, scc *[]int) {
FILE: graph/kosaraju_test.go
function TestKosaraju (line 9) | func TestKosaraju(t *testing.T) {
function sortSlices (line 96) | func sortSlices(s [][]int) {
FILE: graph/kruskal.go
type Vertex (line 15) | type Vertex
type Edge (line 17) | type Edge struct
function KruskalMST (line 23) | func KruskalMST(n int, edges []Edge) ([]Edge, int) {
FILE: graph/kruskal_test.go
function TestKruskalMST (line 8) | func TestKruskalMST(t *testing.T) {
FILE: graph/lowestcommonancestor.go
type TreeEdge (line 14) | type TreeEdge struct
type ITree (line 19) | type ITree interface
type Tree (line 27) | type Tree struct
method addEdge (line 37) | func (tree *Tree) addEdge(u, v int) {
method dfs (line 42) | func (tree *Tree) dfs(u, par int) {
method GetDepth (line 53) | func (tree *Tree) GetDepth(u int) int {
method GetDad (line 57) | func (tree *Tree) GetDad(u int) int {
method GetLCA (line 61) | func (tree *Tree) GetLCA(u, v int) int {
function NewTree (line 86) | func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
function LowestCommonAncestor (line 113) | func LowestCommonAncestor(tree *Tree) {
FILE: graph/lowestcommonancestor_test.go
type Query (line 9) | type Query struct
function TestLCA (line 15) | func TestLCA(t *testing.T) {
function generateTree (line 149) | func generateTree() *Tree {
function generateQuery (line 203) | func generateQuery(tree *Tree) []Query {
function TestLCAWithLargeTree (line 233) | func TestLCAWithLargeTree(t *testing.T) {
FILE: graph/prim.go
type minEdge (line 12) | type minEdge
method Len (line 14) | func (h minEdge) Len() int { return len(h) }
method Less (line 15) | func (h minEdge) Less(i, j int) bool { return h[i].Weight < h[j].Weight }
method Swap (line 16) | func (h minEdge) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
method Push (line 18) | func (h *minEdge) Push(x interface{}) {
method Pop (line 22) | func (h *minEdge) Pop() interface{} {
method PrimMST (line 30) | func (g *Graph) PrimMST(start Vertex) ([]Edge, int) {
FILE: graph/prim_test.go
function TestPrimMST (line 9) | func TestPrimMST(t *testing.T) {
FILE: graph/topological.go
function Topological (line 14) | func Topological(N int, constraints [][]int) []int {
FILE: graph/topological_test.go
function TestTopological (line 36) | func TestTopological(t *testing.T) {
FILE: graph/unionfind.go
type UnionFind (line 19) | type UnionFind struct
method Find (line 37) | func (u *UnionFind) Find(q int) int {
method Union (line 46) | func (u *UnionFind) Union(p, q int) {
function NewUnionFind (line 25) | func NewUnionFind(s int) UnionFind {
FILE: graph/unionfind_test.go
function TestUnionFind (line 7) | func TestUnionFind(t *testing.T) {
FILE: hashing/md5/md5.go
function leftRotate (line 43) | func leftRotate(x, n uint32) uint32 {
function pad (line 48) | func pad(message []byte) []byte {
function Hash (line 63) | func Hash(message []byte) [16]byte {
FILE: hashing/md5/md5_test.go
function toHexString (line 13) | func toHexString(hash [16]byte) string {
function TestHash (line 32) | func TestHash(t *testing.T) {
FILE: hashing/sha1/sha1.go
constant h0 (line 15) | h0 uint32 = 0x67452301
constant h1 (line 16) | h1 uint32 = 0xEFCDAB89
constant h2 (line 17) | h2 uint32 = 0x98BADCFE
constant h3 (line 18) | h3 uint32 = 0x10325476
constant h4 (line 19) | h4 uint32 = 0xC3D2E1F0
function pad (line 23) | func pad(message []byte) []byte {
function leftRotate (line 38) | func leftRotate(x, n uint32) uint32 {
function Hash (line 43) | func Hash(message []byte) [20]byte {
FILE: hashing/sha1/sha1_test.go
function toHexString (line 13) | func toHexString(hash [20]byte) string {
function TestHash (line 32) | func TestHash(t *testing.T) {
FILE: hashing/sha256/sha256.go
constant chunkSize (line 28) | chunkSize = 64
function pad (line 37) | func pad(message []byte) []byte {
function Hash (line 52) | func Hash(message []byte) [32]byte {
FILE: hashing/sha256/sha256_test.go
function TestHash (line 8) | func TestHash(t *testing.T) {
function BenchmarkHash (line 29) | func BenchmarkHash(b *testing.B) {
FILE: math/abs.go
function Abs (line 11) | func Abs(n int) int {
FILE: math/abs_test.go
function TestAbs (line 9) | func TestAbs(t *testing.T) {
function getTests (line 20) | func getTests() []struct {
function BenchmarkSimpleAbs (line 40) | func BenchmarkSimpleAbs(b *testing.B) {
function BenchmarkBinaryAbs32 (line 45) | func BenchmarkBinaryAbs32(b *testing.B) {
function BenchmarkBinaryAbs64 (line 51) | func BenchmarkBinaryAbs64(b *testing.B) {
function BenchmarkStdLibAbs (line 57) | func BenchmarkStdLibAbs(b *testing.B) {
FILE: math/aliquot_test.go
function TestAliquotSum (line 14) | func TestAliquotSum(t *testing.T) {
function BenchmarkAliquotSum (line 36) | func BenchmarkAliquotSum(b *testing.B) {
FILE: math/aliquotsum.go
function AliquotSum (line 16) | func AliquotSum(n int) (int, error) {
FILE: math/armstrong/isarmstrong.go
function IsArmstrong (line 16) | func IsArmstrong(number int) bool {
FILE: math/armstrong/isarmstrong_test.go
function TestIsArmstrong (line 44) | func TestIsArmstrong(t *testing.T) {
FILE: math/binary/abs.go
function Abs (line 15) | func Abs(base, n int) int {
FILE: math/binary/abs_test.go
function TestAbs (line 5) | func TestAbs(t *testing.T) {
function getAbsTests (line 16) | func getAbsTests() []struct {
FILE: math/binary/arithmeticmean.go
function MeanUsingAndXor (line 14) | func MeanUsingAndXor(a int, b int) int {
function MeanUsingRightShift (line 19) | func MeanUsingRightShift(a int, b int) int {
FILE: math/binary/arithmeticmean_test.go
function TestMeanUsingAndXor (line 10) | func TestMeanUsingAndXor(t *testing.T) {
function TestMeanUsingRightShift (line 23) | func TestMeanUsingRightShift(t *testing.T) {
function getTests (line 35) | func getTests() []struct {
function BenchmarkMeanUsingAndXor (line 55) | func BenchmarkMeanUsingAndXor(b *testing.B) {
function BenchmarkMeanUsingRightShift (line 61) | func BenchmarkMeanUsingRightShift(b *testing.B) {
FILE: math/binary/bitcounter.go
function BitCounter (line 13) | func BitCounter(n uint) int {
FILE: math/binary/bitcounter_test.go
function TestBitCounter (line 10) | func TestBitCounter(t *testing.T) {
FILE: math/binary/checkisnumberpoweroftwo.go
function IsPowerOfTwo (line 23) | func IsPowerOfTwo(x int) bool {
function IsPowerOfTwoLeftShift (line 30) | func IsPowerOfTwoLeftShift(number uint) bool {
FILE: math/binary/checkisnumberpoweroftwo_test.go
function getTestsForPowerOfTwo (line 14) | func getTestsForPowerOfTwo() []struct {
function TestIsPowerOfTwo (line 38) | func TestIsPowerOfTwo(t *testing.T) {
function TestIsPowerOfTwoLeftShift (line 51) | func TestIsPowerOfTwoLeftShift(t *testing.T) {
function TestIsPowOfTwoUseLog (line 64) | func TestIsPowOfTwoUseLog(t *testing.T) {
function BenchmarkIsPowerOfTwoBinaryMethod (line 77) | func BenchmarkIsPowerOfTwoBinaryMethod(b *testing.B) {
function BenchmarkIsPowerOfTwoUseCycleAndLeftShift (line 83) | func BenchmarkIsPowerOfTwoUseCycleAndLeftShift(b *testing.B) {
function BenchmarkIsPowerOfTwoUseLog (line 89) | func BenchmarkIsPowerOfTwoUseLog(b *testing.B) {
FILE: math/binary/fast_inverse_sqrt.go
function FastInverseSqrt (line 17) | func FastInverseSqrt(number float32) float32 {
FILE: math/binary/logarithm.go
function LogBase2 (line 9) | func LogBase2(n uint32) uint32 {
FILE: math/binary/logarithm_test.go
function TestLogBase2 (line 13) | func TestLogBase2(t *testing.T) {
function BenchmarkBitwiseLogBase2 (line 38) | func BenchmarkBitwiseLogBase2(b *testing.B) {
function BenchmarkMathPAckageLogBase2 (line 44) | func BenchmarkMathPAckageLogBase2(b *testing.B) {
FILE: math/binary/rbc.go
function SequenceGrayCode (line 13) | func SequenceGrayCode(n uint) []uint {
FILE: math/binary/rbc_test.go
function TestSequenceGrayCode (line 13) | func TestSequenceGrayCode(t *testing.T) {
function BenchmarkSequenceGrayCode (line 33) | func BenchmarkSequenceGrayCode(b *testing.B) {
FILE: math/binary/reversebits.go
function ReverseBits (line 16) | func ReverseBits(number uint) uint {
FILE: math/binary/reversebits_test.go
function TestReverseBits (line 10) | func TestReverseBits(t *testing.T) {
function BenchmarkReverseBits (line 33) | func BenchmarkReverseBits(b *testing.B) {
FILE: math/binary/sqrt.go
function Sqrt (line 12) | func Sqrt(n float32) float32 { return 1 / FastInverseSqrt(n) }
FILE: math/binary/sqrt_test.go
constant epsilon (line 13) | epsilon = 0.001
function TestSquareRootCalculation (line 15) | func TestSquareRootCalculation(t *testing.T) {
function BenchmarkSquareRootCalculation (line 40) | func BenchmarkSquareRootCalculation(b *testing.B) {
function BenchmarkMathSqrt (line 46) | func BenchmarkMathSqrt(b *testing.B) {
FILE: math/binary/xorsearch.go
function XorSearchMissingNumber (line 13) | func XorSearchMissingNumber(a []int) int {
FILE: math/binary/xorsearch_test.go
function TestXorSearchMissingNumber (line 12) | func TestXorSearchMissingNumber(t *testing.T) {
function BenchmarkTestXorSearchMissingNumber (line 35) | func BenchmarkTestXorSearchMissingNumber(b *testing.B) {
FILE: math/binomialcoefficient.go
function Combinations (line 22) | func Combinations(n int, k int) (int, error) {
FILE: math/binomialcoefficient_test.go
function TestCombinations (line 14) | func TestCombinations(t *testing.T) {
function BenchmarkCombinations (line 38) | func BenchmarkCombinations(b *testing.B) {
FILE: math/catalan/catalannumber.go
function factorial (line 17) | func factorial(n int) int {
function CatalanNumber (line 26) | func CatalanNumber(n int) int {
FILE: math/catalan/catalannumber_test.go
function TestCatalanNumber (line 10) | func TestCatalanNumber(t *testing.T) {
function BenchmarkCatalanNumber (line 33) | func BenchmarkCatalanNumber(b *testing.B) {
FILE: math/checkisnumberpoweroftwo.go
function IsPowOfTwoUseLog (line 10) | func IsPowOfTwoUseLog(number float64) bool {
FILE: math/checkisnumberpoweroftwo_test.go
function getTestsForPowerOfTwo (line 13) | func getTestsForPowerOfTwo() []struct {
function TestIsPowOfTwoUseLog (line 37) | func TestIsPowOfTwoUseLog(t *testing.T) {
function BenchmarkIsPowerOfTwoUseLog (line 50) | func BenchmarkIsPowerOfTwoUseLog(b *testing.B) {
FILE: math/cos.go
function Cos (line 10) | func Cos(x float64) float64 {
FILE: math/cos_test.go
constant epsilon (line 9) | epsilon = 0.001
function TestCos (line 11) | func TestCos(t *testing.T) {
function BenchmarkCos (line 35) | func BenchmarkCos(b *testing.B) {
function BenchmarkMathCos (line 42) | func BenchmarkMathCos(b *testing.B) {
FILE: math/eulertotient.go
function Phi (line 5) | func Phi(n int64) int64 {
FILE: math/eulertotient_test.go
function getTestsForPhi (line 7) | func getTestsForPhi() []struct {
function TestPhi (line 28) | func TestPhi(t *testing.T) {
function BenchmarkPhi (line 40) | func BenchmarkPhi(b *testing.B) {
FILE: math/factorial/factorial.go
function Iterative (line 20) | func Iterative(n int) (int, error) {
function Recursive (line 32) | func Recursive(n int) (int, error) {
function UsingTree (line 44) | func UsingTree(n int) (int, error) {
function prodTree (line 57) | func prodTree(l int, r int) int {
FILE: math/factorial/factorial_test.go
type factorialFun (line 10) | type factorialFun
function TestFactorial (line 37) | func TestFactorial(t *testing.T) {
function BenchmarkFactorial (line 59) | func BenchmarkFactorial(b *testing.B) {
FILE: math/fibonacci/fibonacci.go
function Matrix (line 17) | func Matrix(n uint) uint {
function Formula (line 44) | func Formula(n uint) uint {
function Recursive (line 53) | func Recursive(n uint) uint {
FILE: math/fibonacci/fibonacci_test.go
function getTests (line 8) | func getTests() []struct {
function TestMatrix (line 34) | func TestMatrix(t *testing.T) {
function TestNthFibonacci (line 45) | func TestNthFibonacci(t *testing.T) {
function TestFormula (line 56) | func TestFormula(t *testing.T) {
function TestRecursive (line 67) | func TestRecursive(t *testing.T) {
function BenchmarkNthFibonacci (line 80) | func BenchmarkNthFibonacci(b *testing.B) {
function BenchmarkMatrix (line 86) | func BenchmarkMatrix(b *testing.B) {
function BenchmarkFormula (line 92) | func BenchmarkFormula(b *testing.B) {
FILE: math/gcd/extended.go
function Extended (line 14) | func Extended(a, b int64) (int64, int64, int64) {
FILE: math/gcd/extended_test.go
function TestExtended (line 10) | func TestExtended(t *testing.T) {
FILE: math/gcd/extendedgcd.go
function ExtendedRecursive (line 9) | func ExtendedRecursive(a, b int64) (int64, int64, int64) {
FILE: math/gcd/extendedgcd_test.go
type testExtendedFunction (line 5) | type testExtendedFunction
function TemplateTestExtendedGCD (line 7) | func TemplateTestExtendedGCD(t *testing.T, f testExtendedFunction) {
function TestExtendedGCDRecursive (line 36) | func TestExtendedGCDRecursive(t *testing.T) {
function TestExtendedGCDIterative (line 40) | func TestExtendedGCDIterative(t *testing.T) {
function TemplateBenchmarkExtendedGCD (line 44) | func TemplateBenchmarkExtendedGCD(b *testing.B, f testExtendedFunction) {
function BenchmarkExtendedGCDRecursive (line 50) | func BenchmarkExtendedGCDRecursive(b *testing.B) {
function BenchmarkExtendedGCDIterative (line 54) | func BenchmarkExtendedGCDIterative(b *testing.B) {
FILE: math/gcd/extendedgcditerative.go
function ExtendedIterative (line 4) | func ExtendedIterative(a, b int64) (int64, int64, int64) {
FILE: math/gcd/gcd.go
function Recursive (line 7) | func Recursive(a, b int64) int64 {
FILE: math/gcd/gcd_test.go
type testFunction (line 5) | type testFunction
function TemplateTestGCD (line 18) | func TemplateTestGCD(t *testing.T, f testFunction) {
function TestGCDRecursive (line 29) | func TestGCDRecursive(t *testing.T) {
function TestGCDIterative (line 33) | func TestGCDIterative(t *testing.T) {
function TemplateBenchmarkGCD (line 37) | func TemplateBenchmarkGCD(b *testing.B, f testFunction) {
function BenchmarkGCDRecursive (line 43) | func BenchmarkGCDRecursive(b *testing.B) {
function BenchmarkGCDIterative (line 47) | func BenchmarkGCDIterative(b *testing.B) {
FILE: math/gcd/gcditerative.go
function Iterative (line 7) | func Iterative(a, b int64) int64 {
FILE: math/geometry/distance.go
type EuclideanPoint (line 16) | type EuclideanPoint
function EuclideanDistance (line 22) | func EuclideanDistance(p1 EuclideanPoint, p2 EuclideanPoint) (float64, e...
FILE: math/geometry/distance_test.go
type args (line 10) | type args struct
function TestFindDistanceBetweenTwoPoints (line 15) | func TestFindDistanceBetweenTwoPoints(t *testing.T) {
function BenchmarkFindDistanceBetweenTwoPoints (line 73) | func BenchmarkFindDistanceBetweenTwoPoints(b *testing.B) {
FILE: math/geometry/straightlines.go
type Point (line 9) | type Point struct
type Line (line 13) | type Line struct
function Distance (line 18) | func Distance(a, b *Point) float64 {
function Section (line 24) | func Section(p1, p2 *Point, r float64) Point {
function Slope (line 32) | func Slope(l *Line) float64 {
function YIntercept (line 37) | func YIntercept(p *Point, slope float64) float64 {
function IsParallel (line 42) | func IsParallel(l1, l2 *Line) bool {
function IsPerpendicular (line 47) | func IsPerpendicular(l1, l2 *Line) bool {
function PointDistance (line 53) | func PointDistance(p *Point, equation [3]float64) float64 {
FILE: math/geometry/straightlines_test.go
function TestDistance (line 7) | func TestDistance(t *testing.T) {
function TestSection (line 17) | func TestSection(t *testing.T) {
function TestSlope (line 27) | func TestSlope(t *testing.T) {
function TestIntercept (line 36) | func TestIntercept(t *testing.T) {
function TestIsParallel (line 46) | func TestIsParallel(t *testing.T) {
function TestIsPerpendicular (line 54) | func TestIsPerpendicular(t *testing.T) {
function TestPointDistance (line 62) | func TestPointDistance(t *testing.T) {
FILE: math/isautomorphic.go
function IsAutomorphic (line 16) | func IsAutomorphic[T constraints.Integer](n T) bool {
FILE: math/isautomorphic_test.go
function TestIsAutomorphic (line 49) | func TestIsAutomorphic(t *testing.T) {
FILE: math/krishnamurthy.go
function IsKrishnamurthyNumber (line 14) | func IsKrishnamurthyNumber[T constraints.Integer](n T) bool {
FILE: math/krishnamurthy_test.go
function retCases (line 8) | func retCases() []struct {
function TestIsKrishnamurthyNumber (line 32) | func TestIsKrishnamurthyNumber(t *testing.T) {
function BenchmarkIsKrishnamurthyNumber (line 43) | func BenchmarkIsKrishnamurthyNumber(b *testing.B) {
FILE: math/kthnumber.go
function FindKthMax (line 11) | func FindKthMax(nums []int, k int) (int, error) {
function FindKthMin (line 19) | func FindKthMin(nums []int, k int) (int, error) {
function kthNumber (line 25) | func kthNumber(nums []int, k int) (int, error) {
FILE: math/kthnumber_test.go
function TestFindKthMax (line 8) | func TestFindKthMax(t *testing.T) {
function TestFindKthMin (line 57) | func TestFindKthMin(t *testing.T) {
FILE: math/lcm/lcm.go
function Lcm (line 10) | func Lcm(a, b int64) int64 {
FILE: math/lcm/lcm_test.go
function TestLcm (line 5) | func TestLcm(t *testing.T) {
FILE: math/lerp.go
function Lerp (line 5) | func Lerp(v0, v1, t float64) float64 {
FILE: math/lerp_test.go
function TestLerp (line 9) | func TestLerp(t *testing.T) {
FILE: math/liouville.go
function LiouvilleLambda (line 26) | func LiouvilleLambda(n int) (int, error) {
FILE: math/liouville_test.go
function TestLiouvilleLambda (line 14) | func TestLiouvilleLambda(t *testing.T) {
function BenchmarkLiouvilleLambda (line 35) | func BenchmarkLiouvilleLambda(b *testing.B) {
FILE: math/matrix/add.go
method Add (line 15) | func (m1 Matrix[T]) Add(m2 Matrix[T]) (Matrix[T], error) {
FILE: math/matrix/add_test.go
function TestAdd (line 10) | func TestAdd(t *testing.T) {
function BenchmarkAddSmallMatrix (line 39) | func BenchmarkAddSmallMatrix(b *testing.B) {
function BenchmarkAddLargeMatrix (line 48) | func BenchmarkAddLargeMatrix(b *testing.B) {
FILE: math/matrix/checkequal.go
method CheckEqual (line 9) | func (m1 Matrix[T]) CheckEqual(m2 Matrix[T]) bool {
FILE: math/matrix/checkequal_test.go
function TestCheckEqual (line 9) | func TestCheckEqual(t *testing.T) {
function BenchmarkCheckEqualSmallMatrix (line 43) | func BenchmarkCheckEqualSmallMatrix(b *testing.B) {
function BenchmarkCheckEqualLargeMatrix (line 52) | func BenchmarkCheckEqualLargeMatrix(b *testing.B) {
FILE: math/matrix/copy.go
method Copy (line 11) | func (m Matrix[T]) Copy() (Matrix[T], error) {
FILE: math/matrix/copy_test.go
function TestMatrixCopy (line 9) | func TestMatrixCopy(t *testing.T) {
function TestMatrixCopyEmpty (line 45) | func TestMatrixCopyEmpty(t *testing.T) {
function TestMatrixCopyWithDefaultValues (line 66) | func TestMatrixCopyWithDefaultValues(t *testing.T) {
function BenchmarkCopyMatrix (line 101) | func BenchmarkCopyMatrix(b *testing.B) {
FILE: math/matrix/determinant.go
method Determinant (line 18) | func (mat Matrix[T]) Determinant() (T, error) {
FILE: math/matrix/determinant_test.go
function TestMatrixDeterminant (line 13) | func TestMatrixDeterminant(t *testing.T) {
function TestEmptyMatrix (line 48) | func TestEmptyMatrix(t *testing.T) {
function TestNonSquareMatrix (line 70) | func TestNonSquareMatrix(t *testing.T) {
function TestDefaultMatrix (line 99) | func TestDefaultMatrix(t *testing.T) {
function BenchmarkSmallMatrixDeterminant (line 117) | func BenchmarkSmallMatrixDeterminant(b *testing.B) {
function BenchmarkMatrixDeterminant (line 130) | func BenchmarkMatrixDeterminant(b *testing.B) {
FILE: math/matrix/isvalid.go
function IsValid (line 6) | func IsValid[T constraints.Integer](elements [][]T) bool {
FILE: math/matrix/isvalid_test.go
function TestIsValid (line 9) | func TestIsValid(t *testing.T) {
function BenchmarkIsValid (line 45) | func BenchmarkIsValid(b *testing.B) {
FILE: math/matrix/matchdimensions.go
method MatchDimensions (line 4) | func (m Matrix[T]) MatchDimensions(m1 Matrix[T]) bool {
FILE: math/matrix/matchdimensions_test.go
function TestMatrixMatchDimensions (line 9) | func TestMatrixMatchDimensions(t *testing.T) {
function BenchmarkMatchDimensions (line 30) | func BenchmarkMatchDimensions(b *testing.B) {
FILE: math/matrix/matrix.go
type Matrix (line 10) | type Matrix struct
function New (line 17) | func New[T constraints.Integer](rows, columns int, initial T) Matrix[T] {
function NewFromElements (line 43) | func NewFromElements[T constraints.Integer](elements [][]T) (Matrix[T], ...
method Get (line 66) | func (m Matrix[T]) Get(row, col int) (T, error) {
method Set (line 74) | func (m Matrix[T]) Set(row, col int, val T) error {
method Rows (line 83) | func (m Matrix[T]) Rows() int {
method Columns (line 87) | func (m Matrix[T]) Columns() int {
FILE: math/matrix/matrix_test.go
function TestNewMatrix (line 10) | func TestNewMatrix(t *testing.T) {
function TestNewFromElements (line 24) | func TestNewFromElements(t *testing.T) {
function TestMatrixGet (line 71) | func TestMatrixGet(t *testing.T) {
function TestMatrixSet (line 101) | func TestMatrixSet(t *testing.T) {
function TestMatrixRows (line 132) | func TestMatrixRows(t *testing.T) {
function TestMatrixColumns (line 147) | func TestMatrixColumns(t *testing.T) {
function TestMatrixEmptyRowsAndColumns (line 162) | func TestMatrixEmptyRowsAndColumns(t *testing.T) {
function BenchmarkNew (line 180) | func BenchmarkNew(b *testing.B) {
function BenchmarkNewFromElements (line 187) | func BenchmarkNewFromElements(b *testing.B) {
function BenchmarkGet (line 205) | func BenchmarkGet(b *testing.B) {
function BenchmarkSet (line 217) | func BenchmarkSet(b *testing.B) {
function BenchmarkRows (line 229) | func BenchmarkRows(b *testing.B) {
function BenchmarkColumns (line 241) | func BenchmarkColumns(b *testing.B) {
FILE: math/matrix/multiply.go
method Multiply (line 15) | func (m1 Matrix[T]) Multiply(m2 Matrix[T]) (Matrix[T], error) {
FILE: math/matrix/multiply_test.go
function TestMultiplyMatrix (line 9) | func TestMultiplyMatrix(t *testing.T) {
function TestMultiplyIncompatibleMatrix (line 52) | func TestMultiplyIncompatibleMatrix(t *testing.T) {
function BenchmarkMatrixMultiply (line 91) | func BenchmarkMatrixMultiply(b *testing.B) {
FILE: math/matrix/strassenmatrixmultiply.go
method StrassenMatrixMultiply (line 14) | func (A Matrix[T]) StrassenMatrixMultiply(B Matrix[T]) (Matrix[T], error) {
FILE: math/matrix/strassenmatrixmultiply_test.go
function TestStrassenMatrixMultiply (line 12) | func TestStrassenMatrixMultiply(t *testing.T) {
function TestMatrixMultiplication (line 68) | func TestMatrixMultiplication(t *testing.T) {
function MakeRandomMatrix (line 105) | func MakeRandomMatrix[T constraints.Integer](rows, columns int) matrix.M...
function BenchmarkStrassenMatrixMultiply (line 121) | func BenchmarkStrassenMatrixMultiply(b *testing.B) {
FILE: math/matrix/string.go
method String (line 6) | func (m Matrix[T]) String() string {
FILE: math/matrix/string_test.go
function TestMatrixString (line 13) | func TestMatrixString(t *testing.T) {
function TestNullMatrixString (line 52) | func TestNullMatrixString(t *testing.T) {
function BenchmarkString (line 87) | func BenchmarkString(b *testing.B) {
FILE: math/matrix/submatrix.go
method SubMatrix (line 10) | func (m Matrix[T]) SubMatrix(rowStart, colStart, numRows, numCols int) (...
FILE: math/matrix/submatrix_test.go
function TestMatrixSubMatrix (line 9) | func TestMatrixSubMatrix(t *testing.T) {
function TestMatrixInvalidSubMatrix (line 51) | func TestMatrixInvalidSubMatrix(t *testing.T) {
function BenchmarkSubMatrix (line 74) | func BenchmarkSubMatrix(b *testing.B) {
FILE: math/matrix/subtract.go
method Subtract (line 10) | func (m1 Matrix[T]) Subtract(m2 Matrix[T]) (Matrix[T], error) {
FILE: math/matrix/subtract_test.go
function TestSubtract (line 10) | func TestSubtract(t *testing.T) {
function BenchmarkSubtract (line 40) | func BenchmarkSubtract(b *testing.B) {
FILE: math/max/bitwisemax.go
function Bitwise (line 13) | func Bitwise(a int, b int, base int) int {
FILE: math/max/bitwisemax_test.go
function TestBitwiseMax (line 10) | func TestBitwiseMax(t *testing.T) {
FILE: math/max/max.go
function Int (line 6) | func Int[T constraints.Integer](values ...T) T {
FILE: math/max/max_test.go
function TestMax (line 5) | func TestMax(t *testing.T) {
function TestMaxOfThree (line 37) | func TestMaxOfThree(t *testing.T) {
FILE: math/mean.go
function Mean (line 7) | func Mean[T constraints.Number](values []T) float64 {
FILE: math/mean_test.go
function TestMean (line 8) | func TestMean(t *testing.T) {
FILE: math/median.go
function Median (line 14) | func Median[T constraints.Number](values []T) float64 {
FILE: math/median_test.go
function TestMedian (line 13) | func TestMedian(t *testing.T) {
FILE: math/min/bitwisemin.go
function Bitwise (line 11) | func Bitwise(base int, value int, values ...int) int {
FILE: math/min/min.go
function Int (line 6) | func Int[T constraints.Integer](values ...T) T {
FILE: math/min/min_test.go
function getTestCases (line 7) | func getTestCases() []struct {
function TestBitwiseMin (line 29) | func TestBitwiseMin(t *testing.T) {
function TestMin (line 41) | func TestMin(t *testing.T) {
function BenchmarkTestMinInt (line 52) | func BenchmarkTestMinInt(b *testing.B) {
function BenchmarkTestBitwiseMin (line 58) | func BenchmarkTestBitwiseMin(b *testing.B) {
FILE: math/mobius.go
function Mu (line 23) | func Mu(n int) int {
FILE: math/mobius_test.go
function TestMu (line 14) | func TestMu(t *testing.T) {
function BenchmarkMu (line 37) | func BenchmarkMu(b *testing.B) {
FILE: math/mode.go
function Mode (line 21) | func Mode[T constraints.Number](numbers []T) (T, error) {
FILE: math/mode_test.go
type testCase (line 15) | type testCase struct
function testModeFramework (line 22) | func testModeFramework[T constraints.Number](t *testing.T, testCases []t...
function TestMode (line 37) | func TestMode(t *testing.T) {
FILE: math/modular/exponentiation.go
function Exponentiation (line 24) | func Exponentiation(base, exponent, mod int64) (int64, error) {
function Multiply64BitInt (line 53) | func Multiply64BitInt(left, right int64) (int64, error) {
FILE: math/modular/exponentiation_test.go
type cases (line 10) | type cases struct
function TestExponentiation (line 68) | func TestExponentiation(t *testing.T) {
function BenchmarkExponentiation (line 85) | func BenchmarkExponentiation(b *testing.B) {
FILE: math/modular/inverse.go
function Inverse (line 21) | func Inverse(a, m int64) (int64, error) {
FILE: math/modular/inverse_test.go
function TestInverse (line 11) | func TestInverse(t *testing.T) {
FILE: math/moserdebruijnsequence/sequence.go
function MoserDeBruijnSequence (line 9) | func MoserDeBruijnSequence(number int) []int {
function generateNthTerm (line 20) | func generateNthTerm(num int) int {
FILE: math/moserdebruijnsequence/sequence_test.go
function TestMoserDeBruijnSequence (line 16) | func TestMoserDeBruijnSequence(t *testing.T) {
FILE: math/pascal/pascaltriangle.go
function GenerateTriangle (line 26) | func GenerateTriangle(n int) [][]int {
FILE: math/pascal/pascaltriangle_test.go
function TestGenerateTriangle (line 13) | func TestGenerateTriangle(t *testing.T) {
function BenchmarkGenerateTriangle (line 33) | func BenchmarkGenerateTriangle(b *testing.B) {
FILE: math/perfectnumber.go
function SumOfProperDivisors (line 19) | func SumOfProperDivisors(inNumber uint) uint {
function IsPerfectNumber (line 36) | func IsPerfectNumber(inNumber uint) bool {
FILE: math/perfectnumber_test.go
type testCaseSumOfProperDivisors (line 9) | type testCaseSumOfProperDivisors struct
function getSumOfProperDivisorsTestCases (line 18) | func getSumOfProperDivisorsTestCases() []testCaseSumOfProperDivisors {
function TestSumOfProperDivisors (line 91) | func TestSumOfProperDivisors(t *testing.T) {
function BenchmarkSumOfProperDivisors (line 102) | func BenchmarkSumOfProperDivisors(b *testing.B) {
type isPerfectNumberTestCase (line 108) | type isPerfectNumberTestCase struct
function getIsPerfectNumberTestCases (line 117) | func getIsPerfectNumberTestCases() []isPerfectNumberTestCase {
function TestIsPerfectNumber (line 139) | func TestIsPerfectNumber(t *testing.T) {
function BenchmarkIsPerfectNumber (line 147) | func BenchmarkIsPerfectNumber(b *testing.B) {
FILE: math/permutation/heaps.go
function Heaps (line 13) | func Heaps(out chan []string, n int) {
function GenerateElementSet (line 42) | func GenerateElementSet(out chan []string, n int) {
FILE: math/permutation/heaps_test.go
function TestHeaps (line 9) | func TestHeaps(t *testing.T) {
FILE: math/permutation/next_permutation.go
function NextPermutation (line 10) | func NextPermutation(nums []int) {
FILE: math/permutation/next_permutation_test.go
function TestNextPermutation (line 8) | func TestNextPermutation(t *testing.T) {
FILE: math/pi/montecarlopi.go
function MonteCarloPi (line 19) | func MonteCarloPi(randomPoints int) float64 {
function MonteCarloPiConcurrent (line 38) | func MonteCarloPiConcurrent(n int) (float64, error) {
function drawPoints (line 61) | func drawPoints(n int, c chan<- int) {
function splitInt (line 76) | func splitInt(x int, n int) ([]int, error) {
FILE: math/pi/montecarlopi_test.go
function TestMonteCarloPi (line 13) | func TestMonteCarloPi(t *testing.T) {
function BenchmarkMonteCarloPi (line 23) | func BenchmarkMonteCarloPi(b *testing.B) {
function TestSplitInt (line 29) | func TestSplitInt(t *testing.T) {
function TestMonteCarloPi2 (line 64) | func TestMonteCarloPi2(t *testing.T) {
function BenchmarkMonteCarloPi2 (line 76) | func BenchmarkMonteCarloPi2(b *testing.B) {
FILE: math/pi/spigotpi.go
function Spigot (line 14) | func Spigot(n int) string {
function delChar (line 58) | func delChar(s string, index int) string {
FILE: math/pi/spigotpi_test.go
function TestSpigot (line 12) | func TestSpigot(t *testing.T) {
function BenchmarkPiSpigotN10 (line 44) | func BenchmarkPiSpigotN10(b *testing.B) {
function BenchmarkPiSpigotN100 (line 50) | func BenchmarkPiSpigotN100(b *testing.B) {
function BenchmarkPiSpigotN1000 (line 56) | func BenchmarkPiSpigotN1000(b *testing.B) {
FILE: math/pollard.go
function DefaultPolynomial (line 18) | func DefaultPolynomial(n *big.Int) func(*big.Int) *big.Int {
function PollardsRhoFactorization (line 31) | func PollardsRhoFactorization(n *big.Int, f func(n *big.Int) func(x *big...
FILE: math/pollard_test.go
function TestDefaultPolynomial (line 14) | func TestDefaultPolynomial(t *testing.T) {
function TestRho (line 35) | func TestRho(t *testing.T) {
function BenchmarkDefaultPolynomial (line 66) | func BenchmarkDefaultPolynomial(b *testing.B) {
function BenchmarkRho (line 72) | func BenchmarkRho(b *testing.B) {
FILE: math/power/fastexponent.go
function IterativePower (line 4) | func IterativePower(n uint, power uint) uint {
function RecursivePower (line 18) | func RecursivePower(n uint, power uint) uint {
function RecursivePower1 (line 30) | func RecursivePower1(n uint, power uint) uint {
FILE: math/power/fastexponent_test.go
function TestIterativePower (line 18) | func TestIterativePower(t *testing.T) {
function TestRecursivePower (line 29) | func TestRecursivePower(t *testing.T) {
function TestRecursivePower1 (line 40) | func TestRecursivePower1(t *testing.T) {
function BenchmarkIterativePower (line 51) | func BenchmarkIterativePower(b *testing.B) {
function BenchmarkRecursivePower (line 57) | func BenchmarkRecursivePower(b *testing.B) {
function BenchmarkRecursivePower1 (line 63) | func BenchmarkRecursivePower1(b *testing.B) {
FILE: math/power/powvialogarithm.go
function UsingLog (line 16) | func UsingLog(a float64, b float64) float64 {
FILE: math/power/powvialogarithm_test.go
function TestUsingLog (line 10) | func TestUsingLog(t *testing.T) {
function BenchmarkUsingLog (line 40) | func BenchmarkUsingLog(b *testing.B) {
FILE: math/prime/millerrabintest.go
function formatNum (line 21) | func formatNum(num int64) (d int64, s int64) {
function isTrivial (line 33) | func isTrivial(num int64) (prime bool, trivial bool) {
function MillerTest (line 50) | func MillerTest(num, witness int64) (bool, error) {
function MillerRandomTest (line 78) | func MillerRandomTest(num int64) (bool, error) {
function MillerTestMultiple (line 85) | func MillerTestMultiple(num int64, witnesses ...int64) (bool, error) {
function MillerRabinProbabilistic (line 102) | func MillerRabinProbabilistic(num, rounds int64) (bool, error) {
function MillerRabinDeterministic (line 122) | func MillerRabinDeterministic(num int64) (bool, error) {
FILE: math/prime/prime_test.go
type primalityTest (line 11) | type primalityTest
function primalityTestTestingHelper (line 13) | func primalityTestTestingHelper(t *testing.T, name string, f primalityTe...
function primalityTestBenchmarkHelper (line 33) | func primalityTestBenchmarkHelper(b *testing.B, f primalityTest) {
function millerRabinProbabilisticTester (line 41) | func millerRabinProbabilisticTester(n int64) bool {
function TestMillerRabinProbabilistic (line 50) | func TestMillerRabinProbabilistic(t *testing.T) {
function BenchmarkMillerRabinProbabilistic (line 54) | func BenchmarkMillerRabinProbabilistic(b *testing.B) {
function millerRabinDeterministicTester (line 60) | func millerRabinDeterministicTester(n int64) bool {
function TestMillerRabinDeterministic (line 69) | func TestMillerRabinDeterministic(t *testing.T) {
function BenchmarkMillerRabinDeterministic (line 73) | func BenchmarkMillerRabinDeterministic(b *testing.B) {
function TestTrialDivision (line 79) | func TestTrialDivision(t *testing.T) {
function BenchmarkTrialDivision (line 83) | func BenchmarkTrialDivision(b *testing.B) {
function TestOptimizedTrialDivision (line 89) | func TestOptimizedTrialDivision(t *testing.T) {
function BenchmarkOptimizedTrialDivision (line 93) | func BenchmarkOptimizedTrialDivision(b *testing.B) {
FILE: math/prime/primecheck.go
function TrialDivision (line 11) | func TrialDivision(n int64) bool {
function OptimizedTrialDivision (line 28) | func OptimizedTrialDivision(n int64) bool {
FILE: math/prime/primefactorization.go
function Factorize (line 10) | func Factorize(n int64) map[int64]int64 {
FILE: math/prime/primefactorization_test.go
function TestFactorize (line 8) | func TestFactorize(t *testing.T) {
function BenchmarkFactorize (line 29) | func BenchmarkFactorize(b *testing.B) {
FILE: math/prime/sieve.go
function GenerateChannel (line 9) | func GenerateChannel(ch chan<- int) {
function Sieve (line 16) | func Sieve(in <-chan int, out chan<- int, prime int) {
function Generate (line 26) | func Generate(limit int) []int {
FILE: math/prime/sieve2.go
function SieveEratosthenes (line 9) | func SieveEratosthenes(limit int) []int {
FILE: math/prime/sieve2_test.go
function TestSieveEratosthenes (line 10) | func TestSieveEratosthenes(t *testing.T) {
function BenchmarkSieveEratosthenes (line 39) | func BenchmarkSieveEratosthenes(b *testing.B) {
FILE: math/prime/sieve_test.go
function TestSieve (line 13) | func TestSieve(t *testing.T) {
function TestGeneratePrimes (line 36) | func TestGeneratePrimes(t *testing.T) {
function BenchmarkSieve10 (line 48) | func BenchmarkSieve10(b *testing.B) {
FILE: math/prime/twin.go
function Twin (line 17) | func Twin(n int) (int, bool) {
FILE: math/prime/twin_test.go
function TestTwin (line 14) | func TestTwin(t *testing.T) {
function BenchmarkTwin (line 35) | func BenchmarkTwin(b *testing.B) {
FILE: math/pronicnumber.go
function PronicNumber (line 17) | func PronicNumber(n int) bool {
FILE: math/pronicnumber_test.go
function TestPronicNumber (line 13) | func TestPronicNumber(t *testing.T) {
function BenchmarkPronicNumber (line 434) | func BenchmarkPronicNumber(b *testing.B) {
FILE: math/pythagoras/pythagoras.go
type Vector (line 8) | type Vector struct
function Distance (line 15) | func Distance(a, b Vector) float64 {
FILE: math/pythagoras/pythagoras_test.go
function TestDistance (line 22) | func TestDistance(t *testing.T) {
FILE: math/sin.go
function Sin (line 9) | func Sin(x float64) float64 {
FILE: math/sin_test.go
function TestSin (line 9) | func TestSin(t *testing.T) {
function BenchmarkSin (line 32) | func BenchmarkSin(b *testing.B) {
function BenchmarkMathSin (line 39) | func BenchmarkMathSin(b *testing.B) {
FILE: other/maxsubarraysum/maxsubarraysum.go
function MaxSubarraySum (line 13) | func MaxSubarraySum(array []int) int {
FILE: other/maxsubarraysum/maxsubarraysum_test.go
function TestMaxSubarraySum (line 7) | func TestMaxSubarraySum(t *testing.T) {
FILE: other/nested/nestedbrackets.go
function IsBalanced (line 23) | func IsBalanced(input string) bool {
FILE: other/nested/nestedbrackets_test.go
function TestIsBalancedSimple (line 7) | func TestIsBalancedSimple(t *testing.T) {
function TestIsBalancedFalty (line 18) | func TestIsBalancedFalty(t *testing.T) {
function TestIsBalancedHandlesEmpty (line 29) | func TestIsBalancedHandlesEmpty(t *testing.T) {
function TestIsBalancedHandlesOneChar (line 40) | func TestIsBalancedHandlesOneChar(t *testing.T) {
function TestIsBalancedHandlesNonBracketsCorrectly (line 51) | func TestIsBalancedHandlesNonBracketsCorrectly(t *testing.T) {
function TestIsBalancedHandlesOrdering (line 62) | func TestIsBalancedHandlesOrdering(t *testing.T) {
function BenchmarkIsBalanced (line 73) | func BenchmarkIsBalanced(b *testing.B) {
FILE: other/password/generator.go
function Generate (line 18) | func Generate(minLength int, maxLength int) string {
FILE: project_euler/problem_1/problem1.go
function Problem1 (line 14) | func Problem1(n uint) uint {
FILE: project_euler/problem_1/problem1_test.go
function TestProblem1_Func (line 6) | func TestProblem1_Func(t *testing.T) {
function BenchmarkProblem1 (line 41) | func BenchmarkProblem1(b *testing.B) {
FILE: project_euler/problem_10/problem10.go
function Problem10 (line 14) | func Problem10(n int) uint {
FILE: project_euler/problem_10/problem10_test.go
function TestProblem10_Func (line 6) | func TestProblem10_Func(t *testing.T) {
function BenchmarkProblem10 (line 36) | func BenchmarkProblem10(b *testing.B) {
FILE: project_euler/problem_11/problem11.go
function Problem11 (line 39) | func Problem11() uint {
FILE: project_euler/problem_11/problem11_test.go
function TestProblem11_Func (line 6) | func TestProblem11_Func(t *testing.T) {
function BenchmarkProblem11_Func (line 25) | func BenchmarkProblem11_Func(b *testing.B) {
FILE: project_euler/problem_12/problem12.go
function Problem12 (line 28) | func Problem12(limit uint) uint {
function numDivisors (line 38) | func numDivisors(n uint) uint {
FILE: project_euler/problem_12/problem12_test.go
function TestProblem12_Func (line 5) | func TestProblem12_Func(t *testing.T) {
function BenchmarkProblem12_Func (line 27) | func BenchmarkProblem12_Func(b *testing.B) {
FILE: project_euler/problem_13/problem13.go
function Problem13 (line 114) | func Problem13() string {
function add (line 124) | func add(a, b string) string {
FILE: project_euler/problem_13/problem13_test.go
function TestProblem13_Func (line 5) | func TestProblem13_Func(t *testing.T) {
function BenchmarkProblem13_Func (line 23) | func BenchmarkProblem13_Func(b *testing.B) {
FILE: project_euler/problem_14/problem14.go
type dict (line 20) | type dict
function Problem14 (line 26) | func Problem14(limit uint64) uint64 {
function weightNextNode (line 42) | func weightNextNode(current uint64) uint64 {
FILE: project_euler/problem_14/problem14_test.go
function TestProblem14_Func (line 6) | func TestProblem14_Func(t *testing.T) {
function BenchmarkProblem14_Func (line 27) | func BenchmarkProblem14_Func(b *testing.B) {
FILE: project_euler/problem_15/problem15.go
function Problem15 (line 19) | func Problem15(gridSize int) int {
FILE: project_euler/problem_15/problem15_test.go
function TestProblem15_Func (line 6) | func TestProblem15_Func(t *testing.T) {
function BenchmarkProblem15_Func (line 30) | func BenchmarkProblem15_Func(b *testing.B) {
FILE: project_euler/problem_16/problem16.go
function Problem16 (line 17) | func Problem16(exponent int64) int64 {
FILE: project_euler/problem_16/problem16_test.go
function TestProblem16_Func (line 6) | func TestProblem16_Func(t *testing.T) {
function BenchmarkProblem16_Func (line 26) | func BenchmarkProblem16_Func(b *testing.B) {
FILE: project_euler/problem_17/input.go
constant INPUT (line 8) | INPUT = "One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ...
FILE: project_euler/problem_17/problem17.go
function Problem17 (line 21) | func Problem17(input string) int {
FILE: project_euler/problem_17/problem17_test.go
function TestProblem17_Func (line 6) | func TestProblem17_Func(t *testing.T) {
function BenchmarkProblem17_Func (line 26) | func BenchmarkProblem17_Func(b *testing.B) {
FILE: project_euler/problem_18/edge.go
type Edge (line 3) | type Edge struct
method Value (line 11) | func (n *Edge) Value() NodeValue {
method Left (line 15) | func (n *Edge) Left() Node {
method Right (line 19) | func (n *Edge) Right() Node {
method Kind (line 23) | func (n *Edge) Kind() string {
method CreateChild (line 27) | func (n *Edge) CreateChild(value NodeValue, id int) Node {
method GetID (line 59) | func (n *Edge) GetID() int {
method Insert (line 63) | func (n *Edge) Insert(node Node) {
method HasSpace (line 86) | func (n *Edge) HasSpace() bool {
method LeftIsNil (line 90) | func (n *Edge) LeftIsNil() bool {
method RightIsNil (line 94) | func (n *Edge) RightIsNil() bool {
method SetParent (line 98) | func (n *Edge) SetParent(node Node) {
FILE: project_euler/problem_18/input.go
constant problem18_input_string (line 5) | problem18_input_string = `
constant problem18_test_string (line 30) | problem18_test_string = `
FILE: project_euler/problem_18/leaf.go
type Leaf (line 3) | type Leaf struct
method Value (line 11) | func (n *Leaf) Value() NodeValue {
method Left (line 15) | func (n *Leaf) Left() Node {
method Right (line 23) | func (n *Leaf) Right() Node {
method Kind (line 27) | func (n *Leaf) Kind() string {
method CreateChild (line 31) | func (n *Leaf) CreateChild(value NodeValue, id int) Node {
method GetID (line 42) | func (n *Leaf) GetID() int {
method Insert (line 46) | func (n *Leaf) Insert(node Node) {
method HasSpace (line 61) | func (n *Leaf) HasSpace() bool {
method LeftIsNil (line 65) | func (n *Leaf) LeftIsNil() bool {
method RightIsNil (line 69) | func (n *Leaf) RightIsNil() bool {
method SetParent (line 73) | func (n *Leaf) SetParent(node Node) {
FILE: project_euler/problem_18/problem18.go
type NodeValue (line 32) | type NodeValue
type NodeType (line 33) | type NodeType
type Node (line 35) | type Node interface
function Problem18 (line 50) | func Problem18(input []string, deep int) int {
FILE: project_euler/problem_18/problem18_test.go
function TestProblem18_Func (line 6) | func TestProblem18_Func(t *testing.T) {
function BenchmarkProblem18_Func (line 38) | func BenchmarkProblem18_Func(b *testing.B) {
FILE: project_euler/problem_18/root.go
type Root (line 3) | type Root struct
method Value (line 10) | func (n *Root) Value() NodeValue {
method Left (line 14) | func (n *Root) Left() Node {
method Right (line 18) | func (n *Root) Right() Node {
method Kind (line 22) | func (n *Root) Kind() string {
method CreateChild (line 26) | func (n *Root) CreateChild(value NodeValue, id int) Node {
method GetID (line 36) | func (n *Root) GetID() int {
method Insert (line 40) | func (n *Root) Insert(node Node) {
method HasSpace (line 48) | func (n *Root) HasSpace() bool {
method LeftIsNil (line 52) | func (n *Root) LeftIsNil() bool {
method RightIsNil (line 56) | func (n *Root) RightIsNil() bool {
method SetParent (line 60) | func (n *Root) SetParent(node Node) {
FILE: project_euler/problem_18/tree.go
type Tree (line 8) | type Tree struct
method BFSInsert (line 14) | func (t *Tree) BFSInsert(value NodeValue) {
method MaxPathValueSearch (line 51) | func (r *Tree) MaxPathValueSearch(deep int) int {
method PrintReport (line 121) | func (t *Tree) PrintReport() {
method PrintPyramid (line 160) | func (t *Tree) PrintPyramid() {
method isInQueue (line 222) | func (n *Tree) isInQueue(nv int) bool {
FILE: project_euler/problem_19/problem19.go
function Problem19 (line 26) | func Problem19() int {
function IsLeapYear (line 55) | func IsLeapYear(year int) bool {
FILE: project_euler/problem_19/problem19_test.go
function TestProblem19_Func (line 6) | func TestProblem19_Func(t *testing.T) {
function BenchmarkProblem19_Func (line 25) | func BenchmarkProblem19_Func(b *testing.B) {
FILE: project_euler/problem_2/problem2.go
function Problem2 (line 17) | func Problem2(n uint) uint {
FILE: project_euler/problem_2/problem2_test.go
function TestProblem2_Func (line 6) | func TestProblem2_Func(t *testing.T) {
function BenchmarkProblem2 (line 41) | func BenchmarkProblem2(b *testing.B) {
FILE: project_euler/problem_20/problem20.go
function Problem20 (line 18) | func Problem20(input int) int {
function bigFactorial (line 29) | func bigFactorial(n int) *big.Int {
FILE: project_euler/problem_20/problem20_test.go
function TestProblem20_Func (line 6) | func TestProblem20_Func(t *testing.T) {
function BenchmarkProblem20_Func (line 27) | func BenchmarkProblem20_Func(b *testing.B) {
FILE: project_euler/problem_3/problem3.go
function Problem3 (line 12) | func Problem3(n uint) uint {
FILE: project_euler/problem_3/problem3_test.go
function TestProblem3_Func (line 6) | func TestProblem3_Func(t *testing.T) {
function BenchmarkProblem3 (line 36) | func BenchmarkProblem3(b *testing.B) {
FILE: project_euler/problem_4/problem4.go
function Problem4 (line 19) | func Problem4() uint {
FILE: project_euler/problem_4/problem4_test.go
function TestProblem4_Func (line 6) | func TestProblem4_Func(t *testing.T) {
function BenchmarkProblem4 (line 29) | func BenchmarkProblem4(b *testing.B) {
FILE: project_euler/problem_5/problem5.go
function Problem5 (line 13) | func Problem5(limit uint) uint {
function isDivisible (line 25) | func isDivisible(n, limit uint) bool {
FILE: project_euler/problem_5/problem5_test.go
function TestProblem5_Func (line 6) | func TestProblem5_Func(t *testing.T) {
function BenchmarkProblem5 (line 41) | func BenchmarkProblem5(b *testing.B) {
FILE: project_euler/problem_6/problem6.go
function Problem6 (line 21) | func Problem6(n uint) uint {
FILE: project_euler/problem_6/problem6_test.go
function TestProblem6_Func (line 6) | func TestProblem6_Func(t *testing.T) {
function BenchmarkProblem6 (line 36) | func BenchmarkProblem6(b *testing.B) {
FILE: project_euler/problem_7/problem7.go
function Problem7 (line 16) | func Problem7(n uint) int64 {
FILE: project_euler/problem_7/problem7_test.go
function TestProblem7_Func (line 6) | func TestProblem7_Func(t *testing.T) {
function BenchmarkProblem7 (line 36) | func BenchmarkProblem7(b *testing.B) {
FILE: project_euler/problem_8/problem8.go
constant number (line 14) | number = "73167176531330624919225119674426574742355349194934969835203127...
function Problem8 (line 16) | func Problem8(window int) uint {
FILE: project_euler/problem_8/problem8_test.go
function TestProblem8_Func (line 6) | func TestProblem8_Func(t *testing.T) {
function BenchmarkProblem8 (line 36) | func BenchmarkProblem8(b *testing.B) {
FILE: project_euler/problem_9/problem9.go
function Problem9 (line 17) | func Problem9() uint {
FILE: project_euler/problem_9/problem9_test.go
function TestProblem9_Func (line 6) | func TestProblem9_Func(t *testing.T) {
function BenchmarkProblem9 (line 29) | func BenchmarkProblem9(b *testing.B) {
FILE: search/binary.go
function Binary (line 6) | func Binary(array []int, target int, lowIndex int, highIndex int) (int, ...
function BinaryIterative (line 23) | func BinaryIterative(array []int, target int) (int, error) {
function LowerBound (line 42) | func LowerBound(array []int, target int) (int, error) {
function UpperBound (line 64) | func UpperBound(array []int, target int) (int, error) {
FILE: search/binary_test.go
function TestBinary (line 8) | func TestBinary(t *testing.T) {
function TestBinaryIterative (line 20) | func TestBinaryIterative(t *testing.T) {
function TestLowerBound (line 32) | func TestLowerBound(t *testing.T) {
function TestUpperBound (line 44) | func TestUpperBound(t *testing.T) {
function BenchmarkBinary (line 56) | func BenchmarkBinary(b *testing.B) {
function BenchmarkBinaryIterative (line 64) | func BenchmarkBinaryIterative(b *testing.B) {
function BenchmarkLowerBound (line 72) | func BenchmarkLowerBound(b *testing.B) {
function BenchmarkUpperBound (line 80) | func BenchmarkUpperBound(b *testing.B) {
FILE: search/interpolation.go
function Interpolation (line 15) | func Interpolation(sortedData []int, guess int) (int, error) {
FILE: search/interpolation_test.go
function TestInterpolation (line 5) | func TestInterpolation(t *testing.T) {
function BenchmarkInterpolation (line 17) | func BenchmarkInterpolation(b *testing.B) {
FILE: search/jump.go
function Jump (line 17) | func Jump(array []int, target int) (int, error) {
FILE: search/jump2.go
function Jump2 (line 5) | func Jump2(arr []int, target int) (int, error) {
FILE: search/jump2_test.go
function TestJump2 (line 5) | func TestJump2(t *testing.T) {
function BenchmarkJump2 (line 17) | func BenchmarkJump2(b *testing.B) {
FILE: search/jump_test.go
function TestJump (line 5) | func TestJump(t *testing.T) {
function BenchmarkJump (line 17) | func BenchmarkJump(b *testing.B) {
FILE: search/linear.go
function Linear (line 4) | func Linear(array []int, query int) (int, error) {
FILE: search/linear_test.go
function TestLinear (line 7) | func TestLinear(t *testing.T) {
function BenchmarkLinear (line 19) | func BenchmarkLinear(b *testing.B) {
FILE: search/selectk.go
function SelectK (line 3) | func SelectK(array []int, k int) (int, error) {
function selectK (line 11) | func selectK(array []int, l, r, idx int) int {
function partition (line 22) | func partition(array []int, l, r int) int {
FILE: search/selectk_test.go
function TestSelectK (line 7) | func TestSelectK(t *testing.T) {
function BenchmarkSelectK (line 33) | func BenchmarkSelectK(b *testing.B) {
FILE: search/ternary.go
function TernaryMax (line 10) | func TernaryMax(a, b, epsilon float64, f func(x float64) float64) (float...
function TernaryMin (line 27) | func TernaryMin(a, b, epsilon float64, f func(x float64) float64) (float...
FILE: search/ternary_test.go
constant EPS (line 8) | EPS = 1e-6
function equal (line 10) | func equal(a, b float64) bool {
function TestTernaryMax (line 14) | func TestTernaryMax(t *testing.T) {
function TestTernaryMin (line 36) | func TestTernaryMin(t *testing.T) {
FILE: search/testcases.go
type searchTest (line 3) | type searchTest struct
function generateBenchmarkTestCase (line 61) | func generateBenchmarkTestCase() []int {
FILE: sort/binaryinsertionsort.go
function BinaryInsertion (line 13) | func BinaryInsertion[T constraints.Ordered](arr []T) []T {
FILE: sort/bogosort.go
function isSorted (line 16) | func isSorted[T constraints.Number](arr []T) bool {
function shuffle (line 26) | func shuffle[T constraints.Number](arr []T) {
function Bogo (line 33) | func Bogo[T constraints.Number](arr []T) []T {
FILE: sort/bubblesort.go
function Bubble (line 9) | func Bubble[T constraints.Ordered](arr []T) []T {
FILE: sort/bucketsort.go
function Bucket (line 7) | func Bucket[T constraints.Number](arr []T) []T {
FILE: sort/circlesort.go
function Circle (line 7) | func Circle[T constraints.Ordered](arr []T) []T {
function doSort (line 17) | func doSort[T constraints.Ordered](arr []T, left, right int) bool {
FILE: sort/cocktailsort.go
function Cocktail (line 9) | func Cocktail[T constraints.Ordered](arr []T) []T {
FILE: sort/combSort.go
function getNextGap (line 11) | func getNextGap(gap int) int {
function Comb (line 20) | func Comb[T constraints.Ordered](data []T) []T {
FILE: sort/countingsort.go
function Count (line 14) | func Count[T constraints.Integer](data []T) []T {
FILE: sort/cyclesort.go
function Cycle (line 10) | func Cycle[T constraints.Number](arr []T) []T {
FILE: sort/exchangesort.go
function Exchange (line 11) | func Exchange[T constraints.Ordered](arr []T) []T {
FILE: sort/heapsort.go
type MaxHeap (line 11) | type MaxHeap struct
method Init (line 17) | func (h *MaxHeap) Init(slice []Comparable) {
method Heapify (line 28) | func (h MaxHeap) Heapify() {
method Pop (line 37) | func (h *MaxHeap) Pop() Comparable {
method Push (line 53) | func (h *MaxHeap) Push(i Comparable) {
method Size (line 60) | func (h MaxHeap) Size() int {
method Update (line 64) | func (h MaxHeap) Update(i Comparable) {
method updateidx (line 70) | func (h MaxHeap) updateidx(i int) {
method swap (line 74) | func (h *MaxHeap) swap(i, j int) {
method more (line 80) | func (h MaxHeap) more(i, j int) bool {
method heapifyUp (line 84) | func (h MaxHeap) heapifyUp(i int) {
method heapifyDown (line 96) | func (h MaxHeap) heapifyDown(i int) {
function heapifyDown (line 100) | func heapifyDown[T any](slice []T, N, i int, moreFunc func(i, j int) boo...
type Comparable (line 117) | type Comparable interface
function HeapSort (line 122) | func HeapSort[T constraints.Ordered](slice []T) []T {
FILE: sort/insertionsort.go
function Insertion (line 11) | func Insertion[T constraints.Ordered](arr []T) []T {
FILE: sort/mergesort.go
function merge (line 15) | func merge[T constraints.Ordered](a []T, b []T) []T {
function Merge (line 47) | func Merge[T constraints.Ordered](items []T) []T {
function MergeIter (line 61) | func MergeIter[T constraints.Ordered](items []T) []T {
function ParallelMerge (line 72) | func ParallelMerge[T constraints.Ordered](items []T) []T {
FILE: sort/oddevensort.go
function OddEvenSort (line 12) | func OddEvenSort[T constraints.Ordered](arr []T) []T {
FILE: sort/pancakesort.go
function Pancake (line 8) | func Pancake[T constraints.Ordered](arr []T) []T {
function flip (line 38) | func flip[T constraints.Ordered](arr []T, i int) []T {
FILE: sort/patiencesort.go
function Patience (line 16) | func Patience[T constraints.Ordered](arr []T) []T {
function mergePiles (line 44) | func mergePiles[T constraints.Ordered](piles [][]T) []T {
FILE: sort/pigeonholesort.go
function Pigeonhole (line 17) | func Pigeonhole[T constraints.Integer](arr []T) []T {
FILE: sort/quicksort.go
function Partition (line 15) | func Partition[T constraints.Ordered](arr []T, low, high int) int {
function QuicksortRange (line 29) | func QuicksortRange[T constraints.Ordered](arr []T, low, high int) {
function Quicksort (line 42) | func Quicksort[T constraints.Ordered](arr []T) []T {
FILE: sort/radixsort.go
function countSort (line 16) | func countSort[T constraints.Integer](arr []T, exp T) []T {
function unsignedRadixSort (line 35) | func unsignedRadixSort[T constraints.Integer](arr []T) []T {
function RadixSort (line 46) | func RadixSort[T constraints.Integer](arr []T) []T {
FILE: sort/selectionsort.go
function Selection (line 5) | func Selection[T constraints.Ordered](arr []T) []T {
FILE: sort/shellsort.go
function Shell (line 5) | func Shell[T constraints.Ordered](arr []T) []T {
FILE: sort/simplesort.go
function Simple (line 16) | func Simple[T constraints.Ordered](arr []T) []T {
function ImprovedSimple (line 30) | func ImprovedSimple[T constraints.Ordered](arr []T) []T {
FILE: sort/sorts_test.go
function testFramework (line 12) | func testFramework(t *testing.T, sortingFunction func([]int) []int) {
function TestBinaryInsertion (line 80) | func TestBinaryInsertion(t *testing.T) {
function TestBubble (line 84) | func TestBubble(t *testing.T) {
function TestBogo (line 88) | func TestBogo(t *testing.T) {
function TestBucketSort (line 93) | func TestBucketSort(t *testing.T) {
function TestCocktailSort (line 97) | func TestCocktailSort(t *testing.T) {
function TestExchange (line 101) | func TestExchange(t *testing.T) {
function TestInsertion (line 105) | func TestInsertion(t *testing.T) {
function TestMerge (line 109) | func TestMerge(t *testing.T) {
function TestMergeIter (line 113) | func TestMergeIter(t *testing.T) {
function TestMergeParallel (line 117) | func TestMergeParallel(t *testing.T) {
function TestHeap (line 137) | func TestHeap(t *testing.T) {
function TestCount (line 141) | func TestCount(t *testing.T) {
function TestQuick (line 145) | func TestQuick(t *testing.T) {
function TestShell (line 149) | func TestShell(t *testing.T) {
function TestRadix (line 153) | func TestRadix(t *testing.T) {
function TestSimple (line 157) | func TestSimple(t *testing.T) {
function TestImprovedSimple (line 161) | func TestImprovedSimple(t *testing.T) {
function TestSelection (line 165) | func TestSelection(t *testing.T) {
function TestComb (line 169) | func TestComb(t *testing.T) {
function TestPancakeSort (line 173) | func TestPancakeSort(t *testing.T) {
function TestPigeonhole (line 177) | func TestPigeonhole(t *testing.T) {
function TestPatience (line 181) | func TestPatience(t *testing.T) {
function TestCycle (line 185) | func TestCycle(t *testing.T) {
function TestTimsort (line 189) | func TestTimsort(t *testing.T) {
function TestCircle (line 193) | func TestCircle(t *testing.T) {
function TestOddEvenSort (line 197) | func TestOddEvenSort(t *testing.T) {
function TestStooge (line 201) | func TestStooge(t *testing.T) {
function benchmarkFramework (line 207) | func benchmarkFramework(b *testing.B, f func(arr []int) []int) {
function BenchmarkBinaryInsertion (line 246) | func BenchmarkBinaryInsertion(b *testing.B) {
function BenchmarkBubble (line 250) | func BenchmarkBubble(b *testing.B) {
function BenchmarkBogo (line 254) | func BenchmarkBogo(b *testing.B) {
function BenchmarkBucketSort (line 259) | func BenchmarkBucketSort(b *testing.B) {
function BenchmarkCocktailSort (line 263) | func BenchmarkCocktailSort(b *testing.B) {
function BenchmarkExchange (line 267) | func BenchmarkExchange(b *testing.B) {
function BenchmarkInsertion (line 271) | func BenchmarkInsertion(b *testing.B) {
function BenchmarkMerge (line 275) | func BenchmarkMerge(b *testing.B) {
function BenchmarkMergeIter (line 279) | func BenchmarkMergeIter(b *testing.B) {
function BenchmarkMergeParallel (line 283) | func BenchmarkMergeParallel(b *testing.B) {
function BenchmarkHeap (line 287) | func BenchmarkHeap(b *testing.B) {
function BenchmarkCount (line 291) | func BenchmarkCount(b *testing.B) {
function BenchmarkQuick (line 295) | func BenchmarkQuick(b *testing.B) {
function BenchmarkShell (line 299) | func BenchmarkShell(b *testing.B) {
function BenchmarkRadix (line 303) | func BenchmarkRadix(b *testing.B) {
function BenchmarkSimple (line 307) | func BenchmarkSimple(b *testing.B) {
function BenchmarkImprovedSimple (line 311) | func BenchmarkImprovedSimple(b *testing.B) {
function BenchmarkSelection (line 316) | func BenchmarkSelection(b *testing.B) {
function BenchmarkComb (line 320) | func BenchmarkComb(b *testing.B) {
function BenchmarkPancakeSort (line 324) | func BenchmarkPancakeSort(b *testing.B) {
function BenchmarkPigeonhole (line 328) | func BenchmarkPigeonhole(b *testing.B) {
function BenchmarkPatience (line 332) | func BenchmarkPatience(b *testing.B) {
function BenchmarkCycle (line 336) | func BenchmarkCycle(b *testing.B) {
function BenchmarkTimsort (line 340) | func BenchmarkTimsort(b *testing.B) {
function BenchmarkCircle (line 344) | func BenchmarkCircle(b *testing.B) {
function BenchmarkStooge (line 348) | func BenchmarkStooge(b *testing.B) {
FILE: sort/stooge_sort.go
function innerStooge (line 15) | func innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T {
function Stooge (line 28) | func Stooge[T constraints.Ordered](arr []T) []T {
FILE: sort/timsort.go
constant runSizeThreshold (line 10) | runSizeThreshold = 8
function Timsort (line 13) | func Timsort[T constraints.Ordered](data []T) []T {
function calculateRunSize (line 22) | func calculateRunSize(dataLength int) int {
function insertionSortRuns (line 36) | func insertionSortRuns[T constraints.Ordered](data []T, runSize int) {
function mergeRuns (line 48) | func mergeRuns[T constraints.Ordered](data []T, runSize int) {
function mergeRun (line 63) | func mergeRun[T constraints.Ordered](data []T, lower, mid, upper int) {
FILE: sqrt/sqrtdecomposition.go
type SqrtDecomposition (line 21) | type SqrtDecomposition struct
function NewSqrtDecomposition (line 34) | func NewSqrtDecomposition[E any, Q any](
method Query (line 65) | func (s *SqrtDecomposition[E, Q]) Query(start uint64, end uint64) Q {
method Update (line 98) | func (s *SqrtDecomposition[E, Q]) Update(index uint64, newElement E) {
FILE: sqrt/sqrtdecomposition_test.go
type query (line 9) | type query struct
type update (line 14) | type update struct
function TestSqrtDecomposition (line 19) | func TestSqrtDecomposition(t *testing.T) {
FILE: strings/ahocorasick/advancedahocorasick.go
function Advanced (line 10) | func Advanced(t string, p []string) Result {
function BuildExtendedAc (line 46) | func BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f ma...
FILE: strings/ahocorasick/advancedahocorasick_test.go
function TestAdvanced (line 51) | func TestAdvanced(t *testing.T) {
FILE: strings/ahocorasick/ahocorasick.go
type Result (line 9) | type Result struct
function AhoCorasick (line 15) | func AhoCorasick(t string, p []string) Result {
function BuildAc (line 54) | func BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]...
FILE: strings/ahocorasick/ahocorasick_test.go
function TestAhoCorasick (line 10) | func TestAhoCorasick(t *testing.T) {
function convertToString (line 24) | func convertToString(res Result) string {
FILE: strings/ahocorasick/shared.go
function ConstructTrie (line 4) | func ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTermi...
function Contains (line 39) | func Contains(s []int, e int) bool {
function GetWord (line 49) | func GetWord(begin, end int, t string) string {
function ComputeAlphabet (line 61) | func ComputeAlphabet(p []string) (s string) {
function IntArrayCapUp (line 70) | func IntArrayCapUp(old []int) (new []int) {
function BoolArrayCapUp (line 78) | func BoolArrayCapUp(old []bool) (new []bool) {
function ArrayUnion (line 86) | func ArrayUnion(to, from []int) (concat []int) {
function GetParent (line 99) | func GetParent(state int, at map[int]map[uint8]int) (uint8, int) {
function CreateNewState (line 111) | func CreateNewState(state int, at map[int]map[uint8]int) {
function CreateTransition (line 116) | func CreateTransition(fromState int, overChar uint8, toState int, at map...
function GetTransition (line 121) | func GetTransition(fromState int, overChar uint8, at map[int]map[uint8]i...
function StateExists (line 133) | func StateExists(state int, at map[int]map[uint8]int) bool {
FILE: strings/charoccurrence.go
function CountChars (line 12) | func CountChars(text string) map[rune]int {
FILE: strings/charoccurrence_test.go
function TestCountChars (line 9) | func TestCountChars(t *testing.T) {
FILE: strings/combination/combination.go
type Combinations (line 7) | type Combinations struct
method Combine (line 22) | func (c *Combinations) Combine(seed int) {
function Start (line 13) | func Start(input string) {
FILE: strings/generateparentheses/generateparentheses.go
function GenerateParenthesis (line 12) | func GenerateParenthesis(n int) []string {
FILE: strings/generateparentheses/generateparentheses_test.go
function TestGenerateParenthesis (line 10) | func TestGenerateParenthesis(t *testing.T) {
FILE: strings/genetic/genetic.go
type PopulationItem (line 26) | type PopulationItem struct
type Conf (line 32) | type Conf struct
type Result (line 52) | type Result struct
function GeneticString (line 71) | func GeneticString(target string, charmap []rune, conf *Conf) (*Result, ...
FILE: strings/genetic/geneticalgorithm_test.go
function TestSimple (line 7) | func TestSimple(t *testing.T) {
FILE: strings/guid/guid.go
constant pattern (line 24) | pattern string = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx"
constant versionIndex (line 25) | versionIndex int = 14
function New (line 28) | func New() (string, error) {
FILE: strings/guid/guid_test.go
function TestNew (line 8) | func TestNew(t *testing.T) {
function BenchmarkNew (line 64) | func BenchmarkNew(b *testing.B) {
FILE: strings/hamming/hammingdistance.go
function Distance (line 18) | func Distance(str1, str2 string) (int, error) {
FILE: strings/hamming/hammingdistance_test.go
function TestHammingDistance (line 43) | func TestHammingDistance(t *testing.T) {
FILE: strings/horspool/horspool.go
function Horspool (line 10) | func Horspool(t, p string) (int, error) {
function horspool (line 16) | func horspool(t, p []rune) (int, error) {
function isMatch (line 43) | func isMatch(pos int, t, p []rune) bool {
function computeShiftMap (line 51) | func computeShiftMap(t, p []rune) (res map[rune]int) {
FILE: strings/horspool/horspool_test.go
function TestLHorspool (line 10) | func TestLHorspool(t *testing.T) {
function TestLHorspoolNotExisintPattern (line 43) | func TestLHorspoolNotExisintPattern(t *testing.T) {
FILE: strings/isisogram.go
type IsogramOrder (line 16) | type IsogramOrder
constant First (line 19) | First IsogramOrder = iota + 1
constant Second (line 20) | Second
constant Third (line 21) | Third
function hasDigit (line 24) | func hasDigit(text string) bool {
function hasSymbol (line 29) | func hasSymbol(text string) bool {
function IsIsogram (line 34) | func IsIsogram(text string, order IsogramOrder) (bool, error) {
FILE: strings/isisogram_test.go
function TestIsIsogram (line 117) | func TestIsIsogram(t *testing.T) {
FILE: strings/issubsequence.go
function IsSubsequence (line 10) | func IsSubsequence(s string, t string) bool {
FILE: strings/issubsequence_test.go
function TestIsSubsequence (line 10) | func TestIsSubsequence(t *testing.T) {
FILE: strings/kmp/kmp.go
function Kmp (line 4) | func Kmp(word, text string, patternTable []int) []int {
function table (line 36) | func table(w string) []int {
FILE: strings/kmp/kmp_test.go
function TestKmp (line 8) | func TestKmp(t *testing.T) {
function TestTable (line 38) | func TestTable(t *testing.T) {
FILE: strings/levenshtein/levenshteindistance.go
function Distance (line 10) | func Distance(str1, str2 string, icost, scost, dcost int) int {
FILE: strings/levenshtein/levenshteindistance_test.go
function TestLevenshteinDistance (line 43) | func TestLevenshteinDistance(t *testing.T) {
FILE: strings/manacher/longestpalindrome.go
function makeBoundaries (line 15) | func makeBoundaries(s string) string {
function nextBoundary (line 27) | func nextBoundary(s string) string {
function LongestPalindrome (line 37) | func LongestPalindrome(s string) string {
FILE: strings/manacher/longestpalindrome_test.go
function getTests (line 10) | func getTests() []struct {
function TestLongestPalindrome (line 27) | func TestLongestPalindrome(t *testing.T) {
FILE: strings/palindrome/ispalindrome.go
function cleanString (line 19) | func cleanString(text string) string {
function IsPalindrome (line 26) | func IsPalindrome(text string) bool {
function IsPalindromeRecursive (line 39) | func IsPalindromeRecursive(text string) bool {
function isPalindromeRecursiveHelper (line 45) | func isPalindromeRecursiveHelper(runes []rune, start int64, end int64) b...
FILE: strings/palindrome/ispalindrome_test.go
function TestIsPalindrome (line 44) | func TestIsPalindrome(t *testing.T) {
function TestIsPalindromeRecursive (line 55) | func TestIsPalindromeRecursive(t *testing.T) {
FILE: strings/pangram/ispangram.go
function cleanString (line 14) | func cleanString(text string) string {
function IsPangram (line 21) | func IsPangram(text string) bool {
FILE: strings/pangram/ispangram_test.go
function TestIsPangram (line 44) | func TestIsPangram(t *testing.T) {
FILE: strings/parenthesis/parenthesis.go
function Parenthesis (line 8) | func Parenthesis(text string) bool {
FILE: strings/parenthesis/parenthesis_test.go
function TestParenthesis (line 44) | func TestParenthesis(t *testing.T) {
FILE: strings/search/boyermoore.go
function BoyerMoore (line 5) | func BoyerMoore(text string, pattern string) []int {
FILE: strings/search/naive.go
function Naive (line 5) | func Naive(text string, pattern string) []int {
FILE: strings/search/patternsearch_test.go
function TestNaive (line 52) | func TestNaive(t *testing.T) {
function TestBooyerMoore (line 63) | func TestBooyerMoore(t *testing.T) {
FILE: structure/circularqueue/circularqueue_test.go
function TestCircularQueue (line 5) | func TestCircularQueue(t *testing.T) {
function BenchmarkCircularQueue (line 228) | func BenchmarkCircularQueue(b *testing.B) {
FILE: structure/circularqueue/circularqueuearray.go
type CircularQueue (line 20) | type CircularQueue struct
function NewCircularQueue (line 29) | func NewCircularQueue[T any](size int) (*CircularQueue[T], error) {
method Enqueue (line 43) | func (cq *CircularQueue[T]) Enqueue(item T) error {
method Dequeue (line 57) | func (cq *CircularQueue[T]) Dequeue() (T, error) {
method IsFull (line 73) | func (cq *CircularQueue[T]) IsFull() bool {
method IsEmpty (line 78) | func (cq *CircularQueue[T]) IsEmpty() bool {
method Peek (line 84) | func (cq *CircularQueue[T]) Peek() (T, error) {
method Size (line 94) | func (cq *CircularQueue[T]) Size() int {
FILE: structure/deque/deque.go
type DoublyEndedQueue (line 17) | type DoublyEndedQueue struct
function New (line 22) | func New[T any]() *DoublyEndedQueue[T] {
method EnqueueFront (line 27) | func (dq *DoublyEndedQueue[T]) EnqueueFront(item T) {
method EnqueueRear (line 32) | func (dq *DoublyEndedQueue[T]) EnqueueRear(item T) {
method DequeueFront (line 37) | func (dq *DoublyEndedQueue[T]) DequeueFront() (T, error) {
method DequeueRear (line 48) | func (dq *DoublyEndedQueue[T]) DequeueRear() (T, error) {
method Front (line 59) | func (dq *DoublyEndedQueue[T]) Front() (T, error) {
method Rear (line 68) | func (dq *DoublyEndedQueue[T]) Rear() (T, error) {
method IsEmpty (line 77) | func (dq *DoublyEndedQueue[T]) IsEmpty() bool {
method Length (line 82) | func (dq *DoublyEndedQueue[T]) Length() int {
FILE: structure/deque/deque_test.go
type QueryStructure (line 20) | type QueryStructure struct
type TestCaseData (line 27) | type TestCaseData struct
function TestDeque (line 32) | func TestDeque(t *testing.T) {
FILE: structure/dynamicarray/dynamicarray.go
type DynamicArray (line 21) | type DynamicArray struct
method Put (line 28) | func (da *DynamicArray) Put(index int, element any) error {
method Add (line 41) | func (da *DynamicArray) Add(element any) {
method Remove (line 51) | func (da *DynamicArray) Remove(index int) error {
method Get (line 67) | func (da *DynamicArray) Get(index int) (any, error) {
method IsEmpty (line 78) | func (da *DynamicArray) IsEmpty() bool {
method GetData (line 83) | func (da *DynamicArray) GetData() []any {
method CheckRangeFromIndex (line 88) | func (da *DynamicArray) CheckRangeFromIndex(index int) error {
method NewCapacity (line 96) | func (da *DynamicArray) NewCapacity() {
FILE: structure/dynamicarray/dynamicarray_test.go
function TestDynamicArray (line 8) | func TestDynamicArray(t *testing.T) {
FILE: structure/fenwicktree/fenwicktree.go
type FenwickTree (line 11) | type FenwickTree struct
method PrefixSum (line 37) | func (f *FenwickTree) PrefixSum(pos int) int {
method RangeSum (line 50) | func (f *FenwickTree) RangeSum(l int, r int) int {
method Add (line 56) | func (f *FenwickTree) Add(pos int, value int) {
function NewFenwickTree (line 20) | func NewFenwickTree(array []int) *FenwickTree {
FILE: structure/fenwicktree/fenwicktree_test.go
type query (line 8) | type query struct
type update (line 14) | type update struct
function TestFenwickTree (line 19) | func TestFenwickTree(t *testing.T) {
FILE: structure/hashmap/hashmap.go
type node (line 10) | type node struct
type HashMap (line 17) | type HashMap struct
method Get (line 41) | func (hm *HashMap) Get(key any) any {
method Put (line 50) | func (hm *HashMap) Put(key, value any) {
method Contains (line 75) | func (hm *HashMap) Contains(key any) bool {
method getNodeByKey (line 80) | func (hm *HashMap) getNodeByKey(key any) *node {
method resize (line 93) | func (hm *HashMap) resize() {
method hash (line 107) | func (hm *HashMap) hash(key any) uint64 {
function DefaultNew (line 24) | func DefaultNew() *HashMap {
function New (line 32) | func New(size, capacity uint64) *HashMap {
FILE: structure/hashmap/hashmap_test.go
function TestHashMap (line 9) | func TestHashMap(t *testing.T) {
FILE: structure/heap/heap.go
type Heap (line 9) | type Heap struct
function New (line 15) | func New[T constraints.Ordered]() *Heap[T] {
function NewAny (line 24) | func NewAny[T any](less func(a, b T) bool) (*Heap[T], error) {
method Push (line 35) | func (h *Heap[T]) Push(t T) {
method Top (line 42) | func (h *Heap[T]) Top() T {
method Pop (line 48) | func (h *Heap[T]) Pop() {
method Empty (line 59) | func (h *Heap[T]) Empty() bool {
method Size (line 64) | func (h *Heap[T]) Size() int {
method swap (line 68) | func (h *Heap[T]) swap(i, j int) {
method up (line 72) | func (h *Heap[T]) up(child int) {
method down (line 84) | func (h *Heap[T]) down(parent int) {
FILE: structure/heap/heap_test.go
type testInt (line 9) | type testInt
method Less (line 11) | func (u testInt) Less(o testInt) bool {
type testStudent (line 15) | type testStudent struct
method Less (line 20) | func (u testStudent) Less(o testStudent) bool {
function TestHeap_Empty (line 27) | func TestHeap_Empty(t *testing.T) {
type testOpType (line 44) | type testOpType
constant testPush (line 47) | testPush = 1
constant testPop (line 48) | testPop = 2
constant testTop (line 49) | testTop = 3
constant testEmpty (line 50) | testEmpty = 4
type testOp (line 53) | type testOp struct
type testStruct (line 59) | type testStruct struct
function TestHeapExample1 (line 64) | func TestHeapExample1(t *testing.T) {
function TestHeapExample2 (line 98) | func TestHeapExample2(t *testing.T) {
function testFunc (line 115) | func testFunc[T any](t *testing.T, tests []testStruct[T], less func(a, b...
FILE: structure/linkedlist/cyclic.go
type Cyclic (line 6) | type Cyclic struct
function NewCyclic (line 12) | func NewCyclic[T any]() *Cyclic[T] {
method Add (line 20) | func (cl *Cyclic[T]) Add(val T) {
method Rotate (line 49) | func (cl *Cyclic[T]) Rotate(places int) {
method Delete (line 74) | func (cl *Cyclic[T]) Delete() bool {
method Destroy (line 100) | func (cl *Cyclic[T]) Destroy() {
method Walk (line 107) | func (cl *Cyclic[T]) Walk() *Node[T] {
function JosephusProblem (line 120) | func JosephusProblem(cl *Cyclic[int], k int) int {
FILE: structure/linkedlist/cyclic_test.go
function fillList (line 8) | func fillList(list *Cyclic[int], n int) {
function TestAdd (line 14) | func TestAdd(t *testing.T) {
function TestWalk (line 32) | func TestWalk(t *testing.T) {
function TestRotate (line 44) | func TestRotate(t *testing.T) {
function TestDelete (line 71) | func TestDelete(t *testing.T) {
function TestDestroy (line 87) | func TestDestroy(t *testing.T) {
function TestJosephusProblem (line 104) | func TestJosephusProblem(t *testing.T) {
FILE: structure/linkedlist/doubly.go
type Doubly (line 18) | type Doubly struct
method Init (line 23) | func (ll *Doubly[T]) Init() *Doubly[T] {
function NewDoubly (line 31) | func NewDoubly[T any]() *Doubly[T] {
method lazyInit (line 36) | func (ll *Doubly[T]) lazyInit() {
method insert (line 42) | func (ll *Doubly[T]) insert(n, at *Node[T]) *Node[T] {
method insertValue (line 51) | func (ll *Doubly[T]) insertValue(val T, at *Node[T]) *Node[T] {
method AddAtBeg (line 56) | func (ll *Doubly[T]) AddAtBeg(val T) {
method AddAtEnd (line 62) | func (ll *Doubly[T]) AddAtEnd(val T) {
method Remove (line 67) | func (ll *Doubly[T]) Remove(n *Node[T]) T {
method DelAtBeg (line 77) | func (ll *Doubly[T]) DelAtBeg() (T, bool) {
method DelAtEnd (line 91) | func (ll *Doubly[T]) DelAtEnd() (T, bool) {
method DelByPos (line 106) | func (ll *Doubly[T]) DelByPos(pos int) (T, bool) {
method Count (line 138) | func (ll *Doubly[T]) Count() int {
method Reverse (line 153) | func (ll *Doubly[T]) Reverse() {
method Display (line 169) | func (ll *Doubly[T]) Display() {
method DisplayReverse (line 178) | func (ll *Doubly[T]) DisplayReverse() {
method Front (line 190) | func (ll *Doubly[T]) Front() *Node[T] {
method Back (line 198) | func (ll *Doubly[T]) Back() *Node[T] {
method MoveToBack (line 206) | func (ll *Doubly[T]) MoveToBack(n *Node[T]) {
method move (line 214) | func (ll *Doubly[T]) move(n, at *Node[T]) {
FILE: structure/linkedlist/doubly_test.go
function TestDoubly (line 8) | func TestDoubly(t *testing.T) {
FILE: structure/linkedlist/shared.go
type Node (line 5) | type Node struct
function NewNode (line 12) | func NewNode[T any](val T) *Node[T] {
FILE: structure/linkedlist/singlylinkedlist.go
type Singly (line 10) | type Singly struct
function NewSingly (line 19) | func NewSingly[T any]() *Singly[T] {
method AddAtBeg (line 24) | func (ll *Singly[T]) AddAtBeg(val T) {
method AddAtEnd (line 32) | func (ll *Singly[T]) AddAtEnd(val T) {
method DelAtBeg (line 50) | func (ll *Singly[T]) DelAtBeg() (T, bool) {
method DelAtEnd (line 65) | func (ll *Singly[T]) DelAtEnd() (T, bool) {
method DelByPos (line 89) | func (ll *Singly[T]) DelByPos(pos int) (T, bool) {
method Count (line 122) | func (ll *Singly[T]) Count() int {
method Reverse (line 127) | func (ll *Singly[T]) Reverse() {
method ReversePartition (line 142) | func (ll *Singly[T]) ReversePartition(left, right int) error {
method CheckRangeFromIndex (line 163) | func (ll *Singly[T]) CheckRangeFromIndex(left, right int) error {
method Display (line 175) | func (ll *Singly[T]) Display() {
FILE: structure/linkedlist/singlylinkedlist_test.go
function TestSingly (line 8) | func TestSingly(t *testing.T) {
FILE: structure/queue/queue_test.go
function TestQueue (line 17) | func TestQueue(t *testing.T) {
FILE: structure/queue/queuearray.go
function EnQueue (line 15) | func EnQueue(n any) {
function DeQueue (line 20) | func DeQueue() any {
function FrontQueue (line 27) | func FrontQueue() any {
function BackQueue (line 32) | func BackQueue() any {
function LenQueue (line 37) | func LenQueue() int {
function IsEmptyQueue (line 42) | func IsEmptyQueue() bool {
FILE: structure/queue/queuelinkedlist.go
type Node (line 13) | type Node struct
type Queue (line 19) | type Queue struct
method enqueue (line 26) | func (ll *Queue) enqueue(n any) {
method dequeue (line 43) | func (ll *Queue) dequeue() any {
method isEmpty (line 60) | func (ll *Queue) isEmpty() bool {
method len (line 65) | func (ll *Queue) len() int {
method frontQueue (line 70) | func (ll *Queue) frontQueue() any {
method backQueue (line 75) | func (ll *Queue) backQueue() any {
FILE: structure/queue/queuelinklistwithlist.go
type LQueue (line 20) | type LQueue struct
method Enqueue (line 25) | func (lq *LQueue) Enqueue(value any) {
method Dequeue (line 30) | func (lq *LQueue) Dequeue() error {
method Front (line 43) | func (lq *LQueue) Front() (any, error) {
method Back (line 53) | func (lq *LQueue) Back() (any, error) {
method Len (line 63) | func (lq *LQueue) Len() int {
method Empty (line 68) | func (lq *LQueue) Empty() bool {
FILE: structure/segmenttree/segmenttree.go
constant emptyLazyNode (line 14) | emptyLazyNode = 0
type SegmentTree (line 17) | type SegmentTree struct
method Propagate (line 24) | func (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) {
method Query (line 47) | func (s *SegmentTree) Query(node int, leftNode int, rightNode int, fir...
method Update (line 73) | func (s *SegmentTree) Update(node int, leftNode int, rightNode int, fi...
method Build (line 100) | func (s *SegmentTree) Build(node int, left int, right int) {
function NewSegmentTree (line 117) | func NewSegmentTree(Array []int) *SegmentTree {
FILE: structure/segmenttree/segmenttree_test.go
type query (line 8) | type query struct
type update (line 13) | type update struct
function TestSegmentTree (line 19) | func TestSegmentTree(t *testing.T) {
FILE: structure/set/set.go
function New (line 7) | func New[T comparable](items ...T) Set[T] {
type Set (line 18) | type Set interface
type set (line 53) | type set struct
method Add (line 57) | func (st *set[T]) Add(value T) {
method Delete (line 61) | func (st *set[T]) Delete(value T) {
method GetItems (line 65) | func (st *set[T]) GetItems() []T {
method Len (line 73) | func (st *set[T]) Len() int {
method In (line 77) | func (st *set[T]) In(value T) bool {
method IsSubsetOf (line 84) | func (st *set[T]) IsSubsetOf(superSet Set[T]) bool {
method IsProperSubsetOf (line 97) | func (st *set[T]) IsProperSubsetOf(superSet Set[T]) bool {
method IsSupersetOf (line 104) | func (st *set[T]) IsSupersetOf(subSet Set[T]) bool {
method IsProperSupersetOf (line 108) | func (st *set[T]) IsProperSupersetOf(subSet Set[T]) bool {
method Union (line 115) | func (st *set[T]) Union(st2 Set[T]) Set[T] {
method Intersection (line 126) | func (st *set[T]) Intersection(st2 Set[T]) Set[T] {
method Difference (line 144) | func (st *set[T]) Difference(st2 Set[T]) Set[T] {
method SymmetricDifference (line 154) | func (st *set[T]) SymmetricDifference(st2 Set[T]) Set[T] {
FILE: structure/set/set_test.go
function TestNew (line 7) | func TestNew(t *testing.T) {
function TestAdd (line 22) | func TestAdd(t *testing.T) {
function TestDelete (line 47) | func TestDelete(t *testing.T) {
function TestIsSubsetOf (line 72) | func TestIsSubsetOf(t *testing.T) {
function TestIsProperSubsetOf (line 85) | func TestIsProperSubsetOf(t *testing.T) {
function TestIsSupersetOf (line 95) | func TestIsSupersetOf(t *testing.T) {
function TestIsProperSupersetOf (line 108) | func TestIsProperSupersetOf(t *testing.T) {
function TestUnion (line 118) | func TestUnion(t *testing.T) {
function TestIntersection (line 144) | func TestIntersection(t *testing.T) {
function TestDifference (line 170) | func TestDifference(t *testing.T) {
function TestSymmetricDifference (line 196) | func TestSymmetricDifference(t *testing.T) {
FILE: structure/set/setexample_test.go
function ExampleSet (line 7) | func ExampleSet() {
FILE: structure/stack/stack_test.go
function TestStackLinkedList (line 20) | func TestStackLinkedList(t *testing.T) {
function TestStackArray (line 70) | func TestStackArray(t *testing.T) {
function TestStackLinkedListWithList (line 132) | func TestStackLinkedListWithList(t *testing.T) {
FILE: structure/stack/stackarray.go
type Array (line 12) | type Array struct
function NewStack (line 17) | func NewStack[T any]() *Array[T] {
method Push (line 22) | func (s *Array[T]) Push(value T) {
method Length (line 27) | func (s *Array[T]) Length() int {
method Peek (line 32) | func (s *Array[T]) Peek() T {
method IsEmpty (line 41) | func (s *Array[T]) IsEmpty() bool {
method Pop (line 46) | func (s *Array[T]) Pop() T {
FILE: structure/stack/stacklinkedlist.go
type Node (line 13) | type Node struct
type Stack (line 19) | type Stack struct
method Push (line 25) | func (ll *Stack) Push(n any) {
method Pop (line 36) | func (ll *Stack) Pop() any {
method IsEmpty (line 49) | func (ll *Stack) IsEmpty() bool {
method Length (line 54) | func (ll *Stack) Length() int {
method Peek (line 59) | func (ll *Stack) Peek() any {
method Show (line 64) | func (ll *Stack) Show() (in []any) {
FILE: structure/stack/stacklinkedlistwithlist.go
type SList (line 18) | type SList struct
method Push (line 23) | func (sl *SList) Push(val any) {
method Peek (line 28) | func (sl *SList) Peek() (any, error) {
method Pop (line 38) | func (sl *SList) Pop() (any, error) {
method Length (line 51) | func (sl *SList) Length() int {
method IsEmpty (line 56) | func (sl *SList) IsEmpty() bool {
FILE: structure/tree/avl.go
type AVLNode (line 18) | type AVLNode struct
method Key (line 26) | func (n *AVLNode[T]) Key() T {
method Parent (line 30) | func (n *AVLNode[T]) Parent() Node[T] {
method Left (line 34) | func (n *AVLNode[T]) Left() Node[T] {
method Right (line 38) | func (n *AVLNode[T]) Right() Node[T] {
method Height (line 42) | func (n *AVLNode[T]) Height() int {
type AVL (line 48) | type AVL struct
function NewAVL (line 54) | func NewAVL[T constraints.Ordered]() *AVL[T] {
method Empty (line 62) | func (avl *AVL[T]) Empty() bool {
method Push (line 67) | func (avl *AVL[T]) Push(keys ...T) {
method Delete (line 74) | func (avl *AVL[T]) Delete(key T) bool {
method Get (line 84) | func (avl *AVL[T]) Get(key T) (Node[T], bool) {
method Has (line 89) | func (avl *AVL[T]) Has(key T) bool {
method PreOrder (line 95) | func (avl *AVL[T]) PreOrder() []T {
method InOrder (line 102) | func (avl *AVL[T]) InOrder() []T {
method PostOrder (line 107) | func (avl *AVL[T]) PostOrder() []T {
method LevelOrder (line 114) | func (avl *AVL[T]) LevelOrder() []T {
method AccessNodesByLayer (line 121) | func (avl *AVL[T]) AccessNodesByLayer() [][]T {
method Depth (line 126) | func (avl *AVL[T]) Depth() int {
method Max (line 131) | func (avl *AVL[T]) Max() (T, bool) {
method Min (line 141) | func (avl *AVL[T]) Min() (T, bool) {
method Predecessor (line 153) | func (avl *AVL[T]) Predecessor(key T) (T, bool) {
method Successor (line 165) | func (avl *AVL[T]) Successor(key T) (T, bool) {
method pushHelper (line 174) | func (avl *AVL[T]) pushHelper(root *AVLNode[T], key T) *AVLNode[T] {
method deleteHelper (line 224) | func (avl *AVL[T]) deleteHelper(root *AVLNode[T], key T) *AVLNode[T] {
method height (line 295) | func (avl *AVL[T]) height(root *AVLNode[T]) int {
method balanceFactor (line 312) | func (avl *AVL[T]) balanceFactor(root *AVLNode[T]) int {
method leftRotate (line 323) | func (avl *AVL[T]) leftRotate(x *AVLNode[T]) *AVLNode[T] {
method rightRotate (line 341) | func (avl *AVL[T]) rightRotate(x *AVLNode[T]) *AVLNode[T] {
FILE: structure/tree/avl_test.go
function TestAVLPush (line 11) | func TestAVLPush(t *testing.T) {
function TestAVLDelete (line 124) | func TestAVLDelete(t *testing.T) {
FILE: structure/tree/bstree.go
type BSNode (line 15) | type BSNode struct
method Key (line 22) | func (n *BSNode[T]) Key() T {
method Parent (line 26) | func (n *BSNode[T]) Parent() Node[T] {
method Left (line 30) | func (n *BSNode[T]) Left() Node[T] {
method Right (line 34) | func (n *BSNode[T]) Right() Node[T] {
type BinarySearch (line 40) | type BinarySearch struct
function NewBinarySearch (line 46) | func NewBinarySearch[T constraints.Ordered]() *BinarySearch[T] {
method Empty (line 54) | func (t *BinarySearch[T]) Empty() bool {
method Push (line 59) | func (t *BinarySearch[T]) Push(keys ...T) {
method Delete (line 66) | func (t *BinarySearch[T]) Delete(val T) bool {
method Get (line 76) | func (t *BinarySearch[T]) Get(key T) (Node[T], bool) {
method Has (line 81) | func (t *BinarySearch[T]) Has(key T) bool {
method PreOrder (line 87) | func (t *BinarySearch[T]) PreOrder() []T {
method InOrder (line 94) | func (t *BinarySearch[T]) InOrder() []T {
method PostOrder (line 99) | func (t *BinarySearch[T]) PostOrder() []T {
method LevelOrder (line 106) | func (t *BinarySearch[T]) LevelOrder() []T {
method AccessNodesByLayer (line 113) | func (t *BinarySearch[T]) AccessNodesByLayer() [][]T {
method Depth (line 118) | func (t *BinarySearch[T]) Depth() int {
method Max (line 123) | func (t *BinarySearch[T]) Max() (T, bool) {
method Min (line 133) | func (t *BinarySearch[T]) Min() (T, bool) {
method Predecessor (line 145) | func (t *BinarySearch[T]) Predecessor(key T) (T, bool) {
method Successor (line 157) | func (t *BinarySearch[T]) Successor(key T) (T, bool) {
method pushHelper (line 166) | func (t *BinarySearch[T]) pushHelper(x *BSNode[T], val T) {
method deleteHelper (line 195) | func (t *BinarySearch[T]) deleteHelper(z *BSNode[T]) {
method transplant (line 215) | func (t *BinarySearch[T]) transplant(u, v *BSNode[T]) {
FILE: structure/tree/bstree_test.go
function TestPush (line 12) | func TestPush(t *testing.T) {
function TestDelete (line 36) | func TestDelete(t *testing.T) {
FILE: structure/tree/btree.go
type BTreeNode (line 8) | type BTreeNode struct
type BTree (line 15) | type BTree struct
function minKeys (line 20) | func minKeys(maxKeys int) int {
function NewBTreeNode (line 24) | func NewBTreeNode[T constraints.Ordered](maxKeys int, isLeaf bool) *BTre...
function NewBTree (line 35) | func NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] {
method Verify (line 45) | func (node *BTreeNode[T]) Verify(tree *BTree[T]) {
method IsFull (line 54) | func (node *BTreeNode[T]) IsFull(maxKeys int) bool {
method Search (line 58) | func (node *BTreeNode[T]) Search(key T) bool {
method Search (line 74) | func (tree *BTree[T]) Search(key T) bool {
method InsertKeyChild (line 81) | func (node *BTreeNode[T]) InsertKeyChild(key T, child *BTreeNode[T]) {
method Append (line 100) | func (node *BTreeNode[T]) Append(key T, child *BTreeNode[T]) {
method Concat (line 107) | func (node *BTreeNode[T]) Concat(other *BTreeNode[T], idx int) {
method Split (line 128) | func (parent *BTreeNode[T]) Split(idx int, maxKeys int) {
method InsertNonFull (line 149) | func (node *BTreeNode[T]) InsertNonFull(tree *BTree[T], key T) {
method Insert (line 178) | func (tree *BTree[T]) Insert(key T) {
method DeleteIthKey (line 196) | func (node *BTreeNode[T]) DeleteIthKey(i int) {
method Merge (line 219) | func (node *BTreeNode[T]) Merge(idx int) {
method Min (line 230) | func (node *BTreeNode[T]) Min() T {
method Max (line 237) | func (node *BTreeNode[T]) Max() T {
method Delete (line 244) | func (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {
method Delete (line 347) | func (tree *BTree[T]) Delete(key T) {
FILE: structure/tree/btree_test.go
function TestBTreeIncreasing (line 9) | func TestBTreeIncreasing(t *testing.T) {
function TestBTreeDecreasing (line 45) | func TestBTreeDecreasing(t *testing.T) {
function TestBTreeRandom (line 81) | func TestBTreeRandom(t *testing.T) {
function TestBTreeDeleteEverything (line 116) | func TestBTreeDeleteEverything(t *testing.T) {
FILE: structure/tree/example_test.go
type TestTree (line 11) | type TestTree interface
function TestBinarySearch (line 38) | func TestBinarySearch(t *testing.T) {
function TestAVL (line 83) | func TestAVL(t *testing.T) {
function TestRB (line 128) | func TestRB(t *testing.T) {
FILE: structure/tree/rbtree.go
type Color (line 14) | type Color
constant Red (line 17) | Red Color = iota
constant Black (line 18) | Black
type RBNode (line 25) | type RBNode struct
method Key (line 33) | func (n *RBNode[T]) Key() T {
method Parent (line 37) | func (n *RBNode[T]) Parent() Node[T] {
method Left (line 41) | func (n *RBNode[T]) Left() Node[T] {
method Right (line 45) | func (n *RBNode[T]) Right() Node[T] {
type RB (line 51) | type RB struct
function NewRB (line 57) | func NewRB[T constraints.Ordered]() *RB[T] {
method Empty (line 67) | func (t *RB[T]) Empty() bool {
method Push (line 72) | func (t *RB[T]) Push(keys ...T) {
method Delete (line 80) | func (t *RB[T]) Delete(data T) bool {
method Get (line 85) | func (t *RB[T]) Get(key T) (Node[T], bool) {
method Has (line 90) | func (t *RB[T]) Has(key T) bool {
method PreOrder (line 96) | func (t *RB[T]) PreOrder() []T {
method InOrder (line 103) | func (t *RB[T]) InOrder() []T {
method PostOrder (line 108) | func (t *RB[T]) PostOrder() []T {
method LevelOrder (line 115) | func (t *RB[T]) LevelOrder() []T {
method AccessNodesByLayer (line 122) | func (t *RB[T]) AccessNodesByLayer() [][]T {
method Depth (line 127) | func (t *RB[T]) Depth() int {
method Max (line 132) | func (t *RB[T]) Max() (T, bool) {
method Min (line 142) | func (t *RB[T]) Min() (T, bool) {
method Predecessor (line 154) | func (t *RB[T]) Predecessor(key T) (T, bool) {
method Successor (line 166) | func (t *RB[T]) Successor(key T) (T, bool) {
method pushHelper (line 175) | func (t *RB[T]) pushHelper(x *RBNode[T], key T) {
method leftRotate (line 216) | func (t *RB[T]) leftRotate(x *RBNode[T]) {
method rightRotate (line 237) | func (t *RB[T]) rightRotate(x *RBNode[T]) {
method pushFix (line 257) | func (t *RB[T]) pushFix(k *RBNode[T]) {
method deleteHelper (line 300) | func (t *RB[T]) deleteHelper(node *RBNode[T], key T) bool {
method deleteFix (line 352) | func (t *RB[T]) deleteFix(x *RBNode[T]) {
method transplant (line 413) | func (t *RB[T]) transplant(u, v *RBNode[T]) {
FILE: structure/tree/rbtree_test.go
function TestRBTreePush (line 12) | func TestRBTreePush(t *testing.T) {
function TestRBTreeDelete (line 48) | func TestRBTreeDelete(t *testing.T) {
function TestRBTree (line 85) | func TestRBTree(t *testing.T) {
function TestRBTreeString (line 123) | func TestRBTreeString(t *testing.T) {
FILE: structure/tree/tree.go
type Node (line 15) | type Node interface
function accessNodeByLayerHelper (line 24) | func accessNodeByLayerHelper[T constraints.Ordered](root, nilNode Node[T...
function searchTreeHelper (line 52) | func searchTreeHelper[T constraints.Ordered](node, nilNode Node[T], key ...
function inOrderHelper (line 66) | func inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {
function preOrderRecursive (line 85) | func preOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traver...
function postOrderRecursive (line 96) | func postOrderRecursive[T constraints.Ordered](n, nilNode Node[T], trave...
function calculateDepth (line 106) | func calculateDepth[T constraints.Ordered](n, nilNode Node[T], depth int...
function minimum (line 114) | func minimum[T constraints.Ordered](node, nilNode Node[T]) Node[T] {
function maximum (line 125) | func maximum[T constraints.Ordered](node, nilNode Node[T]) Node[T] {
function levelOrderHelper (line 136) | func levelOrderHelper[T constraints.Ordered](root, nilNode Node[T], trav...
function predecessorHelper (line 155) | func predecessorHelper[T constraints.Ordered](node, nilNode Node[T]) (T,...
function successorHelper (line 173) | func successorHelper[T constraints.Ordered](node, nilNode Node[T]) (T, b...
FILE: structure/tree/tree_test.go
function TestTreeGetOrHas (line 12) | func TestTreeGetOrHas(t *testing.T) {
function TestTreePreOrder (line 53) | func TestTreePreOrder(t *testing.T) {
function TestTreeInOrder (line 109) | func TestTreeInOrder(t *testing.T) {
function TestTreePostOrder (line 140) | func TestTreePostOrder(t *testing.T) {
function TestTreeLevelOrder (line 199) | func TestTreeLevelOrder(t *testing.T) {
function TestTreeMinAndMax (line 258) | func TestTreeMinAndMax(t *testing.T) {
function TestTreeDepth (line 295) | func TestTreeDepth(t *testing.T) {
function TestTreeAccessNodesByLayer (line 354) | func TestTreeAccessNodesByLayer(t *testing.T) {
function TestTreePredecessorAndSuccessor (line 417) | func TestTreePredecessorAndSuccessor(t *testing.T) {
constant testNum (line 493) | testNum = 10_000
function BenchmarkBSTree_Insert (line 495) | func BenchmarkBSTree_Insert(b *testing.B) {
function BenchmarkBSTree_Has (line 508) | func BenchmarkBSTree_Has(b *testing.B) {
function BenchmarkBSTree_Delete (line 525) | func BenchmarkBSTree_Delete(b *testing.B) {
function BenchmarkRBTree_Insert (line 542) | func BenchmarkRBTree_Insert(b *testing.B) {
function BenchmarkRBTree_Has (line 555) | func BenchmarkRBTree_Has(b *testing.B) {
function BenchmarkRBTree_Delete (line 572) | func BenchmarkRBTree_Delete(b *testing.B) {
function BenchmarkAVLTree_Insert (line 589) | func BenchmarkAVLTree_Insert(b *testing.B) {
function BenchmarkAVLTree_Has (line 603) | func BenchmarkAVLTree_Has(b *testing.B) {
function BenchmarkAVLTree_Delete (line 620) | func BenchmarkAVLTree_Delete(b *testing.B) {
FILE: structure/trie/trie.go
type Node (line 7) | type Node struct
method insert (line 22) | func (n *Node) insert(s string) {
method Insert (line 36) | func (n *Node) Insert(s ...string) {
method Find (line 43) | func (n *Node) Find(s string) bool {
method Capacity (line 55) | func (n *Node) Capacity() int {
method Size (line 64) | func (n *Node) Size() int {
method remove (line 76) | func (n *Node) remove(s string) {
method Remove (line 92) | func (n *Node) Remove(s ...string) {
method Compact (line 99) | func (n *Node) Compact() (remove bool) {
function NewNode (line 14) | func NewNode() *Node {
FILE: structure/trie/trie_bench_test.go
function BenchmarkTrie_Insert (line 12) | func BenchmarkTrie_Insert(b *testing.B) {
function BenchmarkTrie_Find_non_existent (line 25) | func BenchmarkTrie_Find_non_existent(b *testing.B) {
function BenchmarkTrie_Find_existent (line 40) | func BenchmarkTrie_Find_existent(b *testing.B) {
function BenchmarkTrie_Remove_lazy (line 54) | func BenchmarkTrie_Remove_lazy(b *testing.B) {
function BenchmarkTrie_Remove_and_Compact (line 68) | func BenchmarkTrie_Remove_and_Compact(b *testing.B) {
FILE: structure/trie/trie_test.go
function TestTrieInsert (line 7) | func TestTrieInsert(t *testing.T) {
function TestTrieInsert_substrings (line 27) | func TestTrieInsert_substrings(t *testing.T) {
function TestTrieRemove (line 62) | func TestTrieRemove(t *testing.T) {
method verify (line 131) | func (n *Node) verify(t *testing.T, checkWords map[string]bool) {
method verifySizeCapa (line 150) | func (n *Node) verifySizeCapa(t *testing.T, expectedSize, expectedCapaci...
FILE: structure/trie/trieexample_test.go
function ExampleNode (line 5) | func ExampleNode() {
Condensed preview — 519 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,011K chars).
[
{
"path": ".github/CODEOWNERS",
"chars": 298,
"preview": "# This is a comment.\n# Each line is a file pattern followed by one or more owners.\n\n# More details are here: https://hel"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.yml",
"chars": 1216,
"preview": "name: \"Bug report\"\ndescription: \"Create a report to help us improve\"\ntitle: \"[BUG]\"\nlabels: [\"bug\"]\nbody:\n - type: text"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 28,
"preview": "blank_issues_enabled: false\n"
},
{
"path": ".github/ISSUE_TEMPLATE/new_implementation.yml",
"chars": 1145,
"preview": "name: \"New or optimize implementation\"\ndescription: \"Propose an enhancement or a new algorithm implementation.\"\ntitle: \""
},
{
"path": ".github/ISSUE_TEMPLATE/other.yml",
"chars": 616,
"preview": "name: Other\ndescription: Use this for any other issues. Do NOT create blank issues\ntitle: \"[OTHER]\"\nlabels: [\"awaiting t"
},
{
"path": ".github/PULL_REQUEST_TEMPLATE/pull_request.md",
"chars": 1125,
"preview": "#### Description of Change\n<!--\nThank you for your Pull Request. Please provide a description above and review\nthe requi"
},
{
"path": ".github/dependabot.yml",
"chars": 579,
"preview": "# Keep GitHub Actions up to date with GitHub's Dependabot...\n# https://docs.github.com/en/code-security/dependabot/worki"
},
{
"path": ".github/workflows/ci.yml",
"chars": 932,
"preview": "# https://github.com/golangci/golangci-lint\nname: Continuous Integration\non:\n push:\n # prevent duplication of tests "
},
{
"path": ".github/workflows/citk.yml",
"chars": 646,
"preview": "# https://github.com/golangci/golangci-lint\nname: CI tool kit\non:\n pull_request:\n\njobs:\n CITK:\n name: Code style an"
},
{
"path": ".github/workflows/godocmd.yml",
"chars": 968,
"preview": "name: Generate Documentation\non:\n push:\n branches:\n - master\n\njobs:\n generate_readme:\n name: Markdown Gener"
},
{
"path": ".github/workflows/stale.yml",
"chars": 869,
"preview": "name: 'Close stale issues and PRs'\non:\n schedule:\n - cron: '0 0 * * *'\njobs:\n stale:\n runs-on: ubuntu-latest\n "
},
{
"path": ".github/workflows/upload_coverage_report.yml",
"chars": 1060,
"preview": "---\nname: upload_coverage_report\n\non:\n workflow_dispatch:\n push:\n branches:\n - master\n pull_request:\n\nenv:\n "
},
{
"path": ".gitignore",
"chars": 29,
"preview": ".idea/\n.vscode/\ncoverage.out\n"
},
{
"path": ".gitpod.dockerfile",
"chars": 25,
"preview": "FROM gitpod/workspace-go\n"
},
{
"path": ".gitpod.yml",
"chars": 99,
"preview": "---\nimage:\n file: .gitpod.dockerfile\n\ntasks:\n - init: |\n echo \"Welcome to TheAlgorithms/Go\"\n"
},
{
"path": ".golangci.yml",
"chars": 16,
"preview": "run:\n go: 1.19\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 9542,
"preview": "# CONTRIBUTION GUIDELINES\n\n## Before contributing\n\nWelcome to [TheAlgorithms/Go](https://github.com/TheAlgorithms/Go)! B"
},
{
"path": "LICENSE",
"chars": 1088,
"preview": "MIT License\n\nCopyright (c) 2021 The Algorithms and contributors\n\nPermission is hereby granted, free of charge, to any pe"
},
{
"path": "README.md",
"chars": 55716,
"preview": "# The Algorithms - Go\n[\n\nfunc TestLFU(t *testing.T) {\n\tlfuCache "
},
{
"path": "cache/lru.go",
"chars": 1585,
"preview": "// lru.go\n// description : Least Recently Used (LRU) cache\n// details : A Least Recently Used (LRU) cache is a type of c"
},
{
"path": "cache/lru_test.go",
"chars": 1159,
"preview": "package cache_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/cache\"\n)\n\nfunc TestLRU(t *testing.T) {\n\tcache := "
},
{
"path": "checksum/crc8.go",
"chars": 1649,
"preview": "// crc8.go\n// description: Calculate CRC8\n// details:\n// A cyclic redundancy check (CRC) is an error-detecting code comm"
},
{
"path": "checksum/crc8_test.go",
"chars": 1993,
"preview": "// crc8_test.go\n// description: Test for calculate crc8\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see crc"
},
{
"path": "checksum/luhn.go",
"chars": 783,
"preview": "// lunh.go\n// description: Luhn algorithm\n// details: is a simple checksum formula used to validate a variety of identif"
},
{
"path": "checksum/luhn_test.go",
"chars": 1039,
"preview": "// luhn_test.go\n// description: Test for Luhn algorithm\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see luh"
},
{
"path": "cipher/caesar/caesar.go",
"chars": 1208,
"preview": "// Package caesar is the shift cipher\n// description: Caesar cipher\n// details : Caesar cipher is a type of substitution"
},
{
"path": "cipher/caesar/caesar_test.go",
"chars": 3686,
"preview": "package caesar\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestEncrypt(t *testing.T) {\n\tvar caesarTestData "
},
{
"path": "cipher/cipher_test.go",
"chars": 86,
"preview": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage cipher\n"
},
{
"path": "cipher/diffiehellman/diffiehellmankeyexchange.go",
"chars": 1409,
"preview": "// Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm\n// description: Diffie-Hellman key exchange\n//"
},
{
"path": "cipher/diffiehellman/diffiehellmankeyexchange_test.go",
"chars": 1432,
"preview": "package diffiehellman\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"testing\"\n)\n\nfunc TestDiffieHellmanKeyExchange(t *testing."
},
{
"path": "cipher/doc.go",
"chars": 102,
"preview": "// Package cipher is a package containing different implementations of certain ciphers\npackage cipher\n"
},
{
"path": "cipher/dsa/dsa.go",
"chars": 4927,
"preview": "/*\ndsa.go\ndescription: DSA encryption and decryption including key generation\ndetails: [DSA wiki](https://en.wikipedia.o"
},
{
"path": "cipher/dsa/dsa_test.go",
"chars": 1938,
"preview": "package dsa_test\n\nimport (\n\t\"math/big\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/cipher/dsa\"\n)\n\nfunc TestDSA(t *testing."
},
{
"path": "cipher/polybius/polybius.go",
"chars": 3143,
"preview": "// Package polybius is encrypting method with polybius square\n// description: Polybius square\n// details : The Polybius "
},
{
"path": "cipher/polybius/polybius_test.go",
"chars": 5124,
"preview": "package polybius\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc ExampleNewPolybius() {\n\t// initialize\n\tconst (\n\t\t"
},
{
"path": "cipher/railfence/railfence.go",
"chars": 1840,
"preview": "// railfence.go\n// description: Rail Fence Cipher\n// details: The rail fence cipher is a an encryption algorithm that us"
},
{
"path": "cipher/railfence/railfence_test.go",
"chars": 1563,
"preview": "package railfence\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEncrypt(t *testing.T) {\n\tvar railFenceTestData = []struct {\n\t\tdescrip"
},
{
"path": "cipher/rot13/rot13.go",
"chars": 635,
"preview": "// Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alph"
},
{
"path": "cipher/rot13/rot13_test.go",
"chars": 1835,
"preview": "package rot13\n\nimport (\n\t\"testing\"\n)\n\nvar rot13TestData = []struct {\n\tdescription string\n\tinput string\n\texpected "
},
{
"path": "cipher/rsa/rsa.go",
"chars": 1839,
"preview": "// rsa.go\n// description: Simple RSA algorithm implementation\n// details:\n// A simple RSA Encryption and Decryption algo"
},
{
"path": "cipher/rsa/rsa2.go",
"chars": 3335,
"preview": "/*\nrsa2.go\ndescription: RSA encryption and decryption including key generation\ndetails: [RSA wiki](https://en.wikipedia."
},
{
"path": "cipher/rsa/rsa2_test.go",
"chars": 945,
"preview": "package rsa_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/cipher/rsa\"\n)\n\nfunc TestRSA(t *testing.T) {\n\ttests "
},
{
"path": "cipher/rsa/rsa_test.go",
"chars": 2373,
"preview": "// rsa_test.go\n// description: Test for RSA Encrypt and Decrypt algorithms\n// author(s) [Taj](https://github.com/tjgurwa"
},
{
"path": "cipher/transposition/transposition.go",
"chars": 3028,
"preview": "// transposition.go\n// description: Transposition cipher\n// details:\n// Implementation \"Transposition cipher\" is a metho"
},
{
"path": "cipher/transposition/transposition_test.go",
"chars": 3999,
"preview": "// transposition_test.go\n// description: Transposition cipher\n// author(s) [red_byte](https://github.com/i-redbyte)\n// s"
},
{
"path": "cipher/xor/xor.go",
"chars": 1071,
"preview": "// Package xor is an encryption algorithm that operates the exclusive disjunction(XOR)\n// description: XOR encryption\n//"
},
{
"path": "cipher/xor/xor_test.go",
"chars": 2580,
"preview": "package xor\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc Example() {\n\tconst (\n\t\tseed = \"Hello World\"\n\t\tkey ="
},
{
"path": "compression/huffmancoding.go",
"chars": 3908,
"preview": "// huffman.go\n// description: Implements Huffman compression, encoding and decoding\n// details:\n// We implement the line"
},
{
"path": "compression/huffmancoding_test.go",
"chars": 1710,
"preview": "// huffmancoding_test.go\n// description: Tests the compression, encoding and decoding algorithms of huffmancoding.go.\n//"
},
{
"path": "compression/rlecoding.go",
"chars": 2006,
"preview": "/*\nrlecoding.go\ndescription: run length encoding and decoding\ndetails:\nRun-length encoding (RLE) is a simple form of dat"
},
{
"path": "compression/rlecoding_test.go",
"chars": 3202,
"preview": "package compression_test\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/compression\"\n)\n\nfunc TestCompressi"
},
{
"path": "constraints/constraints.go",
"chars": 1519,
"preview": "// Package constraints has some useful generic type constraints defined which is very similar to\n// [golang.org/x/exp/co"
},
{
"path": "conversion/base64.go",
"chars": 2732,
"preview": "// base64.go\n// description: The base64 encoding algorithm as defined in the RFC4648 standard.\n// author: [Paul Leydier]"
},
{
"path": "conversion/base64_test.go",
"chars": 8261,
"preview": "package conversion\n\nimport \"testing\"\n\nfunc TestBase64Encode(t *testing.T) {\n\ttestCases := []struct {\n\t\tin string\n\t"
},
{
"path": "conversion/binarytodecimal.go",
"chars": 1098,
"preview": "/*\nAuthor: Motasim\nGitHub: https://github.com/motasimmakki\nDate: 19-Oct-2021\n*/\n\n// This algorithm will convert any Bina"
},
{
"path": "conversion/binarytodecimal_test.go",
"chars": 1941,
"preview": "package conversion\n\nimport \"testing\"\n\nvar binaryTestCases = map[string]int{\n\t\"0\": 0, \"1\": 1, \"10\": 2, \"11\": 3, \"100\": 4,"
},
{
"path": "conversion/conversion_test.go",
"chars": 90,
"preview": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage conversion\n"
},
{
"path": "conversion/decimaltobinary.go",
"chars": 1150,
"preview": "/*\nAuthor: Motasim\nGitHub: https://github.com/motasimmakki\nDate: 14-Oct-2021\n*/\n\n// This algorithm will convert any Deci"
},
{
"path": "conversion/decimaltobinary_test.go",
"chars": 1937,
"preview": "package conversion\n\nimport \"testing\"\n\nvar decimalTestCases = map[int]string{\n\t0: \"0\", 1: \"1\", 2: \"10\", 3: \"11\", 4: \"100\""
},
{
"path": "conversion/doc.go",
"chars": 119,
"preview": "// Package conversion is a package of implementations which converts one data structure to another.\npackage conversion\n"
},
{
"path": "conversion/hexadecimaltobinary.go",
"chars": 2158,
"preview": "/*\nAuthor: mapcrafter2048\nGitHub: https://github.com/mapcrafter2048\n*/\n\n// This algorithm will convert any Hexadecimal n"
},
{
"path": "conversion/hexadecimaltobinary_test.go",
"chars": 1004,
"preview": "package conversion\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHexToBinary(t *testing.T) {\n\ttests := []struct {\n\t\thex string\n\t\t"
},
{
"path": "conversion/hexadecimaltodecimal.go",
"chars": 1504,
"preview": "/*\nAuthor: mapcrafter2048\nGitHub: https://github.com/mapcrafter2048\n*/\n\n// This algorithm will convert any Hexadecimal n"
},
{
"path": "conversion/hexadecimaltodecimal_test.go",
"chars": 1054,
"preview": "package conversion\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHexToDecimal(t *testing.T) {\n\ttests := []struct {\n\t\thex string\n\t"
},
{
"path": "conversion/inttoroman.go",
"chars": 1898,
"preview": "// inttoroman.go\n// description: Convert an integer to a roman numeral\n// details: This program converts an integer to a"
},
{
"path": "conversion/inttoroman_test.go",
"chars": 662,
"preview": "package conversion\n\nimport \"testing\"\n\nfunc TestIntToRoman(t *testing.T) {\n\tfor expected, input := range romanTestCases {"
},
{
"path": "conversion/rgbhex.go",
"chars": 1980,
"preview": "// rgbhex.go\n// description: convert hex input to red, green and blue and vice versa\n// time complexity: O(1)\n// space c"
},
{
"path": "conversion/rgbhex_test.go",
"chars": 1028,
"preview": "package conversion\n\nimport \"testing\"\n\nvar HEX = []uint{\n\t0x1abc9c,\n\t0x3498db,\n\t0x9b59b6,\n}\n\nvar RGB = [][]byte{\n\t{26, 18"
},
{
"path": "conversion/romantoint.go",
"chars": 1344,
"preview": "// This algorithm will convert a standard roman number to an integer\n// https://en.wikipedia.org/wiki/Roman_numerals\n// "
},
{
"path": "conversion/romantoint_test.go",
"chars": 1813,
"preview": "package conversion\n\nimport \"testing\"\n\nvar romanTestCases = map[string]int{\n\t\"I\": 1, \"II\": 2, \"III\": 3, \"IV\": 4, \"V\": 5, "
},
{
"path": "dynamic/abbreviation.go",
"chars": 1565,
"preview": "// File: abbreviation.go\n// Description: Abbreviation problem\n// Details:\n// https://www.hackerrank.com/challenges/abb"
},
{
"path": "dynamic/abbreviation_test.go",
"chars": 886,
"preview": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestAbbreviation(t *testing.T) {\n\ttests := []struct {\n\t\ta str"
},
{
"path": "dynamic/binomialcoefficient.go",
"chars": 1328,
"preview": "// binomialcoefficient.go\n// description: Implementation of the binomial coefficient using dynamic programming\n// detail"
},
{
"path": "dynamic/binomialcoefficient_test.go",
"chars": 760,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc TestBin2(t *testing.T) "
},
{
"path": "dynamic/burstballoons.go",
"chars": 676,
"preview": "package dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/max\"\n\n// MaxCoins returns the maximum coins we can collect by "
},
{
"path": "dynamic/burstballoons_test.go",
"chars": 761,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseBurstBalloons struct {"
},
{
"path": "dynamic/catalan.go",
"chars": 870,
"preview": "//The Catalan numbers are a sequence of positive integers that appear in many counting\n// problems in combinatorics.\n// "
},
{
"path": "dynamic/catalan_test.go",
"chars": 1992,
"preview": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestCatalanNumbers(t *testing.T) {\n\tvar testCatalanNumbersData = []s"
},
{
"path": "dynamic/coinchange.go",
"chars": 843,
"preview": "// coinchange.go\n// description: Implementation of the coin change problem using dynamic programming\n// details: The coi"
},
{
"path": "dynamic/coinchange_test.go",
"chars": 565,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n\t\"testing\"\n)\n\nfunc TestCoinChange(t *testin"
},
{
"path": "dynamic/dicethrow.go",
"chars": 673,
"preview": "// dicethrow.go\n// description: Solves the Dice Throw Problem using dynamic programming\n// reference: https://www.geeksf"
},
{
"path": "dynamic/dicethrow_test.go",
"chars": 1305,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseDiceThrow struct {\n\tnu"
},
{
"path": "dynamic/doc.go",
"chars": 106,
"preview": "// Package dynamic is a package of certain implementations of dynamically run algorithms.\npackage dynamic\n"
},
{
"path": "dynamic/dynamic_test.go",
"chars": 87,
"preview": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage dynamic\n"
},
{
"path": "dynamic/editdistance.go",
"chars": 2085,
"preview": "// EDIT DISTANCE PROBLEM\n// time complexity: O(m * n) where m and n are lengths of the strings, first and second respect"
},
{
"path": "dynamic/editdistance_test.go",
"chars": 776,
"preview": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc Test_EditDistance(t *testing.T) {\n\n\tvar testCases = []struct {\n\t\tfir"
},
{
"path": "dynamic/eggdropping.go",
"chars": 1150,
"preview": "package dynamic\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/max\"\n\t\"github.com/TheAlgorithms/Go/math/min\"\n)\n\n// EggDropp"
},
{
"path": "dynamic/eggdropping_test.go",
"chars": 822,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseEggDropping struct {\n\t"
},
{
"path": "dynamic/fibonacci.go",
"chars": 525,
"preview": "// fibonacci.go\n// description: Implementation of the Fibonacci sequence using dynamic programming\n// time complexity: O"
},
{
"path": "dynamic/fibonacci_test.go",
"chars": 915,
"preview": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc Test_NthFibonacci(t *testing.T) {\n\t// source: http://www.maths.surre"
},
{
"path": "dynamic/interleavingstrings.go",
"chars": 900,
"preview": "// interleavingstrings.go\n// description: Solves the Interleaving Strings problem using dynamic programming\n// reference"
},
{
"path": "dynamic/interleavingstrings_test.go",
"chars": 1190,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseInterleaving struct {\n"
},
{
"path": "dynamic/knapsack.go",
"chars": 1021,
"preview": "package dynamic\n\n// Knapsack Problem\n// https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/\n// https://en.wikipedi"
},
{
"path": "dynamic/knapsack_test.go",
"chars": 1252,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc TestKnapsack(t *testing"
},
{
"path": "dynamic/longestarithmeticsubsequence.go",
"chars": 759,
"preview": "// longestarithmeticsubsequence.go\n// description: Implementation of the Longest Arithmetic Subsequence problem\n// refer"
},
{
"path": "dynamic/longestarithmeticsubsequence_test.go",
"chars": 1485,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLongestArithmeticSubse"
},
{
"path": "dynamic/longestcommonsubsequence.go",
"chars": 1091,
"preview": "// LONGEST COMMON SUBSEQUENCE\n// DP - 4\n// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/\n// https://lee"
},
{
"path": "dynamic/longestcommonsubsequence_test.go",
"chars": 1197,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLCS struct {\n\tstringA "
},
{
"path": "dynamic/longestincreasingsubsequence.go",
"chars": 836,
"preview": "// longestincreasingsubsequence.go\n// description: Implementation of the Longest Increasing Subsequence using dynamic pr"
},
{
"path": "dynamic/longestincreasingsubsequence_test.go",
"chars": 1004,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc longestIncreasingSubseq"
},
{
"path": "dynamic/longestincreasingsubsequencegreedy.go",
"chars": 1491,
"preview": "package dynamic\n\n// LongestIncreasingSubsequenceGreedy is a function to find the longest increasing\n// subsequence in a "
},
{
"path": "dynamic/longestpalindromicsubsequence.go",
"chars": 962,
"preview": "// longest palindromic subsequence\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n// http://www.geeksforgeeks.or"
},
{
"path": "dynamic/longestpalindromicsubsequence_test.go",
"chars": 747,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc lpsTestTemplate(t *test"
},
{
"path": "dynamic/longestpalindromicsubstring.go",
"chars": 936,
"preview": "// longestpalindromicsubstring.go\n// description: Implementation of finding the longest palindromic substring\n// referen"
},
{
"path": "dynamic/longestpalindromicsubstring_test.go",
"chars": 1346,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLongestPalindromicSubs"
},
{
"path": "dynamic/matrixmultiplication.go",
"chars": 1241,
"preview": "// matrix chain multiplication problem\n// https://en.wikipedia.org/wiki/Matrix_chain_multiplication\n// www.geeksforgeeks"
},
{
"path": "dynamic/maxsubarraysum.go",
"chars": 588,
"preview": "// maxsubarraysum.go\n// description: Implementation of Kadane's algorithm for Maximum Subarray Sum\n// reference: https:/"
},
{
"path": "dynamic/maxsubarraysum_test.go",
"chars": 1335,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseMaxSubArraySum struct "
},
{
"path": "dynamic/optimalbst.go",
"chars": 1364,
"preview": "package dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// OptimalBST returns the minimum cost of constructing a"
},
{
"path": "dynamic/optimalbst_test.go",
"chars": 952,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseOptimalBST struct {\n\tk"
},
{
"path": "dynamic/partitionproblem.go",
"chars": 700,
"preview": "// partitionproblem.go\n// description: Solves the Partition Problem using dynamic programming\n// reference: https://en.w"
},
{
"path": "dynamic/partitionproblem_test.go",
"chars": 1424,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\n// testCasePartitionProblem holds t"
},
{
"path": "dynamic/rodcutting.go",
"chars": 1188,
"preview": "// Solution to Rod cutting problem\n// https://en.wikipedia.org/wiki/Cutting_stock_problem\n// http://www.geeksforgeeks.or"
},
{
"path": "dynamic/rodcutting_test.go",
"chars": 842,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype rodCuttingTestCase struct {\n\tp"
},
{
"path": "dynamic/subsetsum.go",
"chars": 1295,
"preview": "//Given a set of non-negative integers, and a (positive) value sum,\n//determine if there is a subset of the given set wi"
},
{
"path": "dynamic/subsetsum_test.go",
"chars": 2334,
"preview": "package dynamic\n\nimport \"testing\"\n\nfunc TestSubsetSum(t *testing.T) {\n\n\tvar subsetSumTestData = []struct {\n\t\tdescription"
},
{
"path": "dynamic/tilingproblem.go",
"chars": 478,
"preview": "// tilingproblem.go\n// description: Solves the Tiling Problem using dynamic programming\n// reference: https://en.wikiped"
},
{
"path": "dynamic/tilingproblem_test.go",
"chars": 1008,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseTilingProblem struct {"
},
{
"path": "dynamic/traprainwater.go",
"chars": 1960,
"preview": "// filename: traprainwater.go\n// description: Provides a function to calculate the amount of trapped rainwater between b"
},
{
"path": "dynamic/traprainwater_test.go",
"chars": 575,
"preview": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc TestTrapRainWater(t *te"
},
{
"path": "dynamic/uniquepaths.go",
"chars": 713,
"preview": "// See https://leetcode.com/problems/unique-paths/\n// time complexity: O(m*n) where m and n are the dimensions of the gr"
},
{
"path": "dynamic/uniquepaths_test.go",
"chars": 678,
"preview": "package dynamic\n\nimport (\n\t\"testing\"\n)\n\nfunc TestUniquePaths(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tm in"
},
{
"path": "dynamic/wildcardmatching.go",
"chars": 777,
"preview": "// wildcardmatching.go\n// description: Solves the Wildcard Matching problem using dynamic programming\n// reference: http"
},
{
"path": "dynamic/wildcardmatching_test.go",
"chars": 1615,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\n// testCaseWildcardMatching holds t"
},
{
"path": "dynamic/wordbreak.go",
"chars": 650,
"preview": "// wordbreak.go\n// description: Solves the Word Break Problem using dynamic programming\n// reference: https://en.wikiped"
},
{
"path": "dynamic/wordbreak_test.go",
"chars": 1898,
"preview": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseWordBreak struct {\n\ts "
},
{
"path": "go.mod",
"chars": 44,
"preview": "module github.com/TheAlgorithms/Go\n\ngo 1.19\n"
},
{
"path": "go.sum",
"chars": 0,
"preview": ""
},
{
"path": "graph/articulationpoints.go",
"chars": 3007,
"preview": "// Package graph provides algorithms to analyze graph structures.\npackage graph\n\nimport \"github.com/TheAlgorithms/Go/mat"
},
{
"path": "graph/articulationpoints_test.go",
"chars": 1091,
"preview": "package graph\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestArticulationPoints(t *testing.T) {\n\tvar testCases = []struct {"
},
{
"path": "graph/bellmanford.go",
"chars": 1627,
"preview": "// The Bellman–Ford algorithm is an algorithm that computes shortest paths from a\n// single source vertex to all of the "
},
{
"path": "graph/bellmanford_test.go",
"chars": 2555,
"preview": "package graph\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestBellmanford(t *testing.T) {\n\n\tvar testCases = []"
},
{
"path": "graph/breadthfirstsearch.go",
"chars": 1380,
"preview": "package graph\n\n// BreadthFirstSearch is an algorithm for traversing and searching graph data structures.\n// It starts at"
},
{
"path": "graph/breadthfirstsearch_test.go",
"chars": 1482,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBreadthFirstSearch(t *testing.T) {\n\tvar bfsTestData = []struct {\n\t\tdescri"
},
{
"path": "graph/coloring/backtracking.go",
"chars": 1547,
"preview": "// This file contains the graph coloring implementation using backtracking\n// time complexity: O(V^V) where V is the num"
},
{
"path": "graph/coloring/backtracking_test.go",
"chars": 719,
"preview": "// This file provides tests for coloring using backtracking.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npacka"
},
{
"path": "graph/coloring/bfs.go",
"chars": 1596,
"preview": "// This file contains the graph coloring implementation using BFS\n// time complexity: O(V+E) where V is the number of ve"
},
{
"path": "graph/coloring/bfs_test.go",
"chars": 674,
"preview": "// This file provides tests for coloring using BFS.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage colori"
},
{
"path": "graph/coloring/bipartite.go",
"chars": 1503,
"preview": "package coloring\n\n// Bipartite.go\n// description: Implementation of the Bipartite graph coloring algorithm\n// details: A"
},
{
"path": "graph/coloring/bipartite_test.go",
"chars": 516,
"preview": "package coloring\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname string\n\tN int\n\tisBipartite bo"
},
{
"path": "graph/coloring/doc.go",
"chars": 228,
"preview": "// Package coloring provides implementation of different graph coloring\n// algorithms, e.g. coloring using BFS, using Ba"
},
{
"path": "graph/coloring/graph.go",
"chars": 1518,
"preview": "// This file contains the simple structural implementation of undirected\n// graph, used in coloring algorithms.\n// Autho"
},
{
"path": "graph/coloring/graph_test.go",
"chars": 3343,
"preview": "// This file provides tests for graph coloring validations.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackag"
},
{
"path": "graph/coloring/greedy.go",
"chars": 1857,
"preview": "// This file contains the graph coloring implementation using Greedy Approach.\n// time complexity: O(V^2) where V is the"
},
{
"path": "graph/coloring/greedy_test.go",
"chars": 730,
"preview": "// This file provides tests for coloring using Greedy approach.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npa"
},
{
"path": "graph/cycle.go",
"chars": 2806,
"preview": "// cycle.go\n// this file handle algorithm that related to cycle in graph\n// time complexity: O(V+E) where V is the numbe"
},
{
"path": "graph/cycle_test.go",
"chars": 1236,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHasCycle(t *testing.T) {\n\tgraph := Graph{Directed: true}\n\tedges := [][]in"
},
{
"path": "graph/depthfirstsearch.go",
"chars": 2082,
"preview": "// depthfirstsearch.go\n// description: this file contains the implementation of the depth first search algorithm\n// deta"
},
{
"path": "graph/depthfirstsearch_test.go",
"chars": 1752,
"preview": "package graph\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDfsWhenPathIsFound(t *testing.T) {\n\tnodes := []int{\n\t\t1, 2, 3,"
},
{
"path": "graph/dijkstra.go",
"chars": 1902,
"preview": "// dijkstra.go\n// description: this file contains the implementation of the Dijkstra algorithm\n// details: Dijkstra's al"
},
{
"path": "graph/dijkstra_test.go",
"chars": 928,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nvar tc_dijkstra = []struct {\n\tname string\n\tedges [][]int\n\tnode0 int\n\tnod"
},
{
"path": "graph/doc.go",
"chars": 127,
"preview": "// Package graph demonstrates Graph search algorithms\n// reference: https://en.wikipedia.org/wiki/Tree_traversal\npackage"
},
{
"path": "graph/edmondkarp.go",
"chars": 2516,
"preview": "// Edmond-Karp algorithm is an implementation of the Ford-Fulkerson method\n// to compute max-flow between a pair of sour"
},
{
"path": "graph/edmondkarp_test.go",
"chars": 1551,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEdmondKarp(t *testing.T) {\n\tvar edmondKarpTestData = []struct {\n\t\tdescrip"
},
{
"path": "graph/floydwarshall.go",
"chars": 1567,
"preview": "// Floyd-Warshall algorithm\n// time complexity: O(V^3) where V is the number of vertices in the graph\n// space complexit"
},
{
"path": "graph/floydwarshall_test.go",
"chars": 2212,
"preview": "package graph\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nconst float64EqualityThreshold = 1e-9\n\n// almostEqual subtracts two float6"
},
{
"path": "graph/graph.go",
"chars": 1542,
"preview": "// This file contains the simple structural implementation of\n// directed & undirected graphs used within the graph pack"
},
{
"path": "graph/graph_test.go",
"chars": 2678,
"preview": "// Tests for directed and undirected graphs\n\npackage graph\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar graphTestCases = []struct "
},
{
"path": "graph/kahn.go",
"chars": 2131,
"preview": "// Kahn's algorithm computes a topological ordering of a directed acyclic graph (DAG).\n// Time Complexity: O(V + E)\n// S"
},
{
"path": "graph/kahn_test.go",
"chars": 1980,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestKahn(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tn "
},
{
"path": "graph/kosaraju.go",
"chars": 2599,
"preview": "// kosaraju.go\n// description: Implementation of Kosaraju's algorithm to find Strongly Connected Components (SCCs) in a "
},
{
"path": "graph/kosaraju_test.go",
"chars": 1941,
"preview": "package graph\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestKosaraju(t *testing.T) {\n\ttests := []struct {\n\t\tname "
},
{
"path": "graph/kruskal.go",
"chars": 1559,
"preview": "// KRUSKAL'S ALGORITHM\n// Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorith"
},
{
"path": "graph/kruskal_test.go",
"chars": 1790,
"preview": "package graph\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestKruskalMST(t *testing.T) {\n\t// Define test cases with inputs, expe"
},
{
"path": "graph/lowestcommonancestor.go",
"chars": 3073,
"preview": "// lowestcommonancestor.go\n// description: Implementation of Lowest common ancestor (LCA) algorithm.\n// detail:\n// Let `"
},
{
"path": "graph/lowestcommonancestor_test.go",
"chars": 4207,
"preview": "package graph\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Query struct {\n\tu int\n\tv int\n\texpected int"
},
{
"path": "graph/prim.go",
"chars": 1495,
"preview": "// The Prim's algorithm computes the minimum spanning tree for a weighted undirected graph\n// Worst Case Time Complexity"
},
{
"path": "graph/prim_test.go",
"chars": 3503,
"preview": "package graph\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestPrimMST(t *testing.T) {\n\n\tvar testCases = []struct {\n\t\t"
},
{
"path": "graph/topological.go",
"chars": 1330,
"preview": "// topological.go\n// description: Topological sort\n// details: Topological sorting for Directed Acyclic Graph (DAG) is a"
},
{
"path": "graph/topological_test.go",
"chars": 1022,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname string\n\tN int\n\tconstraints [][]i"
},
{
"path": "graph/unionfind.go",
"chars": 2026,
"preview": "// Union Find Algorithm or Dynamic Connectivity algorithm, often implemented with the help\n//of the union find data stru"
},
{
"path": "graph/unionfind_test.go",
"chars": 1220,
"preview": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestUnionFind(t *testing.T) {\n\tu := NewUnionFind(10) // Creating a Union-Find"
},
{
"path": "hashing/doc.go",
"chars": 90,
"preview": "// Package hashing containing different implementation of certain hashing\npackage hashing\n"
},
{
"path": "hashing/hashing_test.go",
"chars": 87,
"preview": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage hashing\n"
},
{
"path": "hashing/md5/md5.go",
"chars": 3235,
"preview": "// md5.go\n// description: The MD5 hashing function as defined in RFC 1321.\n// author: Simon Waldherr\n// ref: https://dat"
},
{
"path": "hashing/md5/md5_test.go",
"chars": 1304,
"preview": "// md5_test.go\n// description: Tests for the MD5 hashing function as defined in RFC 1321.\n// author: Simon Waldherr\n\npac"
},
{
"path": "hashing/sha1/sha1.go",
"chars": 2496,
"preview": "// sha1.go\n// description: The SHA-1 hashing function as defined in RFC 3174.\n// author: Simon Waldherr\n// ref: https://"
},
{
"path": "hashing/sha1/sha1_test.go",
"chars": 1390,
"preview": "// sha1_test.go\n// description: Tests for the SHA-1 hashing function as defined in RFC 3174.\n// author: Simon Waldherr\n\n"
},
{
"path": "hashing/sha256/sha256.go",
"chars": 4260,
"preview": "// sha256.go\n// description: The sha256 cryptographic hash function as defined in the RFC6234 standard.\n// time complexi"
},
{
"path": "hashing/sha256/sha256_test.go",
"chars": 2345,
"preview": "package sha256\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\nfunc TestHash(t *testing.T) {\n\ttestCases := []struct {\n\t\tin "
},
{
"path": "math/abs.go",
"chars": 445,
"preview": "// abs.go\n// description: Absolute value\n// details:\n// In mathematics, the absolute value or modulus of a real number x"
},
{
"path": "math/abs_test.go",
"chars": 1019,
"preview": "package math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/binary\"\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestAbs(t *testing.T) {\n\tte"
},
{
"path": "math/aliquot_test.go",
"chars": 951,
"preview": "// aliquotsum_test.go\n// description: Returns s(n)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see al"
},
{
"path": "math/aliquotsum.go",
"chars": 703,
"preview": "// aliquotsum.go\n// description: Returns s(n)\n// details:\n// the aliquot sum s(n) of a positive integer n\n// is the sum "
},
{
"path": "math/armstrong/isarmstrong.go",
"chars": 865,
"preview": "// isarmstrong.go\n// description: Checks if the given number is armstrong number or not\n// details: An Armstrong number "
},
{
"path": "math/armstrong/isarmstrong_test.go",
"chars": 891,
"preview": "// isarmstrong_test.go\n\npackage armstrong\n\nimport \"testing\"\n\nvar testCases = []struct {\n\tname string // test descrip"
},
{
"path": "math/binary/abs.go",
"chars": 662,
"preview": "// abs.go\n// description: returns absolute value using binary operation\n// time complexity: O(1)\n// space complexity: O("
},
{
"path": "math/binary/abs_test.go",
"chars": 713,
"preview": "package binary\n\nimport \"testing\"\n\nfunc TestAbs(t *testing.T) {\n\ttests := getAbsTests()\n\tfor _, test := range tests {\n\t\tt"
},
{
"path": "math/binary/arithmeticmean.go",
"chars": 887,
"preview": "// arithmeticmean.go\n// description: Arithmetic mean\n// details:\n// The most common type of average is the arithmetic me"
},
{
"path": "math/binary/arithmeticmean_test.go",
"chars": 1368,
"preview": "// arithmeticmean_test.go\n// description: Test for Arithmetic mean\n// author(s) [red_byte](https://github.com/i-redbyte)"
},
{
"path": "math/binary/bitcounter.go",
"chars": 585,
"preview": "// bitcounter.go\n// description: Counts the number of set bits in a number\n// details:\n// For unsigned integer number N,"
},
{
"path": "math/binary/bitcounter_test.go",
"chars": 949,
"preview": "// bitcounter_test.go\n// description: Test for counts the number of set bits in a number\n// author(s) [red_byte](https:/"
},
{
"path": "math/binary/checkisnumberpoweroftwo.go",
"chars": 1179,
"preview": "// checkisnumberpoweroftwo.go\n// description: Is the number a power of two\n// details:\n// Checks if a number is a power "
},
{
"path": "math/binary/checkisnumberpoweroftwo_test.go",
"chars": 2322,
"preview": "// checkisnumberpoweroftwo_test.go\n// description: Test for Is the number a power of two\n// author(s) [red_byte](https:/"
},
{
"path": "math/binary/fast_inverse_sqrt.go",
"chars": 982,
"preview": "// Calculating the inverse square root\n// time complexity: O(1)\n// space complexity: O(1)\n// [See more](https://en.wikip"
},
{
"path": "math/binary/logarithm.go",
"chars": 564,
"preview": "// author(s) [red_byte](https://github.com/i-redbyte)\n// time complexity: O(1)\n// space complexity: O(1)\n// see logarith"
},
{
"path": "math/binary/logarithm_test.go",
"chars": 987,
"preview": "// logarithm_test.go\n// description: Test for finding the exponent of n = 2**x using bitwise operations (logarithm in ba"
}
]
// ... and 319 more files (download for full content)
About this extraction
This page contains the full source code of the TheAlgorithms/Go GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 519 files (876.1 KB), approximately 295.3k tokens, and a symbol index with 1488 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.