[
  {
    "path": ".github/CODEOWNERS",
    "content": "# This is a comment.\n# Each line is a file pattern followed by one or more owners.\n\n# More details are here: https://help.github.com/articles/about-codeowners/\n\n# The '*' pattern is global owners.\n\n# Order is important. The last matching pattern has the most precedence.\n\n* @raklaptudirm @yanglbme\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "content": "name: \"Bug report\"\ndescription: \"Create a report to help us improve\"\ntitle: \"[BUG]\"\nlabels: [\"bug\"]\nbody:\n  - type: textarea\n    id: description\n    attributes:\n      label: \"Description\"\n      description: \"A clear and concise description of what the bug is.\"\n    validations:\n      required: true\n  - type: textarea\n    id: steps\n    attributes:\n      label: \"Steps to reproduce\"\n      description: \"Steps to reproduce the behavior (if applicable)\"\n      placeholder: |\n       1. Go to '...'\n       2. Click on '....'\n       3. Scroll down to '....'\n       4. See error\n    validations:\n      required: false\n  - type: textarea\n    id: exceptedbhv\n    attributes:\n      label: \"Excepted behavior\"\n      description: \"A clear and concise description of what you expected to happen.\"\n    validations:\n      required: true\n  - type: textarea\n    id: screenshots\n    attributes:\n      label: \"Screenshots\"\n      description: \"If applicable, add screenshots to help explain your problem.\"\n    validations:\n      required: false\n  - type: textarea\n    id: context\n    attributes:\n      label: \"Additional context\"\n      description: \"Add any other context about the problem here.\"\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/new_implementation.yml",
    "content": "name: \"New or optimize implementation\"\ndescription: \"Propose an enhancement or a new algorithm implementation.\"\ntitle: \"[ENHANCEMENT]\"\nlabels: [\"enhancement\"]\nbody:\n  - type: textarea\n    id: description\n    attributes:\n      label: What would you like to share?\n      description: Provide a clear and concise explanation of your issue.\n    validations:\n      required: true\n  - type: markdown\n    attributes:\n      value: |\n        For new implementations, please specify the name and problem statement for the algorithm.\n        For algorithm enhancements, specify what needs to be changed and why. For example:\n\n        - Adding tests.\n        - Optimizing logic.\n        - Refactoring the file and folders for better structure.\n  - type: textarea\n    id: issuedetails\n    attributes:\n      label: \"Extra issue details\"\n      description: \"Write down all the issue/algorithm details mentioned above.\"\n    validations:\n      required: true\n  - type: textarea\n    id: extrainfo\n    attributes:\n      label: Additional information\n      description: Is there anything else we should know about this issue?\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/other.yml",
    "content": "name: Other\ndescription: Use this for any other issues. Do NOT create blank issues\ntitle: \"[OTHER]\"\nlabels: [\"awaiting triage\"]\nbody:\n  - type: markdown\n    attributes:\n      value: \"# Other issue\"\n  - type: textarea\n    id: issuedescription\n    attributes:\n      label: What would you like to share?\n      description: Provide a clear and concise explanation of your issue.\n    validations:\n      required: true\n  - type: textarea\n    id: extrainfo\n    attributes:\n      label: Additional information\n      description: Is there anything else we should know about this issue?\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE/pull_request.md",
    "content": "#### Description of Change\n<!--\nThank you for your Pull Request. Please provide a description above and review\nthe requirements below.\n\nContributors guide: https://github.com/TheAlgorithms/Go/CONTRIBUTING.md\n-->\n\n#### Checklist\n<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->\n\n- [ ] Added description of change\n- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/Go/blob/master/CONTRIBUTING.md#New-File-Name-guidelines)\n- [ ] Added tests and example, test must pass\n- [ ] Added documentation so that the program is self-explanatory and educational - [GoDoc guidelines](https://blog.golang.org/godoc)\n- [ ] Relevant documentation/comments is changed or added\n- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/Go/blob/master/CONTRIBUTING.md#Commit-Guidelines)\n- [ ] Search previous suggestions before making a new one, as yours may be a duplicate.\n- [ ] I acknowledge that all my contributions will be made under the project's license.\n\nNotes: <!-- Please add a one-line description for developers or pull request viewers -->"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# Keep GitHub Actions up to date with GitHub's Dependabot...\n# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot\n# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem\nversion: 2\nupdates:\n  - package-ecosystem: github-actions\n    directory: /\n    groups:\n      github-actions:\n        patterns:\n          - \"*\"  # Group all Actions updates into a single larger pull request\n    schedule:\n      interval: weekly\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "# https://github.com/golangci/golangci-lint\nname: Continuous Integration\non:\n  push:\n    # prevent duplication of tests with\n    # `pull_request` event\n    branches:\n      - master\n  pull_request:\n\njobs:\n  golang_lint_and_test:\n    name: Code style and tests\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n    steps:\n      - uses: actions/checkout@v4\n      - name: Setup Go\n        uses: actions/setup-go@v5\n        with:\n          go-version: '^1.18'\n      - name: Run Golang CI Lint\n        uses: golangci/golangci-lint-action@v6\n        with:\n          version: latest\n          args: -E gofmt\n      - name: Run tests\n        run: go test ./...\n  codespell:\n    name: Check for spelling errors\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: codespell-project/actions-codespell@master\n        with:\n          ignore_words_list: \"actualy,nwe\"\n          skip: \"go.mod,go.sum\"\n"
  },
  {
    "path": ".github/workflows/citk.yml",
    "content": "# https://github.com/golangci/golangci-lint\nname: CI tool kit\non:\n  pull_request:\n\njobs:\n  CITK:\n    name: Code style and tests\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n      - name: Setup Go\n        uses: actions/setup-go@v5\n        with:\n          go-version: \"^1.18\"\n      - name: Checkout branch\n        run: |\n          git fetch origin master:master\n      - name: Install citk tool\n        run: |\n          go install github.com/tjgurwara99/citk@latest\n      - name: Run citk tool\n        run: |\n          citk check -l go -b master\n"
  },
  {
    "path": ".github/workflows/godocmd.yml",
    "content": "name: Generate Documentation\non:\n  push:\n    branches:\n      - master\n\njobs:\n  generate_readme:\n    name: Markdown Generation\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n      - uses: actions/setup-go@v5\n        with:\n          go-version: '^1.18'\n      - name: Install GoDocMD\n        run: |\n          go install github.com/tjgurwara99/godocmd@v0.1.3\n      - name: Configure Github Action\n        run: |\n          git config --global user.name \"$GITHUB_ACTOR\"\n          git config --global user.email \"$GITHUB_ACTOR@users.noreply.github.com\"\n      - name: Update README.md file\n        run: |\n          godocmd -r -module ./ -w\n      - name: Commit changes if README.md is different\n        run: |\n          if [[ `git status --porcelain` ]]; then\n            git commit -am \"Updated Documentation in README.md\"\n            git push\n          else\n            echo \"NO CHANGES DETECTED\"\n          fi\n"
  },
  {
    "path": ".github/workflows/stale.yml",
    "content": "name: 'Close stale issues and PRs'\non:\n  schedule:\n    - cron: '0 0 * * *'\njobs:\n  stale:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/stale@v9\n        with:\n          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.'\n          close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.'\n          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.'\n          close-pr-message: 'This PR was closed because it has been stalled for 7 days with no activity.'\n          exempt-issue-labels: 'dont-close'\n          exempt-pr-labels: 'dont-close'\n          days-before-stale: 30\n          days-before-close: 7\n"
  },
  {
    "path": ".github/workflows/upload_coverage_report.yml",
    "content": "---\nname: upload_coverage_report\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - master\n  pull_request:\n\nenv:\n  REPORT_NAME: \"coverage.out\"\n\njobs:\n  upload_coverage_report:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - name: Setup Go\n        uses: actions/setup-go@v5\n        with:\n          go-version: '^1.18'\n      - name: Generate code coverage\n        run: |\n          go test -coverprofile=\"${{ env.REPORT_NAME }}\" ./...\n      - name: Upload coverage to codecov (tokenless)\n        if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository\n        uses: codecov/codecov-action@v5\n        with:\n          files: \"${{ env.REPORT_NAME }}\"\n          fail_ci_if_error: true\n      - name: Upload coverage to codecov (with token)\n        if: \"! github.event.pull_request.head.repo.fork \"\n        uses: codecov/codecov-action@v5\n        with:\n          token: ${{ secrets.CODECOV_TOKEN }}\n          files: \"${{ env.REPORT_NAME }}\"\n          fail_ci_if_error: true\n...\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea/\n.vscode/\ncoverage.out\n"
  },
  {
    "path": ".gitpod.dockerfile",
    "content": "FROM gitpod/workspace-go\n"
  },
  {
    "path": ".gitpod.yml",
    "content": "---\nimage:\n  file: .gitpod.dockerfile\n\ntasks:\n  - init: |\n      echo \"Welcome to TheAlgorithms/Go\"\n"
  },
  {
    "path": ".golangci.yml",
    "content": "run:\n  go: 1.19\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# CONTRIBUTION GUIDELINES\n\n## Before contributing\n\nWelcome 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.\n\n## Contributing\n\n### Maintainers\n---\n\nPlease check the [`CODEOWNERS`](https://github.com/TheAlgorithms/Go/blob/master/.github/CODEOWNERS) file for a list of repository maintainers.\n\n### Contributor\n---\n\nBeing a contributor at The Algorithms, we request you to follow the points mentioned below:\n\n- You did your own work.\n  - No plagiarism is allowed. Any plagiarized work will not be merged.\n- Your work will be distributed under the [MIT License](https://github.com/TheAlgorithms/Go/blob/master/LICENSE) once your pull request has been merged.\n- Please follow the repository guidelines and standards mentioned below.\n\n#### New implementation\n\n- New implementations are welcome!\n\n- 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)\n\n#### Issues\n\n- 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.\n\n### Making Changes\n---\n\n#### Code\n\n- Please use the directory structure of the repository.\n- Make sure the file extensions should be `*.go`.\n- Use meaningful variable names.\n- Use standard library inside your code and avoid to import packages from other repositories\n- If an implementation of the algorithm already exists, please refer to the [filename section below](#new-file-name-guidelines).\n- You can suggest reasonable changes to existing algorithms.\n- Strictly use snake_case (underscore_separated)  in filenames.\n- If you have added or modified code, please make sure the code compiles before submitting.\n- 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.\n- 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.\n- **Be consistent in the use of these guidelines.**\n\n#### Documentation\n\n- Make sure you put useful comments in your code. Do not comment on obvious things.\n- 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.\n- If you have modified/added documentation, please ensure that your language is concise and must not contain grammatical errors.\n- 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).\n- 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.\n\n#### Test\n\n- Make sure to add examples and test cases in your `filename_test.go` file.\n- If you find an algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes.\n- Please try to add one or more `Test` functions that will invoke the algorithm implementation on random test data with the expected output.\n\n### Benchmark\n---\n\n- 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.\n- If you find an algorithm or document without benchmarks, please feel free to create a pull request or issue describing suggested changes.\n- Please try to add one or more `Benchmark` functions that will invoke the algorithm implementation.\n- 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)\n\n#### Typical structure of a program\n\n```go\n\n// filename\n// description: Add one line description here\n// details:\n// This is a multi-line\n// description containing links, references,\n// math equations, etc.\n// author(s) [Name](https://github.com/handle), [Name](https://github.com/handle)\n// see relatedfile.go, anotherfile.go, file_test.go\n \n// ** Is just an example of how to write description for package and function and other stuff ... **\n\n// Package sort provides primitives for sorting slices and user-defined\n// collections.\npackage sort\n\n// Reasons why you used those packages \n// name package : Add one line description here\n// name2 package : Add one line description here\n// ...\nimport (\n   ...\n)\n\n\n// Fprint formats using the default formats for its operands and writes to w.\n// Spaces are added between operands when neither is a string.\n// It returns the number of bytes written, and any write error encountered.\nfunc Fprint(w io.Writer, a ...any) (n int, err error) {\n    ...\n}\n\n\n```\n\n#### New File Name guidelines\n\n- Use lowercase words without ``\"_\"`` for the file name\n- Use ``\"_\"`` as a separator only for `_test.go` or `_bench.go`\n- For instance\n\n```markdown\nMyNewGoFile.GO       is incorrect\nmy_new_go_file.go    is incorrect\nmynewgofile.go       is the correct format\nmynewgofile_test.go  is the correct format\n```\n\n- It will be used to dynamically create a directory of files and implementation.\n- File name validation will run on Docker to ensure validity.\n- 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`.\n- Check out `Go` [Package names](https://go.dev/blog/package-names) roles\n\n#### New Directory guidelines\n\n- We recommend adding files to existing directories as much as possible.\n- Use lowercase words with ``\"_\"`` as separator ( no spaces or ```\"-\"``` allowed )\n- For instance\n\n```markdown\nSomeNew Fancy-Category          is incorrect\nsome_new_fancy_category         is correct\n```\n\n- Filepaths will be used to dynamically create a directory of our algorithms.\n- Filepath validation will run on GitHub Actions to ensure compliance.\n\n#### Commit Guidelines\n\n- 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.\n\n```bash\ngit add filexyz.go\ngit commit -m \"your message\"\n```\n\nExamples of commit messages with semantic prefixes:\n\n```markdown\nfix: XYZ algorithm bug\nfeat: add XYZ algorithm\ntest: add test for XYZ algorithm\ndocs: add comments and explanation to XYZ algorithm\n```\n\nCommon prefixes:\n\n- fix: A bug fix\n- feat: A new feature\n- docs: Documentation changes\n- test: Correct existing tests or add new ones\n\n### For New Gophers\n---\n\n#### Installing Go\n\n- Installation (only needs to be installed once.)\n  - Mac (using home-brew): `brew install go`\n  - Windows (MSYS2 64-bit): `choco install golang` [Chocolatey Package Manager](https://chocolatey.org/)\n  - Linux (Debian): `sudo apt-get install golang`\n  - Manual Installation: [Downloads - The Go Programming Language](https://golang.org/dl/)\n- Running (all platforms): `go run filexyz.go`\n\n> Note: New packages should not be `main`, and never implement `main` functions for any package.\n\n#### Code formatter\nTo format your code, you can use the gofmt tool directly:\n\n```bash\ngofmt -w filexyz.go\n```\n\nOr you can use the \"go fmt\" command:\n\n```bash\ngo fmt path/to/your/package\n```\n\n#### Building\n\nTo build you code locally, simply run:\n\n```bash\ngo build .\n```\n\n### Pull Requests\n---\n\n- Check out our [pull request template](https://github.com/TheAlgorithms/Go/blob/master/.github/PULL_REQUEST_TEMPLATE/pull_request.md\n  )\n\n#### Building Locally\n\nBefore submitting a pull request, [build the code locally](#building) or using the convenient [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/Go) service.\n\n#### GitHub Actions\n\n- Enable GitHub Actions on your fork of the repository.\n  After enabling, it will execute `golang_lint_and_test` after every push (not a commit).\n- The result can create another commit if the actions made any changes on your behalf.\n- Hence, it is better to wait and check the results of GitHub Actions after every push.\n- Run `git pull` in your local clone if these actions made many changes to avoid merge conflicts.\n\nMost importantly,\n\n- Happy coding!\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 The Algorithms and contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# The Algorithms - Go\n[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/TheAlgorithms/Go)&nbsp;\n[![Continuous Integration](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml/badge.svg)](https://github.com/TheAlgorithms/Go/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/TheAlgorithms/Go/graph/badge.svg?token=aSWh7N8tNx)](https://codecov.io/gh/TheAlgorithms/Go)\n![godocmd](https://github.com/tjgurwara99/Go/workflows/godocmd/badge.svg)\n![](https://img.shields.io/github/repo-size/TheAlgorithms/Go.svg?label=Repo%20size&style=flat-square)&nbsp;\n![update_directory_md](https://github.com/TheAlgorithms/Go/workflows/update_directory_md/badge.svg)\n[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://the-algorithms.com/discord/)&nbsp;\n\n### Algorithms implemented in Go (for education)\n\nThe repository is a collection of open-source implementation of a variety of algorithms implemented in Go and licensed under [MIT License](LICENSE).\n\nRead our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.\n\n## List of Algorithms\n<!--- AUTOGENERATED --->\n<!--- GODOCMD BEGIN --->\n# Packages:\n\n<details>\n\t<summary> <strong> ahocorasick </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Advanced`](./strings/ahocorasick/advancedahocorasick.go#L10):  Advanced Function performing the Advanced Aho-Corasick algorithm. Finds and prints occurrences of each pattern.\n2. [`AhoCorasick`](./strings/ahocorasick/ahocorasick.go#L15):  AhoCorasick Function performing the Basic Aho-Corasick algorithm. Finds and prints occurrences of each pattern.\n3. [`ArrayUnion`](./strings/ahocorasick/shared.go#L86):  ArrayUnion Concats two arrays of int's into one.\n4. [`BoolArrayCapUp`](./strings/ahocorasick/shared.go#L78):  BoolArrayCapUp Dynamically increases an array size of bool's by 1.\n5. [`BuildAc`](./strings/ahocorasick/ahocorasick.go#L54):  Functions that builds Aho Corasick automaton.\n6. [`BuildExtendedAc`](./strings/ahocorasick/advancedahocorasick.go#L46):  BuildExtendedAc Functions that builds extended Aho Corasick automaton.\n7. [`ComputeAlphabet`](./strings/ahocorasick/shared.go#L61):  ComputeAlphabet Function that returns string of all the possible characters in given patterns.\n8. [`ConstructTrie`](./strings/ahocorasick/shared.go#L4):  ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings.\n9. [`Contains`](./strings/ahocorasick/shared.go#L39):  Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.\n10. [`CreateNewState`](./strings/ahocorasick/shared.go#L111):  CreateNewState Automaton function for creating a new state 'state'.\n11. [`CreateTransition`](./strings/ahocorasick/shared.go#L116):  CreateTransition Creates a transition for function σ(state,letter) = end.\n12. [`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.\n13. [`GetTransition`](./strings/ahocorasick/shared.go#L121):  GetTransition Returns ending state for transition σ(fromState,overChar), '-1' if there is none.\n14. [`GetWord`](./strings/ahocorasick/shared.go#L49):  GetWord Function that returns word found in text 't' at position range 'begin' to 'end'.\n15. [`IntArrayCapUp`](./strings/ahocorasick/shared.go#L70):  IntArrayCapUp Dynamically increases an array size of int's by 1.\n16. [`StateExists`](./strings/ahocorasick/shared.go#L133):  StateExists Checks if state 'state' exists. Returns 'true' if it does, 'false' otherwise.\n\n---\n##### Types\n\n1. [`Result`](./strings/ahocorasick/ahocorasick.go#L9): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> armstrong </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`IsArmstrong`](./math/armstrong/isarmstrong.go#L14): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> binary </strong> </summary>\t\n\n---\n\n#####  Package binary describes algorithms that use binary operations for different calculations.\n\n---\n##### Functions:\n\n1. [`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.\n2. [`BitCounter`](./math/binary/bitcounter.go#L11):  BitCounter - The function returns the number of set bits for an unsigned integer number\n3. [`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)).\n4. [`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:\t  10...0\t& 01...1\t  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.\n5. [`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\n6. [`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)\n7. [`MeanUsingAndXor`](./math/binary/arithmeticmean.go#L12):  MeanUsingAndXor This function finds arithmetic mean using \"AND\" and \"XOR\" operations\n8. [`MeanUsingRightShift`](./math/binary/arithmeticmean.go#L17):  MeanUsingRightShift This function finds arithmetic mean using right shift\n9. [`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.\n10. [`SequenceGrayCode`](./math/binary/rbc.go#L11):  SequenceGrayCode The function generates an \"Gray code\" sequence of length n\n11. [`Sqrt`](./math/binary/sqrt.go#L10): No description provided.\n12. [`XorSearchMissingNumber`](./math/binary/xorsearch.go#L11):  XorSearchMissingNumber This function finds a missing number in a sequence\n\n---\n</details><details>\n\t<summary> <strong> cache </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`NewLRU`](./cache/lru.go#L22): NewLRU represent initiate lru cache with capacity\n2. [`NewLFU`](./cache/lfu.go#L33): NewLFU represent initiate lfu cache with capacity\n3. [`Get`](./cache/lfu.go#L52): Get the value by key from LFU cache\n4. [`Put`](./cache/lfu.go#L66): Put the key and value in LFU cache\n\n---\n##### Types\n\n1. [`LRU`](./cache/lru.go#L15): Default the struct of lru cache algorithm.\n2. [`LFU`](./cache/lfu.go#L19): Default the struct of lfu cache algorithm.\n\n\n---\n</details><details>\n\t<summary> <strong> caesar </strong> </summary>\t\n\n---\n\n#####  Package caesar is the shift cipher ref: https://en.wikipedia.org/wiki/Caesar_cipher\n\n---\n##### Functions:\n\n1. [`Decrypt`](./cipher/caesar/caesar.go#L27):  Decrypt decrypts by left shift of \"key\" each character of \"input\"\n2. [`Encrypt`](./cipher/caesar/caesar.go#L6):  Encrypt encrypts by right shift of \"key\" each character of \"input\"\n3. [`FuzzCaesar`](./cipher/caesar/caesar_test.go#L158): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> catalan </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`CatalanNumber`](./math/catalan/catalannumber.go#L16):  CatalanNumber This function returns the `nth` Catalan number\n\n---\n</details><details>\n\t<summary> <strong> checksum </strong> </summary>\t\n\n---\n\n#####  Package checksum describes algorithms for finding various checksums\n\n---\n##### Functions:\n\n1. [`CRC8`](./checksum/crc8.go#L25):  CRC8 calculates CRC8 checksum of the given data.\n2. [`Luhn`](./checksum/luhn.go#L11):  Luhn validates the provided data using the Luhn algorithm.\n\n---\n##### Types\n\n1. [`CRCModel`](./checksum/crc8.go#L15): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> coloring </strong> </summary>\t\n\n---\n\n#####  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)\n\n---\n##### Functions:\n\n1. [`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\n\n---\n##### Types\n\n1. [`Graph`](./graph/coloring/graph.go#L14): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> combination </strong> </summary>\t\n\n---\n\n#####  Package combination ...\n\n---\n##### Functions:\n\n1. [`Start`](./strings/combination/combination.go#L13):  Start ...\n\n---\n##### Types\n\n1. [`Combinations`](./strings/combination/combination.go#L7): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> compression </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`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.\n2. [`HuffEncode`](./compression/huffmancoding.go#L93):  HuffEncode encodes the string in by applying the mapping defined by codes.\n3. [`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.\n4. [`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.\n\n---\n##### Types\n\n1. [`Node`](./compression/huffmancoding.go#L17): No description provided.\n\n2. [`SymbolFreq`](./compression/huffmancoding.go#L25): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> compression_test </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`SymbolCountOrd`](./compression/huffmancoding_test.go#L16):  SymbolCountOrd computes sorted symbol-frequency list of input message\n\n---\n</details><details>\n\t<summary> <strong> conversion </strong> </summary>\t\n\n---\n\n#####  Package conversion is a package of implementations which converts one data structure to another.\n\n---\n##### Functions:\n\n1. [`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\n2. [`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\n3. [`BinaryToDecimal`](./conversion/binarytodecimal.go#L25):  BinaryToDecimal() function that will take Binary number as string, and return its Decimal equivalent as integer.\n4. [`DecimalToBinary`](./conversion/decimaltobinary.go#L32):  DecimalToBinary() function that will take Decimal number as int, and return its Binary equivalent as string.\n5. [`FuzzBase64Encode`](./conversion/base64_test.go#L113): No description provided.\n6. [`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\n7. [`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.\n8. [`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\n9. [`Reverse`](./conversion/decimaltobinary.go#L22):  Reverse() function that will take string, and returns the reverse of that string.\n10. [`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.\n\n---\n</details><details>\n\t<summary> <strong> deque </strong> </summary>\t\n\n---\n\n#####  Package deque implements a Double Ended Queue data structure.\n\n---\n##### Functions:\n\n1. [`New`](./structure/deque/deque.go#L22):  New returns a new DoublyEndedQueue.\n\n---\n##### Types\n\n1. [`DoublyEndedQueue`](./structure/deque/deque.go#L17): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> deque_test </strong> </summary>\t\n\n---\n\n##### Types\n\n1. [`QueryStructure`](./structure/deque/deque_test.go#L20): No description provided.\n\n2. [`TestCaseData`](./structure/deque/deque_test.go#L27): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> diffiehellman </strong> </summary>\t\n\n---\n\n#####  Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI\n\n---\n##### Functions:\n\n1. [`GenerateMutualKey`](./cipher/diffiehellman/diffiehellmankeyexchange.go#L19):  GenerateMutualKey : generates a mutual key that can be used by only alice and bob mutualKey = (shareKey^prvKey)%primeNumber\n2. [`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\n\n---\n</details><details>\n\t<summary> <strong> dynamic </strong> </summary>\t\n\n---\n\n#####  Package dynamic is a package of certain implementations of dynamically run algorithms.\n\n---\n##### Functions:\n\n1. [`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\n2. [`Bin2`](./dynamic/binomialcoefficient.go#L21):  Bin2 function\n3. [`CoinChange`](./dynamic/coinchange.go#L5):  CoinChange finds the number of possible combinations of coins of different values which can get to the target amount.\n4. [`CutRodDp`](./dynamic/rodcutting.go#L21):  CutRodDp solve the same problem using dynamic programming\n5. [`CutRodRec`](./dynamic/rodcutting.go#L8):  CutRodRec solve the problem recursively: initial approach\n6. [`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.\n7. [`EditDistanceRecursive`](./dynamic/editdistance.go#L10):  EditDistanceRecursive is a naive implementation with exponential time complexity.\n8. [`IsSubsetSum`](./dynamic/subsetsum.go#L14): No description provided.\n9. [`Knapsack`](./dynamic/knapsack.go#L17):  Knapsack solves knapsack problem return maxProfit\n10. [`LongestCommonSubsequence`](./dynamic/longestcommonsubsequence.go#L13):  LongestCommonSubsequence function\n11. [`LongestIncreasingSubsequence`](./dynamic/longestincreasingsubsequence.go#L9):  LongestIncreasingSubsequence returns the longest increasing subsequence where all elements of the subsequence are sorted in increasing order\n12. [`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/\n13. [`LpsDp`](./dynamic/longestpalindromicsubsequence.go#L25):  LpsDp function\n14. [`LpsRec`](./dynamic/longestpalindromicsubsequence.go#L20):  LpsRec function\n15. [`MatrixChainDp`](./dynamic/matrixmultiplication.go#L24):  MatrixChainDp function\n16. [`MatrixChainRec`](./dynamic/matrixmultiplication.go#L10):  MatrixChainRec function\n17. [`Max`](./dynamic/knapsack.go#L11):  Max function - possible duplicate\n18. [`NthCatalanNumber`](./dynamic/catalan.go#L13):  NthCatalan returns the n-th Catalan Number Complexity: O(n²)\n19. [`NthFibonacci`](./dynamic/fibonacci.go#L6):  NthFibonacci returns the nth Fibonacci Number\n20. [`TrapRainWater`](./dynamic/traprainwater.go#L17): Calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming.\n---\n</details><details>\n\t<summary> <strong> dynamicarray </strong> </summary>\t\n\n---\n\n#####  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\n\n---\n##### Types\n\n1. [`DynamicArray`](./structure/dynamicarray/dynamicarray.go#L21): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> factorial </strong> </summary>\t\n\n---\n\n#####  Package factorial describes algorithms Factorials calculations.\n\n---\n##### Functions:\n\n1. [`Iterative`](./math/factorial/factorial.go#L12):  Iterative returns the iteratively brute forced factorial of n\n2. [`Recursive`](./math/factorial/factorial.go#L21):  Recursive This function recursively computes the factorial of a number\n3. [`UsingTree`](./math/factorial/factorial.go#L30):  UsingTree This function finds the factorial of a number using a binary tree\n\n---\n</details><details>\n\t<summary> <strong> fibonacci </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`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\n2. [`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)\n3. [`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.\n\n---\n</details><details>\n\t<summary> <strong> gcd </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Extended`](./math/gcd/extended.go#L12):  Extended simple extended gcd\n2. [`ExtendedIterative`](./math/gcd/extendedgcditerative.go#L4):  ExtendedIterative finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).\n3. [`ExtendedRecursive`](./math/gcd/extendedgcd.go#L4):  ExtendedRecursive finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).\n4. [`Iterative`](./math/gcd/gcditerative.go#L4):  Iterative Faster iterative version of GcdRecursive without holding up too much of the stack\n5. [`Recursive`](./math/gcd/gcd.go#L4):  Recursive finds and returns the greatest common divisor of a given integer.\n6. [`TemplateBenchmarkExtendedGCD`](./math/gcd/extendedgcd_test.go#L44): No description provided.\n7. [`TemplateBenchmarkGCD`](./math/gcd/gcd_test.go#L37): No description provided.\n8. [`TemplateTestExtendedGCD`](./math/gcd/extendedgcd_test.go#L7): No description provided.\n9. [`TemplateTestGCD`](./math/gcd/gcd_test.go#L18): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> generateparentheses </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`GenerateParenthesis`](./strings/generateparentheses/generateparentheses.go#L12): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> genetic </strong> </summary>\t\n\n---\n\n#####  Package genetic provides functions to work with strings using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm  Author: D4rkia\n\n---\n##### Functions:\n\n1. [`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\n\n---\n##### Types\n\n1. [`Conf`](./strings/genetic/genetic.go#L32): No description provided.\n\n2. [`PopulationItem`](./strings/genetic/genetic.go#L26): No description provided.\n\n3. [`Result`](./strings/genetic/genetic.go#L52): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> geometry </strong> </summary>\t\n\n---\n\n#####  Package geometry contains geometric algorithms Package geometry contains geometric algorithms\n\n---\n##### Functions:\n\n1. [`Distance`](./math/geometry/straightlines.go#L18):  Distance calculates the shortest distance between two points.\n2. [`EuclideanDistance`](./math/geometry/distance.go#L20):  EuclideanDistance returns the Euclidean distance between points in any `n` dimensional Euclidean space.\n3. [`IsParallel`](./math/geometry/straightlines.go#L42):  IsParallel checks if two lines are parallel or not.\n4. [`IsPerpendicular`](./math/geometry/straightlines.go#L47):  IsPerpendicular checks if two lines are perpendicular or not.\n5. [`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.\n6. [`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.\n7. [`Slope`](./math/geometry/straightlines.go#L32):  Slope calculates the slope (gradient) of a line.\n8. [`YIntercept`](./math/geometry/straightlines.go#L37):  YIntercept calculates the Y-Intercept of a line from a specific Point.\n\n---\n##### Types\n\n1. [`EuclideanPoint`](./math/geometry/distance.go#L14): No description provided.\n\n2. [`Line`](./math/geometry/straightlines.go#L13): No description provided.\n\n3. [`Point`](./math/geometry/straightlines.go#L9): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> graph </strong> </summary>\t\n\n---\n\n#####  Package graph demonstrates Graph search algorithms reference: https://en.wikipedia.org/wiki/Tree_traversal\n\n---\n##### Functions:\n\n1. [`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\n2. [`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\t \t\tO(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) Worst-case space complexity\t \tO(|V|)=O(b^{d})}O(|V|)=O(b^{d}) reference: https://en.wikipedia.org/wiki/Breadth-first_search\n3. [`DepthFirstSearch`](./graph/depthfirstsearch.go#L53): No description provided.\n4. [`DepthFirstSearchHelper`](./graph/depthfirstsearch.go#L21): No description provided.\n5. [`FloydWarshall`](./graph/floydwarshall.go#L15):  FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm\n6. [`GetIdx`](./graph/depthfirstsearch.go#L3): No description provided.\n7. [`KruskalMST`](./graph/kruskal.go#L23): No description provided.\n8. [`PrimMST`](./graph/prim.go#30): Computes the minimum spanning tree of a weighted undirected graph\n9. [`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.\n10. [`New`](./graph/graph.go#L16):  Constructor functions for graphs (undirected by default)\n11. [`NewTree`](./graph/lowestcommonancestor.go#L84): No description provided.\n12. [`NewUnionFind`](./graph/unionfind.go#L24):  Initialise a new union find data structure with s nodes\n13. [`NotExist`](./graph/depthfirstsearch.go#L12): No description provided.\n14. [`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\n15. [`Edmond-Karp`](./graph/edmondkarp.go#L43): Computes the maximum possible flow between a pair of s-t vertices in a weighted graph\n\n---\n##### Types\n\n1. [`Edge`](./graph/kruskal.go#L17): No description provided.\n\n2. [`Graph`](./graph/graph.go#L9): No description provided.\n\n3. [`Item`](./graph/dijkstra.go#L5): No description provided.\n\n4. [`Query`](./graph/lowestcommonancestor_test.go#L9): No description provided.\n\n5. [`Tree`](./graph/lowestcommonancestor.go#L25): No description provided.\n\n6. [`TreeEdge`](./graph/lowestcommonancestor.go#L12): No description provided.\n\n7. [`UnionFind`](./graph/unionfind.go#L18): No description provided.\n\n8. [`WeightedGraph`](./graph/floydwarshall.go#L9): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> guid </strong> </summary>\t\n\n---\n\n#####  Package guid provides facilities for generating random globally unique identifiers.\n\n---\n##### Functions:\n\n1. [`New`](./strings/guid/guid.go#L28):  New returns a randomly generated global unique identifier.\n\n---\n</details><details>\n\t<summary> <strong> hashmap </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Make`](./structure/hashmap/hashmap.go#L32):  Make creates a new HashMap instance with input size and capacity\n2. [`New`](./structure/hashmap/hashmap.go#L24):  New return new HashMap instance\n\n---\n##### Types\n\n1. [`HashMap`](./structure/hashmap/hashmap.go#L17): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> heap </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`New`](./structure/heap/heap.go#L15):  New gives a new heap object.\n2. [`NewAny`](./structure/heap/heap.go#L24):  NewAny gives a new heap object. element can be anything, but must provide less function.\n\n---\n##### Types\n\n1. [`Heap`](./structure/heap/heap.go#L9): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> heap_test </strong> </summary>\t\n\n---\n\n##### Types\n\n1. [`testInt`](#L0): \n\n\tMethods:\n\t1. [`Less`](./structure/heap/heap_test.go#L11): No description provided.\n2. [`testStudent`](#L0): \n\n\tMethods:\n\t1. [`Less`](./structure/heap/heap_test.go#L20): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> horspool </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Horspool`](./strings/horspool/horspool.go#L10): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> kmp </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Kmp`](./strings/kmp/kmp.go#L4):  Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.\n\n---\n##### Types\n\n1. [`args`](./strings/kmp/kmp_test.go#L39): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> lcm </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`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 |\n\n---\n</details><details>\n\t<summary> <strong> levenshtein </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Distance`](./strings/levenshtein/levenshteindistance.go#L10):  Distance Function that gives Levenshtein Distance\n\n---\n</details><details>\n\t<summary> <strong> linkedlist </strong> </summary>\t\n\n---\n\n#####  Package linkedlist demonstrates different implementations on linkedlists.\n\n---\n##### Functions:\n\n1. [`JosephusProblem`](./structure/linkedlist/cyclic.go#L120):  https://en.wikipedia.org/wiki/Josephus_problem This is a struct-based solution for Josephus problem.\n2. [`NewCyclic`](./structure/linkedlist/cyclic.go#L12):  Create new list.\n3. [`NewDoubly`](./structure/linkedlist/doubly.go#L31): No description provided.\n4. [`NewNode`](./structure/linkedlist/shared.go#L12):  Create new node.\n5. [`NewSingly`](./structure/linkedlist/singlylinkedlist.go#L19):  NewSingly returns a new instance of a linked list\n\n---\n##### Types\n\n1. [`Cyclic`](./structure/linkedlist/cyclic.go#L6): No description provided.\n\n2. [`Doubly`](./structure/linkedlist/doubly.go#L18): No description provided.\n\n3. [`Node`](./structure/linkedlist/shared.go#L5): No description provided.\n\n4. [`Singly`](./structure/linkedlist/singlylinkedlist.go#L10): No description provided.\n\n5. [`testCase`](./structure/linkedlist/cyclic_test.go#L105): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> manacher </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`LongestPalindrome`](./strings/manacher/longestpalindrome.go#L37): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> math </strong> </summary>\t\n\n---\n\n#####  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\n\n---\n##### Functions:\n\n1. [`Abs`](./math/abs.go#L11):  Abs returns absolute value\n2. [`AliquotSum`](./math/aliquotsum.go#L14):  This function returns s(n) for given number\n3. [`Combinations`](./math/binomialcoefficient.go#L20):  C is Binomial Coefficient function This function returns C(n, k) for given n and k\n4. [`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)\n5. [`DefaultPolynomial`](./math/pollard.go#L16):  DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n\n6. [`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.\n7. [`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.\n8. [`IsAutomorphic`](./math/isautomorphic.go#L16): No description provided.\n9. [`IsKrishnamurthyNumber`](./math/krishnamurthy.go#L12):  IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not.\n10. [`IsPerfectNumber`](./math/perfectnumber.go#L34):  Checks if inNumber is a perfect number\n11. [`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.\n12. [`Lerp`](./math/lerp.go#L5):  Lerp or Linear interpolation This function will return new value in 't' percentage  between 'v0' and 'v1'\n13. [`LiouvilleLambda`](./math/liouville.go#L24):  Lambda is the liouville function This function returns λ(n) for given number\n14. [`Mean`](./math/mean.go#L7): No description provided.\n15. [`Median`](./math/median.go#L12): No description provided.\n16. [`Mode`](./math/mode.go#L19): No description provided.\n17. [`Mu`](./math/mobius.go#L21):  Mu is the Mobius function This function returns μ(n) for given number\n18. [`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.\n19. [`PollardsRhoFactorization`](./math/pollard.go#L29):  PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm using the default parameters x = y = 2\n20. [`PronicNumber`](./math/pronicnumber.go#L15):  PronicNumber returns true if argument passed to the function is pronic and false otherwise.\n21. [`Sin`](./math/sin.go#L9):  Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine)\n22. [`SumOfProperDivisors`](./math/perfectnumber.go#L17):  Returns the sum of proper divisors of inNumber.\n\n---\n</details><details>\n\t<summary> <strong> matrix </strong> </summary>\t\n\n---\n\n#####  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\n\n---\n##### Functions:\n\n1. [`IsValid`](./math/matrix/isvalid.go#L6):  IsValid checks if the input matrix has consistent row lengths.\n2. [`New`](./math/matrix/matrix.go#L17):  NewMatrix creates a new Matrix based on the provided arguments.\n3. [`NewFromElements`](./math/matrix/matrix.go#L43):  NewFromElements creates a new Matrix from the given elements.\n\n---\n##### Types\n\n1. [`Matrix`](./math/matrix/matrix.go#L10): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> matrix_test </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`MakeRandomMatrix`](./math/matrix/strassenmatrixmultiply_test.go#L105): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> max </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Bitwise`](./math/max/bitwisemax.go#L11):  Bitwise computes using bitwise operator the maximum of all the integer input and returns it\n2. [`Int`](./math/max/max.go#L6):  Int is a function which returns the maximum of all the integers provided as arguments.\n\n---\n</details><details>\n\t<summary> <strong> maxsubarraysum </strong> </summary>\t\n\n---\n\n#####  Package maxsubarraysum is a package containing a solution to a common problem of finding max contiguous sum within a array of ints.\n\n---\n##### Functions:\n\n1. [`MaxSubarraySum`](./other/maxsubarraysum/maxsubarraysum.go#L13):  MaxSubarraySum returns the maximum subarray sum\n\n---\n</details><details>\n\t<summary> <strong> min </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Bitwise`](./math/min/bitwisemin.go#L11):  Bitwise This function returns the minimum integer using bit operations\n2. [`Int`](./math/min/min.go#L6):  Int is a function which returns the minimum of all the integers provided as arguments.\n\n---\n</details><details>\n\t<summary> <strong> modular </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Exponentiation`](./math/modular/exponentiation.go#L22):  Exponentiation returns base^exponent % mod\n2. [`Inverse`](./math/modular/inverse.go#L19):  Inverse Modular function\n3. [`Multiply64BitInt`](./math/modular/exponentiation.go#L51):  Multiply64BitInt Checking if the integer multiplication overflows\n\n---\n</details><details>\n\t<summary> <strong> moserdebruijnsequence </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`MoserDeBruijnSequence`](./math/moserdebruijnsequence/sequence.go#L7): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> nested </strong> </summary>\t\n\n---\n\n#####  Package nested provides functions for testing strings proper brackets nesting.\n\n---\n##### Functions:\n\n1. [`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.\n\n---\n</details><details>\n\t<summary> <strong> palindrome </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`IsPalindrome`](./strings/palindrome/ispalindrome.go#L26): No description provided.\n2. [`IsPalindromeRecursive`](./strings/palindrome/ispalindrome.go#L39): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> pangram </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`IsPangram`](./strings/pangram/ispangram.go#L21): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> parenthesis </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`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.\n\n---\n</details><details>\n\t<summary> <strong> pascal </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`GenerateTriangle`](./math/pascal/pascaltriangle.go#L24):  GenerateTriangle This function generates a Pascal's triangle of n lines\n\n---\n</details><details>\n\t<summary> <strong> password </strong> </summary>\t\n\n---\n\n#####  Package password contains functions to help generate random passwords\n\n---\n##### Functions:\n\n1. [`Generate`](./other/password/generator.go#L15):  Generate returns a newly generated password\n\n---\n</details><details>\n\t<summary> <strong> permutation </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`GenerateElementSet`](./math/permutation/heaps.go#L37): No description provided.\n2. [`Heaps`](./math/permutation/heaps.go#L8):  Heap's Algorithm for generating all permutations of n objects\n3. [`NextPermutation`](./math/permutation/next_permutation.go#8): A solution to find next permutation of an integer array in constant memory\n\n---\n</details><details>\n\t<summary> <strong> pi </strong> </summary>\t\n\n---\n\n#####  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\n\n---\n##### Functions:\n\n1. [`MonteCarloPi`](./math/pi/montecarlopi.go#L17): No description provided.\n2. [`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.\n3. [`Spigot`](./math/pi/spigotpi.go#L12): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> polybius </strong> </summary>\t\n\n---\n\n#####  Package polybius is encrypting method with polybius square ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher\n\n---\n##### Functions:\n\n1. [`FuzzPolybius`](./cipher/polybius/polybius_test.go#L154): No description provided.\n2. [`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\".\n\n---\n##### Types\n\n1. [`Polybius`](./cipher/polybius/polybius.go#L12): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> power </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`IterativePower`](./math/power/fastexponent.go#L4):  IterativePower is iterative O(logn) function for pow(x, y)\n2. [`RecursivePower`](./math/power/fastexponent.go#L18):  RecursivePower is recursive O(logn) function for pow(x, y)\n3. [`RecursivePower1`](./math/power/fastexponent.go#L30):  RecursivePower1 is recursive O(n) function for pow(x, y)\n4. [`UsingLog`](./math/power/powvialogarithm.go#L14): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> prime </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Factorize`](./math/prime/primefactorization.go#L5):  Factorize is a function that computes the exponents of each prime in the prime factorization of n\n2. [`Generate`](./math/prime/sieve.go#L26):  Generate returns a int slice of prime numbers up to the limit\n3. [`GenerateChannel`](./math/prime/sieve.go#L9):  Generate generates the sequence of integers starting at 2 and sends it to the channel `ch`\n4. [`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.\n5. [`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.\n6. [`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.\n7. [`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\n8. [`MillerTestMultiple`](./math/prime/millerrabintest.go#L84):  MillerTestMultiple is like MillerTest but runs the test for multiple witnesses.\n9. [`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.\n10. [`Sieve`](./math/prime/sieve.go#L16):  Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels\n11. [`TrialDivision`](./math/prime/primecheck.go#L9):  TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it.\n12. [`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\n\n---\n</details><details>\n\t<summary> <strong> pythagoras </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Distance`](./math/pythagoras/pythagoras.go#L15):  Distance calculates the distance between to vectors with the   Pythagoras theorem\n\n---\n##### Types\n\n1. [`Vector`](./math/pythagoras/pythagoras.go#L8): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> queue </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`BackQueue`](./structure/queue/queuearray.go#L32):  BackQueue return the Back value\n2. [`DeQueue`](./structure/queue/queuearray.go#L20):  DeQueue it will be removed the first value that added into the list\n3. [`EnQueue`](./structure/queue/queuearray.go#L15):  EnQueue it will be added new value into our list\n4. [`FrontQueue`](./structure/queue/queuearray.go#L27):  FrontQueue return the Front value\n5. [`IsEmptyQueue`](./structure/queue/queuearray.go#L42):  IsEmptyQueue check our list is empty or not\n6. [`LenQueue`](./structure/queue/queuearray.go#L37):  LenQueue will return the length of the queue list\n\n---\n##### Types\n\n1. [`LQueue`](./structure/queue/queuelinklistwithlist.go#L20): No description provided.\n\n2. [`Node`](./structure/queue/queuelinkedlist.go#L13): No description provided.\n\n3. [`Queue`](./structure/queue/queuelinkedlist.go#L19): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> rot13 </strong> </summary>\t\n\n---\n\n#####  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\n\n---\n##### Functions:\n\n1. [`FuzzRot13`](./cipher/rot13/rot13_test.go#L72): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> rsa </strong> </summary>\t\n\n---\n\n#####  Package rsa shows a simple implementation of RSA algorithm\n\n---\n##### Functions:\n\n1. [`Decrypt`](./cipher/rsa/rsa.go#L43):  Decrypt decrypts encrypted rune slice based on the RSA algorithm\n2. [`Encrypt`](./cipher/rsa/rsa.go#L28):  Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory\n3. [`FuzzRsa`](./cipher/rsa/rsa_test.go#L79): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> search </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`BoyerMoore`](./strings/search/boyermoore.go#L5):  Implementation of boyer moore string search O(l) where l=len(text)\n2. [`Naive`](./strings/search/naive.go#L5):  Implementation of naive string search O(n*m) where n=len(txt) and m=len(pattern)\n\n---\n</details><details>\n\t<summary> <strong> segmenttree </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`NewSegmentTree`](./structure/segmenttree/segmenttree.go#L116): No description provided.\n\n---\n##### Types\n\n1. [`SegmentTree`](./structure/segmenttree/segmenttree.go#L17): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> set </strong> </summary>\t\n\n---\n\n#####  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.\n\n---\n##### Functions:\n\n1. [`New`](./structure/set/set.go#L7):  New gives new set.\n\n---\n</details><details>\n\t<summary> <strong> sha256 </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`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\n\n---\n</details><details>\n\t<summary> <strong> sort </strong> </summary>\t\n\n---\n\n#####  Package sort a package for demonstrating sorting algorithms in Go\n\n---\n##### Functions:\n\n1. [`BinaryInsertion`](./sort/binaryinsertionsort.go#L13): No description provided.\n2. [`Bogo`](./sort/bogosort.go#L32): No description provided.\n3. [`Bubble`](./sort/bubblesort.go#L9):  Bubble is a simple generic definition of Bubble sort algorithm.\n4. [`Bucket`](./sort/bucketsort.go#L7):  Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range.\n5. [`Cocktail`](./sort/cocktailsort.go#L9):  Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)\n6. [`Comb`](./sort/combSort.go#L17):  Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm.\n7. [`Count`](./sort/countingsort.go#L11): No description provided.\n8. [`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.\n9. [`Exchange`](./sort/exchangesort.go#L8): No description provided.\n10. [`HeapSort`](./sort/heapsort.go#L116): No description provided.\n11. [`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\n12. [`Insertion`](./sort/insertionsort.go#L5): No description provided.\n13. [`Merge`](./sort/mergesort.go#L41):  Merge Perform merge sort on a slice\n14. [`MergeIter`](./sort/mergesort.go#L55): No description provided.\n15. [`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`.\n16. [`ParallelMerge`](./sort/mergesort.go#L66):  ParallelMerge Perform merge sort on a slice using goroutines\n17. [`Partition`](./sort/quicksort.go#L12): No description provided.\n18. [`Patience`](./sort/patiencesort.go#L13): No description provided.\n19. [`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.\n20. [`Quicksort`](./sort/quicksort.go#L39):  Quicksort Sorts the entire array\n21. [`QuicksortRange`](./sort/quicksort.go#L26):  QuicksortRange Sorts the specified range within the array\n22. [`RadixSort`](./sort/radixsort.go#L43): No description provided.\n23. [`Selection`](./sort/selectionsort.go#L5): No description provided.\n24. [`Shell`](./sort/shellsort.go#L5): No description provided.\n25. [`Simple`](./sort/simplesort.go#L13): No description provided.\n\n---\n##### Types\n\n1. [`MaxHeap`](./sort/heapsort.go#L5): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> sqrt </strong> </summary>\t\n\n---\n\n#####  Package sqrt contains algorithms and data structures that contains a √n in their complexity\n\n---\n##### Functions:\n\n1. [`NewSqrtDecomposition`](./sqrt/sqrtdecomposition.go#L34):  Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment Assumptions:   - len(elements) > 0\n\n---\n##### Types\n\n1. [`SqrtDecomposition`](./sqrt/sqrtdecomposition.go#L21): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> stack </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`NewStack`](./structure/stack/stackarray.go#L17):  NewStack creates and returns a new stack.\n\n---\n##### Types\n\n1. [`Array`](./structure/stack/stackarray.go#L12): No description provided.\n\n2. [`Node`](./structure/stack/stacklinkedlist.go#L13): No description provided.\n\n3. [`SList`](./structure/stack/stacklinkedlistwithlist.go#L18): No description provided.\n\n4. [`Stack`](./structure/stack/stacklinkedlist.go#L19): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> strings </strong> </summary>\t\n\n---\n\n#####  Package strings is a package that contains all algorithms that are used to analyse and manipulate strings.\n\n---\n##### Functions:\n\n1. [`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.\n2. [`IsIsogram`](./strings/isisogram.go#L34): No description provided.\n3. [`IsSubsequence`](./strings/issubsequence.go#L10):  Returns true if s is subsequence of t, otherwise return false.\n\n---\n</details><details>\n\t<summary> <strong> transposition </strong> </summary>\t\n\n---\n\n##### Functions:\n\n1. [`Decrypt`](./cipher/transposition/transposition.go#L81): No description provided.\n2. [`Encrypt`](./cipher/transposition/transposition.go#L51): No description provided.\n3. [`FuzzTransposition`](./cipher/transposition/transposition_test.go#L103): No description provided.\n\n---\n</details><details>\n\t<summary> <strong> tree </strong> </summary>\t\n\n---\n\n#####  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)\n\n---\n##### Functions:\n\n1. [`NewAVL`](./structure/tree/avl.go#L54):  NewAVL creates a novel AVL tree\n2. [`NewBinarySearch`](./structure/tree/bstree.go#L46):  NewBinarySearch creates a novel Binary-Search tree\n3. [`NewRB`](./structure/tree/rbtree.go#L57):  NewRB creates a new Red-Black Tree\n\n---\n##### Types\n\n1. [`AVL`](./structure/tree/avl.go#L48): No description provided.\n\n2. [`AVLNode`](./structure/tree/avl.go#L18): No description provided.\n\n3. [`BSNode`](./structure/tree/bstree.go#L15): No description provided.\n\n4. [`BinarySearch`](./structure/tree/bstree.go#L40): No description provided.\n\n5. [`RB`](./structure/tree/rbtree.go#L51): No description provided.\n\n6. [`RBNode`](./structure/tree/rbtree.go#L25): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> trie </strong> </summary>\t\n\n---\n\n#####  Package trie provides Trie data structures in golang.  Wikipedia: https://en.wikipedia.org/wiki/Trie\n\n---\n##### Functions:\n\n1. [`NewNode`](./structure/trie/trie.go#L14):  NewNode creates a new Trie node with initialized children map.\n\n---\n##### Types\n\n1. [`Node`](./structure/trie/trie.go#L7): No description provided.\n\n\n---\n</details><details>\n\t<summary> <strong> xor </strong> </summary>\t\n\n---\n\n#####  Package xor is an encryption algorithm that operates the exclusive disjunction(XOR) ref: https://en.wikipedia.org/wiki/XOR_cipher\n\n---\n##### Functions:\n\n1. [`Decrypt`](./cipher/xor/xor.go#L19):  Decrypt decrypts with Xor encryption\n2. [`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.\n3. [`FuzzXOR`](./cipher/xor/xor_test.go#L108): No description provided.\n\n---\n</details>\n\n#####  Package rail fence is a classical type of transposition cipher ref : https://en.wikipedia.org/wiki/Rail_fence_cipher\n\n---\n##### Functions:\n\n1. [`Encrypt`](.cipher/railfence/railfence.go#L7):  Encrypt encrypts a message using rail fence cipher\n2. [`Decrypt`](.cipher/railfence/railfence.go#L44):  decrypt decrypts a message using rail fence cipher\n3. [`TestEncrypt`](.cipher/railfence/railfence_test.go#L7) Test function for Encrypt\n4. [`TestDecrypt`](.cipher/railfence/railfence_test.go#L50) Test function for Decrypt\n\n---\n</details>\n<!--- GODOCMD END --->\n"
  },
  {
    "path": "STYLE.md",
    "content": "# The Algorithms Go Repository Style Guide\n\nThis guide contains a set of go idioms and best practices which should be followed while writing\ncode whenever they are applicable. The instructions in this document should be given precedence\nif there is a conflict between this document and [contribution guidelines](./CONTRIBUTING.md). If you find any issue or ambiguity in\nthis document, the maintainers of this repository should be consulted.\n\n## Table of Contents\n\n- [Formatting](#formatting)\n- [Commenting](#commenting)\n  - [Package Comments](#package-comments)\n  - [Documentation Comments](#documentation-comments)\n  - [Author Comments](#author-comments)\n- [Naming](#naming)\n  - [Package Naming](#package-naming)\n  - [Symbol Naming](#symbol-naming)\n  - [Function Naming](#function-naming)\n      - [Constructor Naming](#constructor-naming)\n      - [Getter Naming](#getter-naming)\n      - [Setter Naming](#setter-naming) \n  - [Interface Naming](#interface-naming)\n\n## Formatting\n\nAll go code should be formatted with the official formatting tool `gofmt`. This requirement is\nverified by the repository workflows.\n\n## Commenting\n\nAll exported symbols should be commented with documentation, so that their motivation and use is\nclear. All documentation should record any nuances of the symbol so that users are well aware of\nthem.\n\nC++ style line comments should be preferred over C-style block comments.\n\n<table>\n<thead><tr><th>Bad</th><th>Good</th></tr></thead>\n<tbody>\n<tr><td>\n  \n```go\n/*\n  Unmarshal converts a JSON string into a go interface\n  ...\n*/\n```\n  \n</td><td>\n\n```go\n// Unmarshal converts a JSON string into a go interface\n// ...\n```\n \n</td></tr>\n</tbody></table>\n\n### Package Comments\n\nPackage comments should start with the word \"Package\" followed by the package name. For packages\nspanning multiple files or with a need for a large documentation, use a separate `doc.go` file for package level documentation comment.\n\n<table>\n<thead><tr><th>Bad</th><th>Good</th></tr></thead>\n<tbody>\n<tr><td>\n  \n```go\n// sort is a package which implements sorting functions.\n```\n  \n</td><td>\n\n```go\n// Package sort implements sorting functions.\n```\n \n</td></tr>\n</tbody></table>\n\n### Documentation Comments\n\nAll doc comments for symbols should start with the symbol name.\n\n<table>\n<thead><tr><th>Bad</th><th>Good</th></tr></thead>\n<tbody>\n<tr><td>\n  \n```go\n// Function Quick is an implementation\n// of the Quicksort algorithm.\n```\n  \n</td><td>\n\n```go\n// Quick is an implementation\n// of the Quicksort algorithm.\n```\n \n</td></tr>\n</tbody></table>\n\n### Author Comments\n\nA comment recording the author of a particular file may also be added. This comment should be\nwritten at the top of the file and it should not be a part of the package documentation.\n\n<table>\n<thead><tr><th>Bad</th><th>Good</th></tr></thead>\n<tbody>\n<tr><td>\n  \n```go\n// author: Rak Laptudirm (@raklaptudirm)\npackage sort\n```\nComment is a part of the package documentation.\n  \n</td><td>\n\n```go\n// author: Rak Laptudirm (@raklaptudirm)\n\npackage sort\n```\nComment is not a part of the package documentation.\n \n</td></tr>\n</tbody></table>\n\n## Naming\n\n### Package Naming\n\nPackage names should be short and to the point. Keep in mind that this identifier will be used to\nrefer to your package, so make it easy to remember. It should be only composed of lower case\nletters. Prefer `json` to `JSON` or `Json`. If your package name has two words, merge them\ntogether. 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.\n\nAdd the `_test` suffix to your package name to implement black-box testing for your package in the test files.\n\n### Symbol Naming\n\nGo symbols should be named in the `camelCase` or `PascalCase`, depending of whether the symbol\nis exported or not. The case when using acronyms in names should be consistent. Use `json` or\n`JSON` instead of `Json`.\n\nFor exported symbols, use the package name to your advantage to write concise symbol names. For\nexample, if you have a package `png`, instead of defining a `png.PNGFile`, define a `png.File`.\nIt is much clearer and avoids repetition.\n\n### Function Naming\n\n#### Constructor Naming\n\nConstructors should use the naming format `New<Type>()` for constructors which return pointers and\n`Make<Type>()` for constructors which return values in accordance with the Go Programming Language's\n`new` and `make` functions. If the package only exports a single constructor, use the name `New()`.\nSome valid names are `reader.New()`, `metainfo.NewFile()`.\n\n#### Getter Naming\n\nUsage of Getters and Setters are discouraged. Use exported variables instead.\n\nGetters should use the name of the field that is being fetched. For example, prefer a getter\nname like `user.Name()` to `user.GetName()`.\n\n#### Setter Naming\n\nSetters should use names in the format `Set<Field>`. For example, `user.SetName()`.\n\n### Interface Naming\n\nInterfaces should use names in the format of `<Method>er` or `<Method>`. For example, some\nvalid interface names are:\n\n```go\ntype Node interface {\n  Node()\n}\n \ntype Writer interface {\n  Write()\n}\n```\n"
  },
  {
    "path": "cache/lfu.go",
    "content": "// lfu.go\n// description: a type of cache algorithm used to manage memory within a computer.\n// details:\n// The standard characteristics of this method involve the system keeping track of the number of times a block is referenced in memory.\n// When the cache is full and requires more room the system will purge the item with the lowest reference frequency.\n// ref: (https://en.wikipedia.org/wiki/Least_frequently_used)\n// time complexity: O(N)\n// space complexity: O(1)\n// author: [CocaineCong](https://github.com/CocaineCong)\n\npackage cache\n\nimport (\n\t\"container/list\"\n\t\"math\"\n)\n\n// LFU the Least Frequently Used (LFU) page-replacement algorithm\ntype LFU struct {\n\tlen     int // length\n\tcap     int // capacity\n\tminFreq int // The element that operates least frequently in LFU\n\n\t// key: key of element, value: value of element\n\titemMap map[string]*list.Element\n\n\t// key: frequency of possible occurrences of all elements in the itemMap\n\t// value: elements with the same frequency\n\tfreqMap map[int]*list.List\n}\n\n// NewLFU init the LFU cache with capacity\nfunc NewLFU(capacity int) LFU {\n\treturn LFU{\n\t\tlen:     0,\n\t\tcap:     capacity,\n\t\tminFreq: math.MaxInt,\n\t\titemMap: make(map[string]*list.Element),\n\t\tfreqMap: make(map[int]*list.List),\n\t}\n}\n\n// initItem to init item for LFU\nfunc initItem(k string, v any, f int) item {\n\treturn item{\n\t\tkey:   k,\n\t\tvalue: v,\n\t\tfreq:  f,\n\t}\n}\n\n// Get the key in cache by LFU\nfunc (c *LFU) Get(key string) any {\n\t// if existed, will return value\n\tif e, ok := c.itemMap[key]; ok {\n\t\t// the frequency of e +1 and change freqMap\n\t\tc.increaseFreq(e)\n\t\tobj := e.Value.(item)\n\t\treturn obj.value\n\t}\n\n\t// if not existed, return nil\n\treturn nil\n}\n\n// Put the key in LFU cache\nfunc (c *LFU) Put(key string, value any) {\n\tif e, ok := c.itemMap[key]; ok {\n\t\t// if key existed, update the value\n\t\tobj := e.Value.(item)\n\t\tobj.value = value\n\t\tc.increaseFreq(e)\n\t} else {\n\t\t// if key not existed\n\t\tobj := initItem(key, value, 1)\n\t\t// if the length of item gets to the top line\n\t\t// remove the least frequently operated element\n\t\tif c.len == c.cap {\n\t\t\tc.eliminate()\n\t\t\tc.len--\n\t\t}\n\t\t// insert in freqMap and itemMap\n\t\tc.insertMap(obj)\n\t\t// change minFreq to 1 because insert the newest one\n\t\tc.minFreq = 1\n\t\t// length++\n\t\tc.len++\n\t}\n}\n\n// increaseFreq increase the frequency if element\nfunc (c *LFU) increaseFreq(e *list.Element) {\n\tobj := e.Value.(item)\n\t// remove from low frequency first\n\toldLost := c.freqMap[obj.freq]\n\toldLost.Remove(e)\n\t// change the value of minFreq\n\tif c.minFreq == obj.freq && oldLost.Len() == 0 {\n\t\t// if it is the last node of the minimum frequency that is removed\n\t\tc.minFreq++\n\t}\n\t// add to high frequency list\n\tc.insertMap(obj)\n}\n\n// insertMap insert item in map\nfunc (c *LFU) insertMap(obj item) {\n\t// add in freqMap\n\tl, ok := c.freqMap[obj.freq]\n\tif !ok {\n\t\tl = list.New()\n\t\tc.freqMap[obj.freq] = l\n\t}\n\te := l.PushFront(obj)\n\t// update or add the value of itemMap key to e\n\tc.itemMap[obj.key] = e\n}\n\n// eliminate clear the least frequently operated element\nfunc (c *LFU) eliminate() {\n\tl := c.freqMap[c.minFreq]\n\te := l.Back()\n\tobj := e.Value.(item)\n\tl.Remove(e)\n\n\tdelete(c.itemMap, obj.key)\n}\n"
  },
  {
    "path": "cache/lfu_test.go",
    "content": "package cache_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/cache\"\n)\n\nfunc TestLFU(t *testing.T) {\n\tlfuCache := cache.NewLFU(3)\n\tt.Run(\"Test 1: Put number and Get is correct\", func(t *testing.T) {\n\t\tkey, value := \"1\", 1\n\t\tlfuCache.Put(key, value)\n\t\tgot := lfuCache.Get(key)\n\n\t\tif got != value {\n\t\t\tt.Errorf(\"expected: %v, got: %v\", value, got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 2: Get data not stored in cache should return nil\", func(t *testing.T) {\n\t\tgot := lfuCache.Get(\"2\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 3: Put data over capacity and Get should return nil\", func(t *testing.T) {\n\t\tlfuCache.Put(\"2\", 2)\n\t\tlfuCache.Put(\"3\", 3)\n\t\tlfuCache.Put(\"4\", 4)\n\n\t\tgot := lfuCache.Get(\"1\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\t})\n\n\tt.Run(\"test 4: Put key over capacity but recent key exists\", func(t *testing.T) {\n\t\tlfuCache.Put(\"4\", 4)\n\t\tlfuCache.Put(\"3\", 3)\n\t\tlfuCache.Put(\"2\", 2)\n\t\tlfuCache.Put(\"1\", 1)\n\n\t\tgot := lfuCache.Get(\"4\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\n\t\texpected := 3\n\t\tgot = lfuCache.Get(\"3\")\n\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected: %v, got: %v\", expected, got)\n\t\t}\n\n\t})\n}\n"
  },
  {
    "path": "cache/lru.go",
    "content": "// lru.go\n// description : Least Recently Used (LRU) cache\n// 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.\n// time complexity : O(1)\n// space complexity : O(n)\n// ref : https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)\n\npackage cache\n\nimport (\n\t\"github.com/TheAlgorithms/Go/structure/linkedlist\"\n)\n\ntype item struct {\n\tkey   string\n\tvalue any\n\n\t// the frequency of key\n\tfreq int\n}\n\ntype LRU struct {\n\tdl       *linkedlist.Doubly[any]\n\tsize     int\n\tcapacity int\n\tstorage  map[string]*linkedlist.Node[any]\n}\n\n// NewLRU represent initiate lru cache with capacity\nfunc NewLRU(capacity int) LRU {\n\treturn LRU{\n\t\tdl:       linkedlist.NewDoubly[any](),\n\t\tstorage:  make(map[string]*linkedlist.Node[any], capacity),\n\t\tsize:     0,\n\t\tcapacity: capacity,\n\t}\n}\n\n// Get value from lru\n// if not found, return nil\nfunc (c *LRU) Get(key string) any {\n\tv, ok := c.storage[key]\n\tif ok {\n\t\tc.dl.MoveToBack(v)\n\t\treturn v.Val.(item).value\n\t}\n\n\treturn nil\n}\n\n// Put cache with key and value to lru\nfunc (c *LRU) Put(key string, value any) {\n\te, ok := c.storage[key]\n\tif ok {\n\t\tn := e.Val.(item)\n\t\tn.value = value\n\t\te.Val = n\n\t\tc.dl.MoveToBack(e)\n\t\treturn\n\t}\n\n\tif c.size >= c.capacity {\n\t\te := c.dl.Front()\n\t\tdk := e.Val.(item).key\n\t\tc.dl.Remove(e)\n\t\tdelete(c.storage, dk)\n\t\tc.size--\n\t}\n\n\tn := item{key: key, value: value}\n\tc.dl.AddAtEnd(n)\n\tne := c.dl.Back()\n\tc.storage[key] = ne\n\tc.size++\n}\n"
  },
  {
    "path": "cache/lru_test.go",
    "content": "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 := cache.NewLRU(3)\n\n\tt.Run(\"Test 1: Put number and Get is correct\", func(t *testing.T) {\n\t\tkey, value := \"1\", 1\n\t\tcache.Put(key, value)\n\t\tgot := cache.Get(key)\n\n\t\tif got != value {\n\t\t\tt.Errorf(\"expected: %v, got: %v\", value, got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 2: Get data not stored in cache should return nil\", func(t *testing.T) {\n\t\tgot := cache.Get(\"2\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 3: Put data over capacity and Get should return nil\", func(t *testing.T) {\n\t\tcache.Put(\"2\", 2)\n\t\tcache.Put(\"3\", 3)\n\t\tcache.Put(\"4\", 4)\n\n\t\tgot := cache.Get(\"1\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\t})\n\n\tt.Run(\"test 4: Put key over capacity but recent key exists\", func(t *testing.T) {\n\t\tcache.Put(\"4\", 4)\n\t\tcache.Put(\"3\", 3)\n\t\tcache.Put(\"2\", 2)\n\t\tcache.Put(\"1\", 1)\n\n\t\tgot := cache.Get(\"4\")\n\t\tif got != nil {\n\t\t\tt.Errorf(\"expected: nil, got: %v\", got)\n\t\t}\n\n\t\texpected := 3\n\t\tgot = cache.Get(\"3\")\n\n\t\tif got != expected {\n\t\t\tt.Errorf(\"expected: %v, got: %v\", expected, got)\n\t\t}\n\n\t})\n}\n"
  },
  {
    "path": "checksum/crc8.go",
    "content": "// crc8.go\n// description: Calculate CRC8\n// details:\n// A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks\n// and storage devices to detect accidental changes to raw data.\n// time complexity: O(n)\n// space complexity: O(1)\n// See more [CRC](https://en.wikipedia.org/wiki/Cyclic_redundancy_check)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see crc8_test.go\n\npackage checksum\n\nimport \"math/bits\"\n\n// CRCModel contains the necessary parameters for calculating the DRC algorithm\ntype CRCModel struct {\n\tPoly   uint8\n\tInit   uint8\n\tRefIn  bool\n\tRefOut bool\n\tXorOut uint8\n\tName   string\n}\n\n// CRC8 calculates CRC8 checksum of the given data.\nfunc CRC8(data []byte, model CRCModel) uint8 {\n\ttable := getTable(model)\n\tcrcResult := model.Init\n\tcrcResult = addBytes(data, model, crcResult, table)\n\tif model.RefOut {\n\t\tcrcResult = bits.Reverse8(crcResult)\n\t}\n\treturn crcResult ^ model.XorOut\n}\n\n// This function get the result of adding the bytes in data to the crc\nfunc addBytes(data []byte, model CRCModel, crcResult uint8, table []uint8) uint8 {\n\tif model.RefIn {\n\t\tfor _, d := range data {\n\t\t\td = bits.Reverse8(d)\n\t\t\tcrcResult = table[crcResult^d]\n\t\t}\n\t\treturn crcResult\n\t}\n\tfor _, d := range data {\n\t\tcrcResult = table[crcResult^d]\n\t}\n\treturn crcResult\n}\n\n// This function get 256-byte (256x8) table for efficient processing.\nfunc getTable(model CRCModel) []uint8 {\n\ttable := make([]uint8, 256)\n\tfor i := 0; i < 256; i++ {\n\t\tcrc := uint8(i)\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tisSetBit := (crc & 0x80) != 0\n\t\t\tcrc <<= 1\n\t\t\tif isSetBit {\n\t\t\t\tcrc ^= model.Poly\n\t\t\t}\n\t\t}\n\t\ttable[i] = crc\n\t}\n\treturn table\n}\n"
  },
  {
    "path": "checksum/crc8_test.go",
    "content": "// crc8_test.go\n// description: Test for calculate crc8\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see crc8.go\n\npackage checksum_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/checksum\"\n)\n\nvar (\n\tCRC8         = checksum.CRCModel{0x07, 0x00, false, false, 0x00, \"CRC-8\"}\n\tCRC8CDMA2000 = checksum.CRCModel{0x9B, 0xFF, false, false, 0x00, \"CRC-8/CDMA2000\"}\n\tCRC8DARC     = checksum.CRCModel{0x39, 0x00, true, true, 0x00, \"CRC-8/DARC\"}\n\tCRC8DVBS2    = checksum.CRCModel{0xD5, 0x00, false, false, 0x00, \"CRC-8/DVB-S2\"}\n\tCRC8EBU      = checksum.CRCModel{0x1D, 0xFF, true, true, 0x00, \"CRC-8/EBU\"}\n\tCRC8ICODE    = checksum.CRCModel{0x1D, 0xFD, false, false, 0x00, \"CRC-8/I-CODE\"}\n\tCRC8ITU      = checksum.CRCModel{0x07, 0x00, false, false, 0x55, \"CRC-8/ITU\"}\n\tCRC8MAXIM    = checksum.CRCModel{0x31, 0x00, true, true, 0x00, \"CRC-8/MAXIM\"}\n\tCRC8ROHC     = checksum.CRCModel{0x07, 0xFF, true, true, 0x00, \"CRC-8/ROHC\"}\n\tCRC8WCDMA    = checksum.CRCModel{0x9B, 0x00, true, true, 0x00, \"CRC-8/WCDMA\"}\n)\n\nfunc TestCalculateCRC8(t *testing.T) {\n\tdata := []byte(\"123456789\")\n\ttests := []struct {\n\t\tname  string\n\t\tdata  []byte\n\t\tmodel checksum.CRCModel\n\t\twant  uint8\n\t}{\n\t\t{CRC8.Name, data, CRC8, 0xF4},\n\t\t{CRC8CDMA2000.Name, data, CRC8CDMA2000, 0xDA},\n\t\t{CRC8DARC.Name, data, CRC8DARC, 0x15},\n\t\t{CRC8DVBS2.Name, data, CRC8DVBS2, 0xBC},\n\t\t{CRC8EBU.Name, data, CRC8EBU, 0x97},\n\t\t{CRC8ICODE.Name, data, CRC8ICODE, 0x7E},\n\t\t{CRC8ITU.Name, data, CRC8ITU, 0xA1},\n\t\t{CRC8MAXIM.Name, data, CRC8MAXIM, 0xA1},\n\t\t{CRC8ROHC.Name, data, CRC8ROHC, 0xD0},\n\t\t{CRC8WCDMA.Name, data, CRC8WCDMA, 0x25},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfmt.Println(checksum.CRC8(test.data, test.model))\n\t\t\tif got := checksum.CRC8(test.data, test.model); got != test.want {\n\t\t\t\tt.Errorf(\"CalculateCRC8() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkCalculateCRC8(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tchecksum.CRC8([]byte(\"123456789\"), CRC8)\n\t}\n}\n"
  },
  {
    "path": "checksum/luhn.go",
    "content": "// lunh.go\n// description: Luhn algorithm\n// 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)\n// time complexity: O(n)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see lunh_test.go\n\n// Package checksum describes algorithms for finding various checksums\npackage checksum\n\n// Luhn validates the provided data using the Luhn algorithm.\nfunc Luhn(s []byte) bool {\n\tn := len(s)\n\tnumber := 0\n\tresult := 0\n\tfor i := 0; i < n; i++ {\n\t\tnumber = int(s[i]) - '0'\n\t\tif i%2 != 0 {\n\t\t\tresult += number\n\t\t\tcontinue\n\t\t}\n\t\tnumber *= 2\n\t\tif number > 9 {\n\t\t\tnumber -= 9\n\t\t}\n\t\tresult += number\n\t}\n\treturn result%10 == 0\n}\n"
  },
  {
    "path": "checksum/luhn_test.go",
    "content": "// luhn_test.go\n// description: Test for Luhn algorithm\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see luhn.go\n\npackage checksum_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/checksum\"\n)\n\nfunc TestLuhn(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\ts    []byte\n\t\twant bool\n\t}{\n\t\t{\"check 4242424242424242\", []byte(\"4242424242424242\"), true},\n\t\t{\"check 6200000000000005\", []byte(\"6200000000000005\"), true},\n\t\t{\"check 5534200028533164\", []byte(\"5534200028533164\"), true},\n\t\t{\"check 36227206271667\", []byte(\"36227206271667\"), true},\n\t\t{\"check 471629309440\", []byte(\"471629309440\"), false},\n\t\t{\"check 1111\", []byte(\"1111\"), false},\n\t\t{\"check 12345674\", []byte(\"12345674\"), true},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := checksum.Luhn(test.s); got != test.want {\n\t\t\t\tt.Errorf(\"LuhnAlgorithm() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkBruteForceFactorial(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tchecksum.Luhn([]byte(\"4242424242424242\"))\n\t}\n}\n"
  },
  {
    "path": "cipher/caesar/caesar.go",
    "content": "// Package caesar is the shift cipher\n// description: Caesar cipher\n// 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.\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://en.wikipedia.org/wiki/Caesar_cipher\npackage caesar\n\n// Encrypt encrypts by right shift of \"key\" each character of \"input\"\nfunc Encrypt(input string, key int) string {\n\t// if key is negative value,\n\t// updates \"key\" the number which congruents to \"key\" modulo 26\n\tkey8 := byte(key%26+26) % 26\n\n\tvar outputBuffer []byte\n\t// b is a byte, which is the equivalent of uint8.\n\tfor _, b := range []byte(input) {\n\t\tnewByte := b\n\t\tif 'A' <= b && b <= 'Z' {\n\t\t\toutputBuffer = append(outputBuffer, 'A'+(newByte-'A'+key8)%26)\n\t\t} else if 'a' <= b && b <= 'z' {\n\t\t\toutputBuffer = append(outputBuffer, 'a'+(newByte-'a'+key8)%26)\n\t\t} else {\n\t\t\toutputBuffer = append(outputBuffer, newByte)\n\t\t}\n\t}\n\treturn string(outputBuffer)\n}\n\n// Decrypt decrypts by left shift of \"key\" each character of \"input\"\nfunc Decrypt(input string, key int) string {\n\t// left shift of \"key\" is same as right shift of 26-\"key\"\n\treturn Encrypt(input, 26-key)\n}\n"
  },
  {
    "path": "cipher/caesar/caesar_test.go",
    "content": "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 = []struct {\n\t\tdescription string\n\t\tinput       string\n\t\tkey         int\n\t\texpected    string\n\t}{\n\t\t{\n\t\t\t\"Basic caesar encryption with letter 'a'\",\n\t\t\t\"a\",\n\t\t\t3,\n\t\t\t\"d\",\n\t\t},\n\t\t{\n\t\t\t\"Basic caesar encryption wrap around alphabet on letter 'z'\",\n\t\t\t\"z\",\n\t\t\t3,\n\t\t\t\"c\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt a simple string with caesar encryiption\",\n\t\t\t\"hello\",\n\t\t\t3,\n\t\t\t\"khoor\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt a simple string with key 13\",\n\t\t\t\"hello\",\n\t\t\t13,\n\t\t\t\"uryyb\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt a simple string with key -13\",\n\t\t\t\"hello\",\n\t\t\t-13,\n\t\t\t\"uryyb\",\n\t\t},\n\t\t{\n\t\t\t\"With key of 26 output should be the same as the input\",\n\t\t\t\"no change\",\n\t\t\t26,\n\t\t\t\"no change\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt sentence with key 10\",\n\t\t\t\"the quick brown fox jumps over the lazy dog.\",\n\t\t\t10,\n\t\t\t\"dro aesmu lbygx pyh tewzc yfob dro vkji nyq.\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt sentence with key 10\",\n\t\t\t\"The Quick Brown Fox Jumps over the Lazy Dog.\",\n\t\t\t10,\n\t\t\t\"Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.\",\n\t\t},\n\t}\n\tfor _, test := range caesarTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tactual := Encrypt(test.input, test.key)\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"With input string '%s' and key '%d' was expecting '%s' but actual was '%s'\",\n\t\t\t\t\ttest.input, test.key, test.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDecrypt(t *testing.T) {\n\tvar caesarTestData = []struct {\n\t\tdescription string\n\t\tinput       string\n\t\tkey         int\n\t\texpected    string\n\t}{\n\t\t{\n\t\t\t\"Basic caesar decryption with letter 'a'\",\n\t\t\t\"a\",\n\t\t\t3,\n\t\t\t\"x\",\n\t\t},\n\t\t{\n\t\t\t\"Basic caesar decryption wrap around alphabet on letter 'z'\",\n\t\t\t\"z\",\n\t\t\t3,\n\t\t\t\"w\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt a simple string with caesar encryiption\",\n\t\t\t\"hello\",\n\t\t\t3,\n\t\t\t\"ebiil\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt a simple string with key 13\",\n\t\t\t\"hello\",\n\t\t\t13,\n\t\t\t\"uryyb\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt a simple string with key -13\",\n\t\t\t\"hello\",\n\t\t\t-13,\n\t\t\t\"uryyb\",\n\t\t},\n\t\t{\n\t\t\t\"With key of 26 output should be the same as the input\",\n\t\t\t\"no change\",\n\t\t\t26,\n\t\t\t\"no change\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt sentence with key 10\",\n\t\t\t\"Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.\",\n\t\t\t10,\n\t\t\t\"The Quick Brown Fox Jumps over the Lazy Dog.\",\n\t\t},\n\t}\n\n\tfor _, test := range caesarTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tactual := Decrypt(test.input, test.key)\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"With input string '%s' and key '%d' was expecting '%s' but actual was '%s'\",\n\t\t\t\t\ttest.input, test.key, test.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc Example() {\n\tconst (\n\t\tkey   = 10\n\t\tinput = \"The Quick Brown Fox Jumps over the Lazy Dog.\"\n\t)\n\n\tencryptedText := Encrypt(input, key)\n\tfmt.Printf(\"Encrypt=> key: %d, input: %s, encryptedText: %s\\n\", key, input, encryptedText)\n\n\tdecryptedText := Decrypt(encryptedText, key)\n\tfmt.Printf(\"Decrypt=> key: %d, input: %s, decryptedText: %s\\n\", key, encryptedText, decryptedText)\n\n\t// Output:\n\t// Encrypt=> key: 10, input: The Quick Brown Fox Jumps over the Lazy Dog., encryptedText: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq.\n\t// Decrypt=> key: 10, input: Dro Aesmu Lbygx Pyh Tewzc yfob dro Vkji Nyq., decryptedText: The Quick Brown Fox Jumps over the Lazy Dog.\n}\n\nfunc FuzzCaesar(f *testing.F) {\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tf.Add(\"The Quick Brown Fox Jumps over the Lazy Dog.\")\n\tf.Fuzz(func(t *testing.T, input string) {\n\t\tkey := rnd.Intn(26)\n\t\tif result := Decrypt(Encrypt(input, key), key); result != input {\n\t\t\tt.Fatalf(\"With input: '%s' and key: %d\\n\\tExpected: '%s'\\n\\tGot: '%s'\", input, key, input, result)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/cipher_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage cipher\n"
  },
  {
    "path": "cipher/diffiehellman/diffiehellmankeyexchange.go",
    "content": "// Package diffiehellman implements Diffie-Hellman Key Exchange Algorithm\n// description: Diffie-Hellman key exchange\n// 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.\n// time complexity: O(log(n))\n// space complexity: O(1)\n// for more information watch : https://www.youtube.com/watch?v=NmM9HA2MQGI\npackage diffiehellman\n\nconst (\n\tgenerator         = 3\n\tprimeNumber int64 = 6700417 // prime number discovered by Leonhard Euler\n)\n\n// GenerateShareKey : generates a key using client private key , generator and primeNumber\n// this key can be made public\n// shareKey = (g^key)%primeNumber\nfunc GenerateShareKey(prvKey int64) int64 {\n\treturn modularExponentiation(generator, prvKey, primeNumber)\n}\n\n// GenerateMutualKey : generates a mutual key that can be used by only alice and bob\n// mutualKey = (shareKey^prvKey)%primeNumber\nfunc GenerateMutualKey(prvKey, shareKey int64) int64 {\n\treturn modularExponentiation(shareKey, prvKey, primeNumber)\n}\n\n// r = (b^e)%mod\nfunc modularExponentiation(b, e, mod int64) int64 {\n\n\t//runs in O(log(n)) where n = e\n\t//uses exponentiation by squaring to speed up the process\n\tif mod == 1 {\n\t\treturn 0\n\t}\n\tvar r int64 = 1\n\tb = b % mod\n\tfor e > 0 {\n\t\tif e&1 == 1 {\n\t\t\tr = (r * b) % mod\n\t\t}\n\t\te = e >> 1\n\t\tb = (b * b) % mod\n\t}\n\treturn r\n}\n"
  },
  {
    "path": "cipher/diffiehellman/diffiehellmankeyexchange_test.go",
    "content": "package diffiehellman\n\nimport (\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"testing\"\n)\n\nfunc TestDiffieHellmanKeyExchange(t *testing.T) {\n\tt.Run(\"Test 1: modularExponentiation\", func(t *testing.T) {\n\t\tvar want int64 = 9 // (3^5)mod13 = 243mod13 = 9\n\t\tvar prvKey int64 = 5\n\t\tvar generator int64 = 3\n\t\tvar primeNumber int64 = 13\n\t\tgot := modularExponentiation(generator, prvKey, primeNumber)\n\t\tif got != want {\n\t\t\tt.Errorf(`with privateKey=%d, generator=%d and primeNumber=%d  \n\t\t\tmodularExponentiation should result=%d, but resulted=%d`, prvKey, generator, primeNumber, want, got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 2: Key Exchange\", func(t *testing.T) {\n\t\t// generating a small sized rsa_cipher key for testing\n\t\talicePrvKey, _ := rsa.GenerateKey(rand.Reader, 31)\n\t\tbobPrvKey, _ := rsa.GenerateKey(rand.Reader, 31)\n\n\t\t// alice and bob generates their respective share key with their privateKey\n\t\tshareKeyByAlice := GenerateShareKey(alicePrvKey.D.Int64())\n\t\tshareKeyByBob := GenerateShareKey(bobPrvKey.D.Int64())\n\n\t\t// generated share key now can be exchanged even via insecure channel\n\n\t\t// mutualKey can be computed using shared key\n\t\tmutualKeyComputedByAlice := GenerateMutualKey(alicePrvKey.D.Int64(), shareKeyByBob)\n\t\tmutualKeyComputedByBob := GenerateMutualKey(bobPrvKey.D.Int64(), shareKeyByAlice)\n\n\t\tif mutualKeyComputedByAlice != mutualKeyComputedByBob {\n\t\t\tt.Errorf(\"mutual key computed by alice and bob should be same, but got un-equal\")\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/doc.go",
    "content": "// Package cipher is a package containing different implementations of certain ciphers\npackage cipher\n"
  },
  {
    "path": "cipher/dsa/dsa.go",
    "content": "/*\ndsa.go\ndescription: DSA encryption and decryption including key generation\ndetails: [DSA wiki](https://en.wikipedia.org/wiki/Digital_Signature_Algorithm)\nauthor(s): [ddaniel27](https://github.com/ddaniel27)\n*/\npackage dsa\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\t\"math/big\"\n)\n\nconst (\n\tnumMRTests = 64   // Number of Miller-Rabin tests\n\tL          = 1024 // Number of bits in p\n\tN          = 160  // Number of bits in q\n)\n\ntype (\n\t// parameters represents the DSA parameters\n\tparameters struct {\n\t\tP, Q, G *big.Int\n\t}\n\n\t// dsa represents the DSA\n\tdsa struct {\n\t\tparameters\n\t\tpubKey  *big.Int // public key (y)\n\t\tprivKey *big.Int // private key (x)\n\t}\n)\n\n// New creates a new DSA instance\nfunc New() *dsa {\n\td := new(dsa)\n\td.dsaParameterGeneration()\n\td.keyGen()\n\treturn d\n}\n\n// Parameter generation for DSA\n// 1. FIPS 186-4 specifies that the L and N values must be (1024, 160), (2048, 224), or (3072, 256)\n// 2. Choose a N-bit prime q\n// 3. Choose a L-bit prime p such that p-1 is a multiple of q\n// 4. Choose an integer h randomly from the range [2, p-2]\n// 5. Compute g = h^((p-1)/q) mod p\n// 6. Return (p, q, g)\nfunc (dsa *dsa) dsaParameterGeneration() {\n\tvar err error\n\tp, q, bigInt := new(big.Int), new(big.Int), new(big.Int)\n\tone, g, h := big.NewInt(1), big.NewInt(1), big.NewInt(2)\n\tpBytes := make([]byte, L/8)\n\n\t// GPLoop is a label for the loop\n\t// We use this loop to change the prime q if we don't find a prime p\nGPLoop:\n\tfor {\n\t\t// 2. Choose a N-bit prime q\n\t\tq, err = rand.Prime(rand.Reader, N)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor i := 0; i < 4*L; i++ {\n\t\t\t// 3. Choose a L-bit prime p such that p-1 is a multiple of q\n\t\t\t// In this case we generate a random number of L bits\n\t\t\tif _, err := io.ReadFull(rand.Reader, pBytes); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t// This are the minimum conditions for p being a possible prime\n\t\t\tpBytes[len(pBytes)-1] |= 1 // p is odd\n\t\t\tpBytes[0] |= 0x80          // p has the highest bit set\n\t\t\tp.SetBytes(pBytes)\n\n\t\t\t// Instead of using (p-1)%q == 0\n\t\t\t// We ensure that p-1 is a multiple of q and validates if p is prime\n\t\t\tbigInt.Mod(p, q)\n\t\t\tbigInt.Sub(bigInt, one)\n\t\t\tp.Sub(p, bigInt)\n\t\t\tif p.BitLen() < L || !p.ProbablyPrime(numMRTests) { // Check if p is prime and has L bits\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdsa.P = p\n\t\t\tdsa.Q = q\n\t\t\tbreak GPLoop\n\t\t}\n\t}\n\n\t// 4. Choose an integer h randomly from the range [2, p-2]. Commonly, h = 2\n\t// 5. Compute g = h^((p-1)/q) mod p. In case g == 1, increment h until g != 1\n\tpm1 := new(big.Int).Sub(p, one)\n\n\tfor g.Cmp(one) == 0 {\n\t\tg.Exp(h, new(big.Int).Div(pm1, q), p)\n\t\th.Add(h, one)\n\t}\n\n\tdsa.G = g\n}\n\n// keyGen is key generation for DSA\n// 1. Choose a random integer x from the range [1, q-1]\n// 2. Compute y = g^x mod p\nfunc (dsa *dsa) keyGen() {\n\t// 1. Choose a random integer x from the range [1, q-1]\n\tx, err := rand.Int(rand.Reader, new(big.Int).Sub(dsa.Q, big.NewInt(1)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdsa.privKey = x\n\n\t// 2. Compute y = g^x mod p\n\tdsa.pubKey = new(big.Int).Exp(dsa.G, x, dsa.P)\n}\n\n// Sign is signature generation for DSA\n// 1. Choose a random integer k from the range [1, q-1]\n// 2. Compute r = (g^k mod p) mod q\n// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q\nfunc Sign(m []byte, p, q, g, x *big.Int) (r, s *big.Int) {\n\t// 1. Choose a random integer k from the range [1, q-1]\n\tk, err := rand.Int(rand.Reader, new(big.Int).Sub(q, big.NewInt(1)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// 2. Compute r = (g^k mod p) mod q\n\tr = new(big.Int).Exp(g, k, p)\n\tr.Mod(r, q)\n\n\t// 3. Compute s = (k^-1 * (H(m) + x*r)) mod q\n\th := new(big.Int).SetBytes(m)     // This should be the hash of the message\n\ts = new(big.Int).ModInverse(k, q) // k^-1 mod q\n\ts.Mul(\n\t\ts,\n\t\tnew(big.Int).Add( // (H(m) + x*r)\n\t\t\th,\n\t\t\tnew(big.Int).Mul(x, r),\n\t\t),\n\t)\n\ts.Mod(s, q) // mod q\n\n\treturn r, s\n}\n\n// Verify is signature verification for DSA\n// 1. Compute w = s^-1 mod q\n// 2. Compute u1 = (H(m) * w) mod q\n// 3. Compute u2 = (r * w) mod q\n// 4. Compute v = ((g^u1 * y^u2) mod p) mod q\n// 5. If v == r, the signature is valid\nfunc Verify(m []byte, r, s, p, q, g, y *big.Int) bool {\n\t// 1. Compute w = s^-1 mod q\n\tw := new(big.Int).ModInverse(s, q)\n\n\t// 2. Compute u1 = (H(m) * w) mod q\n\th := new(big.Int).SetBytes(m) // This should be the hash of the message\n\tu1 := new(big.Int).Mul(h, w)\n\tu1.Mod(u1, q)\n\n\t// 3. Compute u2 = (r * w) mod q\n\tu2 := new(big.Int).Mul(r, w)\n\tu2.Mod(u2, q)\n\n\t// 4. Compute v = ((g^u1 * y^u2) mod p) mod q\n\tv := new(big.Int).Exp(g, u1, p)\n\tv.Mul(\n\t\tv,\n\t\tnew(big.Int).Exp(y, u2, p),\n\t)\n\tv.Mod(v, p)\n\tv.Mod(v, q)\n\n\t// 5. If v == r, the signature is valid\n\treturn v.Cmp(r) == 0\n}\n\n// GetPublicKey returns the public key (y)\nfunc (dsa *dsa) GetPublicKey() *big.Int {\n\treturn dsa.pubKey\n}\n\n// GetParameters returns the DSA parameters (p, q, g)\nfunc (dsa *dsa) GetParameters() parameters {\n\treturn dsa.parameters\n}\n\n// GetPrivateKey returns the private Key (x)\nfunc (dsa *dsa) GetPrivateKey() *big.Int {\n\treturn dsa.privKey\n}\n"
  },
  {
    "path": "cipher/dsa/dsa_test.go",
    "content": "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.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmessage string\n\t\talter   bool\n\t\twant    bool\n\t}{\n\t\t{\n\t\t\tname:    \"valid signature\",\n\t\t\tmessage: \"Hello, world!\",\n\t\t\talter:   false,\n\t\t\twant:    true,\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid signature\",\n\t\t\tmessage: \"Hello, world!\",\n\t\t\talter:   true,\n\t\t\twant:    false,\n\t\t},\n\t}\n\t// Generate a DSA key pair\n\tdsaInstance := dsa.New()\n\tpubKey := dsaInstance.GetPublicKey()\n\tparams := dsaInstance.GetParameters()\n\tprivKey := dsaInstance.GetPrivateKey()\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\t// Sign the message\n\t\t\tr, s := dsa.Sign(\n\t\t\t\t[]byte(tt.message),\n\t\t\t\tparams.P,\n\t\t\t\tparams.Q,\n\t\t\t\tparams.G,\n\t\t\t\tprivKey,\n\t\t\t)\n\n\t\t\tif tt.alter {\n\t\t\t\t// Alter the signature\n\t\t\t\tr.Add(r, big.NewInt(1))\n\t\t\t}\n\n\t\t\t// Verify the signature\n\t\t\tif got := dsa.Verify(\n\t\t\t\t[]byte(tt.message),\n\t\t\t\tr,\n\t\t\t\ts,\n\t\t\t\tparams.P,\n\t\t\t\tparams.Q,\n\t\t\t\tparams.G,\n\t\t\t\tpubKey,\n\t\t\t); got != tt.want {\n\t\t\t\tt.Errorf(\"got %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n/* ------------------- BENCHMARKS ------------------- */\nfunc BenchmarkDSANew(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tdsa.New()\n\t}\n}\n\nfunc BenchmarkDSASign(b *testing.B) {\n\tdsaInstance := dsa.New()\n\tparams := dsaInstance.GetParameters()\n\tprivKey := dsaInstance.GetPrivateKey()\n\tfor i := 0; i < b.N; i++ {\n\t\tdsa.Sign(\n\t\t\t[]byte(\"Hello, World!\"),\n\t\t\tparams.P,\n\t\t\tparams.Q,\n\t\t\tparams.G,\n\t\t\tprivKey,\n\t\t)\n\t}\n}\n\nfunc BenchmarkDSAVerify(b *testing.B) {\n\tdsaInstance := dsa.New()\n\tpubKey := dsaInstance.GetPublicKey()\n\tparams := dsaInstance.GetParameters()\n\tprivKey := dsaInstance.GetPrivateKey()\n\tr, s := dsa.Sign(\n\t\t[]byte(\"Hello, World!\"),\n\t\tparams.P,\n\t\tparams.Q,\n\t\tparams.G,\n\t\tprivKey,\n\t)\n\tfor i := 0; i < b.N; i++ {\n\t\tdsa.Verify(\n\t\t\t[]byte(\"Hello, World!\"),\n\t\t\tr,\n\t\t\ts,\n\t\t\tparams.P,\n\t\t\tparams.Q,\n\t\t\tparams.G,\n\t\t\tpubKey,\n\t\t)\n\t}\n}\n"
  },
  {
    "path": "cipher/polybius/polybius.go",
    "content": "// Package polybius is encrypting method with polybius square\n// description: Polybius square\n// details : The Polybius algorithm is a simple algorithm that is used to encode a message by converting each letter to a pair of numbers.\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://en.wikipedia.org/wiki/Polybius_square#Hybrid_Polybius_Playfair_Cipher\npackage polybius\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\n// Polybius is struct having size, characters, and key\ntype Polybius struct {\n\tsize       int\n\tcharacters string\n\tkey        string\n}\n\n// NewPolybius returns a pointer to object of Polybius.\n// If the size of \"chars\" is longer than \"size\",\n// \"chars\" are truncated to \"size\".\nfunc NewPolybius(key string, size int, chars string) (*Polybius, error) {\n\tif size < 0 {\n\t\treturn nil, fmt.Errorf(\"provided size %d cannot be negative\", size)\n\t}\n\tkey = strings.ToUpper(key)\n\tif size > len(chars) {\n\t\treturn nil, fmt.Errorf(\"provided size %d is too small to use to slice string %q of len %d\", size, chars, len(chars))\n\t}\n\tfor _, r := range chars {\n\t\tif (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {\n\t\t\treturn nil, fmt.Errorf(\"provided string %q should only contain latin characters\", chars)\n\t\t}\n\t}\n\tchars = strings.ToUpper(chars)[:size]\n\tfor i, r := range chars {\n\t\tif strings.ContainsRune(chars[i+1:], r) {\n\t\t\treturn nil, fmt.Errorf(\"%q contains same character %q\", chars[i+1:], r)\n\t\t}\n\t}\n\n\tif len(key) != size*size {\n\t\treturn nil, fmt.Errorf(\"len(key): %d must be as long as size squared: %d\", len(key), size*size)\n\t}\n\treturn &Polybius{size, chars, key}, nil\n}\n\n// Encrypt encrypts with polybius encryption\nfunc (p *Polybius) Encrypt(text string) (string, error) {\n\tencryptedText := \"\"\n\tfor _, char := range strings.ToUpper(text) {\n\t\tencryptedChar, err := p.encipher(char)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed encipher: %w\", err)\n\t\t}\n\t\tencryptedText += encryptedChar\n\t}\n\treturn encryptedText, nil\n}\n\n// Decrypt decrypts with polybius encryption\nfunc (p *Polybius) Decrypt(text string) (string, error) {\n\tchars := []rune(strings.ToUpper(text))\n\tdecryptedText := \"\"\n\tfor i := 0; i < len(chars); i += 2 {\n\t\tdecryptedChar, err := p.decipher(chars[i:int(math.Min(float64(i+2), float64(len(chars))))])\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed decipher: %w\", err)\n\t\t}\n\t\tdecryptedText += decryptedChar\n\t}\n\treturn decryptedText, nil\n}\n\nfunc (p *Polybius) encipher(char rune) (string, error) {\n\tindex := strings.IndexRune(p.key, char)\n\tif index < 0 {\n\t\treturn \"\", fmt.Errorf(\"%q does not exist in keys\", char)\n\t}\n\trow := index / p.size\n\tcol := index % p.size\n\tchars := []rune(p.characters)\n\treturn string([]rune{chars[row], chars[col]}), nil\n}\n\nfunc (p *Polybius) decipher(chars []rune) (string, error) {\n\tif len(chars) != 2 {\n\t\treturn \"\", fmt.Errorf(\"the size of \\\"chars\\\" must be even\")\n\t}\n\trow := strings.IndexRune(p.characters, chars[0])\n\tif row < 0 {\n\t\treturn \"\", fmt.Errorf(\"%c does not exist in characters\", chars[0])\n\t}\n\tcol := strings.IndexRune(p.characters, chars[1])\n\tif col < 0 {\n\t\treturn \"\", fmt.Errorf(\"%c does not exist in characters\", chars[1])\n\t}\n\treturn string(p.key[row*p.size+col]), nil\n}\n"
  },
  {
    "path": "cipher/polybius/polybius_test.go",
    "content": "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\tplainText  = \"HogeFugaPiyoSpam\"\n\t\tsize       = 5\n\t\tcharacters = \"HogeF\"\n\t\tkey        = \"abcdefghijklmnopqrstuvwxy\"\n\t)\n\tp, err := NewPolybius(key, size, characters)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed NewPolybius: %v\", err)\n\t}\n\tencryptedText, err := p.Encrypt(plainText)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed Encrypt: %v\", err)\n\t}\n\tfmt.Printf(\"Encrypt=> plainText: %s, encryptedText: %s\\n\", plainText, encryptedText)\n\n\tdecryptedText, err := p.Decrypt(encryptedText)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed Decrypt: %v\", err)\n\t}\n\tfmt.Printf(\"Decrypt=> encryptedText: %s, decryptedText: %s\\n\", encryptedText, decryptedText)\n\n\t// Output:\n\t// Encrypt=> plainText: HogeFugaPiyoSpam, encryptedText: OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG\n\t// Decrypt=> encryptedText: OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG, decryptedText: HOGEFUGAPIYOSPAM\n}\n\nfunc TestNewPolybius(t *testing.T) {\n\tt.Parallel()\n\tcases := []struct {\n\t\tname       string\n\t\tsize       int\n\t\tcharacters string\n\t\tkey        string\n\t\twantErr    string\n\t}{\n\t\t{\n\t\t\tname: \"correct initialization\", size: 5, characters: \"HogeF\", key: \"abcdefghijklmnopqrstuvwxy\", wantErr: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"truncate characters\", size: 5, characters: \"HogeFuga\", key: \"abcdefghijklmnopqrstuvwxy\", wantErr: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid key\", size: 5, characters: \"HogeFuga\", key: \"abcdefghi\", wantErr: \"len(key): 9 must be as long as size squared: 25\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid characters\", size: 5, characters: \"HogeH\", key: \"abcdefghijklmnopqrstuvwxy\", wantErr: \"\\\"OGEH\\\" contains same character 'H'\",\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t_, err := NewPolybius(tc.key, tc.size, tc.characters)\n\t\t\tif err != nil && err.Error() != tc.wantErr {\n\t\t\t\tt.Errorf(\"failed NewPolybius: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPolybiusEncrypt(t *testing.T) {\n\tt.Parallel()\n\tcases := []struct {\n\t\tname string\n\t\ttext string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"correct encryption\", text: \"HogeFugaPiyoSpam\", want: \"OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid encryption\", text: \"hogz\", want: \"failed encipher: 'Z' does not exist in keys\",\n\t\t},\n\t}\n\t// initialize\n\tconst (\n\t\tsize       = 5\n\t\tcharacters = \"HogeF\"\n\t\tkey        = \"abcdefghijklmnopqrstuvwxy\"\n\t)\n\tp, err := NewPolybius(key, size, characters)\n\tif err != nil {\n\t\tt.Fatalf(\"failed NewPolybius: %v\", err)\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tencrypted, err := p.Encrypt(tc.text)\n\t\t\tif err != nil {\n\t\t\t\tif err.Error() != tc.want {\n\t\t\t\t\tt.Errorf(\"failed Encrypt: %v\", err)\n\t\t\t\t}\n\t\t\t} else if encrypted != tc.want {\n\t\t\t\tt.Errorf(\"Encrypt: %v, want: %v\", encrypted, tc.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPolybiusDecrypt(t *testing.T) {\n\tt.Parallel()\n\tcases := []struct {\n\t\tname string\n\t\ttext string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"correct decryption\", text: \"OGGFOOHFOHFHOOHHEHOEFFGFEEEHHHGG\", want: \"HOGEFUGAPIYOSPAM\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid decryption(position of even number)\", text: \"hogz\", want: \"failed decipher: Z does not exist in characters\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid decryption(position of odd number)\", text: \"hode\", want: \"failed decipher: D does not exist in characters\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid text size which is odd\", text: \"hog\", want: \"failed decipher: the size of \\\"chars\\\" must be even\",\n\t\t},\n\t}\n\t// initialize\n\tconst (\n\t\tsize       = 5\n\t\tcharacters = \"HogeF\"\n\t\tkey        = \"abcdefghijklmnopqrstuvwxy\"\n\t)\n\tp, err := NewPolybius(key, size, characters)\n\tif err != nil {\n\t\tt.Fatalf(\"failed NewPolybius: %v\", err)\n\t}\n\tfor _, tc := range cases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tencrypted, err := p.Decrypt(tc.text)\n\t\t\tif err != nil {\n\t\t\t\tif err.Error() != tc.want {\n\t\t\t\t\tt.Errorf(\"failed Encrypt: %v\", err)\n\t\t\t\t}\n\t\t\t} else if encrypted != tc.want {\n\t\t\t\tt.Errorf(\"Encrypt: %v, want: %v\", encrypted, tc.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc FuzzPolybius(f *testing.F) {\n\tconst (\n\t\tsize       = 5\n\t\tcharacters = \"HogeF\"\n\t\tkey        = \"abcdefghijklmnopqrstuvwxy\"\n\t)\n\tf.Add(size, characters, key)\n\tf.Fuzz(func(t *testing.T, size int, characters, key string) {\n\t\tp, err := NewPolybius(key, size, characters)\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase strings.Contains(err.Error(), \"cannot be negative\"),\n\t\t\tstrings.Contains(err.Error(), \"is too small\"),\n\t\t\tstrings.Contains(err.Error(), \"should only contain latin characters\"),\n\t\t\tstrings.Contains(err.Error(), \"contains same character\"),\n\t\t\tstrings.Contains(err.Error(), \"must be as long as size squared\"):\n\t\t\treturn\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error when creating a new polybius variable: %v\", err)\n\t\t}\n\t\tencrypted, err := p.Encrypt(characters)\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase strings.Contains(err.Error(), \"does not exist in keys\"):\n\t\t\treturn\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error during encryption: %v\", err)\n\t\t}\n\t\tdecrypted, err := p.Decrypt(encrypted)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error during decryption: %v\", err)\n\t\t}\n\t\tif decrypted != strings.ToUpper(characters) {\n\t\t\tt.Errorf(\"Expecting output to match with %q but was %q\", characters, decrypted)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/railfence/railfence.go",
    "content": "// railfence.go\n// description: Rail Fence Cipher\n// 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.\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://en.wikipedia.org/wiki/Rail_fence_cipher\npackage railfence\n\nimport (\n\t\"strings\"\n)\n\nfunc Encrypt(text string, rails int) string {\n\tif rails == 1 {\n\t\treturn text\n\t}\n\n\t// Create a matrix for the rail fence pattern\n\tmatrix := make([][]rune, rails)\n\tfor i := range matrix {\n\t\tmatrix[i] = make([]rune, len(text))\n\t}\n\n\t// Fill the matrix\n\tdirDown := false\n\trow, col := 0, 0\n\tfor _, char := range text {\n\t\tif row == 0 || row == rails-1 {\n\t\t\tdirDown = !dirDown\n\t\t}\n\t\tmatrix[row][col] = char\n\t\tcol++\n\t\tif dirDown {\n\t\t\trow++\n\t\t} else {\n\t\t\trow--\n\t\t}\n\t}\n\tvar result strings.Builder\n\tfor _, line := range matrix {\n\t\tfor _, char := range line {\n\t\t\tif char != 0 {\n\t\t\t\tresult.WriteRune(char)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result.String()\n}\nfunc Decrypt(cipherText string, rails int) string {\n\tif rails == 1 || rails >= len(cipherText) {\n\t\treturn cipherText\n\t}\n\n\t// Placeholder for the decrypted message\n\tdecrypted := make([]rune, len(cipherText))\n\n\t// Calculate the zigzag pattern and place characters accordingly\n\tindex := 0\n\tfor rail := 0; rail < rails; rail++ {\n\t\tposition := rail\n\t\tdown := true // Direction flag\n\t\tfor position < len(cipherText) {\n\t\t\tdecrypted[position] = rune(cipherText[index])\n\t\t\tindex++\n\n\t\t\t// Determine the next position based on the current rail and direction\n\t\t\tif rail == 0 || rail == rails-1 {\n\t\t\t\tposition += 2 * (rails - 1)\n\t\t\t} else if down {\n\t\t\t\tposition += 2 * (rails - 1 - rail)\n\t\t\t\tdown = false\n\t\t\t} else {\n\t\t\t\tposition += 2 * rail\n\t\t\t\tdown = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn string(decrypted)\n}\n"
  },
  {
    "path": "cipher/railfence/railfence_test.go",
    "content": "package railfence\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEncrypt(t *testing.T) {\n\tvar railFenceTestData = []struct {\n\t\tdescription string\n\t\tinput       string\n\t\trails       int\n\t\texpected    string\n\t}{\n\t\t{\n\t\t\t\"Encrypt with 2 rails\",\n\t\t\t\"hello\",\n\t\t\t2,\n\t\t\t\"hloel\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt with 3 rails\",\n\t\t\t\"hello world\",\n\t\t\t3,\n\t\t\t\"horel ollwd\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt with edge case: 1 rail\",\n\t\t\t\"hello\",\n\t\t\t1,\n\t\t\t\"hello\",\n\t\t},\n\t\t{\n\t\t\t\"Encrypt with more rails than letters\",\n\t\t\t\"hi\",\n\t\t\t100,\n\t\t\t\"hi\",\n\t\t},\n\t}\n\n\tfor _, test := range railFenceTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tactual := Encrypt(test.input, test.rails)\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Errorf(\"FAIL: %s - Encrypt(%s, %d) = %s, want %s\", test.description, test.input, test.rails, actual, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDecrypt(t *testing.T) {\n\tvar railFenceTestData = []struct {\n\t\tdescription string\n\t\tinput       string\n\t\trails       int\n\t\texpected    string\n\t}{\n\t\t{\n\t\t\t\"Decrypt with 2 rails\",\n\t\t\t\"hloel\",\n\t\t\t2,\n\t\t\t\"hello\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt with 3 rails\",\n\t\t\t\"ho l lewrdlo\",\n\t\t\t3,\n\t\t\t\"hld olle wor\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt with edge case: 1 rail\",\n\t\t\t\"hello\",\n\t\t\t1,\n\t\t\t\"hello\",\n\t\t},\n\t\t{\n\t\t\t\"Decrypt with more rails than letters\",\n\t\t\t\"hi\",\n\t\t\t100,\n\t\t\t\"hi\",\n\t\t},\n\t}\n\n\tfor _, test := range railFenceTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tactual := Decrypt(test.input, test.rails)\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Errorf(\"FAIL: %s - Decrypt(%s, %d) = %s, want %s\", test.description, test.input, test.rails, actual, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cipher/rot13/rot13.go",
    "content": "// Package rot13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet.\n// description: ROT13\n// 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\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://en.wikipedia.org/wiki/ROT13\npackage rot13\n\nimport (\n\t\"github.com/TheAlgorithms/Go/cipher/caesar\"\n)\n\n// rot13 is a special case, which is fixed the shift of 13, of the Caesar cipher\nfunc rot13(input string) string {\n\treturn caesar.Encrypt(input, 13)\n}\n"
  },
  {
    "path": "cipher/rot13/rot13_test.go",
    "content": "package rot13\n\nimport (\n\t\"testing\"\n)\n\nvar rot13TestData = []struct {\n\tdescription string\n\tinput       string\n\texpected    string\n}{\n\t{\n\t\t\"Basic rotation with letter 'a' gives 'n\",\n\t\t\"a\",\n\t\t\"n\",\n\t},\n\t{\n\t\t\"Rotation with wrapping around alphabet on letter 'z' gives 'm'\",\n\t\t\"z\",\n\t\t\"m\",\n\t},\n\t{\n\t\t\"Rotation on 'hello world'\",\n\t\t\"hello world\",\n\t\t\"uryyb jbeyq\",\n\t},\n\t{\n\t\t\"Rotation on the rotation of 'hello world' gives 'hello world' back\",\n\t\t\"uryyb jbeyq\",\n\t\t\"hello world\",\n\t},\n\t{\n\t\t\"Full sentence rotation\",\n\t\t\"the quick brown fox jumps over the lazy dog.\",\n\t\t\"gur dhvpx oebja sbk whzcf bire gur ynml qbt.\",\n\t},\n\t{\n\t\t\"Sentence from Rot13.go main function\",\n\t\t\"we'll just make him an offer he can't refuse... tell me you get the pop culture reference\",\n\t\t\"jr'yy whfg znxr uvz na bssre ur pna'g ershfr... gryy zr lbh trg gur cbc phygher ersrerapr\",\n\t},\n}\n\nfunc TestRot13Encrypt(t *testing.T) {\n\tfor _, test := range rot13TestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tinput := test.input\n\t\t\texpected := test.expected\n\t\t\tassertRot13Output(t, input, expected)\n\t\t})\n\t}\n}\n\nfunc TestRot13Decrypt(t *testing.T) {\n\tfor _, test := range rot13TestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tinput := test.expected\n\t\t\texpected := test.input\n\t\t\tassertRot13Output(t, input, expected)\n\t\t})\n\t}\n}\n\nfunc assertRot13Output(t *testing.T, input, expected string) {\n\tactual := rot13(input)\n\tif actual != expected {\n\t\tt.Fatalf(\"With input string %q was expecting %q but actual was %q\",\n\t\t\tinput, expected, actual)\n\t}\n}\n\nfunc FuzzRot13(f *testing.F) {\n\tfor _, rot13TestInput := range rot13TestData {\n\t\tf.Add(rot13TestInput.input)\n\t}\n\tf.Fuzz(func(t *testing.T, input string) {\n\t\tif result := rot13(rot13(input)); result != input {\n\t\t\tt.Fatalf(\"With input string %q was expecting %q but actual was %q\",\n\t\t\t\tinput, input, result)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/rsa/rsa.go",
    "content": "// rsa.go\n// description: Simple RSA algorithm implementation\n// details:\n// A simple RSA Encryption and Decryption algorithm.\n// It uses prime numbers that fit in int64 datatypes and\n// thus both the Encrypt and Decrypt are not a production\n// ready implementation. The OpenSSL implementation of RSA\n// also adds a padding which is not present in this algorithm.\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see rsa_test.go\n\n// Package rsa shows a simple implementation of RSA algorithm\npackage rsa\n\nimport (\n\t\"errors\"\n\n\tmodular \"github.com/TheAlgorithms/Go/math/modular\"\n)\n\n// ErrorFailedToEncrypt Raised when Encrypt function fails to encrypt the message\nvar ErrorFailedToEncrypt = errors.New(\"failed to Encrypt\")\n\n// ErrorFailedToDecrypt Raised when Decrypt function fails to decrypt the encrypted message\nvar ErrorFailedToDecrypt = errors.New(\"failed to Decrypt\")\n\n// Encrypt encrypts based on the RSA algorithm - uses modular exponentitation in math directory\nfunc Encrypt(message []rune, publicExponent, modulus int64) ([]rune, error) {\n\tvar encrypted []rune\n\n\tfor _, letter := range message {\n\t\tencryptedLetter, err := modular.Exponentiation(int64(letter), publicExponent, modulus)\n\t\tif err != nil {\n\t\t\treturn nil, ErrorFailedToEncrypt\n\t\t}\n\t\tencrypted = append(encrypted, rune(encryptedLetter))\n\t}\n\n\treturn encrypted, nil\n}\n\n// Decrypt decrypts encrypted rune slice based on the RSA algorithm\nfunc Decrypt(encrypted []rune, privateExponent, modulus int64) (string, error) {\n\tvar decrypted []rune\n\n\tfor _, letter := range encrypted {\n\t\tdecryptedLetter, err := modular.Exponentiation(int64(letter), privateExponent, modulus)\n\t\tif err != nil {\n\t\t\treturn \"\", ErrorFailedToDecrypt\n\t\t}\n\t\tdecrypted = append(decrypted, rune(decryptedLetter))\n\t}\n\treturn string(decrypted), nil\n}\n"
  },
  {
    "path": "cipher/rsa/rsa2.go",
    "content": "/*\nrsa2.go\ndescription: RSA encryption and decryption including key generation\ndetails: [RSA wiki](https://en.wikipedia.org/wiki/RSA_(cryptosystem))\ntime complexity: O(n)\nspace complexity: O(1)\nauthor(s): [ddaniel27](https://github.com/ddaniel27)\n*/\npackage rsa\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"math/rand\"\n\n\t\"github.com/TheAlgorithms/Go/math/gcd\"\n\t\"github.com/TheAlgorithms/Go/math/lcm\"\n\t\"github.com/TheAlgorithms/Go/math/modular\"\n\t\"github.com/TheAlgorithms/Go/math/prime\"\n)\n\n// rsa struct contains the public key, private key and modulus\ntype rsa struct {\n\tpublicKey  uint64\n\tprivateKey uint64\n\tmodulus    uint64\n}\n\n// New initializes the RSA algorithm\n// returns the RSA object\nfunc New() *rsa {\n\t// The following code generates keys for RSA encryption/decryption\n\t// 1. Choose two large prime numbers, p and q and compute n = p * q\n\tp, q := randomPrime() // p and q stands for prime numbers\n\tmodulus := p * q      // n stands for common number\n\n\t// 2. Compute the totient of n, lcm(p-1, q-1)\n\ttotient := uint64(lcm.Lcm(int64(p-1), int64(q-1)))\n\n\t// 3. Choose an integer e such that 1 < e < totient(n) and gcd(e, totient(n)) = 1\n\tpublicKey := uint64(2) // e stands for encryption key (public key)\n\tfor publicKey < totient {\n\t\tif gcd.Recursive(int64(publicKey), int64(totient)) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tpublicKey++\n\t}\n\n\t// 4. Compute d such that d * e ≡ 1 (mod totient(n))\n\tinv, _ := modular.Inverse(int64(publicKey), int64(totient))\n\tprivateKey := uint64(inv)\n\n\treturn &rsa{\n\t\tpublicKey:  publicKey,\n\t\tprivateKey: privateKey,\n\t\tmodulus:    modulus,\n\t}\n}\n\n// EncryptString encrypts the data using RSA algorithm\n// returns the encrypted string\nfunc (rsa *rsa) EncryptString(data string) string {\n\tvar nums []byte\n\n\tfor _, char := range data {\n\t\tslice := make([]byte, 8)\n\t\tbinary.BigEndian.PutUint64( // convert uint64 to byte slice\n\t\t\tslice,\n\t\t\tencryptDecryptInt(rsa.publicKey, rsa.modulus, uint64(char)), // encrypt each character\n\t\t)\n\t\tnums = append(nums, slice...)\n\t}\n\n\treturn string(nums)\n}\n\n// DecryptString decrypts the data using RSA algorithm\n// returns the decrypted string\nfunc (rsa *rsa) DecryptString(data string) string {\n\tresult := \"\"\n\tmiddle := []byte(data)\n\n\tfor i := 0; i < len(middle); i += 8 {\n\t\tif i+8 > len(middle) {\n\t\t\tbreak\n\t\t}\n\n\t\tslice := middle[i : i+8]\n\t\tnum := binary.BigEndian.Uint64(slice) // convert byte slice to uint64\n\t\tresult += fmt.Sprintf(\"%c\", encryptDecryptInt(rsa.privateKey, rsa.modulus, num))\n\t}\n\n\treturn result\n}\n\n// GetPublicKey returns the public key and modulus\nfunc (rsa *rsa) GetPublicKey() (uint64, uint64) {\n\treturn rsa.publicKey, rsa.modulus\n}\n\n// GetPrivateKey returns the private key\nfunc (rsa *rsa) GetPrivateKey() uint64 {\n\treturn rsa.privateKey\n}\n\n// encryptDecryptInt encrypts or decrypts the data using RSA algorithm\nfunc encryptDecryptInt(e, n, data uint64) uint64 {\n\tpow := new(big.Int).Exp(big.NewInt(int64(data)), big.NewInt(int64(e)), big.NewInt(int64(n)))\n\treturn pow.Uint64()\n}\n\n// randomPrime returns two random prime numbers\nfunc randomPrime() (uint64, uint64) {\n\tsieve := prime.SieveEratosthenes(1000)\n\tsieve = sieve[10:] // remove first 10 prime numbers (small numbers)\n\tindex1 := rand.Intn(len(sieve))\n\tindex2 := rand.Intn(len(sieve))\n\n\tfor index1 == index2 {\n\t\tindex2 = rand.Intn(len(sieve))\n\t}\n\n\treturn uint64(sieve[index1]), uint64(sieve[index2])\n}\n"
  },
  {
    "path": "cipher/rsa/rsa2_test.go",
    "content": "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 := []struct {\n\t\tname    string\n\t\tmessage string\n\t}{\n\t\t{\n\t\t\tname:    \"Encrypt letter 'a' and decrypt it back\",\n\t\t\tmessage: \"a\",\n\t\t},\n\t\t{\n\t\t\tname:    \"Encrypt 'Hello, World!' and decrypt it back\",\n\t\t\tmessage: \"Hello, World!\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trsa := rsa.New()\n\t\t\tencrypted := rsa.EncryptString(tt.message)\n\t\t\tdecrypted := rsa.DecryptString(encrypted)\n\t\t\tif decrypted != tt.message {\n\t\t\t\tt.Errorf(\"expected %s, got %s\", tt.message, decrypted)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkRSAEncryption(b *testing.B) {\n\trsa := rsa.New()\n\tfor i := 0; i < b.N; i++ {\n\t\trsa.EncryptString(\"Hello, World!\")\n\t}\n}\n\nfunc BenchmarkRSADecryption(b *testing.B) {\n\trsa := rsa.New()\n\tencrypted := rsa.EncryptString(\"Hello, World!\")\n\tfor i := 0; i < b.N; i++ {\n\t\trsa.DecryptString(encrypted)\n\t}\n}\n"
  },
  {
    "path": "cipher/rsa/rsa_test.go",
    "content": "// rsa_test.go\n// description: Test for RSA Encrypt and Decrypt algorithms\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see rsa.go\n\npackage rsa\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/gcd\"\n\t\"github.com/TheAlgorithms/Go/math/lcm\"\n\t\"github.com/TheAlgorithms/Go/math/modular\"\n)\n\nvar rsaTestData = []struct {\n\tdescription string\n\tinput       string\n}{\n\t{\n\t\t\"Encrypt letter 'a'\",\n\t\t\"a\",\n\t},\n\t{\n\t\t\"Encrypt 'hello world'\",\n\t\t\"hello world\",\n\t},\n\t{\n\t\t\"Encrypt full sentence\",\n\t\t\"the quick brown fox jumps over the lazy dog.\",\n\t},\n\t{\n\t\t\"Encrypt full sentence from rsacipher.go main function\",\n\t\t\"I think RSA is really great\",\n\t},\n}\n\nfunc testPrecondition(t *testing.T) (int64, int64, int64) {\n\t// Both prime numbers\n\tt.Helper()\n\tp := int64(61)\n\tq := int64(53)\n\tn := p * q\n\tdelta := lcm.Lcm(p-1, q-1)\n\te := int64(17) // Coprime with delta\n\tif gcd.Recursive(e, delta) != 1 {\n\t\tt.Fatal(\"something went wrong: prime numbers are chosen statically and it shouldn't fail at this stage\")\n\t}\n\td, err := modular.Inverse(e, delta)\n\tif err != nil {\n\t\tt.Fatalf(\"something went wrong: problem with %q: %v\", \"modular.Inverse\", err)\n\t}\n\treturn e, d, n\n}\n\nfunc TestEncryptDecrypt(t *testing.T) {\n\tfor _, test := range rsaTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\te, d, n := testPrecondition(t)\n\t\t\tmessage := []rune(test.input)\n\t\t\tencrypted, err := Encrypt(message, e, n)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to Encrypt test string:\\n\\tDescription: %v\\n\\tErrMessage: %v\", test.description, err)\n\t\t\t}\n\n\t\t\tdecrypted, err := Decrypt(encrypted, d, n)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to Decrypt test message:\\n\\tDescription: %v\\n\\tErrMessage: %v\", test.description, err)\n\t\t\t}\n\n\t\t\tif actual := test.input; actual != decrypted {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expecting %v, actual %v\", decrypted, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc FuzzRsa(f *testing.F) {\n\tfor _, rsaTestInput := range rsaTestData {\n\t\tf.Add(rsaTestInput.input)\n\t}\n\tf.Fuzz(func(t *testing.T, input string) {\n\t\te, d, n := testPrecondition(t)\n\t\tencrypted, err := Encrypt([]rune(input), e, n)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to encrypt string: %v\", err)\n\t\t}\n\t\tdecrypted, err := Decrypt(encrypted, d, n)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to decrypt string: %v\", err)\n\t\t}\n\t\tif decrypted != input {\n\t\t\tt.Fatalf(\"expected: %q, got: %q\", input, decrypted)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/transposition/transposition.go",
    "content": "// transposition.go\n// description: Transposition cipher\n// details:\n// 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)\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see transposition_test.go\n\npackage transposition\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\nvar ErrNoTextToEncrypt = errors.New(\"no text to encrypt\")\nvar ErrKeyMissing = errors.New(\"missing Key\")\n\nconst placeholder = ' '\n\nfunc getKey(keyWord string) []int {\n\tkeyWord = strings.ToLower(keyWord)\n\tword := []rune(keyWord)\n\tvar sortedWord = make([]rune, len(word))\n\tcopy(sortedWord, word)\n\tsort.Slice(sortedWord, func(i, j int) bool { return sortedWord[i] < sortedWord[j] })\n\tusedLettersMap := make(map[rune]int)\n\twordLength := len(word)\n\tresultKey := make([]int, wordLength)\n\tfor i := 0; i < wordLength; i++ {\n\t\tchar := word[i]\n\t\tnumberOfUsage := usedLettersMap[char]\n\t\tresultKey[i] = getIndex(sortedWord, char) + numberOfUsage + 1 //+1 -so that indexing does not start at 0\n\t\tnumberOfUsage++\n\t\tusedLettersMap[char] = numberOfUsage\n\t}\n\treturn resultKey\n}\n\nfunc getIndex(wordSet []rune, subString rune) int {\n\tn := len(wordSet)\n\tfor i := 0; i < n; i++ {\n\t\tif wordSet[i] == subString {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc Encrypt(text []rune, keyWord string) ([]rune, error) {\n\tkey := getKey(keyWord)\n\tkeyLength := len(key)\n\ttextLength := len(text)\n\tif keyLength <= 0 {\n\t\treturn nil, ErrKeyMissing\n\t}\n\tif textLength <= 0 {\n\t\treturn nil, ErrNoTextToEncrypt\n\t}\n\tif text[len(text)-1] == placeholder {\n\t\treturn nil, fmt.Errorf(\"%w: cannot encrypt a text, %q, ending with the placeholder char %q\", ErrNoTextToEncrypt, text, placeholder)\n\t}\n\tn := textLength % keyLength\n\n\tfor i := 0; i < keyLength-n; i++ {\n\t\ttext = append(text, placeholder)\n\t}\n\ttextLength = len(text)\n\tvar result []rune\n\tfor i := 0; i < textLength; i += keyLength {\n\t\ttransposition := make([]rune, keyLength)\n\t\tfor j := 0; j < keyLength; j++ {\n\t\t\ttransposition[key[j]-1] = text[i+j]\n\t\t}\n\t\tresult = append(result, transposition...)\n\t}\n\treturn result, nil\n}\n\nfunc Decrypt(text []rune, keyWord string) ([]rune, error) {\n\tkey := getKey(keyWord)\n\ttextLength := len(text)\n\tif textLength <= 0 {\n\t\treturn nil, ErrNoTextToEncrypt\n\t}\n\tkeyLength := len(key)\n\tif keyLength <= 0 {\n\t\treturn nil, ErrKeyMissing\n\t}\n\tn := textLength % keyLength\n\tfor i := 0; i < keyLength-n; i++ {\n\t\ttext = append(text, placeholder)\n\t}\n\tvar result []rune\n\tfor i := 0; i < textLength; i += keyLength {\n\t\ttransposition := make([]rune, keyLength)\n\t\tfor j := 0; j < keyLength; j++ {\n\t\t\ttransposition[j] = text[i+key[j]-1]\n\t\t}\n\t\tresult = append(result, transposition...)\n\t}\n\tresult = []rune(strings.TrimRight(string(result), string(placeholder)))\n\treturn result, nil\n}\n"
  },
  {
    "path": "cipher/transposition/transposition_test.go",
    "content": "// transposition_test.go\n// description: Transposition cipher\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see transposition.go\n\npackage transposition\n\nimport (\n\t\"errors\"\n\t\"math/rand\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst enAlphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\nvar texts = []string{\n\t\"Ilya Sokolov\",\n\t\"A slice literal is declared just like an array literal, except you leave out the element count\",\n\t\"Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.\",\n\t\"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:\",\n\t\"А тут для примера русский текст\",\n}\n\nfunc getRandomString() string {\n\tenRunes := []rune(enAlphabet)\n\tb := make([]rune, rand.Intn(100))\n\tfor i := range b {\n\t\tb[i] = enRunes[rand.Intn(len(enRunes))]\n\t}\n\treturn string(b)\n}\n\nfunc TestEncrypt(t *testing.T) {\n\tfn := func(text string, keyWord string) (bool, error) {\n\t\tencrypt, err := Encrypt([]rune(text), keyWord)\n\t\tif err != nil && !errors.Is(err, ErrNoTextToEncrypt) && !errors.Is(err, ErrKeyMissing) {\n\t\t\tt.Error(\"Unexpected error \", err)\n\t\t}\n\t\treturn text == string(encrypt), err\n\t}\n\tfor _, s := range texts {\n\t\tif check, err := fn(s, getRandomString()); check || err != nil {\n\t\t\tt.Error(\"String \", s, \" not encrypted\")\n\t\t}\n\t}\n\tif _, err := fn(getRandomString(), \"\"); err == nil {\n\t\tt.Error(\"Error! empty string encryption\")\n\t}\n}\n\nfunc TestDecrypt(t *testing.T) {\n\tfor _, s := range texts {\n\t\tkeyWord := getRandomString()\n\t\tencrypt, errEncrypt := Encrypt([]rune(s), keyWord)\n\t\tif errEncrypt != nil &&\n\t\t\t!errors.Is(errEncrypt, ErrNoTextToEncrypt) &&\n\t\t\t!errors.Is(errEncrypt, ErrKeyMissing) {\n\t\t\tt.Error(\"Unexpected error \", errEncrypt)\n\t\t}\n\t\tif errEncrypt != nil {\n\t\t\tt.Error(errEncrypt)\n\t\t}\n\t\tdecrypt, errDecrypt := Decrypt([]rune(encrypt), keyWord)\n\t\tif errDecrypt != nil &&\n\t\t\t!errors.Is(errDecrypt, ErrNoTextToEncrypt) &&\n\t\t\t!errors.Is(errDecrypt, ErrKeyMissing) {\n\t\t\tt.Error(\"Unexpected error \", errDecrypt)\n\t\t}\n\t\tif errDecrypt != nil {\n\t\t\tt.Error(errDecrypt)\n\t\t}\n\t\tif reflect.DeepEqual(encrypt, decrypt) {\n\t\t\tt.Error(\"String \", s, \" not encrypted\")\n\t\t}\n\t\tif reflect.DeepEqual(encrypt, s) {\n\t\t\tt.Error(\"String \", s, \" not encrypted\")\n\t\t}\n\t}\n}\n\nfunc TestEncryptDecrypt(t *testing.T) {\n\ttext := []rune(\"Test text for checking the algorithm\")\n\tkey1 := \"testKey\"\n\tkey2 := \"Test Key2\"\n\tencrypt, errEncrypt := Encrypt(text, key1)\n\tif errEncrypt != nil {\n\t\tt.Error(errEncrypt)\n\t}\n\tdecrypt, errDecrypt := Decrypt(encrypt, key1)\n\tif errDecrypt != nil {\n\t\tt.Error(errDecrypt)\n\t}\n\tif !reflect.DeepEqual(decrypt, text) {\n\t\tt.Errorf(\"The string was not decrypted correctly %q %q\", decrypt, text)\n\t}\n\tdecrypt, _ = Decrypt([]rune(encrypt), key2)\n\tif reflect.DeepEqual(decrypt, text) {\n\t\tt.Errorf(\"The string was decrypted with a different key: %q %q\", decrypt, text)\n\t}\n}\n\nfunc FuzzTransposition(f *testing.F) {\n\tfor _, transpositionTestInput := range texts {\n\t\tf.Add(transpositionTestInput)\n\t}\n\tf.Fuzz(func(t *testing.T, input string) {\n\t\tkeyword := getRandomString()\n\t\tmessage := []rune(input)\n\t\tencrypted, err := Encrypt(message, keyword)\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase errors.Is(err, ErrKeyMissing),\n\t\t\terrors.Is(err, ErrNoTextToEncrypt):\n\t\t\treturn\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error when encrypting string %q: %v\", input, err)\n\t\t}\n\t\tdecrypted, err := Decrypt([]rune(encrypted), keyword)\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase errors.Is(err, ErrKeyMissing),\n\t\t\terrors.Is(err, ErrNoTextToEncrypt):\n\t\t\treturn\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error when decrypting string %q: %v\", encrypted, err)\n\t\t}\n\n\t\tif !reflect.DeepEqual(message, decrypted) {\n\t\t\tt.Fatalf(\"expected: %+v, got: %+v\", message, []rune(decrypted))\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "cipher/xor/xor.go",
    "content": "// Package xor is an encryption algorithm that operates the exclusive disjunction(XOR)\n// description: XOR encryption\n// details: The XOR encryption is an algorithm that operates the exclusive disjunction(XOR) on each character of the plaintext with a given key\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://en.wikipedia.org/wiki/XOR_cipher\npackage xor\n\n// Encrypt encrypts with Xor encryption after converting each character to byte\n// The returned value might not be readable because there is no guarantee\n// which is within the ASCII range\n// If using other type such as string, []int, or some other types,\n// add the statements for converting the type to []byte.\nfunc Encrypt(key byte, plaintext []byte) []byte {\n\tcipherText := []byte{}\n\tfor _, ch := range plaintext {\n\t\tcipherText = append(cipherText, key^ch)\n\t}\n\treturn cipherText\n}\n\n// Decrypt decrypts with Xor encryption\nfunc Decrypt(key byte, cipherText []byte) []byte {\n\tplainText := []byte{}\n\tfor _, ch := range cipherText {\n\t\tplainText = append(plainText, key^ch)\n\t}\n\treturn plainText\n}\n"
  },
  {
    "path": "cipher/xor/xor_test.go",
    "content": "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  = 97\n\t)\n\n\tencrypted := Encrypt(byte(key), []byte(seed))\n\tfmt.Printf(\"Encrypt=> key: %d, seed: %s, encryptedText: %v\\n\", key, seed, encrypted)\n\n\tdecrypted := Decrypt(byte(key), encrypted)\n\tfmt.Printf(\"Decrypt=> key: %d, encryptedText: %v, DecryptedText: %s\\n\", key, encrypted, string(decrypted))\n\n\t// Output:\n\t// Encrypt=> key: 97, seed: Hello World, encryptedText: [41 4 13 13 14 65 54 14 19 13 5]\n\t// Decrypt=> key: 97, encryptedText: [41 4 13 13 14 65 54 14 19 13 5], DecryptedText: Hello World\n}\n\nvar xorTestData = []struct {\n\tdescription string\n\tinput       string\n\tkey         int\n\tencrypted   string\n}{\n\t{\n\t\t\"Encrypt letter 'a' with key 0 makes no changes\",\n\t\t\"a\",\n\t\t0,\n\t\t\"a\",\n\t},\n\t{\n\t\t\"Encrypt letter 'a' with key 1\",\n\t\t\"a\",\n\t\t1,\n\t\t\"`\",\n\t},\n\t{\n\t\t\"Encrypt letter 'a' with key 10\",\n\t\t\"a\",\n\t\t10,\n\t\t\"k\",\n\t},\n\t{\n\t\t\"Encrypt 'hello world' with key 0 makes no changes\",\n\t\t\"hello world\",\n\t\t0,\n\t\t\"hello world\",\n\t},\n\t{\n\t\t\"Encrypt 'hello world' with key 1\",\n\t\t\"hello world\",\n\t\t1,\n\t\t\"idmmn!vnsme\",\n\t},\n\t{\n\t\t\"Encrypt 'hello world' with key 10\",\n\t\t\"hello world\",\n\t\t10,\n\t\t\"boffe*}exfn\",\n\t},\n\t{\n\t\t\"Encrypt full sentence with key 64\",\n\t\t\"the quick brown fox jumps over the lazy dog.\",\n\t\t64,\n\t\t\"4(%`15)#+`\\\"2/7.`&/8`*5-03`/6%2`4(%`,!:9`$/'n\",\n\t},\n\t{\n\t\t\"Encrypt a word with key 32 make the case swap\",\n\t\t\"abcdefghijklmNOPQRSTUVWXYZ\",\n\t\t32,\n\t\t\"ABCDEFGHIJKLMnopqrstuvwxyz\",\n\t},\n}\n\nfunc TestXorCipherEncrypt(t *testing.T) {\n\tfor _, test := range xorTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tencrypted := Encrypt(byte(test.key), []byte(test.input))\n\t\t\tif !reflect.DeepEqual(string(encrypted), test.encrypted) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expecting %s, actual %s\", test.encrypted, string(encrypted))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestXorCipherDecrypt(t *testing.T) {\n\tfor _, test := range xorTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tdecrypted := Decrypt(byte(test.key), []byte(test.encrypted))\n\n\t\t\tif !reflect.DeepEqual(string(decrypted), test.input) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expecting %s, actual %s\", test.input, string(decrypted))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc FuzzXOR(f *testing.F) {\n\tf.Add([]byte(\"The Quick Brown Fox Jumps over the Lazy Dog.\"), byte('X'))\n\tf.Fuzz(func(t *testing.T, input []byte, key byte) {\n\t\tcipherText := Encrypt(key, input)\n\t\tresult := Decrypt(key, cipherText)\n\t\tif !bytes.Equal(input, result) {\n\t\t\tt.Errorf(\"Before: %s, after: %s, key: %d\", input, result, key)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "compression/huffmancoding.go",
    "content": "// huffman.go\n// description: Implements Huffman compression, encoding and decoding\n// details:\n// We implement the linear-time 2-queue method described here https://en.wikipedia.org/wiki/Huffman_coding.\n// It assumes that the list of symbol-frequencies is sorted.\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [pedromsrocha](https://github.com/pedromsrocha)\n// see also huffmancoding_test.go\n\npackage compression\n\nimport \"fmt\"\n\n// A Node of an Huffman tree, which can either be a leaf or an internal node.\n// Each node has a weight.\n// A leaf node has an associated symbol, but no children (i.e., left == right == nil).\n// A parent node has a left and right child and no symbol (i.e., symbol == -1).\ntype Node struct {\n\tleft   *Node\n\tright  *Node\n\tsymbol rune\n\tweight int\n}\n\n// A SymbolFreq is a pair of a symbol and its associated frequency.\ntype SymbolFreq struct {\n\tSymbol rune\n\tFreq   int\n}\n\n// HuffTree returns the root Node of the Huffman tree by compressing listfreq.\n// The compression produces the most optimal code lengths, provided listfreq is ordered,\n// i.e.: listfreq[i] <= listfreq[j], whenever i < j.\nfunc HuffTree(listfreq []SymbolFreq) (*Node, error) {\n\tif len(listfreq) < 1 {\n\t\treturn nil, fmt.Errorf(\"huffman coding: HuffTree : calling method with empty list of symbol-frequency pairs\")\n\t}\n\tq1 := make([]Node, len(listfreq))\n\tq2 := make([]Node, 0, len(listfreq))\n\tfor i, x := range listfreq { // after the loop, q1 is a slice of leaf nodes representing listfreq\n\t\tq1[i] = Node{left: nil, right: nil, symbol: x.Symbol, weight: x.Freq}\n\t}\n\t//loop invariant: q1, q2 are ordered by increasing weights\n\tfor len(q1)+len(q2) > 1 {\n\t\tvar node1, node2 Node\n\t\tnode1, q1, q2 = least(q1, q2)\n\t\tnode2, q1, q2 = least(q1, q2)\n\t\tnode := Node{left: &node1, right: &node2,\n\t\t\tsymbol: -1, weight: node1.weight + node2.weight}\n\t\tq2 = append(q2, node)\n\t}\n\tif len(q1) == 1 { // returns the remaining node in q1, q2\n\t\treturn &q1[0], nil\n\t}\n\treturn &q2[0], nil\n}\n\n// least removes the node with lowest weight from q1, q2.\n// It returns the node with lowest weight and the slices q1, q2 after the update.\nfunc least(q1 []Node, q2 []Node) (Node, []Node, []Node) {\n\tif len(q1) == 0 {\n\t\treturn q2[0], q1, q2[1:]\n\t}\n\tif len(q2) == 0 {\n\t\treturn q1[0], q1[1:], q2\n\t}\n\tif q1[0].weight <= q2[0].weight {\n\t\treturn q1[0], q1[1:], q2\n\t}\n\treturn q2[0], q1, q2[1:]\n}\n\n// HuffEncoding recursively traverses the Huffman tree pointed by node to obtain\n// the map codes, that associates a rune with a slice of booleans.\n// Each code is prefixed by prefix and left and right children are labelled with\n// the booleans false and true, respectively.\nfunc HuffEncoding(node *Node, prefix []bool, codes map[rune][]bool) {\n\tif node.symbol != -1 { //base case\n\t\tcodes[node.symbol] = prefix\n\t\treturn\n\t}\n\t// inductive step\n\tprefixLeft := make([]bool, len(prefix))\n\tcopy(prefixLeft, prefix)\n\tprefixLeft = append(prefixLeft, false)\n\tHuffEncoding(node.left, prefixLeft, codes)\n\tprefixRight := make([]bool, len(prefix))\n\tcopy(prefixRight, prefix)\n\tprefixRight = append(prefixRight, true)\n\tHuffEncoding(node.right, prefixRight, codes)\n}\n\n// HuffEncode encodes the string in by applying the mapping defined by codes.\nfunc HuffEncode(codes map[rune][]bool, in string) []bool {\n\tout := make([]bool, 0)\n\tfor _, s := range in {\n\t\tout = append(out, codes[s]...)\n\t}\n\treturn out\n}\n\n// HuffDecode recursively decodes the binary code in, by traversing the Huffman compression tree pointed by root.\n// current stores the current node of the traversing algorithm.\n// out stores the current decoded string.\nfunc HuffDecode(root, current *Node, in []bool, out string) string {\n\tif current.symbol != -1 {\n\t\tout += string(current.symbol)\n\t\treturn HuffDecode(root, root, in, out)\n\t}\n\tif len(in) == 0 {\n\t\treturn out\n\t}\n\tif in[0] {\n\t\treturn HuffDecode(root, current.right, in[1:], out)\n\t}\n\treturn HuffDecode(root, current.left, in[1:], out)\n}\n"
  },
  {
    "path": "compression/huffmancoding_test.go",
    "content": "// huffmancoding_test.go\n// description: Tests the compression, encoding and decoding algorithms of huffmancoding.go.\n// author(s) [pedromsrocha](https://github.com/pedromsrocha)\n// see huffmancoding.go\n\npackage compression_test\n\nimport (\n\t\"sort\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/compression\"\n)\n\n// SymbolCountOrd computes sorted symbol-frequency list of input message\nfunc SymbolCountOrd(message string) []compression.SymbolFreq {\n\truneCount := make(map[rune]int)\n\tfor _, s := range message {\n\t\truneCount[s]++\n\t}\n\tlistfreq := make([]compression.SymbolFreq, len(runeCount))\n\ti := 0\n\tfor s, n := range runeCount {\n\t\tlistfreq[i] = compression.SymbolFreq{Symbol: s, Freq: n}\n\t\ti++\n\t}\n\tsort.Slice(listfreq, func(i, j int) bool { return listfreq[i].Freq < listfreq[j].Freq })\n\treturn listfreq\n}\n\nfunc TestHuffman(t *testing.T) {\n\tmessages := []string{\n\t\t\"hello world \\U0001F600\",\n\t\t\"colorless green ideas sleep furiously\",\n\t\t\"the quick brown fox jumps over the lazy dog\",\n\t\t`Lorem ipsum dolor sit amet, consectetur adipiscing elit,\n\t\tsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n\t\tUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut\n\t\taliquip ex ea commodo consequat.`,\n\t}\n\n\tfor _, message := range messages {\n\t\tt.Run(\"huffman: \"+message, func(t *testing.T) {\n\t\t\ttree, _ := compression.HuffTree(SymbolCountOrd(message))\n\t\t\tcodes := make(map[rune][]bool)\n\t\t\tcompression.HuffEncoding(tree, nil, codes)\n\t\t\tmessageCoded := compression.HuffEncode(codes, message)\n\t\t\tmessageHuffDecoded := compression.HuffDecode(tree, tree, messageCoded, \"\")\n\t\t\tif messageHuffDecoded != message {\n\t\t\t\tt.Errorf(\"got: %q\\nbut expected: %q\", messageHuffDecoded, message)\n\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "compression/rlecoding.go",
    "content": "/*\nrlecoding.go\ndescription: run length encoding and decoding\ndetails:\nRun-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.\ntime complexity: O(n)\nspace complexity: O(n)\nref: https://en.wikipedia.org/wiki/Run-length_encoding\nauthor(s) [ddaniel27](https://github.com/ddaniel27)\n*/\npackage compression\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// RLEncode takes a string and returns its run-length encoding\nfunc RLEncode(data string) string {\n\tvar result string\n\tcount := 1\n\tfor i := 0; i < len(data); i++ {\n\t\tif i+1 < len(data) && data[i] == data[i+1] {\n\t\t\tcount++\n\t\t\tcontinue\n\t\t}\n\t\tresult += fmt.Sprintf(\"%d%c\", count, data[i])\n\t\tcount = 1\n\t}\n\treturn result\n}\n\n// RLEdecode takes a run-length encoded string and returns the original string\nfunc RLEdecode(data string) string {\n\tvar result string\n\tregex := regexp.MustCompile(`(\\d+)(\\w)`)\n\n\tfor _, match := range regex.FindAllStringSubmatch(data, -1) {\n\t\tnum, _ := strconv.Atoi(match[1])\n\t\tresult += strings.Repeat(match[2], num)\n\t}\n\n\treturn result\n}\n\n// RLEncodebytes takes a byte slice and returns its run-length encoding as a byte slice\nfunc RLEncodebytes(data []byte) []byte {\n\tvar result []byte\n\tvar count byte = 1\n\n\tfor i := 0; i < len(data); i++ {\n\t\tif i+1 < len(data) && data[i] == data[i+1] {\n\t\t\tcount++\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, count, data[i])\n\t\tcount = 1\n\t}\n\n\treturn result\n}\n\n// RLEdecodebytes takes a run-length encoded byte slice and returns the original byte slice\nfunc RLEdecodebytes(data []byte) []byte {\n\tvar result []byte\n\n\tfor i := 0; i < len(data); i += 2 {\n\t\tcount := int(data[i])\n\t\tresult = append(result, bytes.Repeat([]byte{data[i+1]}, count)...)\n\t}\n\n\treturn result\n}\n"
  },
  {
    "path": "compression/rlecoding_test.go",
    "content": "package compression_test\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/compression\"\n)\n\nfunc TestCompressionRLEncode(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdata string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"test 1\",\n\t\t\tdata: \"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\",\n\t\t\twant: \"12W1B12W3B\",\n\t\t},\n\t\t{\n\t\t\tname: \"test 2\",\n\t\t\tdata: \"AABCCCDEEEE\",\n\t\t\twant: \"2A1B3C1D4E\",\n\t\t},\n\t\t{\n\t\t\tname: \"test 3\",\n\t\t\tdata: \"AAAABBBCCDA\",\n\t\t\twant: \"4A3B2C1D1A\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := compression.RLEncode(tt.data); got != tt.want {\n\t\t\t\tt.Errorf(\"RLEncode() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompressionRLEDecode(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdata string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"test 1\",\n\t\t\tdata: \"12W1B12W3B\",\n\t\t\twant: \"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\",\n\t\t},\n\t\t{\n\t\t\tname: \"test 2\",\n\t\t\tdata: \"2A1B3C1D4E\",\n\t\t\twant: \"AABCCCDEEEE\",\n\t\t},\n\t\t{\n\t\t\tname: \"test 3\",\n\t\t\tdata: \"4A3B2C1D1A\",\n\t\t\twant: \"AAAABBBCCDA\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := compression.RLEdecode(tt.data); got != tt.want {\n\t\t\t\tt.Errorf(\"RLEdecode() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompressionRLEncodeBytes(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdata []byte\n\t\twant []byte\n\t}{\n\t\t{\n\t\t\tname: \"test 1\",\n\t\t\tdata: []byte(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\"),\n\t\t\twant: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'},\n\t\t},\n\t\t{\n\t\t\tname: \"test 2\",\n\t\t\tdata: []byte(\"AABCCCDEEEE\"),\n\t\t\twant: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'},\n\t\t},\n\t\t{\n\t\t\tname: \"test 3\",\n\t\t\tdata: []byte(\"AAAABBBCCDA\"),\n\t\t\twant: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := compression.RLEncodebytes(tt.data); !bytes.Equal(got, tt.want) {\n\t\t\t\tt.Errorf(\"RLEncodebytes() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCompressionRLEDecodeBytes(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdata []byte\n\t\twant []byte\n\t}{\n\t\t{\n\t\t\tname: \"test 1\",\n\t\t\tdata: []byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'},\n\t\t\twant: []byte(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\"),\n\t\t},\n\t\t{\n\t\t\tname: \"test 2\",\n\t\t\tdata: []byte{2, 'A', 1, 'B', 3, 'C', 1, 'D', 4, 'E'},\n\t\t\twant: []byte(\"AABCCCDEEEE\"),\n\t\t},\n\t\t{\n\t\t\tname: \"test 3\",\n\t\t\tdata: []byte{4, 'A', 3, 'B', 2, 'C', 1, 'D', 1, 'A'},\n\t\t\twant: []byte(\"AAAABBBCCDA\"),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := compression.RLEdecodebytes(tt.data); !bytes.Equal(got, tt.want) {\n\t\t\t\tt.Errorf(\"RLEdecodebytes() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n/* --- BENCHMARKS --- */\nfunc BenchmarkRLEncode(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = compression.RLEncode(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\")\n\t}\n}\n\nfunc BenchmarkRLEDecode(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = compression.RLEdecode(\"12W1B12W3B\")\n\t}\n}\n\nfunc BenchmarkRLEncodeBytes(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = compression.RLEncodebytes([]byte(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBB\"))\n\t}\n}\n\nfunc BenchmarkRLEDecodeBytes(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = compression.RLEdecodebytes([]byte{12, 'W', 1, 'B', 12, 'W', 3, 'B'})\n\t}\n}\n"
  },
  {
    "path": "constraints/constraints.go",
    "content": "// Package constraints has some useful generic type constraints defined which is very similar to\n// [golang.org/x/exp/constraints](https://pkg.go.dev/golang.org/x/exp/constraints) package.\n// We refrained from using that until it gets placed into the standard library - currently\n// there are some questions regarding this package [ref](https://github.com/golang/go/issues/50792).\npackage constraints\n\n// Signed is a generic type constraint for all signed integers.\ntype Signed interface {\n\t~int | ~int8 | ~int16 | ~int32 | ~int64\n}\n\n// Unsigned is a generic type constraint for all unsigned integers.\ntype Unsigned interface {\n\t~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64\n}\n\n// Integer is a generic type constraint for all integers (signed and unsigned.)\ntype Integer interface {\n\tSigned | Unsigned\n}\n\n// Float is a generic type constraint for all floating point types.\ntype Float interface {\n\t~float32 | ~float64\n}\n\n// Number is a generic type constraint for all numeric types in Go except Complex types.\ntype Number interface {\n\tInteger | Float\n}\n\n// Ordered is a generic type constraint for all ordered data types in Go.\n// Loosely speaking, in mathematics a field is an ordered field if there is a \"total\n// order\" (a binary relation - in this case `<` symbol) such that we will always have\n// if a < b then a + c < b + c and if 0 < a, 0 < b then 0 < a.b\n// The idea in Go is quite similar, though only limited to Go standard types\n// not user defined types.\ntype Ordered interface {\n\tInteger | ~string | Float\n}\n"
  },
  {
    "path": "conversion/base64.go",
    "content": "// base64.go\n// description: The base64 encoding algorithm as defined in the RFC4648 standard.\n// author: [Paul Leydier] (https://github.com/paul-leydier)\n// time complexity: O(n)\n// space complexity: O(n)\n// ref: https://datatracker.ietf.org/doc/html/rfc4648#section-4\n// ref: https://en.wikipedia.org/wiki/Base64\n// see base64_test.go\n\npackage conversion\n\nimport (\n\t\"strings\" // Used for efficient string builder (more efficient than simply appending strings)\n)\n\nconst Alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n\n// Base64Encode encodes the received input bytes slice into a base64 string.\n// The implementation follows the RFC4648 standard, which is documented\n// at https://datatracker.ietf.org/doc/html/rfc4648#section-4\nfunc Base64Encode(input []byte) string {\n\tvar sb strings.Builder\n\t// If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with \"=\" for the output\n\tvar padding string\n\tfor i := len(input) % 3; i > 0 && i < 3; i++ {\n\t\tvar zeroByte byte\n\t\tinput = append(input, zeroByte)\n\t\tpadding += \"=\"\n\t}\n\n\t// encode 24 bits per 24 bits (3 bytes per 3 bytes)\n\tfor i := 0; i < len(input); i += 3 {\n\t\t// select 3 8-bit input groups, and re-arrange them into 4 6-bit groups\n\t\t// the literal 0x3F corresponds to the byte \"0011 1111\"\n\t\t// the operation \"byte & 0x3F\" masks the two left-most bits\n\t\tgroup := [4]byte{\n\t\t\tinput[i] >> 2,\n\t\t\t(input[i]<<4)&0x3F + input[i+1]>>4,\n\t\t\t(input[i+1]<<2)&0x3F + input[i+2]>>6,\n\t\t\tinput[i+2] & 0x3F,\n\t\t}\n\n\t\t// translate each group into a char using the static map\n\t\tfor _, b := range group {\n\t\t\tsb.WriteString(string(Alphabet[int(b)]))\n\t\t}\n\t}\n\tencoded := sb.String()\n\n\t// Apply the output padding\n\tencoded = encoded[:len(encoded)-len(padding)] + padding[:]\n\n\treturn encoded\n}\n\n// Base64Decode decodes the received input base64 string into a byte slice.\n// The implementation follows the RFC4648 standard, which is documented\n// at https://datatracker.ietf.org/doc/html/rfc4648#section-4\nfunc Base64Decode(input string) []byte {\n\tpadding := strings.Count(input, \"=\") // Number of bytes which will be ignored\n\tvar decoded []byte\n\n\t// select 4 6-bit input groups, and re-arrange them into 3 8-bit groups\n\tfor i := 0; i < len(input); i += 4 {\n\t\t// translate each group into a byte using the static map\n\t\tbyteInput := [4]byte{\n\t\t\tbyte(strings.IndexByte(Alphabet, input[i])),\n\t\t\tbyte(strings.IndexByte(Alphabet, input[i+1])),\n\t\t\tbyte(strings.IndexByte(Alphabet, input[i+2])),\n\t\t\tbyte(strings.IndexByte(Alphabet, input[i+3])),\n\t\t}\n\n\t\tgroup := [3]byte{\n\t\t\tbyteInput[0]<<2 + byteInput[1]>>4,\n\t\t\tbyteInput[1]<<4 + byteInput[2]>>2,\n\t\t\tbyteInput[2]<<6 + byteInput[3],\n\t\t}\n\n\t\tdecoded = append(decoded, group[:]...)\n\t}\n\n\treturn decoded[:len(decoded)-padding]\n}\n"
  },
  {
    "path": "conversion/base64_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nfunc TestBase64Encode(t *testing.T) {\n\ttestCases := []struct {\n\t\tin       string\n\t\texpected string\n\t}{\n\t\t{\"Hello World!\", \"SGVsbG8gV29ybGQh\"},       // multiple of 3 byte length (multiple of 24-bits)\n\t\t{\"Hello World!a\", \"SGVsbG8gV29ybGQhYQ==\"},  // multiple of 3 byte length + 1\n\t\t{\"Hello World!ab\", \"SGVsbG8gV29ybGQhYWI=\"}, // multiple of 3 byte length + 2\n\t\t{\"\", \"\"},      // empty byte slice\n\t\t{\"6\", \"Ng==\"}, // short text\n\t\t{\"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\n\t}\n\n\tfor _, tc := range testCases {\n\t\tresult := Base64Encode([]byte(tc.in))\n\t\tif result != tc.expected {\n\t\t\tt.Fatalf(\"Base64Encode(%s) = %s, want %s\", tc.in, result, tc.expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkBase64Encode(b *testing.B) {\n\tbenchmarks := []struct {\n\t\tname     string\n\t\tin       string\n\t\texpected string\n\t}{\n\t\t{\"Hello World!\", \"Hello World!\", \"SGVsbG8gV29ybGQh\"},         // multiple of 3 byte length (multiple of 24-bits)\n\t\t{\"Hello World!a\", \"Hello World!a\", \"SGVsbG8gV29ybGQhYQ==\"},   // multiple of 3 byte length + 1\n\t\t{\"Hello World!ab\", \"Hello World!ab\", \"SGVsbG8gV29ybGQhYWI=\"}, // multiple of 3 byte length + 2\n\t\t{\"Empty\", \"\", \"\"},  // empty byte slice\n\t\t{\"6\", \"6\", \"Ng==\"}, // short text\n\t\t{\"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\n\t}\n\n\tfor _, bm := range benchmarks {\n\t\tb.Run(bm.name, func(b *testing.B) {\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tBase64Encode([]byte(bm.in))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBase64Decode(t *testing.T) {\n\ttestCases := []struct {\n\t\texpected string\n\t\tin       string\n\t}{\n\t\t{\"Hello World!\", \"SGVsbG8gV29ybGQh\"},       // multiple of 3 byte length (multiple of 24-bits)\n\t\t{\"Hello World!a\", \"SGVsbG8gV29ybGQhYQ==\"},  // multiple of 3 byte length + 1\n\t\t{\"Hello World!ab\", \"SGVsbG8gV29ybGQhYWI=\"}, // multiple of 3 byte length + 2\n\t\t{\"\", \"\"},      // empty byte slice\n\t\t{\"6\", \"Ng==\"}, // short text\n\t\t{\"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\n\t}\n\n\tfor _, tc := range testCases {\n\t\tresult := string(Base64Decode(tc.in))\n\t\tif result != tc.expected {\n\t\t\tt.Fatalf(\"Base64Decode(%s) = %s, want %s\", tc.in, result, tc.expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkBase64Decode(b *testing.B) {\n\tbenchmarks := []struct {\n\t\tname     string\n\t\texpected string\n\t\tin       string\n\t}{\n\t\t{\"Hello World!\", \"Hello World!\", \"SGVsbG8gV29ybGQh\"},         // multiple of 3 byte length (multiple of 24-bits)\n\t\t{\"Hello World!a\", \"Hello World!a\", \"SGVsbG8gV29ybGQhYQ==\"},   // multiple of 3 byte length + 1\n\t\t{\"Hello World!ab\", \"Hello World!ab\", \"SGVsbG8gV29ybGQhYWI=\"}, // multiple of 3 byte length + 2\n\t\t{\"Empty\", \"\", \"\"},  // empty byte slice\n\t\t{\"6\", \"6\", \"Ng==\"}, // short text\n\t\t{\"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\n\t}\n\n\tfor _, bm := range benchmarks {\n\t\tb.Run(bm.name, func(b *testing.B) {\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tBase64Decode(bm.in)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBase64EncodeDecodeInverse(t *testing.T) {\n\ttestCases := []struct {\n\t\tin string\n\t}{\n\t\t{\"Hello World!\"},   // multiple of 3 byte length (multiple of 24-bits)\n\t\t{\"Hello World!a\"},  // multiple of 3 byte length + 1\n\t\t{\"Hello World!ab\"}, // multiple of 3 byte length + 2\n\t\t{\"\"},               // empty byte slice\n\t\t{\"6\"},              // short text\n\t\t{\"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\n\t}\n\n\tfor _, tc := range testCases {\n\t\tresult := string(Base64Decode(Base64Encode([]byte(tc.in))))\n\t\tif result != tc.in {\n\t\t\tt.Fatalf(\"Base64Decode(Base64Encode(%s)) = %s, want %s\", tc.in, result, tc.in)\n\t\t}\n\t}\n}\n\nfunc FuzzBase64Encode(f *testing.F) {\n\tf.Add([]byte(\"hello\"))\n\tf.Fuzz(func(t *testing.T, input []byte) {\n\t\tresult := Base64Decode(Base64Encode(input))\n\t\tfor i := 0; i < len(input); i++ {\n\t\t\tif result[i] != input[i] {\n\t\t\t\tt.Fatalf(\"with input '%s' - expected '%s', got '%s' (mismatch at position %d)\", input, input, result, i)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "conversion/binarytodecimal.go",
    "content": "/*\nAuthor: Motasim\nGitHub: https://github.com/motasimmakki\nDate: 19-Oct-2021\n*/\n\n// This algorithm will convert any Binary number(0 or 1) to Decimal number(+ve number).\n// https://en.wikipedia.org/wiki/Binary_number\n// https://en.wikipedia.org/wiki/Decimal\n// Function receives a Binary Number as string and returns the Decimal number as integer.\n// Supported Binary number range is 0 to 2^(31-1).\n// time complexity: O(n)\n// space complexity: O(1)\n\npackage conversion\n\n// Importing necessary package.\nimport (\n\t\"errors\"\n\t\"regexp\"\n)\n\nvar isValid = regexp.MustCompile(\"^[0-1]{1,}$\").MatchString\n\n// BinaryToDecimal() function that will take Binary number as string,\n// and return its Decimal equivalent as an integer.\nfunc BinaryToDecimal(binary string) (int, error) {\n\tif !isValid(binary) {\n\t\treturn -1, errors.New(\"not a valid binary string\")\n\t}\n\tif len(binary) > 32 {\n\t\treturn -1, errors.New(\"binary number must be in range 0 to 2^(31-1)\")\n\t}\n\tvar result, base int = 0, 1\n\tfor i := len(binary) - 1; i >= 0; i-- {\n\t\tif binary[i] == '1' {\n\t\t\tresult += base\n\t\t}\n\t\tbase *= 2\n\t}\n\treturn result, nil\n}\n"
  },
  {
    "path": "conversion/binarytodecimal_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nvar binaryTestCases = map[string]int{\n\t\"0\": 0, \"1\": 1, \"10\": 2, \"11\": 3, \"100\": 4,\n\t\"101\": 5, \"110\": 6, \"111\": 7, \"1000\": 8, \"1001\": 9,\n\t\"1010\": 10, \"1011\": 11, \"1100\": 12, \"1101\": 13, \"1110\": 14,\n\t\"1111\": 15, \"10000\": 16, \"10001\": 17, \"10010\": 18, \"10011\": 19,\n\t\"10100\": 20, \"10101\": 21, \"10110\": 22, \"10111\": 23, \"11000\": 24,\n\t\"11001\": 25, \"11010\": 26, \"11011\": 27, \"11100\": 28, \"11101\": 29,\n\t\"11110\": 30, \"11111\": 31, \"100000\": 32, \"100001\": 33, \"100010\": 34,\n\t\"100011\": 35, \"100100\": 36, \"100101\": 37, \"100110\": 38, \"100111\": 39,\n\t\"101000\": 40, \"101001\": 41, \"101010\": 42, \"101011\": 43, \"101100\": 44,\n\t\"101101\": 45, \"101110\": 46, \"101111\": 47, \"110000\": 48, \"110001\": 49,\n\t\"110010\": 50, \"110011\": 51, \"110100\": 52, \"110101\": 53, \"110110\": 54,\n\t\"110111\": 55, \"111000\": 56, \"111001\": 57, \"111010\": 58, \"111011\": 59,\n\t\"111100\": 60, \"111101\": 61, \"111110\": 62, \"111111\": 63, \"1000000\": 64,\n\t\"1000001\": 65, \"1000010\": 66, \"1000011\": 67, \"1000100\": 68, \"1000101\": 69,\n\t\"1000110\": 70, \"1000111\": 71, \"1001000\": 72, \"1001001\": 73, \"1001010\": 74,\n\t\"1001011\": 75, \"1001100\": 76, \"1001101\": 77, \"1001110\": 78, \"1001111\": 79,\n\t\"1010000\": 80, \"1010001\": 81, \"1010010\": 82, \"1010011\": 83, \"1010100\": 84,\n\t\"1010101\": 85, \"1010110\": 86, \"1010111\": 87, \"1011000\": 88, \"1011001\": 89,\n\t\"1011010\": 90, \"1011011\": 91, \"1011100\": 92, \"1011101\": 93, \"1011110\": 94,\n\t\"1011111\": 95, \"1100000\": 96, \"1100001\": 97, \"1100010\": 98, \"1100011\": 99,\n\t\"1100100\": 100,\n}\n\nfunc TestBinaryToDecimal(t *testing.T) {\n\tfor input, expected := range binaryTestCases {\n\t\tout, err := BinaryToDecimal(input)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"BinaryToDecimal(%s) returned an error %s\", input, err.Error())\n\t\t}\n\t\tif out != expected {\n\t\t\tt.Errorf(\"BinaryToDecimal(%s) = %d; want %d\", input, out, expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkBinaryToDecimal(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = BinaryToDecimal(\"1100100\")\n\t}\n}\n"
  },
  {
    "path": "conversion/conversion_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage conversion\n"
  },
  {
    "path": "conversion/decimaltobinary.go",
    "content": "/*\nAuthor: Motasim\nGitHub: https://github.com/motasimmakki\nDate: 14-Oct-2021\n*/\n\n// This algorithm will convert any Decimal (+ve integer) number to Binary number.\n// https://en.wikipedia.org/wiki/Binary_number\n// Function receives a integer as a Decimal number and returns the Binary number.\n// Supported integer value range is 0 to 2^(31 -1).\n// time complexity: O(log(n))\n// space complexity: O(1)\n\npackage conversion\n\n// Importing necessary package.\nimport (\n\t\"errors\"\n\t\"strconv\"\n)\n\n// Reverse() function that will take string,\n// and returns the reverse of that string.\nfunc Reverse(str string) string {\n\trStr := []rune(str)\n\tfor i, j := 0, len(rStr)-1; i < len(rStr)/2; i, j = i+1, j-1 {\n\t\trStr[i], rStr[j] = rStr[j], rStr[i]\n\t}\n\treturn string(rStr)\n}\n\n// DecimalToBinary() function that will take Decimal number as int,\n// and return its Binary equivalent as a string.\nfunc DecimalToBinary(num int) (string, error) {\n\tif num < 0 {\n\t\treturn \"\", errors.New(\"integer must have +ve value\")\n\t}\n\tif num == 0 {\n\t\treturn \"0\", nil\n\t}\n\tvar result string = \"\"\n\tfor num > 0 {\n\t\tresult += strconv.Itoa(num & 1)\n\t\tnum >>= 1\n\t}\n\treturn Reverse(result), nil\n}\n"
  },
  {
    "path": "conversion/decimaltobinary_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nvar decimalTestCases = map[int]string{\n\t0: \"0\", 1: \"1\", 2: \"10\", 3: \"11\", 4: \"100\",\n\t5: \"101\", 6: \"110\", 7: \"111\", 8: \"1000\", 9: \"1001\",\n\t10: \"1010\", 11: \"1011\", 12: \"1100\", 13: \"1101\", 14: \"1110\",\n\t15: \"1111\", 16: \"10000\", 17: \"10001\", 18: \"10010\", 19: \"10011\",\n\t20: \"10100\", 21: \"10101\", 22: \"10110\", 23: \"10111\", 24: \"11000\",\n\t25: \"11001\", 26: \"11010\", 27: \"11011\", 28: \"11100\", 29: \"11101\",\n\t30: \"11110\", 31: \"11111\", 32: \"100000\", 33: \"100001\", 34: \"100010\",\n\t35: \"100011\", 36: \"100100\", 37: \"100101\", 38: \"100110\", 39: \"100111\",\n\t40: \"101000\", 41: \"101001\", 42: \"101010\", 43: \"101011\", 44: \"101100\",\n\t45: \"101101\", 46: \"101110\", 47: \"101111\", 48: \"110000\", 49: \"110001\",\n\t50: \"110010\", 51: \"110011\", 52: \"110100\", 53: \"110101\", 54: \"110110\",\n\t55: \"110111\", 56: \"111000\", 57: \"111001\", 58: \"111010\", 59: \"111011\",\n\t60: \"111100\", 61: \"111101\", 62: \"111110\", 63: \"111111\", 64: \"1000000\",\n\t65: \"1000001\", 66: \"1000010\", 67: \"1000011\", 68: \"1000100\", 69: \"1000101\",\n\t70: \"1000110\", 71: \"1000111\", 72: \"1001000\", 73: \"1001001\", 74: \"1001010\",\n\t75: \"1001011\", 76: \"1001100\", 77: \"1001101\", 78: \"1001110\", 79: \"1001111\",\n\t80: \"1010000\", 81: \"1010001\", 82: \"1010010\", 83: \"1010011\", 84: \"1010100\",\n\t85: \"1010101\", 86: \"1010110\", 87: \"1010111\", 88: \"1011000\", 89: \"1011001\",\n\t90: \"1011010\", 91: \"1011011\", 92: \"1011100\", 93: \"1011101\", 94: \"1011110\",\n\t95: \"1011111\", 96: \"1100000\", 97: \"1100001\", 98: \"1100010\", 99: \"1100011\",\n\t100: \"1100100\",\n}\n\nfunc TestDecimalToBinary(t *testing.T) {\n\tfor input, expected := range decimalTestCases {\n\t\tout, err := DecimalToBinary(input)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"DecimalToBinary(%d) returned an error %s\", input, err.Error())\n\t\t}\n\t\tif out != expected {\n\t\t\tt.Errorf(\"DecimalToBinary(%d) = %s; want %s\", input, out, expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkDecimalToBinary(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = DecimalToBinary(100)\n\t}\n}\n"
  },
  {
    "path": "conversion/doc.go",
    "content": "// Package conversion is a package of implementations which converts one data structure to another.\npackage conversion\n"
  },
  {
    "path": "conversion/hexadecimaltobinary.go",
    "content": "/*\nAuthor: mapcrafter2048\nGitHub: https://github.com/mapcrafter2048\n*/\n\n// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Binary number(0 or 1).\n// https://en.wikipedia.org/wiki/Hexadecimal\n// https://en.wikipedia.org/wiki/Binary_number\n// Function receives a Hexadecimal Number as string and returns the Binary number as string.\n// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF.\n\npackage conversion\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar isValidHex = regexp.MustCompile(\"^[0-9A-Fa-f]+$\").MatchString\n\n// hexToBinary() function that will take Hexadecimal number as string,\n// and return its Binary equivalent as a string.\nfunc hexToBinary(hex string) (string, error) {\n\t// Trim any leading or trailing whitespace\n\thex = strings.TrimSpace(hex)\n\n\t// Check if the hexadecimal string is empty\n\tif hex == \"\" {\n\t\treturn \"\", errors.New(\"input string is empty\")\n\t}\n\n\t// Check if the hexadecimal string is valid\n\tif !isValidHex(hex) {\n\t\treturn \"\", errors.New(\"invalid hexadecimal string: \" + hex)\n\t}\n\n\t// Parse the hexadecimal string to an integer\n\tvar decimal int64\n\tfor i := 0; i < len(hex); i++ {\n\t\tchar := hex[i]\n\t\tvar value int64\n\t\tif char >= '0' && char <= '9' {\n\t\t\tvalue = int64(char - '0')\n\t\t} else if char >= 'A' && char <= 'F' {\n\t\t\tvalue = int64(char - 'A' + 10)\n\t\t} else if char >= 'a' && char <= 'f' {\n\t\t\tvalue = int64(char - 'a' + 10)\n\t\t} else {\n\t\t\treturn \"\", errors.New(\"invalid character in hexadecimal string: \" + string(char))\n\t\t}\n\t\tdecimal = decimal*16 + value\n\t}\n\n\t// Convert the integer to a binary string without using predefined functions\n\tvar binaryBuilder strings.Builder\n\tif decimal == 0 {\n\t\tbinaryBuilder.WriteString(\"0\")\n\t} else {\n\t\tfor decimal > 0 {\n\t\t\tbit := decimal % 2\n\t\t\tif bit == 0 {\n\t\t\t\tbinaryBuilder.WriteString(\"0\")\n\t\t\t} else {\n\t\t\t\tbinaryBuilder.WriteString(\"1\")\n\t\t\t}\n\t\t\tdecimal = decimal / 2\n\t\t}\n\t}\n\n\t// Reverse the binary string since the bits are added in reverse order\n\tbinaryRunes := []rune(binaryBuilder.String())\n\tfor i, j := 0, len(binaryRunes)-1; i < j; i, j = i+1, j-1 {\n\t\tbinaryRunes[i], binaryRunes[j] = binaryRunes[j], binaryRunes[i]\n\t}\n\n\treturn string(binaryRunes), nil\n}\n"
  },
  {
    "path": "conversion/hexadecimaltobinary_test.go",
    "content": "package conversion\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHexToBinary(t *testing.T) {\n\ttests := []struct {\n\t\thex     string\n\t\twant    string\n\t\twantErr bool\n\t}{\n\t\t{\"\", \"\", true},\n\t\t{\"G123\", \"\", true},\n\t\t{\"12XZ\", \"\", true},\n\t\t{\"1\", \"1\", false},\n\t\t{\"A\", \"1010\", false},\n\t\t{\"10\", \"10000\", false},\n\t\t{\"1A\", \"11010\", false},\n\t\t{\"aB\", \"10101011\", false},\n\t\t{\"0Ff\", \"11111111\", false},\n\t\t{\"  1A \", \"11010\", false},\n\t\t{\"0001A\", \"11010\", false},\n\t\t{\"7FFFFFFFFFFFFFFF\", \"111111111111111111111111111111111111111111111111111111111111111\", false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.hex, func(t *testing.T) {\n\t\t\tgot, err := hexToBinary(tt.hex)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"hexToBinary(%q) error = %v, wantErr %v\", tt.hex, err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"hexToBinary(%q) = %v, want %v\", tt.hex, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkHexToBinary(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = hexToBinary(\"7FFFFFFFFFFFFFFF\")\n\t}\n}\n"
  },
  {
    "path": "conversion/hexadecimaltodecimal.go",
    "content": "/*\nAuthor: mapcrafter2048\nGitHub: https://github.com/mapcrafter2048\n*/\n\n// This algorithm will convert any Hexadecimal number(0-9, A-F, a-f) to Decimal number(0-9).\n// https://en.wikipedia.org/wiki/Hexadecimal\n// https://en.wikipedia.org/wiki/Decimal\n// Function receives a Hexadecimal Number as string and returns the Decimal number as integer.\n// Supported Hexadecimal number range is 0 to 7FFFFFFFFFFFFFFF.\n\npackage conversion\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar isValidHexadecimal = regexp.MustCompile(\"^[0-9A-Fa-f]+$\").MatchString\n\n// hexToDecimal converts a hexadecimal string to a decimal integer.\nfunc hexToDecimal(hexStr string) (int64, error) {\n\n\thexStr = strings.TrimSpace(hexStr)\n\n\tif len(hexStr) == 0 {\n\t\treturn 0, fmt.Errorf(\"input string is empty\")\n\t}\n\n\t// Check if the string has a valid hexadecimal prefix\n\tif len(hexStr) > 2 && (hexStr[:2] == \"0x\" || hexStr[:2] == \"0X\") {\n\t\thexStr = hexStr[2:]\n\t}\n\n\t// Validate the hexadecimal string\n\tif !isValidHexadecimal(hexStr) {\n\t\treturn 0, fmt.Errorf(\"invalid hexadecimal string\")\n\t}\n\n\tvar decimalValue int64\n\tfor _, char := range hexStr {\n\t\tvar digit int64\n\t\tif char >= '0' && char <= '9' {\n\t\t\tdigit = int64(char - '0')\n\t\t} else if char >= 'A' && char <= 'F' {\n\t\t\tdigit = int64(char - 'A' + 10)\n\t\t} else if char >= 'a' && char <= 'f' {\n\t\t\tdigit = int64(char - 'a' + 10)\n\t\t} else {\n\t\t\treturn 0, fmt.Errorf(\"invalid character in hexadecimal string: %c\", char)\n\t\t}\n\t\tdecimalValue = decimalValue*16 + digit\n\t}\n\n\treturn decimalValue, nil\n}\n"
  },
  {
    "path": "conversion/hexadecimaltodecimal_test.go",
    "content": "package conversion\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHexToDecimal(t *testing.T) {\n\ttests := []struct {\n\t\thex     string\n\t\twant    int64\n\t\twantErr bool\n\t}{\n\t\t{\"\", 0, true},\n\t\t{\"G123\", 0, true},\n\t\t{\"123Z\", 0, true},\n\t\t{\"1\", 1, false},\n\t\t{\"A\", 10, false},\n\t\t{\"10\", 16, false},\n\t\t{\"1A\", 26, false},\n\t\t{\"aB\", 171, false},\n\t\t{\"0Ff\", 255, false},\n\t\t{\" 1A \", 26, false},\n\t\t{\"0x1A\", 26, false},\n\t\t{\"0X1A\", 26, false},\n\t\t{\"1A\", 26, false},\n\t\t{\"7FFFFFFFFFFFFFFF\", 9223372036854775807, false},\n\t\t{\"0001A\", 26, false},\n\t\t{\"0000007F\", 127, false},\n\t\t{\"0\", 0, false},\n\t\t{\"0x0\", 0, false},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.hex, func(t *testing.T) {\n\t\t\tgot, err := hexToDecimal(tt.hex)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"hexToDecimal(%q) error = %v, wantErr %v\", tt.hex, err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"hexToDecimal(%q) = %v, want %v\", tt.hex, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkHexToDecimal(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = hexToDecimal(\"7FFFFFFFFFFFFFFF\")\n\t}\n}\n"
  },
  {
    "path": "conversion/inttoroman.go",
    "content": "// inttoroman.go\n// description: Convert an integer to a roman numeral\n// details: This program converts an integer to a roman numeral. The program uses a lookup array to convert the integer to a roman numeral.\n// time complexity: O(1)\n// space complexity: O(1)\n\npackage conversion\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\t// lookup arrays used for converting from an int to a roman numeral extremely quickly.\n\tr0 = []string{\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"} // 1 - 9\n\tr1 = []string{\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"} // 10 - 90\n\tr2 = []string{\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"} // 100 - 900\n\tr3 = []string{\"\", \"M\", \"MM\", \"MMM\"}                                       // 1,000 - 3,000\n)\n\n// IntToRoman converts an integer value to a roman numeral string. An error is\n// returned if the integer is not between 1 and 3999.\nfunc IntToRoman(n int) (string, error) {\n\tif n < 1 || n > 3999 {\n\t\treturn \"\", errors.New(\"integer must be between 1 and 3999\")\n\t}\n\t// Concatenate strings for each of 4 lookup array categories.\n\t//\n\t// Key behavior to note here is how math with integers is handled. Values are floored to the\n\t// nearest int, not rounded up. For example, 26/10 = 2 even though the actual result is 2.6.\n\t//\n\t// For example, lets use an input value of 126:\n\t// `r3[n%1e4/1e3]` --> 126 % 10_000 = 126 --> 126 / 1_000 = 0.126 (0 as int) --> r3[0] = \"\"\n\t// `r2[n%1e3/1e2]` --> 126 % 1_000 = 126 --> 126 / 100 = 1.26 (1 as int) --> r2[1] = \"C\"\n\t// `r1[n%100/10]` --> 126 % 100 = 26 --> 26 / 10 = 2.6 (2 as int) --> r1[2] = \"XX\"\n\t// `r0[n%10]` --> 126 % 10 = 6 --> r0[6] = \"VI\"\n\t// FINAL --> \"\" + \"C\" + \"XX\" + \"VI\" = \"CXXVI\"\n\t//\n\t// This is efficient in Go. The 4 operands are evaluated,\n\t// then a single allocation is made of the exact size needed for the result.\n\treturn r3[n%1e4/1e3] + r2[n%1e3/1e2] + r1[n%100/10] + r0[n%10], nil\n}\n"
  },
  {
    "path": "conversion/inttoroman_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nfunc TestIntToRoman(t *testing.T) {\n\tfor expected, input := range romanTestCases {\n\t\tout, err := IntToRoman(input)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"IntToRoman(%d) returned an error %s\", input, err.Error())\n\t\t}\n\t\tif out != expected {\n\t\t\tt.Errorf(\"IntToRoman(%d) = %s; want %s\", input, out, expected)\n\t\t}\n\t}\n\t_, err := IntToRoman(100000)\n\tif err == nil {\n\t\tt.Errorf(\"IntToRoman(%d) expected an error\", 100000)\n\t}\n\t_, err = IntToRoman(0)\n\tif err == nil {\n\t\tt.Errorf(\"IntToRoman(%d) expected an error\", 0)\n\t}\n}\n\nfunc BenchmarkIntToRoman(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = IntToRoman(3999)\n\t}\n}\n"
  },
  {
    "path": "conversion/rgbhex.go",
    "content": "// rgbhex.go\n// description: convert hex input to red, green and blue and vice versa\n// time complexity: O(1)\n// space complexity: O(1)\n// author(s) [darmiel](https://github.com/darmiel)\n// see rgbhex_test.go\n\npackage conversion\n\n// HEXToRGB splits an RGB input (e.g. a color in hex format; 0x<color-code>)\n// into the individual components: red, green and blue\nfunc HEXToRGB(hex uint) (red, green, blue byte) {\n\t// A hex code is structured like this:\n\t// #3498db (light blue) - converted to binary:\n\t// 00110100 10011000 11011011\n\t//  <red>   <green>   <blue>\n\n\t// To get the blue value we use the bit operation AND with the bit mask 0xFF (in binary: 11111111)\n\t// 00110100 10011000 <11011011> &\n\t// 00000000 00000000  11111111  =\n\t// 00000000 00000000 <11011011> =\n\tblue = byte(hex & 0xFF)\n\n\t// To get the green value, we first shift the value 8 bits to the right:\n\t//  00110100 <10011000>  11011011  >> 8 =\n\t//  00000000  00110100  <10011000> &\n\t//  00000000  00000000   11111111  =\n\t//  00000000  00000000  <10011000> =\n\tgreen = byte((hex >> 8) & 0xFF)\n\n\t// Same as green value, only this time shift 16 to the right\n\t// Alternatively, you can apply a bitmask first and then shift it.\n\t// <00110100> 10011000  11011011 &\n\t//  11111111  00000000  00000000 =\n\t// <00110100> 00000000  00000000 >> 16\n\t//  00000000  00000000 <00110100> =\n\tred = byte((hex >> 16) & 0xFF)\n\treturn\n}\n\n// RGBToHEX does exactly the opposite of HEXToRGB:\n// it combines the three components red, green and blue to an RGB value, which can be converted to e.g. Hex\nfunc RGBToHEX(red, green, blue byte) (hex uint) {\n\t// Sets the bits of blue in position 1-8, green in 9-16 and red in 17-24\n\n\t// Red: 00110100\n\t// Green: 10011000\n\t// Blue: 11011011\n\t// RGB:\n\t// R << 16: [00110100]  00000000   00000000 |\n\t// G << 8 :  00000000  {10011000}  00000000 |\n\t// B      :  00000000   00000000  <11011011> =\n\t//          [00110100] {10011000} <11011011>\n\treturn (uint(red) << 16) | (uint(green) << 8) | uint(blue)\n}\n"
  },
  {
    "path": "conversion/rgbhex_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nvar HEX = []uint{\n\t0x1abc9c,\n\t0x3498db,\n\t0x9b59b6,\n}\n\nvar RGB = [][]byte{\n\t{26, 188, 156},\n\t{52, 152, 219},\n\t{155, 89, 182},\n}\n\nfunc TestHEXToRGB(t *testing.T) {\n\tfor i := 0; i < len(HEX); i++ {\n\t\thex := HEX[i]\n\t\texpected := RGB[i]\n\t\tresultR, resultG, resultB := HEXToRGB(hex)\n\t\tif resultR != expected[0] || resultG != expected[1] || resultB != expected[2] {\n\t\t\tt.Errorf(\"HEXToRGB(%d) = %d,%d,%d; want %d,%d,%d\",\n\t\t\t\thex, resultR, resultG, resultB, expected[0], expected[1], expected[2])\n\t\t}\n\t}\n}\n\nfunc BenchmarkHEXToRGB(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _, _ = HEXToRGB(0xdeadbe)\n\t}\n}\n\nfunc TestRGBToHEX(t *testing.T) {\n\tfor i := 0; i < len(RGB); i++ {\n\t\targs := RGB[i]\n\t\texpected := HEX[i]\n\t\tresult := RGBToHEX(args[0], args[1], args[2])\n\t\tif result != expected {\n\t\t\tt.Errorf(\"RGBToHEX(%d,%d,%d) = %d; want %d\",\n\t\t\t\targs[0], args[1], args[2], result, expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkRGBToHEX(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = RGBToHEX(222, 173, 190)\n\t}\n}\n"
  },
  {
    "path": "conversion/romantoint.go",
    "content": "// This algorithm will convert a standard roman number to an integer\n// https://en.wikipedia.org/wiki/Roman_numerals\n// Function receives a string as a roman number and outputs an integer\n// Maximum output will be 3999\n// Only standard form is supported\n// time complexity: O(n)\n// space complexity: O(1)\n\npackage conversion\n\nimport (\n\t\"errors\"\n\t\"strings\"\n)\n\n// numeral describes the value and symbol of a single roman numeral\ntype numeral struct {\n\tval int\n\tsym string\n}\n\n// lookup array for numeral values sorted by largest to smallest\nvar nums = []numeral{\n\t{1000, \"M\"},\n\t{900, \"CM\"},\n\t{500, \"D\"},\n\t{400, \"CD\"},\n\t{100, \"C\"},\n\t{90, \"XC\"},\n\t{50, \"L\"},\n\t{40, \"XL\"},\n\t{10, \"X\"},\n\t{9, \"IX\"},\n\t{5, \"V\"},\n\t{4, \"IV\"},\n\t{1, \"I\"},\n}\n\n// RomanToInt converts a roman numeral string to an integer. Roman numerals for numbers\n// outside the range 1 to 3,999 will return an error. Nil or empty string return 0\n// with no error thrown.\nfunc RomanToInt(input string) (int, error) {\n\tif input == \"\" {\n\t\treturn 0, nil\n\t}\n\tvar output int\n\tfor _, n := range nums {\n\t\tfor strings.HasPrefix(input, n.sym) {\n\t\t\toutput += n.val\n\t\t\tinput = input[len(n.sym):]\n\t\t}\n\t}\n\t// if we are still left with input string values then the\n\t// input was invalid and an error is returned.\n\tif len(input) > 0 {\n\t\treturn 0, errors.New(\"invalid roman numeral\")\n\t}\n\treturn output, nil\n}\n"
  },
  {
    "path": "conversion/romantoint_test.go",
    "content": "package conversion\n\nimport \"testing\"\n\nvar romanTestCases = map[string]int{\n\t\"I\": 1, \"II\": 2, \"III\": 3, \"IV\": 4, \"V\": 5, \"VI\": 6,\n\t\"VII\": 7, \"VIII\": 8, \"IX\": 9, \"X\": 10, \"XI\": 11, \"XII\": 12,\n\t\"XIII\": 13, \"XIV\": 14, \"XV\": 15, \"XVI\": 16, \"XVII\": 17,\n\t\"XVIII\": 18, \"XIX\": 19, \"XX\": 20, \"XXXI\": 31, \"XXXII\": 32,\n\t\"XXXIII\": 33, \"XXXIV\": 34, \"XXXV\": 35, \"XXXVI\": 36, \"XXXVII\": 37,\n\t\"XXXVIII\": 38, \"XXXIX\": 39, \"XL\": 40, \"XLI\": 41, \"XLII\": 42,\n\t\"XLIII\": 43, \"XLIV\": 44, \"XLV\": 45, \"XLVI\": 46, \"XLVII\": 47,\n\t\"XLVIII\": 48, \"XLIX\": 49, \"L\": 50, \"LXXXIX\": 89, \"XC\": 90,\n\t\"XCI\": 91, \"XCII\": 92, \"XCIII\": 93, \"XCIV\": 94, \"XCV\": 95,\n\t\"XCVI\": 96, \"XCVII\": 97, \"XCVIII\": 98, \"XCIX\": 99, \"C\": 100,\n\t\"CI\": 101, \"CII\": 102, \"CIII\": 103, \"CIV\": 104, \"CV\": 105,\n\t\"CVI\": 106, \"CVII\": 107, \"CVIII\": 108, \"CIX\": 109, \"CXLIX\": 149,\n\t\"CCCXLIX\": 349, \"CDLVI\": 456, \"D\": 500, \"DCIV\": 604, \"DCCLXXXIX\": 789,\n\t\"DCCCXLIX\": 849, \"CMIV\": 904, \"M\": 1000, \"MVII\": 1007, \"MLXVI\": 1066,\n\t\"MCCXXXIV\": 1234, \"MDCCLXXVI\": 1776, \"MMXXI\": 2021, \"MMDCCCVI\": 2806,\n\t\"MMCMXCIX\": 2999, \"MMM\": 3000, \"MMMCMLXXIX\": 3979, \"MMMCMXCIX\": 3999,\n}\n\nfunc TestRomanToInt(t *testing.T) {\n\tfor input, expected := range romanTestCases {\n\t\tout, err := RomanToInt(input)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"RomanToInt(%s) returned an error %s\", input, err.Error())\n\t\t}\n\t\tif out != expected {\n\t\t\tt.Errorf(\"RomanToInt(%s) = %d; want %d\", input, out, expected)\n\t\t}\n\t}\n\t_, err := RomanToInt(\"IVCMXCIX\")\n\tif err == nil {\n\t\tt.Error(\"RomanToInt(IVCMXCIX) expected an error\")\n\t}\n\n\tval, err := RomanToInt(\"\")\n\tif val != 0 {\n\t\tt.Errorf(\"RomanToInt(\\\"\\\") = %d; want 0\", val)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"RomanToInt(\\\"\\\") returned an error %s\", err.Error())\n\t}\n}\n\nfunc BenchmarkRomanToInt(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = RomanToInt(\"MMMCMXCIX\")\n\t}\n}\n"
  },
  {
    "path": "dynamic/abbreviation.go",
    "content": "// File: abbreviation.go\n// Description: Abbreviation problem\n// Details:\n//   https://www.hackerrank.com/challenges/abbr/problem\n// Problem description (from hackerrank):\n//   You can perform the following operations on the string, a:\n//   1. Capitalize zero or more of a's lowercase letters.\n//   2. Delete all of the remaining lowercase letters in a.\n//   Given 2 strings a and b, determine if it's possible to make a equal to be using above operations.\n// Example:\n//\t Given a = \"ABcde\" and b = \"ABCD\"\n//   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.\n// Author: [duongoku](https://github.com/duongoku)\n// Time Complexity: O(n*m) where n is the length of a and m is the length of b\n// Space Complexity: O(n*m) where n is the length of a and m is the length of b\n// See abbreviation_test.go for test cases\n\npackage dynamic\n\n// strings for getting uppercases and lowercases\nimport (\n\t\"strings\"\n)\n\n// Returns true if it is possible to make a equals b (if b is an abbreviation of a), returns false otherwise\nfunc Abbreviation(a string, b string) bool {\n\tdp := make([][]bool, len(a)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]bool, len(b)+1)\n\t}\n\tdp[0][0] = true\n\n\tfor i := 0; i < len(a); i++ {\n\t\tfor j := 0; j <= len(b); j++ {\n\t\t\tif dp[i][j] {\n\t\t\t\tif j < len(b) && strings.ToUpper(string(a[i])) == string(b[j]) {\n\t\t\t\t\tdp[i+1][j+1] = true\n\t\t\t\t}\n\t\t\t\tif string(a[i]) == strings.ToLower(string(a[i])) {\n\t\t\t\t\tdp[i+1][j] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(a)][len(b)]\n}\n"
  },
  {
    "path": "dynamic/abbreviation_test.go",
    "content": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestAbbreviation(t *testing.T) {\n\ttests := []struct {\n\t\ta        string\n\t\tb        string\n\t\texpected bool\n\t}{\n\t\t{\"uOHlGMdUBc\", \"uOalGMdUBCasdcavsdf\", false},\n\t\t{\"kotgDIUagj\", \"DIU\", true},\n\t\t{\"WPTffVkSNl\", \"WPTVSN\", true},\n\t\t{\"CoJsPURrVX\", \"CPUVX\", false},\n\t\t{\"xasreDHndqvCnFfX\", \"DHndqvCnFX\", false},\n\t\t{\"XFEaWCxpeepGjOnCCsFh\", \"XFEAWCPEPGOCCSF\", true},\n\t\t{\"\", \"\", true},\n\t\t{\"a\", \"\", true},\n\t\t{\"a\", \"b\", false},\n\t\t{\"a\", \"a\", false},\n\t\t{\"A\", \"A\", true},\n\t}\n\tcount := len(tests)\n\tfor i := 0; i < count; i++ {\n\t\tname := fmt.Sprintf(\n\t\t\t\"Test case #%d: string a = \\\"%s\\\", string b = \\\"%s\\\"\",\n\t\t\ti+1,\n\t\t\ttests[i].a,\n\t\t\ttests[i].b,\n\t\t)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tresult := Abbreviation(tests[i].a, tests[i].b)\n\t\t\tif result != tests[i].expected {\n\t\t\t\tt.Errorf(\"Expected the %t, got %t\", tests[i].expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/binomialcoefficient.go",
    "content": "// binomialcoefficient.go\n// description: Implementation of the binomial coefficient using dynamic programming\n// 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.\n// time complexity: O(n*k) where n is the number of elements and k is the number of elements to choose\n// space complexity: O(n*k) where n is the number of elements and k is the number of elements to choose\npackage dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// func main() {\n// \tmyArrayOfK := [4]int{5, 6, 7, 8}\n// \tvar x int\n\n// \tfmt.Println(\"\\nBinomial Coefficient Using Dynamic Programming:\", bin2(50, 5))\n// \tfor _, element := range myArrayOfK {\n// \t\tstart := time.Now()\n// \t\tx = bin2(50, element)\n// \t\telapsed := time.Since(start)\n// \t\tfmt.Println(\"bin2 (50,\", element, \") = \", x, \"    took \", elapsed)\n\n// \t}\n\n// }\n\n// Bin2 function\nfunc Bin2(n int, k int) int {\n\tvar i, j int\n\tB := make([][]int, (n + 1))\n\tfor i := range B {\n\t\tB[i] = make([]int, k+1)\n\t}\n\n\tfor i = 0; i <= n; i++ {\n\t\tfor j = 0; j <= min.Int(i, k); j++ {\n\t\t\tif j == 0 || j == i {\n\t\t\t\tB[i][j] = 1\n\t\t\t} else {\n\t\t\t\tB[i][j] = B[i-1][j-1] + B[i-1][j]\n\t\t\t}\n\t\t}\n\t}\n\treturn B[n][k]\n}\n"
  },
  {
    "path": "dynamic/binomialcoefficient_test.go",
    "content": "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) {\n\ttd := []struct {\n\t\tn, k, expected int\n\t}{\n\t\t{0, 0, 1},\n\t\t{1, 1, 1},\n\t\t{2, 0, 1}, {2, 1, 2}, {2, 2, 1},\n\t\t{3, 0, 1}, {3, 1, 3}, {3, 2, 3}, {3, 3, 1},\n\t\t{4, 0, 1}, {4, 1, 4}, {4, 2, 6}, {4, 3, 4}, {4, 4, 1},\n\t\t{5, 0, 1}, {5, 1, 5}, {5, 2, 10}, {5, 3, 10}, {5, 4, 5}, {5, 5, 1},\n\t\t{10, 2, 45},\n\t\t{15, 10, 3003},\n\t}\n\tfor _, tc := range td {\n\t\tname := fmt.Sprintf(\"binomial coefficient of (%d, %d)\", tc.n, tc.k)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tactual := dynamic.Bin2(tc.n, tc.k)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"expecting binomial coefficient of (%d, %d) to be %d but got %d\", tc.n, tc.k, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/burstballoons.go",
    "content": "package dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/max\"\n\n// MaxCoins returns the maximum coins we can collect by bursting the balloons\nfunc MaxCoins(nums []int) int {\n\tn := len(nums)\n\tif n == 0 {\n\t\treturn 0\n\t}\n\n\tnums = append([]int{1}, nums...)\n\tnums = append(nums, 1)\n\n\tdp := make([][]int, n+2)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, n+2)\n\t}\n\n\tfor length := 1; length <= n; length++ {\n\t\tfor left := 1; left+length-1 <= n; left++ {\n\t\t\tright := left + length - 1\n\t\t\tfor k := left; k <= right; k++ {\n\t\t\t\tcoins := nums[left-1] * nums[k] * nums[right+1]\n\t\t\t\tdp[left][right] = max.Int(dp[left][right], dp[left][k-1]+dp[k+1][right]+coins)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[1][n]\n}\n"
  },
  {
    "path": "dynamic/burstballoons_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseBurstBalloons struct {\n\tnums     []int\n\texpected int\n}\n\nfunc getBurstBalloonsTestCases() []testCaseBurstBalloons {\n\treturn []testCaseBurstBalloons{\n\t\t{[]int{3, 1, 5, 8}, 167}, // Maximum coins from [3,1,5,8]\n\t\t{[]int{1, 5}, 10},        // Maximum coins from [1,5]\n\t\t{[]int{1}, 1},            // Single balloon\n\t\t{[]int{}, 0},             // No balloons\n\t}\n\n}\n\nfunc TestMaxCoins(t *testing.T) {\n\tt.Run(\"Burst Balloons test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getBurstBalloonsTestCases() {\n\t\t\tactual := dynamic.MaxCoins(tc.nums)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"MaxCoins(%v) = %d; expected %d\", tc.nums, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/catalan.go",
    "content": "//The Catalan numbers are a sequence of positive integers that appear in many counting\n// problems in combinatorics.\n// time complexity: O(n²)\n// space complexity: O(n)\n//reference: https://brilliant.org/wiki/catalan-numbers/\n\npackage dynamic\n\nimport \"fmt\"\n\nvar errCatalan = fmt.Errorf(\"can't have a negative n-th catalan number\")\n\n// NthCatalan returns the n-th Catalan Number\n// Complexity: O(n²)\nfunc NthCatalanNumber(n int) (int64, error) {\n\tif n < 0 {\n\t\t//doesn't accept negative number\n\t\treturn 0, errCatalan\n\t}\n\n\tvar catalanNumberList []int64\n\tcatalanNumberList = append(catalanNumberList, 1) //first value is 1\n\n\tfor i := 1; i <= n; i++ {\n\t\tcatalanNumberList = append(catalanNumberList, 0) //append 0 and calculate\n\n\t\tfor j := 0; j < i; j++ {\n\t\t\tcatalanNumberList[i] += catalanNumberList[j] * catalanNumberList[i-j-1]\n\t\t}\n\t}\n\n\treturn catalanNumberList[n], nil\n}\n"
  },
  {
    "path": "dynamic/catalan_test.go",
    "content": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestCatalanNumbers(t *testing.T) {\n\tvar testCatalanNumbersData = []struct {\n\t\tnthCatalanNumber      int\n\t\texpectedCatalanNumber int64\n\t\texpectedError         error\n\t}{\n\t\t{nthCatalanNumber: -1000, expectedCatalanNumber: 0, expectedError: errCatalan},\n\t\t{nthCatalanNumber: -1, expectedCatalanNumber: 0, expectedError: errCatalan},\n\t\t{nthCatalanNumber: 0, expectedCatalanNumber: 1, expectedError: nil},\n\t\t{nthCatalanNumber: 1, expectedCatalanNumber: 1, expectedError: nil},\n\t\t{nthCatalanNumber: 2, expectedCatalanNumber: 2, expectedError: nil},\n\t\t{nthCatalanNumber: 3, expectedCatalanNumber: 5, expectedError: nil},\n\t\t{nthCatalanNumber: 4, expectedCatalanNumber: 14, expectedError: nil},\n\t\t{nthCatalanNumber: 5, expectedCatalanNumber: 42, expectedError: nil},\n\t\t{nthCatalanNumber: 6, expectedCatalanNumber: 132, expectedError: nil},\n\t\t{nthCatalanNumber: 7, expectedCatalanNumber: 429, expectedError: nil},\n\t\t{nthCatalanNumber: 8, expectedCatalanNumber: 1430, expectedError: nil},\n\t\t{nthCatalanNumber: 9, expectedCatalanNumber: 4862, expectedError: nil},\n\t\t{nthCatalanNumber: 10, expectedCatalanNumber: 16796, expectedError: nil},\n\t\t{nthCatalanNumber: 1000, expectedCatalanNumber: 4233371109654655040, expectedError: nil},\n\t}\n\n\tfor i := range testCatalanNumbersData {\n\t\tt.Run(fmt.Sprintf(\"the %dth Catalan Number\", testCatalanNumbersData[i].nthCatalanNumber), func(t *testing.T) {\n\t\t\tnthCatalanNumber := testCatalanNumbersData[i].nthCatalanNumber\n\t\t\tresult, err := NthCatalanNumber(nthCatalanNumber)\n\t\t\texpectedCatalanNumber := testCatalanNumbersData[i].expectedCatalanNumber\n\t\t\texpectedError := testCatalanNumbersData[i].expectedError\n\n\t\t\tif err != expectedError {\n\t\t\t\tt.Errorf(\"Expected %dth Catalan Number error: %d\\nFound: %d\\n\", nthCatalanNumber, expectedError, err)\n\t\t\t}\n\n\t\t\tif result != expectedCatalanNumber {\n\t\t\t\tt.Errorf(\"Expected %dth Catalan Number: %d\\nFound: %d\\n\", nthCatalanNumber, expectedCatalanNumber, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/coinchange.go",
    "content": "// coinchange.go\n// description: Implementation of the coin change problem using dynamic programming\n// details: The coin change problem is a problem that asks for the number of ways to make change for a given amount of money using a given set of coins. The problem can be solved using dynamic programming.\n// time complexity: O(n*m) where n is the number of coins and m is the amount of money\n// space complexity: O(m) where m is the amount of money\n\npackage dynamic\n\n// CoinChange finds the number of possible combinations of coins\n// of different values which can get to the target amount.\nfunc CoinChange(coins []int32, amount int32) int32 {\n\tcombination := make([]int32, amount)\n\tcombination[0] = 1\n\n\tfor _, c := range coins {\n\t\tfor i := c; i < amount; i++ {\n\n\t\t\tcombination[i] += combination[i-c]\n\t\t}\n\t}\n\n\treturn combination[amount-1]\n}\n"
  },
  {
    "path": "dynamic/coinchange_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n\t\"testing\"\n)\n\nfunc TestCoinChange(t *testing.T) {\n\tcoinCombination := []int32{1, 2, 5, 10}\n\ttargets := []struct {\n\t\ttarget   int32\n\t\texpected int32\n\t}{\n\t\t{4, 2},\n\t\t{5, 3},\n\t\t{10, 8},\n\t\t{15, 19},\n\t\t{20, 34},\n\t}\n\n\tfor _, v := range targets {\n\t\tt.Run(fmt.Sprintf(\"target: %d \", v.target), func(t *testing.T) {\n\t\t\tresult := dynamic.CoinChange(coinCombination, v.target)\n\t\t\tif result != v.expected {\n\t\t\t\tt.Errorf(\"target: %d Expected %d, got %d\", v.target, v.expected, result)\n\t\t\t}\n\t\t})\n\t}\n\n}\n"
  },
  {
    "path": "dynamic/dicethrow.go",
    "content": "// dicethrow.go\n// description: Solves the Dice Throw Problem using dynamic programming\n// reference: https://www.geeksforgeeks.org/dice-throw-problem/\n// time complexity: O(m * n)\n// space complexity: O(m * n)\n\npackage dynamic\n\n// DiceThrow returns the number of ways to get sum `sum` using `m` dice with `n` faces\nfunc DiceThrow(m, n, sum int) int {\n\tdp := make([][]int, m+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, sum+1)\n\t}\n\n\tfor i := 1; i <= n; i++ {\n\t\tif i <= sum {\n\t\t\tdp[1][i] = 1\n\t\t}\n\t}\n\n\tfor i := 2; i <= m; i++ {\n\t\tfor j := 1; j <= sum; j++ {\n\t\t\tfor k := 1; k <= n; k++ {\n\t\t\t\tif j-k >= 0 {\n\t\t\t\t\tdp[i][j] += dp[i-1][j-k]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[m][sum]\n}\n"
  },
  {
    "path": "dynamic/dicethrow_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseDiceThrow struct {\n\tnumDice   int\n\tnumFaces  int\n\ttargetSum int\n\texpected  int\n}\n\n// getDiceThrowTestCases provides the test cases for DiceThrow\nfunc getDiceThrowTestCases() []testCaseDiceThrow {\n\treturn []testCaseDiceThrow{\n\t\t{2, 6, 7, 6},  // Two dice, six faces each, sum = 7\n\t\t{1, 6, 3, 1},  // One die, six faces, sum = 3\n\t\t{3, 4, 5, 6},  // Three dice, four faces each, sum = 5\n\t\t{1, 6, 1, 1},  // One die, six faces, sum = 1\n\t\t{2, 6, 12, 1}, // Two dice, six faces each, sum = 12\n\t\t{3, 6, 18, 1}, // Three dice, six faces each, sum = 18\n\t\t{2, 6, 20, 0}, // Two dice, six faces each, sum = 20 (impossible)\n\t\t{1, 1, 1, 1},  // One die, one face, sum = 1\n\t\t{1, 1, 2, 0},  // One die, one face, sum = 2 (impossible)\n\t\t{2, 1, 2, 1},  // Two dice, one face each, sum = 2\n\t}\n}\n\n// TestDiceThrow tests the DiceThrow function with basic test cases\nfunc TestDiceThrow(t *testing.T) {\n\tt.Run(\"Basic test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getDiceThrowTestCases() {\n\t\t\tactual := dynamic.DiceThrow(tc.numDice, tc.numFaces, tc.targetSum)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"DiceThrow(%d, %d, %d) = %d; expected %d\", tc.numDice, tc.numFaces, tc.targetSum, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/doc.go",
    "content": "// Package dynamic is a package of certain implementations of dynamically run algorithms.\npackage dynamic\n"
  },
  {
    "path": "dynamic/dynamic_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage dynamic\n"
  },
  {
    "path": "dynamic/editdistance.go",
    "content": "// EDIT DISTANCE PROBLEM\n// time complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.\n// space complexity: O(m * n) where m and n are lengths of the strings, first and second respectively.\n// https://www.geeksforgeeks.org/edit-distance-dp-5/\n// https://leetcode.com/problems/edit-distance/\n\npackage dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// EditDistanceRecursive is a naive implementation with exponential time complexity.\nfunc EditDistanceRecursive(first string, second string, pointerFirst int, pointerSecond int) int {\n\n\tif pointerFirst == 0 {\n\t\treturn pointerSecond\n\t}\n\n\tif pointerSecond == 0 {\n\t\treturn pointerFirst\n\t}\n\n\t// Characters match, so we recur for the remaining portions\n\tif first[pointerFirst-1] == second[pointerSecond-1] {\n\t\treturn EditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)\n\t}\n\n\t// We have three choices, all with cost of 1 unit\n\treturn 1 + min.Int(EditDistanceRecursive(first, second, pointerFirst, pointerSecond-1), // Insert\n\t\tEditDistanceRecursive(first, second, pointerFirst-1, pointerSecond),   // Delete\n\t\tEditDistanceRecursive(first, second, pointerFirst-1, pointerSecond-1)) // Replace\n}\n\n// EditDistanceDP is an optimised implementation which builds on the ideas of the recursive implementation.\n// We use dynamic programming to compute the DP table where dp[i][j] denotes the edit distance value\n// 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,\n// first and second respectively.\nfunc EditDistanceDP(first string, second string) int {\n\n\tm := len(first)\n\tn := len(second)\n\n\t// Create the DP table\n\tdp := make([][]int, m+1)\n\tfor i := 0; i <= m; i++ {\n\t\tdp[i] = make([]int, n+1)\n\t}\n\n\tfor i := 0; i <= m; i++ {\n\t\tfor j := 0; j <= n; j++ {\n\n\t\t\tif i == 0 {\n\t\t\t\tdp[i][j] = j\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif j == 0 {\n\t\t\t\tdp[i][j] = i\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif first[i-1] == second[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdp[i][j] = 1 + min.Int(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])\n\t\t}\n\t}\n\n\treturn dp[m][n]\n}\n"
  },
  {
    "path": "dynamic/editdistance_test.go",
    "content": "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\tfirst    string\n\t\tsecond   string\n\t\texpected int\n\t}{\n\t\t{\"\", \"\", 0},\n\t\t{\"horse\", \"ros\", 3},\n\t\t{\"intention\", \"execution\", 5},\n\t\t{\"abcdxabcde\", \"abcdeabcdx\", 2},\n\t\t{\"sunday\", \"saturday\", 3},\n\t\t{\"food\", \"money\", 4},\n\t\t{\"voldemort\", \"dumbledore\", 7},\n\t}\n\n\tfor i := range testCases {\n\n\t\tt.Run(fmt.Sprintf(\"Word 1: %s, Word 2: %s\", testCases[i].first, testCases[i].second), func(t *testing.T) {\n\n\t\t\tcomputed := EditDistanceDP(testCases[i].first, testCases[i].second)\n\n\t\t\tif computed != testCases[i].expected {\n\t\t\t\tt.Errorf(\"Word 1: %s, Word 2: %s, Expected: %d, Computed: %d\", testCases[i].first, testCases[i].second, testCases[i].expected, computed)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/eggdropping.go",
    "content": "package dynamic\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/max\"\n\t\"github.com/TheAlgorithms/Go/math/min\"\n)\n\n// EggDropping finds the minimum number of attempts needed to find the critical floor\n// with `eggs` number of eggs and `floors` number of floors\nfunc EggDropping(eggs, floors int) int {\n\t// Edge case: If there are no floors, no attempts needed\n\tif floors == 0 {\n\t\treturn 0\n\t}\n\t// Edge case: If there is one floor, one attempt needed\n\tif floors == 1 {\n\t\treturn 1\n\t}\n\t// Edge case: If there is one egg, need to test all floors one by one\n\tif eggs == 1 {\n\t\treturn floors\n\t}\n\n\t// Initialize DP table\n\tdp := make([][]int, eggs+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, floors+1)\n\t}\n\n\t// Fill the DP table for 1 egg\n\tfor j := 1; j <= floors; j++ {\n\t\tdp[1][j] = j\n\t}\n\n\t// Fill the DP table for more than 1 egg\n\tfor i := 2; i <= eggs; i++ {\n\t\tfor j := 2; j <= floors; j++ {\n\t\t\tdp[i][j] = int(^uint(0) >> 1) // initialize with a large number\n\t\t\tfor x := 1; x <= j; x++ {\n\t\t\t\t// Recurrence relation to fill the DP table\n\t\t\t\tres := max.Int(dp[i-1][x-1], dp[i][j-x]) + 1\n\t\t\t\tdp[i][j] = min.Int(dp[i][j], res)\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[eggs][floors]\n}\n"
  },
  {
    "path": "dynamic/eggdropping_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseEggDropping struct {\n\teggs     int\n\tfloors   int\n\texpected int\n}\n\nfunc getEggDroppingTestCases() []testCaseEggDropping {\n\treturn []testCaseEggDropping{\n\t\t{1, 10, 10}, // One egg, need to test all floors\n\t\t{2, 10, 4},  // Two eggs and ten floors\n\t\t{3, 14, 4},  // Three eggs and fourteen floors\n\t\t{2, 36, 8},  // Two eggs and thirty-six floors\n\t\t{2, 0, 0},   // Two eggs, zero floors\n\t}\n\n}\n\nfunc TestEggDropping(t *testing.T) {\n\tt.Run(\"Egg Dropping test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getEggDroppingTestCases() {\n\t\t\tactual := dynamic.EggDropping(tc.eggs, tc.floors)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"EggDropping(%d, %d) = %d; expected %d\", tc.eggs, tc.floors, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/fibonacci.go",
    "content": "// fibonacci.go\n// description: Implementation of the Fibonacci sequence using dynamic programming\n// time complexity: O(n)\n// space complexity: O(1)\npackage dynamic\n\n// https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/\n\n// NthFibonacci returns the nth Fibonacci Number\nfunc NthFibonacci(n uint) uint {\n\tif n == 0 {\n\t\treturn 0\n\t}\n\n\t// n1 and n2 are the (i-1)th and ith Fibonacci numbers, respectively\n\tvar n1, n2 uint = 0, 1\n\n\tfor i := uint(1); i < n; i++ {\n\t\tn3 := n1 + n2\n\t\tn1 = n2\n\t\tn2 = n3\n\t}\n\n\treturn n2\n}\n"
  },
  {
    "path": "dynamic/fibonacci_test.go",
    "content": "package dynamic\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc Test_NthFibonacci(t *testing.T) {\n\t// source: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html\n\tvar fibonacciNumbers = []struct {\n\t\tnth       uint\n\t\tfibonacci uint\n\t}{\n\t\t{0, 0},\n\t\t{1, 1},\n\t\t{2, 1},\n\t\t{3, 2},\n\t\t{4, 3},\n\t\t{5, 5},\n\t\t{6, 8},\n\t\t{7, 13},\n\t\t{8, 21},\n\t\t{9, 34},\n\t\t{10, 55},\n\t\t{20, 6765},\n\t\t{30, 832040},\n\t\t{40, 102334155},\n\t\t{50, 12586269025},\n\t\t{60, 1548008755920},\n\t\t{70, 190392490709135},\n\t\t{80, 23416728348467685},\n\t\t{90, 2880067194370816120},\n\t}\n\tfor i := range fibonacciNumbers {\n\t\tt.Run(fmt.Sprintf(\"the %dth Fibonacci number\", fibonacciNumbers[i].nth), func(t *testing.T) {\n\t\t\tresult := NthFibonacci(fibonacciNumbers[i].nth)\n\t\t\tif result != fibonacciNumbers[i].fibonacci {\n\t\t\t\tt.Errorf(\"Expected the %dth Fibonacci number to be %d, got %d\", fibonacciNumbers[i].nth, fibonacciNumbers[i].fibonacci, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/interleavingstrings.go",
    "content": "// interleavingstrings.go\n// description: Solves the Interleaving Strings problem using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Interleaving_strings\n// time complexity: O(m*n)\n// space complexity: O(m*n)\n\npackage dynamic\n\n// IsInterleave checks if string `s1` and `s2` can be interleaved to form string `s3`\nfunc IsInterleave(s1, s2, s3 string) bool {\n\tif len(s1)+len(s2) != len(s3) {\n\t\treturn false\n\t}\n\n\tdp := make([][]bool, len(s1)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]bool, len(s2)+1)\n\t}\n\n\tdp[0][0] = true\n\tfor i := 1; i <= len(s1); i++ {\n\t\tdp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1]\n\t}\n\n\tfor j := 1; j <= len(s2); j++ {\n\t\tdp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1]\n\t}\n\n\tfor i := 1; i <= len(s1); i++ {\n\t\tfor j := 1; j <= len(s2); j++ {\n\t\t\tdp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])\n\t\t}\n\t}\n\n\treturn dp[len(s1)][len(s2)]\n}\n"
  },
  {
    "path": "dynamic/interleavingstrings_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseInterleaving struct {\n\ts1, s2, s3 string\n\texpected   bool\n}\n\nfunc getInterleavingTestCases() []testCaseInterleaving {\n\treturn []testCaseInterleaving{\n\t\t{\"aab\", \"axy\", \"aaxaby\", true},   // Valid interleaving\n\t\t{\"aab\", \"axy\", \"abaaxy\", false},  // Invalid interleaving\n\t\t{\"\", \"\", \"\", true},               // All empty strings\n\t\t{\"abc\", \"\", \"abc\", true},         // Only s1 matches s3\n\t\t{\"\", \"xyz\", \"xyz\", true},         // Only s2 matches s3\n\t\t{\"abc\", \"xyz\", \"abxcyz\", true},   // Valid interleaving\n\t\t{\"aaa\", \"aaa\", \"aaaaaa\", true},   // Identical strings\n\t\t{\"aaa\", \"aaa\", \"aaaaaaa\", false}, // Extra character\n\t\t{\"abc\", \"def\", \"abcdef\", true},   // Concatenation order\n\t\t{\"abc\", \"def\", \"adbcef\", true},   // Valid mixed interleaving\n\t}\n}\n\nfunc TestIsInterleave(t *testing.T) {\n\tt.Run(\"Interleaving Strings test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getInterleavingTestCases() {\n\t\t\tactual := dynamic.IsInterleave(tc.s1, tc.s2, tc.s3)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"IsInterleave(%q, %q, %q) = %v; expected %v\", tc.s1, tc.s2, tc.s3, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/knapsack.go",
    "content": "package dynamic\n\n// Knapsack Problem\n// https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/\n// https://en.wikipedia.org/wiki/Knapsack_problem\n// time complexity: O(n*maxWeight)\n// space complexity: O(n*maxWeight)\n\nimport (\n\t\"math\"\n)\n\n// Max function - possible duplicate\nfunc Max(a, b int) int {\n\treturn int(math.Max(float64(a), float64(b)))\n}\n\n// Knapsack solves knapsack problem\n// return maxProfit\nfunc Knapsack(maxWeight int, weights, values []int) int {\n\tn := len(weights)\n\tm := maxWeight\n\t// create dp data structure\n\tdp := make([][]int, n+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, m+1)\n\t}\n\tfor i := 0; i < len(weights); i++ {\n\t\tfor j := 0; j <= maxWeight; j++ {\n\t\t\tif weights[i] > j {\n\t\t\t\tdp[i+1][j] = dp[i][j]\n\t\t\t} else {\n\t\t\t\tdp[i+1][j] = Max(dp[i][j-weights[i]]+values[i], dp[i][j])\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[n][m]\n}\n\n/*\nfunc main() {\n\tmaxWeight := 50\n\tvalues := []int{\n\t\t60, 100, 120,\n\t}\n\tweights := []int{\n\t\t10, 20, 30,\n\t}\n\tmaxProfit := Knapsack(maxWeight, weights, values)\n\tfmt.Println(maxProfit)\n}\n*/\n"
  },
  {
    "path": "dynamic/knapsack_test.go",
    "content": "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.T) {\n\ttd := []struct {\n\t\tmaxWeight int\n\t\tweights   []int\n\t\tvalues    []int\n\t\texpected  int\n\t}{\n\t\t{0, []int{0}, []int{0}, 0},\n\t\t{10, []int{1, 2, 3}, []int{1, 1, 1}, 3},                              // picks all\n\t\t{10, []int{1, 2, 3, 4, 5, 6}, []int{1, 1, 1, 1, 1, 1}, 4},            // picks 1,2,3,4\n\t\t{10, []int{1, 2, 3, 4, 5, 6}, []int{1, 1, 1, 1, 1, 5}, 7},            // picks 1,3,6\n\t\t{10, []int{1, 2, 3, 4, 5, 6}, []int{-1, 10, -3, -4, 10, 1}, 20},      // picks 2,5\n\t\t{10, []int{1, 2, 3, 4, 5, 6}, []int{-10, -10, -10, -10, 10, 10}, 10}, // picks 5 or 6\n\t}\n\tfor _, tc := range td {\n\t\tname := fmt.Sprintf(\"Knapsack problem with (maxWeight: %d, weights: %v, values: %v)\", tc.maxWeight, tc.weights, tc.values)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tactual := dynamic.Knapsack(tc.maxWeight, tc.weights, tc.values)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"expecting knapsack with (maxWeight: %d, weights: %v, values: %v) to return %d but got %d\", tc.maxWeight, tc.weights, tc.values, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc ExampleKnapsack() {\n\tfmt.Print(dynamic.Knapsack(10, []int{4, 5, 8}, []int{50, 15, 60}))\n\t//Output:65\n}\n"
  },
  {
    "path": "dynamic/longestarithmeticsubsequence.go",
    "content": "// longestarithmeticsubsequence.go\n// description: Implementation of the Longest Arithmetic Subsequence problem\n// reference: https://en.wikipedia.org/wiki/Longest_arithmetic_progression\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n\npackage dynamic\n\n// LongestArithmeticSubsequence returns the length of the longest arithmetic subsequence\nfunc LongestArithmeticSubsequence(nums []int) int {\n\tn := len(nums)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\n\tdp := make([]map[int]int, n)\n\tfor i := range dp {\n\t\tdp[i] = make(map[int]int)\n\t}\n\n\tmaxLength := 1\n\n\tfor i := 1; i < n; i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tdiff := nums[i] - nums[j]\n\t\t\tdp[i][diff] = dp[j][diff] + 1\n\t\t\tif dp[i][diff]+1 > maxLength {\n\t\t\t\tmaxLength = dp[i][diff] + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn maxLength\n}\n"
  },
  {
    "path": "dynamic/longestarithmeticsubsequence_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLongestArithmeticSubsequence struct {\n\tnums     []int\n\texpected int\n}\n\nfunc getLongestArithmeticSubsequenceTestCases() []testCaseLongestArithmeticSubsequence {\n\treturn []testCaseLongestArithmeticSubsequence{\n\t\t{[]int{3, 6, 9, 12}, 4},                  // Arithmetic sequence of length 4\n\t\t{[]int{9, 4, 7, 2, 10}, 3},               // Arithmetic sequence of length 3\n\t\t{[]int{20, 1, 15, 3, 10, 5, 8}, 4},       // Arithmetic sequence of length 4\n\t\t{[]int{1, 2, 3, 4, 5}, 5},                // Arithmetic sequence of length 5\n\t\t{[]int{10, 7, 4, 1}, 4},                  // Arithmetic sequence of length 4\n\t\t{[]int{1, 5, 7, 8, 5, 3, 4, 3, 1, 2}, 4}, // Arithmetic sequence of length 4\n\t\t{[]int{1, 3, 5, 7, 9}, 5},                // Arithmetic sequence of length 5\n\t\t{[]int{5, 10, 15, 20}, 4},                // Arithmetic sequence of length 4\n\t\t{[]int{1}, 1},                            // Single element, length is 1\n\t\t{[]int{}, 0},                             // Empty array, length is 0\n\t}\n}\n\nfunc TestLongestArithmeticSubsequence(t *testing.T) {\n\tt.Run(\"Longest Arithmetic Subsequence test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getLongestArithmeticSubsequenceTestCases() {\n\t\t\tactual := dynamic.LongestArithmeticSubsequence(tc.nums)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"LongestArithmeticSubsequence(%v) = %v; expected %v\", tc.nums, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/longestcommonsubsequence.go",
    "content": "// LONGEST COMMON SUBSEQUENCE\n// DP - 4\n// https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/\n// https://leetcode.com/problems/longest-common-subsequence/\n// time complexity: O(m*n) where m and n are lengths of the strings\n// space complexity: O(m*n) where m and n are lengths of the strings\n\npackage dynamic\n\nfunc strToRuneSlice(s string) (r []rune, size int) {\n\tr = []rune(s)\n\treturn r, len(r)\n}\n\n// LongestCommonSubsequence function\nfunc LongestCommonSubsequence(a string, b string) int {\n\taRunes, aLen := strToRuneSlice(a)\n\tbRunes, bLen := strToRuneSlice(b)\n\n\t// here we are making a 2d slice of size (aLen+1)*(bLen+1)\n\tlcs := make([][]int, aLen+1)\n\tfor i := 0; i <= aLen; i++ {\n\t\tlcs[i] = make([]int, bLen+1)\n\t}\n\n\t// block that implements LCS\n\tfor i := 0; i <= aLen; i++ {\n\t\tfor j := 0; j <= bLen; j++ {\n\t\t\tif i == 0 || j == 0 {\n\t\t\t\tlcs[i][j] = 0\n\t\t\t} else if aRunes[i-1] == bRunes[j-1] {\n\t\t\t\tlcs[i][j] = lcs[i-1][j-1] + 1\n\t\t\t} else {\n\t\t\t\tlcs[i][j] = Max(lcs[i-1][j], lcs[i][j-1])\n\t\t\t}\n\t\t}\n\t}\n\t// returning the length of longest common subsequence\n\treturn lcs[aLen][bLen]\n}\n"
  },
  {
    "path": "dynamic/longestcommonsubsequence_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLCS struct {\n\tstringA  string\n\tstringB  string\n\texpected int\n}\n\nfunc getLCSTestCases() []testCaseLCS {\n\treturn []testCaseLCS{\n\t\t{\"ABCDGH\", \"AEDFHR\", 3},\n\t\t{\"AGGTAB\", \"GXTXAYB\", 4},\n\t\t{\"programming\", \"gaming\", 6},\n\t\t{\"physics\", \"smartphone\", 2},\n\t\t{\"computer\", \"food\", 1},\n\t\t{\"123\", \"12345\", 3},\n\t\t{\"XYZ\", \"XYZ\", 3},\n\t\t{\"XYZ\", \"XYZa\", 3},\n\t\t{\"XYZ\", \"aXYZ\", 3},\n\t\t{\"0123\", \"abc\", 0},\n\t\t{\"abcdef\", \"aXbXcXXXdeXXf\", 6},\n\t\t{\"\", \"abc\", 0},\n\t\t{\"\", \"\", 0},\n\t\t{\"££\", \"££\", 2},\n\t\t{\"x笑x笑\", \"aaa笑a笑\", 2},\n\t\t{\"xYxY\", \"aaaYaY\", 2},\n\t}\n}\n\nfunc TestLongestCommonSubsequence(t *testing.T) {\n\tt.Run(\"Simple test\", func(t *testing.T) {\n\t\tfor _, tc := range getLCSTestCases() {\n\t\t\tactual := dynamic.LongestCommonSubsequence(tc.stringA, tc.stringB)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"expected: %d, but got: %d\", tc.expected, actual)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Symmetry test\", func(t *testing.T) {\n\t\tfor _, tc := range getLCSTestCases() {\n\t\t\tactual := dynamic.LongestCommonSubsequence(tc.stringB, tc.stringA)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"expected: %d, but got: %d\", tc.expected, actual)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/longestincreasingsubsequence.go",
    "content": "// longestincreasingsubsequence.go\n// description: Implementation of the Longest Increasing Subsequence using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Longest_increasing_subsequence\n// time complexity: O(n^2)\n// space complexity: O(n)\n\npackage dynamic\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/max\"\n)\n\n// LongestIncreasingSubsequence returns the longest increasing subsequence\n// where all elements of the subsequence are sorted in increasing order\nfunc LongestIncreasingSubsequence(elements []int) int {\n\tn := len(elements)\n\tlis := make([]int, n)\n\tfor i := range lis {\n\t\tlis[i] = 1\n\t}\n\tfor i := range lis {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif elements[i] > elements[j] && lis[i] < lis[j]+1 {\n\t\t\t\tlis[i] = lis[j] + 1\n\t\t\t}\n\t\t}\n\t}\n\tres := 0\n\tfor _, value := range lis {\n\t\tres = max.Int(res, value)\n\t}\n\treturn res\n}\n"
  },
  {
    "path": "dynamic/longestincreasingsubsequence_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc longestIncreasingSubsequenceTest(t *testing.T, algorithm func(nums []int) int) {\n\ttd := []struct {\n\t\telements    []int\n\t\texpectedLen int\n\t}{\n\t\t{[]int{1, 2, 3, 4, 5, 10}, 6},\n\t\t{[]int{1, 7, 3, 4, 5}, 4}, // 1,3,4,5\n\t\t{[]int{1, 3, 5}, 3},\n\t\t{[]int{7, 1, 6}, 2},\n\t\t{[]int{4, 1, 6, 2}, 2},\n\t\t{[]int{11, 9, 6}, 1},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(fmt.Sprint(\"test with\", tc.elements), func(t *testing.T) {\n\t\t\tactualLen := algorithm(tc.elements)\n\t\t\tif tc.expectedLen != actualLen {\n\t\t\t\tt.Fatalf(\"expecting a sequence of len %d to be found but the actual len was %d; input: %v\", tc.expectedLen, actualLen, tc.elements)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLongestIncreasingSubsequence(t *testing.T) {\n\tlongestIncreasingSubsequenceTest(t, dynamic.LongestIncreasingSubsequence)\n}\n\nfunc TestLongestIncreasingSubsequenceGreedy(t *testing.T) {\n\tlongestIncreasingSubsequenceTest(t, dynamic.LongestIncreasingSubsequenceGreedy)\n}\n"
  },
  {
    "path": "dynamic/longestincreasingsubsequencegreedy.go",
    "content": "package dynamic\n\n// LongestIncreasingSubsequenceGreedy is a function to find the longest increasing\n// subsequence in a given array using a greedy approach.\n// The dynamic programming approach is implemented alongside this one.\n// Worst Case Time Complexity: O(nlogn)\n// Auxiliary Space: O(n), where n is the length of the array(slice).\n// Reference: https://www.geeksforgeeks.org/construction-of-longest-monotonically-increasing-subsequence-n-log-n/\nfunc LongestIncreasingSubsequenceGreedy(nums []int) int {\n\tlongestIncreasingSubsequence := make([]int, 0)\n\n\tfor _, num := range nums {\n\t\t// find the leftmost index in longestIncreasingSubsequence with value >= num\n\t\tleftmostIndex := lowerBound(longestIncreasingSubsequence, num)\n\n\t\tif leftmostIndex == len(longestIncreasingSubsequence) {\n\t\t\tlongestIncreasingSubsequence = append(longestIncreasingSubsequence, num)\n\t\t} else {\n\t\t\tlongestIncreasingSubsequence[leftmostIndex] = num\n\t\t}\n\t}\n\n\treturn len(longestIncreasingSubsequence)\n}\n\n// Function to find the leftmost index in arr with value >= val, mimicking the inbuild lower_bound function in C++\n// Time Complexity: O(logn)\n// Auxiliary Space: O(1)\nfunc lowerBound(arr []int, val int) int {\n\tsearchWindowLeft, searchWindowRight := 0, len(arr)-1\n\n\tfor searchWindowLeft <= searchWindowRight {\n\t\tmiddle := (searchWindowLeft + searchWindowRight) / 2\n\n\t\tif arr[middle] < val {\n\t\t\tsearchWindowLeft = middle + 1\n\t\t} else {\n\t\t\tsearchWindowRight = middle - 1\n\t\t}\n\t}\n\n\treturn searchWindowRight + 1\n}\n"
  },
  {
    "path": "dynamic/longestpalindromicsubsequence.go",
    "content": "// longest palindromic subsequence\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n// http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/\n\npackage dynamic\n\nfunc lpsRec(word string, i, j int) int {\n\tif i == j {\n\t\treturn 1\n\t}\n\tif i > j {\n\t\treturn 0\n\t}\n\tif word[i] == word[j] {\n\t\treturn 2 + lpsRec(word, i+1, j-1)\n\t}\n\treturn Max(lpsRec(word, i, j-1), lpsRec(word, i+1, j))\n}\n\n// LpsRec function\nfunc LpsRec(word string) int {\n\treturn lpsRec(word, 0, len(word)-1)\n}\n\n// LpsDp function\nfunc LpsDp(word string) int {\n\tN := len(word)\n\tdp := make([][]int, N)\n\n\tfor i := 0; i < N; i++ {\n\t\tdp[i] = make([]int, N)\n\t\tdp[i][i] = 1\n\t}\n\n\tfor l := 2; l <= N; l++ {\n\t\t// for length l\n\t\tfor i := 0; i < N-l+1; i++ {\n\t\t\tj := i + l - 1\n\t\t\tif word[i] == word[j] {\n\t\t\t\tif l == 2 {\n\t\t\t\t\tdp[i][j] = 2\n\t\t\t\t} else {\n\t\t\t\t\tdp[i][j] = 2 + dp[i+1][j-1]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdp[i][j] = Max(dp[i+1][j], dp[i][j-1])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[0][N-1]\n}\n"
  },
  {
    "path": "dynamic/longestpalindromicsubsequence_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc lpsTestTemplate(t *testing.T, algorithm func(input string) int) {\n\ttestCases := []struct {\n\t\tinput    string\n\t\texpected int\n\t}{\n\t\t{\"BBABCBCAB\", 7},\n\t\t{\"BBBAB\", 4},\n\t\t{\"ABBD\", 2},\n\t\t{\"GEEKSFORGEEKS\", 5},\n\t\t{\"abcdefgh\", 1},\n\t\t{\"bbbab\", 4},\n\t\t{\"cbbd\", 2},\n\t\t{\"racexyzcxar\", 7},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(fmt.Sprint(\"test with \", tc.input), func(t *testing.T) {\n\t\t\tresult := algorithm(tc.input)\n\t\t\tif tc.expected != result {\n\t\t\t\tt.Fatalf(\"expected %d, got %d\", tc.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLpsRec(t *testing.T) {\n\tlpsTestTemplate(t, dynamic.LpsRec)\n}\n\nfunc TestLpsDp(t *testing.T) {\n\tlpsTestTemplate(t, dynamic.LpsDp)\n}\n"
  },
  {
    "path": "dynamic/longestpalindromicsubstring.go",
    "content": "// longestpalindromicsubstring.go\n// description: Implementation of finding the longest palindromic substring\n// reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n\npackage dynamic\n\n// LongestPalindromicSubstring returns the longest palindromic substring in the input string\nfunc LongestPalindromicSubstring(s string) string {\n\tn := len(s)\n\tif n == 0 {\n\t\treturn \"\"\n\t}\n\n\tdp := make([][]bool, n)\n\tfor i := range dp {\n\t\tdp[i] = make([]bool, n)\n\t}\n\n\tstart := 0\n\tmaxLength := 1\n\tfor i := 0; i < n; i++ {\n\t\tdp[i][i] = true\n\t}\n\n\tfor length := 2; length <= n; length++ {\n\t\tfor i := 0; i < n-length+1; i++ {\n\t\t\tj := i + length - 1\n\t\t\tif length == 2 {\n\t\t\t\tdp[i][j] = (s[i] == s[j])\n\t\t\t} else {\n\t\t\t\tdp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]\n\t\t\t}\n\n\t\t\tif dp[i][j] && length > maxLength {\n\t\t\t\tmaxLength = length\n\t\t\t\tstart = i\n\t\t\t}\n\t\t}\n\t}\n\treturn s[start : start+maxLength]\n}\n"
  },
  {
    "path": "dynamic/longestpalindromicsubstring_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseLongestPalindromicSubstring struct {\n\ts        string\n\texpected string\n}\n\nfunc getLongestPalindromicSubstringTestCases() []testCaseLongestPalindromicSubstring {\n\treturn []testCaseLongestPalindromicSubstring{\n\t\t{\"babad\", \"bab\"},                   // Example with multiple palindromes\n\t\t{\"cbbd\", \"bb\"},                     // Example with longest even palindrome\n\t\t{\"a\", \"a\"},                         // Single character, palindrome is itself\n\t\t{\"\", \"\"},                           // Empty string, no palindrome\n\t\t{\"racecar\", \"racecar\"},             // Whole string is a palindrome\n\t\t{\"abcba\", \"abcba\"},                 // Palindrome in the middle\n\t\t{\"aabbcc\", \"aa\"},                   // Multiple substrings, longest \"aa\"\n\t\t{\"madam\", \"madam\"},                 // Full palindrome string\n\t\t{\"forgeeksskeegfor\", \"geeksskeeg\"}, // Complex palindrome in the middle\n\t}\n}\n\nfunc TestLongestPalindromicSubstring(t *testing.T) {\n\tt.Run(\"Longest Palindromic Substring test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getLongestPalindromicSubstringTestCases() {\n\t\t\tactual := dynamic.LongestPalindromicSubstring(tc.s)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"LongestPalindromicSubstring(%q) = %q; expected %q\", tc.s, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/matrixmultiplication.go",
    "content": "// matrix chain multiplication problem\n// https://en.wikipedia.org/wiki/Matrix_chain_multiplication\n// www.geeksforgeeks.org/dynamic_programming-set-8-matrix-chain-multiplication/\n// time complexity: O(n^3)\n// space complexity: O(n^2)\n\npackage dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// MatrixChainRec function\nfunc MatrixChainRec(D []int, i, j int) int {\n\t// d[i-1] x d[i] : dimension of matrix i\n\tif i == j {\n\t\treturn 0\n\t}\n\tq := 1 << 32\n\tfor k := i; k < j; k++ {\n\t\tprod := MatrixChainRec(D, i, k) + MatrixChainRec(D, k+1, j) + D[i-1]*D[k]*D[j]\n\t\tq = min.Int(prod, q)\n\t}\n\treturn q\n}\n\n// MatrixChainDp function\nfunc MatrixChainDp(D []int) int {\n\t// d[i-1] x d[i] : dimension of matrix i\n\tN := len(D)\n\n\tdp := make([][]int, N) // dp[i][j] = matrixChainRec(D, i, j)\n\tfor i := 0; i < N; i++ {\n\t\tdp[i] = make([]int, N)\n\t\tdp[i][i] = 0\n\t}\n\n\tfor l := 2; l < N; l++ {\n\t\tfor i := 1; i < N-l+1; i++ {\n\t\t\tj := i + l - 1\n\t\t\tdp[i][j] = 1 << 31\n\t\t\tfor k := i; k < j; k++ {\n\t\t\t\tprod := dp[i][k] + dp[k+1][j] + D[i-1]*D[k]*D[j]\n\t\t\t\tdp[i][j] = min.Int(prod, dp[i][j])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[1][N-1]\n}\n\n/*\nfunc main() {\n\tD := []int{2, 2, 2, 2, 2} // 4 matrices\n\tfmt.Print(matrixChainRec(D, 1, 4), \"\\n\")\n\tfmt.Print(matrixChainDp(D), \"\\n\")\n}\n*/\n"
  },
  {
    "path": "dynamic/maxsubarraysum.go",
    "content": "// maxsubarraysum.go\n// description: Implementation of Kadane's algorithm for Maximum Subarray Sum\n// reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem\n// time complexity: O(n)\n// space complexity: O(1)\n\npackage dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/max\"\n\n// MaxSubArraySum returns the sum of the maximum subarray in the input array\nfunc MaxSubArraySum(nums []int) int {\n\tmaxSum := nums[0]\n\tcurrentSum := nums[0]\n\n\tfor i := 1; i < len(nums); i++ {\n\t\tcurrentSum = max.Int(nums[i], currentSum+nums[i])\n\t\tmaxSum = max.Int(maxSum, currentSum)\n\t}\n\n\treturn maxSum\n}\n"
  },
  {
    "path": "dynamic/maxsubarraysum_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseMaxSubArraySum struct {\n\tnums     []int\n\texpected int\n}\n\nfunc getMaxSubArraySumTestCases() []testCaseMaxSubArraySum {\n\treturn []testCaseMaxSubArraySum{\n\t\t{[]int{-2, -3, 4, -1, -2, 1, 5, -3}, 7},   // Kadane's algorithm example\n\t\t{[]int{-1, -2, -3, -4}, -1},               // All negative numbers, max single element\n\t\t{[]int{5, 4, -1, 7, 8}, 23},               // Positive numbers with a large sum\n\t\t{[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, 6}, // Mixed with a maximum subarray of length 4\n\t\t{[]int{1, 2, 3, 4, 5}, 15},                // All positive numbers, sum is the entire array\n\t\t{[]int{-1, -2, -3, -4, -5}, -1},           // Only negative numbers, largest single element\n\t\t{[]int{0, 0, 0, 0, 0}, 0},                 // Array of zeros, maximum subarray is zero\n\t\t{[]int{3}, 3},                             // Single positive number\n\t\t{[]int{-1}, -1},                           // Single negative number\n\t}\n}\n\nfunc TestMaxSubArraySum(t *testing.T) {\n\tt.Run(\"Max SubArray Sum test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getMaxSubArraySumTestCases() {\n\t\t\tactual := dynamic.MaxSubArraySum(tc.nums)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"MaxSubArraySum(%v) = %v; expected %v\", tc.nums, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/optimalbst.go",
    "content": "package dynamic\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// OptimalBST returns the minimum cost of constructing a Binary Search Tree\nfunc OptimalBST(keys []int, freq []int, n int) int {\n\t// Initialize DP table with size n x n\n\tdp := make([][]int, n)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, n)\n\t}\n\n\t// Base case: single key cost\n\tfor i := 0; i < n; i++ {\n\t\tdp[i][i] = freq[i]\n\t}\n\n\t// Build the DP table for sequences of length 2 to n\n\tfor length := 2; length <= n; length++ {\n\t\tfor i := 0; i < n-length+1; i++ {\n\t\t\tj := i + length - 1\n\t\t\tdp[i][j] = int(^uint(0) >> 1) // Initialize with a large value\n\t\t\tsum := sum(freq, i, j)\n\n\t\t\t// Try every key as root and compute cost\n\t\t\tfor k := i; k <= j; k++ {\n\t\t\t\t// Left cost: dp[i][k-1] is valid only if k > i\n\t\t\t\tvar leftCost int\n\t\t\t\tif k > i {\n\t\t\t\t\tleftCost = dp[i][k-1]\n\t\t\t\t} else {\n\t\t\t\t\tleftCost = 0\n\t\t\t\t}\n\n\t\t\t\t// Right cost: dp[k+1][j] is valid only if k < j\n\t\t\t\tvar rightCost int\n\t\t\t\tif k < j {\n\t\t\t\t\trightCost = dp[k+1][j]\n\t\t\t\t} else {\n\t\t\t\t\trightCost = 0\n\t\t\t\t}\n\n\t\t\t\t// Total cost for root k\n\t\t\t\tcost := sum + leftCost + rightCost\n\n\t\t\t\t// Update dp[i][j] with the minimum cost\n\t\t\t\tdp[i][j] = min.Int(dp[i][j], cost)\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[0][n-1]\n}\n\n// Helper function to sum the frequencies\nfunc sum(freq []int, i, j int) int {\n\ttotal := 0\n\tfor k := i; k <= j; k++ {\n\t\ttotal += freq[k]\n\t}\n\treturn total\n}\n"
  },
  {
    "path": "dynamic/optimalbst_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseOptimalBST struct {\n\tkeys     []int\n\tfreq     []int\n\tn        int\n\texpected int\n}\n\nfunc getOptimalBSTTestCases() []testCaseOptimalBST {\n\treturn []testCaseOptimalBST{\n\t\t{[]int{10, 12, 20}, []int{34, 8, 50}, 3, 142},                  // Example with 3 keys\n\t\t{[]int{10, 20, 30, 40, 50}, []int{10, 20, 30, 40, 50}, 5, 300}, // Example with 5 keys\n\t\t{[]int{10}, []int{100}, 1, 100},                                // Single key case\n\t}\n}\n\nfunc TestOptimalBST(t *testing.T) {\n\tt.Run(\"Optimal Binary Search Tree test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getOptimalBSTTestCases() {\n\t\t\tt.Run(\"testing optimal BST\", func(t *testing.T) {\n\t\t\t\tactual := dynamic.OptimalBST(tc.keys, tc.freq, tc.n)\n\t\t\t\tif actual != tc.expected {\n\t\t\t\t\tt.Errorf(\"OptimalBST(%v, %v, %d) = %d; expected %d\", tc.keys, tc.freq, tc.n, actual, tc.expected)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/partitionproblem.go",
    "content": "// partitionproblem.go\n// description: Solves the Partition Problem using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Partition_problem\n// time complexity: O(n*sum)\n// space complexity: O(n*sum)\n\npackage dynamic\n\n// PartitionProblem checks whether the given set can be partitioned into two subsets\n// such that the sum of the elements in both subsets is the same.\nfunc PartitionProblem(nums []int) bool {\n\tsum := 0\n\tfor _, num := range nums {\n\t\tsum += num\n\t}\n\tif sum%2 != 0 {\n\t\treturn false\n\t}\n\n\ttarget := sum / 2\n\tdp := make([]bool, target+1)\n\tdp[0] = true\n\n\tfor _, num := range nums {\n\t\tfor i := target; i >= num; i-- {\n\t\t\tdp[i] = dp[i] || dp[i-num]\n\t\t}\n\t}\n\treturn dp[target]\n}\n"
  },
  {
    "path": "dynamic/partitionproblem_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\n// testCasePartitionProblem holds the test cases for the Partition Problem\ntype testCasePartitionProblem struct {\n\tnums     []int\n\texpected bool\n}\n\n// getPartitionProblemTestCases returns a list of test cases for the Partition Problem\nfunc getPartitionProblemTestCases() []testCasePartitionProblem {\n\treturn []testCasePartitionProblem{\n\t\t{[]int{1, 5, 11, 5}, true},    // Example with a partitionable set\n\t\t{[]int{1, 2, 3, 5}, false},    // Example where partition is not possible\n\t\t{[]int{1, 2, 5}, false},       // Set cannot be partitioned into two subsets\n\t\t{[]int{2, 2, 2, 2}, true},     // Even split possible with equal elements\n\t\t{[]int{7, 3, 2, 1}, false},    // Set cannot be partitioned\n\t\t{[]int{}, true},               // Empty set, can be partitioned trivially\n\t\t{[]int{1}, false},             // Single element, cannot be partitioned\n\t\t{[]int{10, 10, 10, 10}, true}, // Equal elements, partitionable\n\t}\n}\n\n// TestPartitionProblem tests the PartitionProblem function with different test cases\nfunc TestPartitionProblem(t *testing.T) {\n\tt.Run(\"Partition Problem test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getPartitionProblemTestCases() {\n\t\t\tactual := dynamic.PartitionProblem(tc.nums)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"PartitionProblem(%v) = %v; expected %v\", tc.nums, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/rodcutting.go",
    "content": "// Solution to Rod cutting problem\n// https://en.wikipedia.org/wiki/Cutting_stock_problem\n// http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/\n// time complexity: O(n^2)\n// space complexity: O(n)\n\npackage dynamic\n\n// CutRodRec solve the problem recursively: initial approach\nfunc CutRodRec(price []int, length int) int {\n\tif length == 0 {\n\t\treturn 0\n\t}\n\n\tq := -1\n\tfor i := 1; i <= length; i++ {\n\t\tq = Max(q, price[i]+CutRodRec(price, length-i))\n\t}\n\treturn q\n}\n\n// CutRodDp solve the same problem using dynamic programming\nfunc CutRodDp(price []int, length int) int {\n\tr := make([]int, length+1) // a.k.a the memoization array\n\tr[0] = 0                   // cost of 0 length rod is 0\n\n\tfor j := 1; j <= length; j++ { // for each length (subproblem)\n\t\tq := -1\n\t\tfor i := 1; i <= j; i++ {\n\t\t\tq = Max(q, price[i]+r[j-i]) // avoiding recursive call\n\t\t}\n\t\tr[j] = q\n\t}\n\n\treturn r[length]\n}\n\n/*\nfunc main() {\n\tlength := 10\n\tprice := []int{0, 1, 5, 8, 9, 17, 17, 17, 20, 24, 30}\n\t// price := []int{0, 10, 5, 8, 9, 17, 17, 17, 20, 24, 30}\n\n\t// fmt.Print(price[5]+price[length-5], \"\\n\")\n\n\tfmt.Print(cutRodRec(price, length), \"\\n\")\n\tfmt.Print(cutRodDp(price, length), \"\\n\")\n}\n*/\n"
  },
  {
    "path": "dynamic/rodcutting_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype rodCuttingTestCase struct {\n\tprice    []int\n\tlength   int\n\texpected int\n}\n\nfunc getRodCuttingTestCases() []rodCuttingTestCase {\n\treturn []rodCuttingTestCase{\n\t\t{[]int{0, 1, 5, 8, 9}, 4, 10},\n\t\t{[]int{0, 2, 5, 7, 8, 0}, 5, 12},\n\t\t{[]int{0, 1, 5, 8, 9, 10, 17, 17, 20}, 8, 22},\n\t\t{[]int{0, 3, 5, 8, 9, 10, 17, 17, 20}, 8, 24},\n\t}\n}\n\nfunc cutRodSolTestFunc(t *testing.T, cutRodSolFunc func([]int, int) int) {\n\tfor _, tc := range getRodCuttingTestCases() {\n\t\tactual := cutRodSolFunc(tc.price, tc.length)\n\t\tif actual != tc.expected {\n\t\t\tt.Errorf(\"expected: %d, got: %d\", tc.expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestCutRodRec(t *testing.T) {\n\tcutRodSolTestFunc(t, dynamic.CutRodRec)\n}\n\nfunc TestCutRodDp(t *testing.T) {\n\tcutRodSolTestFunc(t, dynamic.CutRodDp)\n}\n"
  },
  {
    "path": "dynamic/subsetsum.go",
    "content": "//Given a set of non-negative integers, and a (positive) value sum,\n//determine if there is a subset of the given set with sum\n//equal to given sum.\n// time complexity: O(n*sum)\n// space complexity: O(n*sum)\n//references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/\n\npackage dynamic\n\nimport \"fmt\"\n\nvar ErrInvalidPosition = fmt.Errorf(\"invalid position in subset\")\nvar ErrNegativeSum = fmt.Errorf(\"negative sum is not allowed\")\n\nfunc IsSubsetSum(array []int, sum int) (bool, error) {\n\tif sum < 0 {\n\t\t//not allow negative sum\n\t\treturn false, ErrNegativeSum\n\t}\n\n\t//create subset matrix\n\tarraySize := len(array)\n\tsubset := make([][]bool, arraySize+1)\n\tfor i := 0; i <= arraySize; i++ {\n\t\tsubset[i] = make([]bool, sum+1)\n\t}\n\n\tfor i := 0; i <= arraySize; i++ {\n\t\t//sum 0 is always true\n\t\tsubset[i][0] = true\n\t}\n\n\tfor i := 1; i <= sum; i++ {\n\t\t//empty set is false when sum is not 0\n\t\tsubset[0][i] = false\n\t}\n\n\tfor i := 1; i <= arraySize; i++ {\n\t\tfor j := 1; j <= sum; j++ {\n\t\t\tif array[i-1] > j {\n\t\t\t\tsubset[i][j] = subset[i-1][j]\n\t\t\t}\n\n\t\t\tif array[i-1] <= j {\n\t\t\t\tif j-array[i-1] < 0 || j-array[i-1] > sum {\n\t\t\t\t\t//out of bounds\n\t\t\t\t\treturn false, ErrInvalidPosition\n\t\t\t\t}\n\n\t\t\t\tsubset[i][j] = subset[i-1][j] || subset[i-1][j-array[i-1]]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn subset[arraySize][sum], nil\n}\n"
  },
  {
    "path": "dynamic/subsetsum_test.go",
    "content": "package dynamic\n\nimport \"testing\"\n\nfunc TestSubsetSum(t *testing.T) {\n\n\tvar subsetSumTestData = []struct {\n\t\tdescription    string\n\t\tarray          []int\n\t\tsum            int\n\t\texpectedResult bool\n\t\texpectedError  error\n\t}{\n\t\t{\n\t\t\tdescription:    \"array of size 0 and sum 0\",\n\t\t\tarray:          []int{},\n\t\t\tsum:            0,\n\t\t\texpectedResult: true,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 0 and non-zero sum\",\n\t\t\tarray:          []int{},\n\t\t\tsum:            2,\n\t\t\texpectedResult: false,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 2 and sum 0\",\n\t\t\tarray:          []int{1, 2},\n\t\t\tsum:            0,\n\t\t\texpectedResult: true,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 5 and sum 6\",\n\t\t\tarray:          []int{1, 2, 3, 4, 5},\n\t\t\tsum:            6,\n\t\t\texpectedResult: true,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 5 and sum 7\",\n\t\t\tarray:          []int{1, 2, 3, 4, 5},\n\t\t\tsum:            7,\n\t\t\texpectedResult: true,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 5 and sum 17\",\n\t\t\tarray:          []int{1, 2, 3, 4, 5},\n\t\t\tsum:            17,\n\t\t\texpectedResult: false,\n\t\t\texpectedError:  nil,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 6 negative values and sum positive\",\n\t\t\tarray:          []int{-1, -2, -3, -4, -5, -6},\n\t\t\tsum:            1,\n\t\t\texpectedResult: false,\n\t\t\texpectedError:  ErrInvalidPosition,\n\t\t},\n\t\t{\n\t\t\tdescription:    \"array of size 6 with positive and negative values, also with a negative sum\",\n\t\t\tarray:          []int{-1, -1, 3, 4, 5, 6},\n\t\t\tsum:            -2,\n\t\t\texpectedResult: false,\n\t\t\texpectedError:  ErrNegativeSum,\n\t\t},\n\t}\n\n\tfor i := range subsetSumTestData {\n\n\t\tt.Run(subsetSumTestData[i].description, func(t *testing.T) {\n\t\t\tarray := subsetSumTestData[i].array\n\t\t\tsum := subsetSumTestData[i].sum\n\n\t\t\texpectedResult := subsetSumTestData[i].expectedResult\n\t\t\tresult, err := IsSubsetSum(array, sum)\n\t\t\texpectedError := subsetSumTestData[i].expectedError\n\n\t\t\tif err != expectedError {\n\t\t\t\tt.Logf(\"FAIL: %s\", subsetSumTestData[i].description)\n\t\t\t\tt.Fatalf(\"Expected error:%t\\nFound: %t\", expectedError, err)\n\t\t\t}\n\n\t\t\tif result != expectedResult {\n\t\t\t\tt.Logf(\"FAIL: %s\", subsetSumTestData[i].description)\n\t\t\t\tt.Fatalf(\"Expected result:%t\\nFound: %t\", expectedResult, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/tilingproblem.go",
    "content": "// tilingproblem.go\n// description: Solves the Tiling Problem using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Tiling_problem\n// time complexity: O(n)\n// space complexity: O(n)\n\npackage dynamic\n\n// TilingProblem returns the number of ways to tile a 2xN grid using 2x1 dominoes\nfunc TilingProblem(n int) int {\n\tif n <= 1 {\n\t\treturn 1\n\t}\n\tdp := make([]int, n+1)\n\tdp[0] = 1\n\tdp[1] = 1\n\n\tfor i := 2; i <= n; i++ {\n\t\tdp[i] = dp[i-1] + dp[i-2]\n\t}\n\treturn dp[n]\n}\n"
  },
  {
    "path": "dynamic/tilingproblem_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseTilingProblem struct {\n\tn        int\n\texpected int\n}\n\nfunc getTilingProblemTestCases() []testCaseTilingProblem {\n\treturn []testCaseTilingProblem{\n\t\t{1, 1},   // Base case: 1 way to tile a 2x1 grid\n\t\t{2, 2},   // 2 ways to tile a 2x2 grid\n\t\t{3, 3},   // 3 ways to tile a 2x3 grid\n\t\t{4, 5},   // 5 ways to tile a 2x4 grid\n\t\t{5, 8},   // 8 ways to tile a 2x5 grid\n\t\t{6, 13},  // 13 ways to tile a 2x6 grid\n\t\t{10, 89}, // 89 ways to tile a 2x10 grid\n\t\t{0, 1},   // Edge case: 1 way to tile a 2x0 grid (no tiles)\n\t\t{7, 21},  // 21 ways to tile a 2x7 grid\n\t\t{8, 34},  // 34 ways to tile a 2x8 grid\n\t}\n}\n\nfunc TestTilingProblem(t *testing.T) {\n\tt.Run(\"Tiling Problem test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getTilingProblemTestCases() {\n\t\t\tactual := dynamic.TilingProblem(tc.n)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"TilingProblem(%d) = %d; expected %d\", tc.n, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/traprainwater.go",
    "content": "// filename: traprainwater.go\n// description: Provides a function to calculate the amount of trapped rainwater between bars represented by an elevation map using dynamic programming.\n// details:\n// The TrapRainWater function calculates the amount of trapped rainwater between the bars represented by the given elevation map.\n// It uses dynamic programming to precompute the maximum height of bars to the left and right of each position.\n// Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights.\n// Finally, it sums up the trapped rainwater for all positions and returns the total amount.\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [TruongNhanNguyen (SOZEL)](https://github.com/TruongNhanNguyen)\npackage dynamic\n\nimport \"math\"\n\n// TrapRainWater calculates the amount of trapped rainwater between the bars represented by the given elevation map.\n// It uses dynamic programming to precompute the maximum height of bars to the left and right of each position.\n// Then, it iterates through the array to calculate the amount of trapped rainwater at each position based on the minimum of the left and right maximum heights.\n// Finally, it sums up the trapped rainwater for all positions and returns the total amount.\nfunc TrapRainWater(height []int) int {\n\tif len(height) == 0 {\n\t\treturn 0\n\t}\n\n\tleftMax := make([]int, len(height))\n\trightMax := make([]int, len(height))\n\n\tleftMax[0] = height[0]\n\tfor i := 1; i < len(height); i++ {\n\t\tleftMax[i] = int(math.Max(float64(leftMax[i-1]), float64(height[i])))\n\t}\n\n\trightMax[len(height)-1] = height[len(height)-1]\n\tfor i := len(height) - 2; i >= 0; i-- {\n\t\trightMax[i] = int(math.Max(float64(rightMax[i+1]), float64(height[i])))\n\t}\n\n\ttrappedWater := 0\n\tfor i := 0; i < len(height); i++ {\n\t\ttrappedWater += int(math.Min(float64(leftMax[i]), float64(rightMax[i]))) - height[i]\n\t}\n\n\treturn trappedWater\n}\n"
  },
  {
    "path": "dynamic/traprainwater_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\nfunc TestTrapRainWater(t *testing.T) {\n\theights := [][]int{\n\t\t{},\n\t\t{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1},\n\t\t{4, 2, 0, 3, 2, 5},\n\t\t{3, 1, 2, 4, 0, 1, 3, 2, 4},\n\t}\n\n\texpectedResults := []int{\n\t\t0,\n\t\t6,\n\t\t9,\n\t\t13,\n\t}\n\n\tfor i, height := range heights {\n\t\texpected := expectedResults[i]\n\t\tt.Run(fmt.Sprintf(\"Case %d\", i+1), func(t *testing.T) {\n\t\t\tresult := dynamic.TrapRainWater(height)\n\t\t\tif result != expected {\n\t\t\t\tt.Errorf(\"Expected %d, but got %d\", expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/uniquepaths.go",
    "content": "// See https://leetcode.com/problems/unique-paths/\n// time complexity: O(m*n) where m and n are the dimensions of the grid\n// space complexity: O(m*n) where m and n are the dimensions of the grid\n// author: Rares Mateizer (https://github.com/rares985)\npackage dynamic\n\n// UniquePaths implements the solution to the \"Unique Paths\" problem\nfunc UniquePaths(m, n int) int {\n\tif m <= 0 || n <= 0 {\n\t\treturn 0\n\t}\n\n\tgrid := make([][]int, m)\n\tfor i := range grid {\n\t\tgrid[i] = make([]int, n)\n\t}\n\n\tfor i := 0; i < m; i++ {\n\t\tgrid[i][0] = 1\n\t}\n\n\tfor j := 0; j < n; j++ {\n\t\tgrid[0][j] = 1\n\t}\n\n\tfor i := 1; i < m; i++ {\n\t\tfor j := 1; j < n; j++ {\n\t\t\tgrid[i][j] = grid[i-1][j] + grid[i][j-1]\n\t\t}\n\t}\n\n\treturn grid[m-1][n-1]\n}\n"
  },
  {
    "path": "dynamic/uniquepaths_test.go",
    "content": "package dynamic\n\nimport (\n\t\"testing\"\n)\n\nfunc TestUniquePaths(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tm    int\n\t\tn    int\n\t\twant int\n\t}{\n\t\t\"negative sizes\":               {-1, -1, 0},\n\t\t\"empty matrix both dimensions\": {0, 0, 0},\n\t\t\"empty matrix one dimension\":   {0, 1, 0},\n\t\t\"one element\":                  {1, 1, 1},\n\t\t\"small matrix\":                 {2, 2, 2},\n\t\t\"stress test\":                  {1000, 1000, 2874513998398909184},\n\t}\n\n\tfor name, test := range testCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tif got := UniquePaths(test.m, test.n); got != test.want {\n\t\t\t\tt.Errorf(\"UniquePaths(%v, %v) = %v, want %v\", test.m, test.n, got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "dynamic/wildcardmatching.go",
    "content": "// wildcardmatching.go\n// description: Solves the Wildcard Matching problem using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Wildcard_matching\n// time complexity: O(m*n)\n// space complexity: O(m*n)\n\npackage dynamic\n\n// IsMatch checks if the string `s` matches the wildcard pattern `p`\nfunc IsMatch(s, p string) bool {\n\tdp := make([][]bool, len(s)+1)\n\tfor i := range dp {\n\t\tdp[i] = make([]bool, len(p)+1)\n\t}\n\n\tdp[0][0] = true\n\tfor j := 1; j <= len(p); j++ {\n\t\tif p[j-1] == '*' {\n\t\t\tdp[0][j] = dp[0][j-1]\n\t\t}\n\t}\n\n\tfor i := 1; i <= len(s); i++ {\n\t\tfor j := 1; j <= len(p); j++ {\n\t\t\tif p[j-1] == s[i-1] || p[j-1] == '?' {\n\t\t\t\tdp[i][j] = dp[i-1][j-1]\n\t\t\t} else if p[j-1] == '*' {\n\t\t\t\tdp[i][j] = dp[i-1][j] || dp[i][j-1]\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(s)][len(p)]\n}\n"
  },
  {
    "path": "dynamic/wildcardmatching_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\n// testCaseWildcardMatching holds the test cases for the Wildcard Matching problem\ntype testCaseWildcardMatching struct {\n\ts        string\n\tp        string\n\texpected bool\n}\n\n// getWildcardMatchingTestCases returns a list of test cases for the Wildcard Matching problem\nfunc getWildcardMatchingTestCases() []testCaseWildcardMatching {\n\treturn []testCaseWildcardMatching{\n\t\t{\"aa\", \"a*\", true},     // '*' can match zero or more characters\n\t\t{\"aa\", \"a\", false},     // No match due to no wildcard\n\t\t{\"ab\", \"?*\", true},     // '?' matches any single character, '*' matches remaining\n\t\t{\"abcd\", \"a*d\", true},  // '*' matches the characters between 'a' and 'd'\n\t\t{\"abcd\", \"a*c\", false}, // No match as 'c' doesn't match the last character 'd'\n\t\t{\"abc\", \"*\", true},     // '*' matches the entire string\n\t\t{\"abc\", \"a*c\", true},   // '*' matches 'b'\n\t\t{\"abc\", \"a?c\", true},   // '?' matches 'b'\n\t\t{\"abc\", \"a?d\", false},  // '?' cannot match 'd'\n\t\t{\"\", \"\", true},         // Both strings empty, so they match\n\t\t{\"a\", \"?\", true},       // '?' matches any single character\n\t\t{\"a\", \"*\", true},       // '*' matches any number of characters, including one\n\t}\n}\n\n// TestIsMatch tests the IsMatch function with various test cases\nfunc TestIsMatch(t *testing.T) {\n\tt.Run(\"Wildcard Matching test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getWildcardMatchingTestCases() {\n\t\t\tactual := dynamic.IsMatch(tc.s, tc.p)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"IsMatch(%q, %q) = %v; expected %v\", tc.s, tc.p, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "dynamic/wordbreak.go",
    "content": "// wordbreak.go\n// description: Solves the Word Break Problem using dynamic programming\n// reference: https://en.wikipedia.org/wiki/Word_break_problem\n// time complexity: O(n^2)\n// space complexity: O(n)\n\npackage dynamic\n\n// WordBreak checks if the input string can be segmented into words from a dictionary\nfunc WordBreak(s string, wordDict []string) bool {\n\twordSet := make(map[string]bool)\n\tfor _, word := range wordDict {\n\t\twordSet[word] = true\n\t}\n\n\tdp := make([]bool, len(s)+1)\n\tdp[0] = true\n\n\tfor i := 1; i <= len(s); i++ {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif dp[j] && wordSet[s[j:i]] {\n\t\t\t\tdp[i] = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn dp[len(s)]\n}\n"
  },
  {
    "path": "dynamic/wordbreak_test.go",
    "content": "package dynamic_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n)\n\ntype testCaseWordBreak struct {\n\ts        string\n\twordDict []string\n\texpected bool\n}\n\nfunc getWordBreakTestCases() []testCaseWordBreak {\n\treturn []testCaseWordBreak{\n\t\t{\"leetcode\", []string{\"leet\", \"code\"}, true},                        // \"leetcode\" can be segmented into \"leet\" and \"code\"\n\t\t{\"applepenapple\", []string{\"apple\", \"pen\"}, true},                   // \"applepenapple\" can be segmented into \"apple\", \"pen\", \"apple\"\n\t\t{\"catsanddog\", []string{\"cats\", \"dog\", \"sand\", \"and\", \"cat\"}, true}, // \"catsanddog\" can be segmented into \"cats\", \"and\", \"dog\"\n\t\t{\"bb\", []string{\"a\", \"b\", \"bbb\", \"aaaa\", \"aaa\"}, true},              // \"bb\" can be segmented into \"b\" and \"b\"\n\t\t{\"\", []string{\"cat\", \"dog\", \"sand\", \"and\"}, true},                   // Empty string can always be segmented (empty words)\n\t\t{\"applepie\", []string{\"apple\", \"pie\"}, true},                        // \"applepie\" can be segmented into \"apple\" and \"pie\"\n\t\t{\"catsandog\", []string{\"cats\", \"dog\", \"sand\", \"and\", \"cat\"}, false}, // \"catsandog\" cannot be segmented\n\t\t{\"ilovecoding\", []string{\"i\", \"love\", \"coding\"}, true},              // \"ilovecoding\" can be segmented into \"i\", \"love\", \"coding\"\n\t\t{\"cars\", []string{\"car\", \"ca\", \"rs\"}, true},                         // \"cars\" can be segmented into \"car\" and \"s\"\n\t\t{\"pen\", []string{\"pen\", \"pencil\"}, true},                            // \"pen\" is a direct match\n\t\t{\"apple\", []string{\"orange\", \"banana\"}, false},                      // \"apple\" is not in the word dictionary\n\t}\n}\n\nfunc TestWordBreak(t *testing.T) {\n\tt.Run(\"Word Break test cases\", func(t *testing.T) {\n\t\tfor _, tc := range getWordBreakTestCases() {\n\t\t\tactual := dynamic.WordBreak(tc.s, tc.wordDict)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"WordBreak(%q, %v) = %v; expected %v\", tc.s, tc.wordDict, actual, tc.expected)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/TheAlgorithms/Go\n\ngo 1.19\n"
  },
  {
    "path": "go.sum",
    "content": ""
  },
  {
    "path": "graph/articulationpoints.go",
    "content": "// Package graph provides algorithms to analyze graph structures.\npackage graph\n\nimport \"github.com/TheAlgorithms/Go/math/min\"\n\n// apHelper stores auxiliary data used to identify articulation points in a graph.\ntype apHelper struct {\n\tisAP              []bool\n\tvisited           []bool\n\tchildCount        []int\n\tdiscoveryTime     []int\n\tearliestDiscovery []int\n}\n\n// ArticulationPoint identifies articulation points in a graph. It returns a boolean slice\n// where each element indicates whether a vertex is an articulation point.\n// Worst Case Time Complexity: O(|V| + |E|)\n// Auxiliary Space: O(|V|)\n// Reference: https://en.wikipedia.org/wiki/Biconnected_component and https://cptalks.quora.com/Cut-Vertex-Articulation-point\nfunc ArticulationPoint(graph *Graph) []bool {\n\t// Time variable to keep track of the discovery time of a vertex\n\ttime := 0\n\n\t// Initialize apHelper instance with the required data structures\n\tapHelperInstance := &apHelper{\n\t\tisAP:              make([]bool, graph.vertices),\n\t\tvisited:           make([]bool, graph.vertices),\n\t\tchildCount:        make([]int, graph.vertices),\n\t\tdiscoveryTime:     make([]int, graph.vertices),\n\t\tearliestDiscovery: make([]int, graph.vertices),\n\t}\n\n\t// Start traversal from the root (0)\n\tarticulationPointHelper(apHelperInstance, 0, -1, &time, graph)\n\n\t// Check if the root has only one child, making it non-articulate\n\tif apHelperInstance.childCount[0] == 1 {\n\t\tapHelperInstance.isAP[0] = false\n\t}\n\n\treturn apHelperInstance.isAP\n}\n\n// articulationPointHelper recursively traverses the graph using DFS and marks articulation points.\n// It updates `childCount`, `discoveryTime`, and `earliestDiscovery` slices for the given vertex.\nfunc articulationPointHelper(\n\tapHelperInstance *apHelper,\n\tvertex int,\n\tparent int,\n\ttime *int,\n\tgraph *Graph,\n) {\n\tapHelperInstance.visited[vertex] = true\n\n\t// Set discovery and earliest discovery times for the vertex\n\tapHelperInstance.discoveryTime[vertex] = *time\n\tapHelperInstance.earliestDiscovery[vertex] = *time\n\t*time++\n\n\tfor nextVertex := range graph.edges[vertex] {\n\t\tif nextVertex == parent {\n\t\t\tcontinue\n\t\t}\n\n\t\tif apHelperInstance.visited[nextVertex] {\n\t\t\t// Update the earliest discovery time to the smallest reachable discovery time\n\t\t\tapHelperInstance.earliestDiscovery[vertex] = min.Int(\n\t\t\t\tapHelperInstance.earliestDiscovery[vertex],\n\t\t\t\tapHelperInstance.discoveryTime[nextVertex],\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Increment child count and perform recursive traversal for DFS\n\t\tapHelperInstance.childCount[vertex]++\n\t\tarticulationPointHelper(apHelperInstance, nextVertex, vertex, time, graph)\n\n\t\t// Update the earliest discovery time post DFS\n\t\tapHelperInstance.earliestDiscovery[vertex] = min.Int(\n\t\t\tapHelperInstance.earliestDiscovery[vertex],\n\t\t\tapHelperInstance.earliestDiscovery[nextVertex],\n\t\t)\n\n\t\t// Mark vertex as articulation point if condition meets\n\t\tif apHelperInstance.earliestDiscovery[nextVertex] >= apHelperInstance.discoveryTime[vertex] {\n\t\t\tapHelperInstance.isAP[vertex] = true\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "graph/articulationpoints_test.go",
    "content": "package graph\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestArticulationPoints(t *testing.T) {\n\tvar testCases = []struct {\n\t\tdescription string\n\t\tgraph       Graph\n\t\texpected    []bool\n\t}{\n\t\t{\n\t\t\t\"Linear tree structure\",\n\t\t\tGraph{\n\t\t\t\tvertices: 5,\n\t\t\t\tedges: map[int]map[int]int{\n\t\t\t\t\t0: {\n\t\t\t\t\t\t1: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t1: {\n\t\t\t\t\t\t0: 0,\n\t\t\t\t\t\t2: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t2: {\n\t\t\t\t\t\t1: 0,\n\t\t\t\t\t\t3: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t3: {\n\t\t\t\t\t\t2: 0,\n\t\t\t\t\t\t4: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t[]bool{false, true, true, true, false},\n\t\t}, {\n\t\t\t\"A complete graph\",\n\t\t\tGraph{\n\t\t\t\tvertices: 4,\n\t\t\t\tedges: map[int]map[int]int{\n\t\t\t\t\t0: {\n\t\t\t\t\t\t1: 0,\n\t\t\t\t\t\t2: 0,\n\t\t\t\t\t\t3: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t1: {\n\t\t\t\t\t\t0: 0,\n\t\t\t\t\t\t2: 0,\n\t\t\t\t\t\t3: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t2: {\n\t\t\t\t\t\t0: 0,\n\t\t\t\t\t\t1: 0,\n\t\t\t\t\t\t3: 0,\n\t\t\t\t\t},\n\n\t\t\t\t\t3: {\n\t\t\t\t\t\t0: 0,\n\t\t\t\t\t\t1: 0,\n\t\t\t\t\t\t2: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t[]bool{false, false, false, false},\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tis_ap := ArticulationPoint(&test.graph)\n\t\t\tif !reflect.DeepEqual(is_ap, test.expected) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/bellmanford.go",
    "content": "// The Bellman–Ford algorithm is an algorithm that computes shortest paths from a\n// single source vertex to all of the other vertices in a weighted directed graph.\n// It is slower than Dijkstra but capable of handling negative edge weights.\n// https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm\n// Implementation is based on the book 'Introduction to Algorithms' (CLRS)\n// time complexity: O(V*E) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n\npackage graph\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nfunc (g *Graph) BellmanFord(start, end int) (isReachable bool, distance int, err error) {\n\tINF := math.Inf(1)\n\tdistances := make([]float64, g.vertices)\n\n\t// Set all vertices to unreachable, initialize source\n\tfor i := 0; i < g.vertices; i++ {\n\t\tdistances[i] = INF\n\t}\n\tdistances[start] = 0\n\n\t// Making iterations equal to #vertices\n\tfor n := 0; n < g.vertices; n++ {\n\n\t\t// Looping over all edges\n\t\tfor u, adjacents := range g.edges {\n\t\t\tfor v, weightUV := range adjacents {\n\n\t\t\t\t// If new shorter distance is found, update distance value (relaxation step)\n\t\t\t\tif newDistance := distances[u] + float64(weightUV); distances[v] > newDistance {\n\t\t\t\t\tdistances[v] = newDistance\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for negative weight cycle\n\tfor u, adjacents := range g.edges {\n\t\tfor v, weightUV := range adjacents {\n\t\t\tif newDistance := distances[u] + float64(weightUV); distances[v] > newDistance {\n\t\t\t\treturn false, -1, errors.New(\"negative weight cycle present\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distances[end] != INF, int(distances[end]), nil\n}\n"
  },
  {
    "path": "graph/bellmanford_test.go",
    "content": "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 = []struct {\n\t\tname        string\n\t\tedges       [][]int\n\t\tvertices    int\n\t\tstart       int\n\t\tend         int\n\t\tisReachable bool\n\t\tdistance    int\n\t\terr         error\n\t}{\n\t\t{\n\t\t\t\"single edge\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1},\n\t\t\t},\n\t\t\t2, 0, 1, true, 1, nil,\n\t\t},\n\t\t{\n\t\t\t\"negative weights\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1},\n\t\t\t\t{1, 2, -3},\n\t\t\t\t{2, 1, 4},\n\t\t\t\t{2, 3, 1},\n\t\t\t},\n\t\t\t4, 0, 1, true, 1, nil,\n\t\t},\n\t\t{\n\t\t\t\"negative cycle\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1},\n\t\t\t\t{1, 2, -3},\n\t\t\t\t{2, 1, 1},\n\t\t\t\t{2, 3, 1},\n\t\t\t},\n\t\t\t4, 0, 1, false, -1, errors.New(\"negative weight cycle present\"),\n\t\t},\n\t\t{\n\t\t\t\"unreachable vertex\",\n\t\t\t[][]int{\n\t\t\t\t{0, 6, 771},\n\t\t\t\t{0, 9, 782},\n\t\t\t\t{1, 2, 454},\n\t\t\t\t{2, 8, 48},\n\t\t\t\t{3, 8, 249},\n\t\t\t\t{3, 9, 880},\n\t\t\t\t{3, 5, 280},\n\t\t\t\t{7, 1, 92},\n\t\t\t\t{7, 2, 497},\n\t\t\t\t{8, 1, 102},\n\t\t\t\t{8, 4, 977},\n\t\t\t},\n\t\t\t10, 8, 3, false, int(math.Inf(1)), nil,\n\t\t},\n\t\t{\n\t\t\t\"disconnected graph\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 10},\n\t\t\t\t{2, 3, 15},\n\t\t\t\t{3, 5, 10},\n\t\t\t},\n\t\t\t6, 0, 3, false, int(math.Inf(1)), nil,\n\t\t},\n\t\t{\n\t\t\t\"multiple paths\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 5},\n\t\t\t\t{1, 2, 10},\n\t\t\t\t{1, 3, 30},\n\t\t\t\t{2, 4, 10},\n\t\t\t\t{4, 5, 15},\n\t\t\t\t{3, 5, 10},\n\t\t\t},\n\t\t\t6, 0, 5, true, 40, nil,\n\t\t},\n\t\t{\n\t\t\t\"random 1\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 10},\n\t\t\t\t{1, 2, 10},\n\t\t\t\t{0, 2, 100},\n\t\t\t\t{2, 0, -10},\n\t\t\t\t{1, 2, 1},\n\t\t\t},\n\t\t\t3, 0, 1, true, 10, nil,\n\t\t},\n\t\t{\n\t\t\t\"random 2\",\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 5498},\n\t\t\t\t{2, 0, 7679},\n\t\t\t\t{0, 3, 4999},\n\t\t\t\t{1, 2, 8629},\n\t\t\t\t{1, 3, -948},\n\t\t\t\t{2, 3, 6231},\n\t\t\t},\n\t\t\t4, 0, 3, true, 4550, nil,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(fmt.Sprint(test.name), func(t *testing.T) {\n\t\t\t// Initializing graph, adding edges\n\t\t\tgraph := New(test.vertices)\n\t\t\tgraph.Directed = true\n\t\t\tfor _, edge := range test.edges {\n\t\t\t\tgraph.AddWeightedEdge(edge[0], edge[1], edge[2])\n\t\t\t}\n\n\t\t\tresIsReachable, resDistance, resError := graph.BellmanFord(test.start, test.end)\n\t\t\tif resDistance != test.distance {\n\t\t\t\tt.Errorf(\"Distance, Expected: %d, Computed: %d\", test.distance, resDistance)\n\t\t\t}\n\t\t\tif resIsReachable != test.isReachable {\n\t\t\t\tt.Errorf(\"Reachable, Expected: %t, Computed: %t\", test.isReachable, resIsReachable)\n\t\t\t}\n\t\t\tif !errors.Is(test.err, resError) {\n\t\t\t\tif resError == nil || test.err == nil {\n\t\t\t\t\tt.Errorf(\"Reachable, Expected: %s, Computed: %s\", test.err, resError)\n\t\t\t\t} else if resError.Error() != test.err.Error() {\n\t\t\t\t\tt.Errorf(\"Reachable, Expected: %s, Computed: %s\", test.err.Error(), resError.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/breadthfirstsearch.go",
    "content": "package graph\n\n// BreadthFirstSearch is an algorithm for traversing and searching graph data structures.\n// It starts at an arbitrary node of a graph, and explores all of the neighbor nodes\n// at the present depth prior to moving on to the nodes at the next depth level.\n// Worst-case performance\t \t\tO(|V|+|E|)=O(b^{d})}O(|V|+|E|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node.\n// Worst-case space complexity\t \tO(|V|)=O(b^{d})}O(|V|)=O(b^{d}) where |V| is the number of vertices and |E| is the number of edges in the graph and b is the branching factor of the graph (the average number of successors of a node). d is the depth of the goal node.\n// reference: https://en.wikipedia.org/wiki/Breadth-first_search\nfunc BreadthFirstSearch(start, end, nodes int, edges [][]int) (isConnected bool, distance int) {\n\tqueue := make([]int, 0)\n\tdiscovered := make([]int, nodes)\n\tdiscovered[start] = 1\n\tqueue = append(queue, start)\n\tfor len(queue) > 0 {\n\t\tv := queue[0]\n\t\tqueue = queue[1:]\n\t\tfor i := 0; i < len(edges[v]); i++ {\n\t\t\tif discovered[i] == 0 && edges[v][i] > 0 {\n\t\t\t\tif i == end {\n\t\t\t\t\treturn true, discovered[v]\n\t\t\t\t}\n\t\t\t\tdiscovered[i] = discovered[v] + 1\n\t\t\t\tqueue = append(queue, i)\n\t\t\t}\n\t\t}\n\t}\n\treturn false, 0\n}\n"
  },
  {
    "path": "graph/breadthfirstsearch_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBreadthFirstSearch(t *testing.T) {\n\tvar bfsTestData = []struct {\n\t\tdescription string\n\t\tstart       int\n\t\tend         int\n\t\tnodes       int\n\t\tedges       [][]int\n\t\texpected1   bool\n\t\texpected2   int\n\t}{\n\t\t{\n\t\t\t\"test 1 connected with distance 2\",\n\t\t\t0,\n\t\t\t5,\n\t\t\t6,\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1, 0, 0, 0},\n\t\t\t\t{1, 0, 0, 1, 0, 1},\n\t\t\t\t{1, 0, 0, 1, 0, 0},\n\t\t\t\t{0, 1, 1, 0, 1, 0},\n\t\t\t\t{0, 0, 0, 1, 0, 0},\n\t\t\t\t{0, 1, 0, 0, 0, 0},\n\t\t\t},\n\t\t\ttrue,\n\t\t\t2,\n\t\t},\n\t\t{\n\t\t\t\"test 2 connected with distance 4\",\n\t\t\t0,\n\t\t\t5,\n\t\t\t6,\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1, 0, 0, 0},\n\t\t\t\t{1, 0, 0, 1, 0, 0},\n\t\t\t\t{1, 0, 0, 1, 0, 0},\n\t\t\t\t{0, 1, 1, 0, 1, 0},\n\t\t\t\t{0, 0, 0, 1, 0, 1},\n\t\t\t\t{0, 0, 0, 0, 1, 0},\n\t\t\t},\n\t\t\ttrue,\n\t\t\t4,\n\t\t},\n\t\t{\n\t\t\t\"test 2 not connected\",\n\t\t\t0,\n\t\t\t5,\n\t\t\t6,\n\t\t\t[][]int{\n\t\t\t\t{0, 1, 1, 0, 0, 0},\n\t\t\t\t{1, 0, 0, 1, 0, 0},\n\t\t\t\t{1, 0, 0, 1, 0, 0},\n\t\t\t\t{0, 1, 1, 0, 1, 0},\n\t\t\t\t{0, 0, 0, 1, 0, 0},\n\t\t\t\t{0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t\tfalse,\n\t\t\t0,\n\t\t},\n\t}\n\tfor _, test := range bfsTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tr1, r2 := BreadthFirstSearch(test.start, test.end,\n\t\t\t\ttest.nodes, test.edges)\n\t\t\tif r1 != test.expected1 || r2 != test.expected2 {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Nodes '%v' and Edges '%v' start from '%d' and end in '%d' \"+\n\t\t\t\t\t\"was expecting '%v' with distance '%d' but result was '%v','%d'\",\n\t\t\t\t\ttest.nodes, test.edges, test.start, test.end, test.expected1, test.expected2, r1, r2)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/coloring/backtracking.go",
    "content": "// This file contains the graph coloring implementation using backtracking\n// time complexity: O(V^V) where V is the number of vertices in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring\n\n// ColorUsingBacktracking will return the Color of each vertex and the\n// total number of different colors used, using backtracking\nfunc (g *Graph) ColorUsingBacktracking() (map[int]Color, int) {\n\tvertexColors := make(map[int]Color, g.vertices)\n\tg.colorVertex(0, vertexColors)\n\n\tcolorsUsed := 0\n\tfor _, cr := range vertexColors {\n\t\tif colorsUsed < int(cr) {\n\t\t\tcolorsUsed = int(cr)\n\t\t}\n\t}\n\treturn vertexColors, colorsUsed\n}\n\n// colorVertex will try to color provided vertex, v\nfunc (g *Graph) colorVertex(v int, color map[int]Color) bool {\n\t// If all vertices are colored, the colors store will be completely filled.\n\tif len(color) == g.vertices {\n\t\treturn true\n\t}\n\n\t// As the upper bound of no. of colors is the no. of vertices in graph,\n\t// try assigning each color to the vertex v\n\tfor cr := Color(1); cr <= Color(g.vertices); cr++ {\n\t\t// Use the color, cr for vertex, v if it is safe to use, by\n\t\t// checking its neighbours\n\t\tsafe := true\n\t\tfor nb := range g.edges[v] {\n\t\t\t// cr, color is not safe if color of nb, crnb is not equal to cr\n\t\t\tif crnb, ok := color[nb]; ok && crnb == cr {\n\t\t\t\tsafe = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif safe {\n\t\t\tcolor[v] = cr\n\t\t\tif g.colorVertex(v+1, color) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tdelete(color, v)\n\t\t}\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "graph/coloring/backtracking_test.go",
    "content": "// This file provides tests for coloring using backtracking.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring_test\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestGraphColorUsingBacktracking(t *testing.T) {\n\tfor i, tt := range getTestGraphs() {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tcolorsOfVertices, colors := tt.Graph.ColorUsingBacktracking()\n\t\t\tif colors != tt.ColorsUsed {\n\t\t\t\tt.Errorf(\"ColorUsingBacktracking() return more number of colors: %v, want %v colors\", colors, tt.ColorsUsed)\n\t\t\t}\n\t\t\t// check colors\n\t\t\tif err := tt.Graph.ValidateColorsOfVertex(colorsOfVertices); err != nil {\n\t\t\t\tt.Errorf(\"ColorUsingBacktracking() assigned colors are wrong, error = %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/coloring/bfs.go",
    "content": "// This file contains the graph coloring implementation using BFS\n// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring\n\nimport \"container/list\"\n\n// ColorUsingBFS will return the Color of each vertex and the\n// total number of different colors used, using BFS\nfunc (g *Graph) ColorUsingBFS() (map[int]Color, int) {\n\t// Initially all vertices will have same color\n\tvertexColors := make(map[int]Color, g.vertices)\n\tfor i := 0; i < g.vertices; i++ {\n\t\tvertexColors[i] = 1\n\t}\n\n\tvisited := make(map[int]struct{})\n\t// Run BFS from each non-visited vertex\n\tfor i := 0; i < g.vertices; i++ {\n\t\tif _, ok := visited[i]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tvisited[i] = struct{}{}\n\n\t\tqueue := list.New()\n\t\tqueue.PushBack(i)\n\n\t\tfor queue.Len() != 0 {\n\t\t\t// front vertex in the queue\n\t\t\tfrontNode := queue.Front()\n\t\t\tfront := frontNode.Value.(int)\n\t\t\tqueue.Remove(frontNode)\n\n\t\t\t// Now, check all neighbours of front vertex, if they have same\n\t\t\t// color as that of front, change their color\n\t\t\tfor nb := range g.edges[front] {\n\t\t\t\tif vertexColors[nb] == vertexColors[front] {\n\t\t\t\t\tvertexColors[nb]++\n\t\t\t\t}\n\t\t\t\t// if the neighbour is not already visited, add it to the queue\n\t\t\t\tif _, ok := visited[nb]; !ok {\n\t\t\t\t\tvisited[nb] = struct{}{}\n\t\t\t\t\tqueue.PushBack(nb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcolorsUsed := 0\n\tfor _, cr := range vertexColors {\n\t\tif colorsUsed < int(cr) {\n\t\t\tcolorsUsed = int(cr)\n\t\t}\n\t}\n\treturn vertexColors, colorsUsed\n}\n"
  },
  {
    "path": "graph/coloring/bfs_test.go",
    "content": "// This file provides tests for coloring using BFS.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring_test\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestGraphColorUsingBFS(t *testing.T) {\n\tfor i, tt := range getTestGraphs() {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tcolorsOfVertices, colors := tt.Graph.ColorUsingBFS()\n\t\t\tif colors != tt.ColorsUsed {\n\t\t\t\tt.Errorf(\"ColorUsingBFS() return more number of colors: %v, want %v colors\", colors, tt.ColorsUsed)\n\t\t\t}\n\t\t\t// check colors\n\t\t\tif err := tt.Graph.ValidateColorsOfVertex(colorsOfVertices); err != nil {\n\t\t\t\tt.Errorf(\"ColorUsingBFS() assigned colors are wrong, error = %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/coloring/bipartite.go",
    "content": "package coloring\n\n// Bipartite.go\n// description: Implementation of the Bipartite graph coloring algorithm\n// details: A bipartite graph is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V. The Bipartite graph coloring algorithm is used to determine if a graph is bipartite or not.\n// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n\nfunc (g *Graph) TryBipartiteColoring() map[int]Color {\n\t// 0 is uncolored, 1/2 are colors\n\tcolors := make(map[int]Color)\n\tvisited := make(map[int]bool)\n\n\tfor i := range g.edges {\n\t\tcolors[i] = 0\n\t\tvisited[i] = false\n\t}\n\n\tvar colorNode func(int)\n\tcolorNode = func(s int) {\n\t\tvisited[s] = true\n\t\tcoloring := []Color{0, 2, 1}\n\n\t\tfor n := range g.edges[s] {\n\t\t\tif colors[n] == 0 {\n\t\t\t\tcolors[n] = coloring[colors[s]]\n\t\t\t}\n\t\t\tif !visited[n] {\n\t\t\t\tcolorNode(n)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := range g.edges {\n\t\tif colors[i] == 0 {\n\t\t\tcolors[i] = 1\n\t\t\tcolorNode(i)\n\t\t}\n\t}\n\n\treturn colors\n}\n\n// basically tries to color the graph in two colors if each edge\n// connects 2 differently colored nodes the graph can be considered bipartite\nfunc BipartiteCheck(N int, edges [][]int) bool {\n\tvar graph Graph\n\tfor i := 0; i < N; i++ {\n\t\tgraph.AddVertex(i)\n\t}\n\tfor _, e := range edges {\n\t\tgraph.AddEdge(e[0], e[1])\n\t}\n\treturn graph.ValidateColorsOfVertex(graph.TryBipartiteColoring()) == nil\n}\n"
  },
  {
    "path": "graph/coloring/bipartite_test.go",
    "content": "package coloring\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname        string\n\tN           int\n\tisBipartite bool\n\tedges       [][]int\n}{\n\t{\n\t\t\"basic true\", 2, true,\n\t\t[][]int{{1, 0}},\n\t},\n\t{\n\t\t\"basic false\", 3, false,\n\t\t[][]int{{0, 1}, {1, 2}, {2, 0}},\n\t},\n}\n\nfunc TestBipartite(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := BipartiteCheck(tc.N, tc.edges)\n\t\t\tif tc.isBipartite != actual {\n\t\t\t\tt.Errorf(\"failed %s: %v\", tc.name, tc.edges)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/coloring/doc.go",
    "content": "// Package coloring provides implementation of different graph coloring\n// algorithms, e.g. coloring using BFS, using Backtracking, using greedy\n// approach.\n// Author(s): [Shivam](https://github.com/Shivam010)\npackage coloring\n"
  },
  {
    "path": "graph/coloring/graph.go",
    "content": "// This file contains the simple structural implementation of undirected\n// graph, used in coloring algorithms.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring\n\nimport \"errors\"\n\n// Color provides a type for vertex color\ntype Color int\n\n// Graph provides a structure to store an undirected graph.\n// It is safe to use its empty object.\ntype Graph struct {\n\tvertices int\n\tedges    map[int]map[int]struct{}\n}\n\n// AddVertex will add a new vertex in the graph, if the vertex already\n// exist it will do nothing\nfunc (g *Graph) AddVertex(v int) {\n\tif g.edges == nil {\n\t\tg.edges = make(map[int]map[int]struct{})\n\t}\n\n\t// Check if vertex is present or not\n\tif _, ok := g.edges[v]; !ok {\n\t\tg.vertices++\n\t\tg.edges[v] = make(map[int]struct{})\n\t}\n}\n\n// AddEdge will add a new edge between the provided vertices in the graph\nfunc (g *Graph) AddEdge(one, two int) {\n\t// Add vertices: one and two to the graph if they are not present\n\tg.AddVertex(one)\n\tg.AddVertex(two)\n\n\t// and finally add the edges: one->two and two->one for undirected graph\n\tg.edges[one][two] = struct{}{}\n\tg.edges[two][one] = struct{}{}\n}\n\nfunc (g *Graph) ValidateColorsOfVertex(colors map[int]Color) error {\n\tif g.vertices != len(colors) {\n\t\treturn errors.New(\"coloring: not all vertices of graph are colored\")\n\t}\n\t// check colors\n\tfor vertex, neighbours := range g.edges {\n\t\tfor nb := range neighbours {\n\t\t\tif colors[vertex] == colors[nb] {\n\t\t\t\treturn errors.New(\"coloring: same colors of neighbouring vertex\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "graph/coloring/graph_test.go",
    "content": "// This file provides tests for graph coloring validations.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/graph/coloring\"\n\t\"strconv\"\n\t\"testing\"\n)\n\ntype testGraph struct {\n\tGraph        *coloring.Graph\n\tColorsUsed   int\n\tVertexColors map[int]coloring.Color\n}\n\nfunc getTestGraphs() (list []*testGraph) {\n\t// Graph 0th:\n\t//     1---2\n\t//     | /  \\\n\t// 4---3    0\n\t// Min number of colors required = 3\n\tg0 := &testGraph{\n\t\tGraph:      &coloring.Graph{},\n\t\tColorsUsed: 3,\n\t\tVertexColors: map[int]coloring.Color{\n\t\t\t1: 1, 4: 1, 0: 1,\n\t\t\t2: 2,\n\t\t\t3: 3,\n\t\t},\n\t}\n\tlist = append(list, g0)\n\tg0.Graph.AddEdge(4, 3)\n\tg0.Graph.AddEdge(3, 1)\n\tg0.Graph.AddEdge(3, 2)\n\tg0.Graph.AddEdge(1, 2)\n\tg0.Graph.AddEdge(2, 0)\n\n\t// Graph 1st:\n\t//      1---2\n\t//      | / |\n\t//  4---3---0\n\t// Min number of colors required = 3\n\tg1 := &testGraph{\n\t\tGraph:      &coloring.Graph{},\n\t\tColorsUsed: 3,\n\t\tVertexColors: map[int]coloring.Color{\n\t\t\t1: 1, 4: 1, 0: 1,\n\t\t\t2: 2,\n\t\t\t3: 3,\n\t\t},\n\t}\n\tlist = append(list, g1)\n\tg1.Graph.AddEdge(4, 3)\n\tg1.Graph.AddEdge(3, 1)\n\tg1.Graph.AddEdge(3, 2)\n\tg1.Graph.AddEdge(1, 2)\n\tg1.Graph.AddEdge(2, 0)\n\tg1.Graph.AddEdge(3, 0)\n\n\t// Graph 2nd:\n\t//      1---2\n\t//      |\n\t//  4---3   0\n\t// Min number of colors required = 2\n\tg2 := &testGraph{\n\t\tGraph:      &coloring.Graph{},\n\t\tColorsUsed: 2,\n\t\tVertexColors: map[int]coloring.Color{\n\t\t\t1: 1, 4: 1, 0: 1,\n\t\t\t2: 2, 3: 2,\n\t\t},\n\t}\n\tlist = append(list, g2)\n\tg2.Graph.AddVertex(0)\n\tg2.Graph.AddEdge(4, 3)\n\tg2.Graph.AddEdge(3, 1)\n\tg2.Graph.AddEdge(1, 2)\n\n\t// Graph 3rd:\n\t//  1---2   4\n\t//  |   |   |\n\t//  0---3   5\n\t// Min number of colors required = 2\n\tg3 := &testGraph{\n\t\tGraph:      &coloring.Graph{},\n\t\tColorsUsed: 2,\n\t\tVertexColors: map[int]coloring.Color{\n\t\t\t1: 1, 3: 1, 4: 1,\n\t\t\t0: 2, 2: 2, 5: 2,\n\t\t},\n\t}\n\tlist = append(list, g3)\n\tg3.Graph.AddEdge(0, 3)\n\tg3.Graph.AddEdge(1, 2)\n\tg3.Graph.AddEdge(1, 0)\n\tg3.Graph.AddEdge(3, 2)\n\tg3.Graph.AddEdge(4, 5)\n\n\t// Graph 4th:\n\t// Completely Connected graph of vertex 4\n\t// Min number of colors required = 2\n\tg4 := &testGraph{\n\t\tGraph:      &coloring.Graph{},\n\t\tColorsUsed: 4,\n\t\tVertexColors: map[int]coloring.Color{\n\t\t\t0: 1, 1: 2, 2: 3, 4: 4,\n\t\t},\n\t}\n\tlist = append(list, g4)\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := i + 1; j < 4; j++ {\n\t\t\tg4.Graph.AddEdge(i, j)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc TestGraph_ValidateColorsOfVertex(t *testing.T) {\n\tfor i, tt := range getTestGraphs() {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tif err := tt.Graph.ValidateColorsOfVertex(tt.VertexColors); err != nil {\n\t\t\t\tt.Errorf(\"ValidateColorsOfVertex() error = %v, wantErr nil\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc getTestGraphsForNegativeTests() (list []*testGraph) {\n\tlist = getTestGraphs()\n\tlist[0].VertexColors = nil\n\tlist[1].VertexColors = map[int]coloring.Color{}\n\tfor v := range list[2].VertexColors {\n\t\tin := len(list[2].VertexColors) - v - 1\n\t\tlist[2].VertexColors[v] = list[2].VertexColors[in]\n\t}\n\tfor v := range list[3].VertexColors {\n\t\tlist[3].VertexColors[v] = 1\n\t}\n\treturn list[:4]\n}\n\nfunc TestGraphValidateColorsOfVertex_Negative(t *testing.T) {\n\tfor i, tt := range getTestGraphsForNegativeTests() {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tif err := tt.Graph.ValidateColorsOfVertex(tt.VertexColors); err == nil {\n\t\t\t\tt.Errorf(\"ValidateColorsOfVertex() error = nil, want some err\")\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/coloring/greedy.go",
    "content": "// This file contains the graph coloring implementation using Greedy Approach.\n// time complexity: O(V^2) where V is the number of vertices in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring\n\nimport \"sort\"\n\n// ColorUsingGreedyApproach will return the Color of each vertex and the\n// total number of different colors used, using a greedy approach, based on\n// the number of edges (or degree) from any vertex.\nfunc (g *Graph) ColorUsingGreedyApproach() (map[int]Color, int) {\n\tdegreeOfVertex := make([]struct{ degree, vertex int }, 0, g.vertices)\n\tfor v, neighbours := range g.edges {\n\t\tdegreeOfVertex = append(degreeOfVertex,\n\t\t\tstruct{ degree, vertex int }{\n\t\t\t\tvertex: v,\n\t\t\t\tdegree: len(neighbours),\n\t\t\t},\n\t\t)\n\t}\n\t// sort the degreeOfVertex in decreasing order of degrees\n\tsort.Slice(degreeOfVertex, func(i, j int) bool {\n\t\treturn degreeOfVertex[i].degree > degreeOfVertex[j].degree\n\t})\n\n\tvertexColors := make(map[int]Color, g.vertices)\n\t// Start with a color and assign the color to all possible vertices in the degreeOfVertex slice\n\t// and then, re-iterate with new color for all those which are left\n\tfor color := 1; color <= g.vertices; color++ {\n\tvertexLoop:\n\t\tfor _, val := range degreeOfVertex {\n\t\t\t// skip, if already assigned\n\t\t\tif _, ok := vertexColors[val.vertex]; ok {\n\t\t\t\tcontinue vertexLoop\n\t\t\t}\n\t\t\t// Check its neighbours\n\t\t\tfor ng := range g.edges[val.vertex] {\n\t\t\t\tif vertexColors[ng] == Color(color) {\n\t\t\t\t\t// not possible to use this color for val.vertex\n\t\t\t\t\tcontinue vertexLoop\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Assign color to the vertex\n\t\t\tvertexColors[val.vertex] = Color(color)\n\t\t}\n\t\t// continue till all the vertices are colored\n\t\tif len(vertexColors) == g.vertices {\n\t\t\treturn vertexColors, color\n\t\t}\n\t}\n\treturn vertexColors, g.vertices\n}\n"
  },
  {
    "path": "graph/coloring/greedy_test.go",
    "content": "// This file provides tests for coloring using Greedy approach.\n// Author(s): [Shivam](https://github.com/Shivam010)\n\npackage coloring_test\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestGraphColorUsingGreedyApproach(t *testing.T) {\n\tfor i, tt := range getTestGraphs() {\n\t\tt.Run(strconv.Itoa(i), func(t *testing.T) {\n\t\t\tcolorsOfVertices, colors := tt.Graph.ColorUsingGreedyApproach()\n\t\t\tif colors != tt.ColorsUsed {\n\t\t\t\tt.Errorf(\"ColorUsingGreedyApproach() return more number of colors: %v, want %v colors\", colors, tt.ColorsUsed)\n\t\t\t}\n\t\t\t// check colors\n\t\t\tif err := tt.Graph.ValidateColorsOfVertex(colorsOfVertices); err != nil {\n\t\t\t\tt.Errorf(\"ColorUsingGreedyApproach() assigned colors are wrong, error = %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/cycle.go",
    "content": "// cycle.go\n// this file handle algorithm that related to cycle in graph\n// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// reference: https://en.wikipedia.org/wiki/Cycle_(graph_theory)\n// [kiarash hajian](https://github.com/kiarash8112)\n\npackage graph\n\nfunc (g *Graph) HasCycle() bool {\n\t//this implimetation referred as 3-color too\n\tall := map[int]struct{}{}\n\tvisiting := map[int]struct{}{}\n\tvisited := map[int]struct{}{}\n\n\tfor v := range g.edges {\n\t\tall[v] = struct{}{}\n\t}\n\n\tfor current := range all {\n\t\tif g.hasCycleHelper(current, all, visiting, visited) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n\n}\n\nfunc (g Graph) hasCycleHelper(v int, all, visiting, visited map[int]struct{}) bool {\n\tdelete(all, v)\n\tvisiting[v] = struct{}{}\n\n\tneighbors := g.edges[v]\n\tfor v := range neighbors {\n\t\tif _, ok := visited[v]; ok {\n\t\t\tcontinue\n\t\t} else if _, ok := visiting[v]; ok {\n\t\t\treturn true\n\t\t} else if g.hasCycleHelper(v, all, visiting, visited) {\n\t\t\treturn true\n\t\t}\n\t}\n\tdelete(visiting, v)\n\tvisited[v] = struct{}{}\n\treturn false\n}\n\n// this function can do HasCycle() job but it is slower\nfunc (g *Graph) FindAllCycles() []Graph {\n\tall := map[int]struct{}{}\n\tvisiting := map[int]struct{}{}\n\tvisited := map[int]struct{}{}\n\n\tallCycles := []Graph{}\n\n\tfor v := range g.edges {\n\t\tall[v] = struct{}{}\n\t}\n\n\tfor current := range all {\n\t\tfoundCycle, parents := g.findAllCyclesHelper(current, all, visiting, visited)\n\n\t\tif foundCycle {\n\t\t\tfoundCycleFromCurrent := false\n\t\t\t//this loop remove additional vertex from detected cycle\n\t\t\t//using foundCycleFromCurrent bool to make sure after removing vertex we still have cycle\n\t\t\tfor i := len(parents) - 1; i > 0; i-- {\n\t\t\t\tif parents[i][1] == parents[0][0] {\n\t\t\t\t\tparents = parents[:i+1]\n\t\t\t\t\tfoundCycleFromCurrent = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif foundCycleFromCurrent {\n\t\t\t\tgraph := Graph{Directed: true}\n\t\t\t\tfor _, edges := range parents {\n\t\t\t\t\tgraph.AddEdge(edges[1], edges[0])\n\t\t\t\t}\n\t\t\t\tallCycles = append(allCycles, graph)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn allCycles\n\n}\n\nfunc (g Graph) findAllCyclesHelper(current int, all, visiting, visited map[int]struct{}) (bool, [][]int) {\n\tparents := [][]int{}\n\n\tdelete(all, current)\n\tvisiting[current] = struct{}{}\n\n\tneighbors := g.edges[current]\n\tfor v := range neighbors {\n\t\tif _, ok := visited[v]; ok {\n\t\t\tcontinue\n\t\t} else if _, ok := visiting[v]; ok {\n\t\t\tparents = append(parents, []int{v, current})\n\t\t\treturn true, parents\n\t\t} else if ok, savedParents := g.findAllCyclesHelper(v, all, visiting, visited); ok {\n\t\t\tparents = append(parents, savedParents...)\n\t\t\tparents = append(parents, []int{v, current})\n\t\t\treturn true, parents\n\t\t}\n\t}\n\tdelete(visiting, current)\n\tvisited[current] = struct{}{}\n\treturn false, parents\n}\n"
  },
  {
    "path": "graph/cycle_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestHasCycle(t *testing.T) {\n\tgraph := Graph{Directed: true}\n\tedges := [][]int{{0, 1}, {1, 2}, {2, 0}, {4, 0}}\n\tfor _, edge := range edges {\n\t\tgraph.AddEdge(edge[0], edge[1])\n\t}\n\tif !graph.HasCycle() {\n\t\tt.Error(\"answer of hasCycle is not correct\")\n\t}\n\n\tgraph = Graph{Directed: true}\n\tedges = [][]int{{0, 1}, {1, 2}, {2, 6}, {4, 0}}\n\tfor _, edge := range edges {\n\t\tgraph.AddEdge(edge[0], edge[1])\n\t}\n\tif graph.HasCycle() {\n\t\tt.Error(\"answer of hasCycle is not correct\")\n\t}\n}\n\nfunc TestFindAllCycles(t *testing.T) {\n\tgraph := Graph{Directed: true}\n\tedges := [][]int{{0, 4}, {1, 3}, {2, 3}, {3, 4}, {4, 7}, {5, 2}, {6, 3}, {7, 3}}\n\tfor _, edge := range edges {\n\t\tgraph.AddEdge(edge[0], edge[1])\n\t}\n\n\tres := graph.FindAllCycles()\n\n\tif len(res) != 1 {\n\t\tt.Error(\"number of cycles is not correct\")\n\t}\n\n\tfirstCycle := res[0]\n\tif len(firstCycle.edges) != 3 {\n\t\tt.Error(\"number of vertex in cycle is not correct\")\n\t}\n\tif _, ok := firstCycle.edges[3][4]; !ok {\n\t\tt.Error(\"connection in cycle is not correct\")\n\t}\n\tif _, ok := firstCycle.edges[4][7]; !ok {\n\t\tt.Error(\"connection in cycle is not correct\")\n\t}\n\tif _, ok := firstCycle.edges[7][3]; !ok {\n\t\tt.Error(\"connection in cycle is not correct\")\n\t}\n}\n"
  },
  {
    "path": "graph/depthfirstsearch.go",
    "content": "// depthfirstsearch.go\n// description: this file contains the implementation of the depth first search algorithm\n// details: Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.\n// time complexity: O(n)\n// space complexity: O(n)\n\npackage graph\n\nfunc GetIdx(target int, nodes []int) int {\n\tfor i := 0; i < len(nodes); i++ {\n\t\tif nodes[i] == target {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc NotExist(target int, slice []int) bool {\n\tfor i := 0; i < len(slice); i++ {\n\t\tif slice[i] == target {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc DepthFirstSearchHelper(start, end int, nodes []int, edges [][]bool, showroute bool) ([]int, bool) {\n\tvar route []int\n\tvar stack []int\n\tstartIdx := GetIdx(start, nodes)\n\tstack = append(stack, startIdx)\n\tfor len(stack) > 0 {\n\t\tnow := stack[len(stack)-1]\n\t\troute = append(route, nodes[now])\n\t\tif len(stack) > 1 {\n\t\t\tstack = stack[:len(stack)-1]\n\t\t} else {\n\t\t\tstack = stack[:len(stack)-1]\n\t\t}\n\t\tfor i := 0; i < len(edges[now]); i++ {\n\t\t\tif edges[now][i] && NotExist(i, stack) {\n\t\t\t\tstack = append(stack, i)\n\t\t\t}\n\t\t\tedges[now][i] = false\n\t\t\tedges[i][now] = false\n\t\t}\n\t\tif route[len(route)-1] == end {\n\t\t\treturn route, true\n\t\t}\n\t}\n\n\tif showroute {\n\t\treturn route, false\n\t} else {\n\t\treturn nil, false\n\t}\n}\n\nfunc DepthFirstSearch(start, end int, nodes []int, edges [][]bool) ([]int, bool) {\n\treturn DepthFirstSearchHelper(start, end, nodes, edges, false)\n}\n\n// func main() {\n// \tnodes := []int{\n// \t\t1, 2, 3, 4, 5, 6,\n// \t}\n// \t/*\n// \t\tsample graph\n// \t\t①-②\n// \t\t|  |\n// \t\t③-④-⑤-⑥\n// \t*/\n// \tedges := [][]bool{\n// \t\t{false, true, true, false, false, false},\n// \t\t{true, false, false, true, false, false},\n// \t\t{true, false, false, true, false, false},\n// \t\t{false, true, true, false, true, false},\n// \t\t{false, false, false, true, false, true},\n// \t\t{false, false, false, false, true, false},\n// \t}\n// \tstart := 1\n// \tend := 6\n// \troute, _ := dfs(start, end, nodes, edges)\n// \tfmt.Println(route)\n// }\n"
  },
  {
    "path": "graph/depthfirstsearch_test.go",
    "content": "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, 4, 5, 6,\n\t}\n\n\t//Adjacency Matrix for connected nodes\n\tedges := [][]bool{\n\t\t{false, true, true, false, false, false},\n\t\t{true, false, false, true, false, false},\n\t\t{true, false, false, true, false, false},\n\t\t{false, true, true, false, true, false},\n\t\t{false, false, false, true, false, true},\n\t\t{false, false, false, false, true, false},\n\t}\n\n\tstart := 1\n\tend := 6\n\n\tactual, actualIsFound := DepthFirstSearch(start, end, nodes, edges)\n\texpected := []int{1, 3, 4, 5, 6}\n\texpectedIsFound := true\n\tt.Run(\"Test Dfs\", func(t *testing.T) {\n\t\tif !reflect.DeepEqual(expected, actual) || !reflect.DeepEqual(actualIsFound, expectedIsFound) {\n\t\t\tt.Errorf(\"got route: %v, want route: %v\", actual, expected)\n\t\t\tt.Errorf(\"got isFound: %v, want isFound: %v\", actualIsFound, expectedIsFound)\n\t\t}\n\t})\n}\n\nfunc TestDfsWhenPathIsNotFound(t *testing.T) {\n\tnodes := []int{\n\t\t1, 2, 3, 4, 5, 6,\n\t}\n\n\t//Adjacency Matrix for connected nodes\n\tedges := [][]bool{\n\t\t{false, true, true, false, false, false},\n\t\t{true, false, false, true, false, false},\n\t\t{true, false, false, true, false, false},\n\t\t{false, true, true, false, true, false},\n\t\t{false, false, false, true, false, true},\n\t\t{false, false, false, false, true, false},\n\t}\n\n\tstart := 1\n\tend := 7\n\n\tactual, actualIsFound := DepthFirstSearch(start, end, nodes, edges)\n\tvar expected []int\n\texpectedIsFound := false\n\tt.Run(\"Test Dfs\", func(t *testing.T) {\n\t\tif !reflect.DeepEqual(expected, actual) || !reflect.DeepEqual(actualIsFound, expectedIsFound) {\n\t\t\tt.Errorf(\"got route: %v, want route: %v\", actual, expected)\n\t\t\tt.Errorf(\"got isFound: %v, want isFound: %v\", actualIsFound, expectedIsFound)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "graph/dijkstra.go",
    "content": "// dijkstra.go\n// description: this file contains the implementation of the Dijkstra algorithm\n// details: Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later. The algorithm exists in many variants; Dijkstra's original variant found the shortest path between two nodes, but a more common variant fixes a single node as the \"source\" node and finds shortest paths from the source to all other nodes in the graph, producing a shortest-path tree.\n// time complexity: O((V+E) log V) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\n\npackage graph\n\nimport \"github.com/TheAlgorithms/Go/sort\"\n\ntype Item struct {\n\tnode int\n\tdist int\n}\n\nfunc (a Item) More(b any) bool {\n\t// reverse direction for minheap\n\treturn a.dist < b.(Item).dist\n}\nfunc (a Item) Idx() int {\n\treturn a.node\n}\n\nfunc (g *Graph) Dijkstra(start, end int) (int, bool) {\n\tvisited := make(map[int]bool)\n\tnodes := make(map[int]*Item)\n\n\tnodes[start] = &Item{\n\t\tdist: 0,\n\t\tnode: start,\n\t}\n\tpq := sort.MaxHeap{}\n\tpq.Init(nil)\n\tpq.Push(*nodes[start])\n\n\tvisit := func(curr Item) {\n\t\tvisited[curr.node] = true\n\t\tfor n, d := range g.edges[curr.node] {\n\t\t\tif visited[n] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\titem := nodes[n]\n\t\t\tdist2 := curr.dist + d\n\t\t\tif item == nil {\n\t\t\t\tnodes[n] = &Item{node: n, dist: dist2}\n\t\t\t\tpq.Push(*nodes[n])\n\t\t\t} else if item.dist > dist2 {\n\t\t\t\titem.dist = dist2\n\t\t\t\tpq.Update(*item)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor pq.Size() > 0 {\n\t\tcurr := pq.Pop().(Item)\n\t\tif curr.node == end {\n\t\t\tbreak\n\t\t}\n\t\tvisit(curr)\n\t}\n\n\titem := nodes[end]\n\tif item == nil {\n\t\treturn -1, false\n\t}\n\treturn item.dist, true\n}\n"
  },
  {
    "path": "graph/dijkstra_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nvar tc_dijkstra = []struct {\n\tname     string\n\tedges    [][]int\n\tnode0    int\n\tnode1    int\n\texpected int\n}{\n\t{\n\t\t\"straight line graph\",\n\t\t[][]int{{0, 1, 5}, {1, 2, 2}},\n\t\t0, 2, 7,\n\t},\n\t{\n\t\t\"unconnected node\",\n\t\t[][]int{{0, 1, 5}},\n\t\t0, 2, -1,\n\t},\n\t{\n\t\t\"double paths\",\n\t\t[][]int{{0, 1, 5}, {1, 3, 5}, {0, 2, 5}, {2, 3, 4}},\n\t\t0, 3, 9,\n\t},\n\t{\n\t\t\"double paths extended\",\n\t\t[][]int{{0, 1, 5}, {1, 3, 5}, {0, 2, 5}, {2, 3, 4}, {3, 4, 1}},\n\t\t0, 4, 10,\n\t},\n}\n\nfunc TestDijkstra(t *testing.T) {\n\tfor _, tc := range tc_dijkstra {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tvar graph Graph\n\t\t\tfor _, edge := range tc.edges {\n\t\t\t\tgraph.AddWeightedEdge(edge[0], edge[1], edge[2])\n\t\t\t}\n\n\t\t\tactual, _ := graph.Dijkstra(tc.node0, tc.node1)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"expected %d, got %d, from node %d to %d, with %v\",\n\t\t\t\t\ttc.expected, actual, tc.node0, tc.node1, tc.edges)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/doc.go",
    "content": "// Package graph demonstrates Graph search algorithms\n// reference: https://en.wikipedia.org/wiki/Tree_traversal\npackage graph\n"
  },
  {
    "path": "graph/edmondkarp.go",
    "content": "// Edmond-Karp algorithm is an implementation of the Ford-Fulkerson method\n// to compute max-flow between a pair of source-sink vertices in a weighted graph\n// It uses BFS (Breadth First Search) to find the residual paths\n// Time Complexity: O(V * E^2) where V is the number of vertices and E is the number of edges\n// Space Complexity: O(V + E) Because we keep residual graph in size of the original graph\n// Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. 2009. Introduction to Algorithms, Third Edition (3rd. ed.). The MIT Press.\n\npackage graph\n\nimport (\n\t\"math\"\n)\n\n// Returns a mapping of vertices as path, if there is any from source to sink\n// Otherwise, returns nil\nfunc FindPath(rGraph WeightedGraph, source int, sink int) map[int]int {\n\tqueue := make([]int, 0)\n\tmarked := make([]bool, len(rGraph))\n\tmarked[source] = true\n\tqueue = append(queue, source)\n\tparent := make(map[int]int)\n\n\t// BFS loop with saving the path found\n\tfor len(queue) > 0 {\n\t\tv := queue[0]\n\t\tqueue = queue[1:]\n\t\tfor i := 0; i < len(rGraph[v]); i++ {\n\t\t\tif !marked[i] && rGraph[v][i] > 0 {\n\t\t\t\tparent[i] = v\n\t\t\t\t// Terminate the BFS, if we reach to sink\n\t\t\t\tif i == sink {\n\t\t\t\t\treturn parent\n\t\t\t\t}\n\t\t\t\tmarked[i] = true\n\t\t\t\tqueue = append(queue, i)\n\t\t\t}\n\t\t}\n\t}\n\t// source and sink are not in the same connected component\n\treturn nil\n}\n\nfunc EdmondKarp(graph WeightedGraph, source int, sink int) float64 {\n\t// Check graph emptiness\n\tif len(graph) == 0 {\n\t\treturn 0.0\n\t}\n\n\t// Check correct dimensions of the graph slice\n\tfor i := 0; i < len(graph); i++ {\n\t\tif len(graph[i]) != len(graph) {\n\t\t\treturn 0.0\n\t\t}\n\t}\n\n\trGraph := make(WeightedGraph, len(graph))\n\tfor i := 0; i < len(graph); i++ {\n\t\trGraph[i] = make([]float64, len(graph))\n\t}\n\t// Init the residual graph with the same capacities as the original graph\n\tcopy(rGraph, graph)\n\n\tmaxFlow := 0.0\n\n\tfor {\n\t\tparent := FindPath(rGraph, source, sink)\n\t\tif parent == nil {\n\t\t\tbreak\n\t\t}\n\t\t// Finding the max flow over the path returned by BFS\n\t\t// i.e. finding minimum residual capacity amonth the path edges\n\t\tpathFlow := math.MaxFloat64\n\t\tfor v := sink; v != source; v = parent[v] {\n\t\t\tu := parent[v]\n\t\t\tif rGraph[u][v] < pathFlow {\n\t\t\t\tpathFlow = rGraph[u][v]\n\t\t\t}\n\t\t}\n\n\t\t// update residual capacities of the edges and\n\t\t// reverse edges along the path\n\t\tfor v := sink; v != source; v = parent[v] {\n\t\t\tu := parent[v]\n\t\t\trGraph[u][v] -= pathFlow\n\t\t\trGraph[v][u] += pathFlow\n\t\t}\n\n\t\t// Update the total flow found so far\n\t\tmaxFlow += pathFlow\n\t}\n\n\treturn maxFlow\n}\n"
  },
  {
    "path": "graph/edmondkarp_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEdmondKarp(t *testing.T) {\n\tvar edmondKarpTestData = []struct {\n\t\tdescription string\n\t\tgraph       WeightedGraph\n\t\tsource      int\n\t\tsink        int\n\t\texpected    float64\n\t}{\n\t\t{\n\t\t\tdescription: \"test empty graph\",\n\t\t\tgraph:       nil,\n\t\t\tsource:      0,\n\t\t\tsink:        0,\n\t\t\texpected:    0.0,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with wrong dimensions\",\n\t\t\tgraph: WeightedGraph{\n\t\t\t\t{1, 2},\n\t\t\t\t{0},\n\t\t\t},\n\t\t\tsource:   0,\n\t\t\tsink:     1,\n\t\t\texpected: 0.0,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with no edges\",\n\t\t\tgraph: WeightedGraph{\n\t\t\t\t{0, 0},\n\t\t\t\t{0, 0},\n\t\t\t},\n\t\t\tsource:   0,\n\t\t\tsink:     1,\n\t\t\texpected: 0.0,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with 4 vertices\",\n\t\t\tgraph: WeightedGraph{\n\t\t\t\t{0, 1000000, 1000000, 0},\n\t\t\t\t{0, 0, 1, 1000000},\n\t\t\t\t{0, 0, 0, 1000000},\n\t\t\t\t{0, 0, 0, 0},\n\t\t\t},\n\t\t\tsource:   0,\n\t\t\tsink:     3,\n\t\t\texpected: 2000000,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with 6 vertices and some float64 weights\",\n\t\t\tgraph: WeightedGraph{\n\t\t\t\t{0, 16, 13.8, 0, 0, 0},\n\t\t\t\t{0, 0, 10, 12.7, 0, 0},\n\t\t\t\t{0, 4.2, 0, 0, 14, 0},\n\t\t\t\t{0, 0, 9.1, 0, 0, 21.3},\n\t\t\t\t{0, 0, 0, 7.5, 0, 4},\n\t\t\t\t{0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t\tsource:   0,\n\t\t\tsink:     5,\n\t\t\texpected: 24.2,\n\t\t},\n\t}\n\tfor _, test := range edmondKarpTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tresult := EdmondKarp(test.graph, test.source, test.sink)\n\n\t\t\tif !almostEqual(test.expected, result) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expected result:%f\\nFound: %f\", test.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/floydwarshall.go",
    "content": "// Floyd-Warshall algorithm\n// time complexity: O(V^3) where V is the number of vertices in the graph\n// space complexity: O(V^2) where V is the number of vertices in the graph\n// https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\n\npackage graph\n\nimport \"math\"\n\n// WeightedGraph defining matrix to use 2d array easier\ntype WeightedGraph [][]float64\n\n// Defining maximum value. If two vertices share this value, it means they are not connected\nvar Inf = math.Inf(1)\n\n// FloydWarshall Returns all pair's shortest path using Floyd Warshall algorithm\nfunc FloydWarshall(graph WeightedGraph) WeightedGraph {\n\t// If graph is empty, returns nil\n\tif len(graph) == 0 || len(graph) != len(graph[0]) {\n\t\treturn nil\n\t}\n\n\tfor i := 0; i < len(graph); i++ {\n\t\t//If graph matrix width is different than the height, returns nil\n\t\tif len(graph[i]) != len(graph) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tnumVertices := len(graph)\n\n\t// Initializing result matrix and filling it up with same values as given graph\n\tresult := make(WeightedGraph, numVertices)\n\n\tfor i := 0; i < numVertices; i++ {\n\t\tresult[i] = make([]float64, numVertices)\n\t\tfor j := 0; j < numVertices; j++ {\n\t\t\tresult[i][j] = graph[i][j]\n\t\t}\n\t}\n\n\t// Running over the result matrix and following the algorithm\n\tfor k := 0; k < numVertices; k++ {\n\t\tfor i := 0; i < numVertices; i++ {\n\t\t\tfor j := 0; j < numVertices; j++ {\n\t\t\t\t// If there is a less costly path from i to j node, remembering it\n\t\t\t\tif result[i][j] > result[i][k]+result[k][j] {\n\t\t\t\t\tresult[i][j] = result[i][k] + result[k][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n"
  },
  {
    "path": "graph/floydwarshall_test.go",
    "content": "package graph\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nconst float64EqualityThreshold = 1e-9\n\n// almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold\n// reference: https://stackoverflow.com/a/47969546\nfunc almostEqual(a, b float64) bool {\n\treturn math.Abs(a-b) <= float64EqualityThreshold\n}\n\n// IsAlmostEqualTo verifies if two WeightedGraphs can be considered almost equal\nfunc (a *WeightedGraph) IsAlmostEqualTo(b WeightedGraph) bool {\n\tif len(*a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor i := range *a {\n\t\tif len((*a)[i]) != len(b[i]) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor j := range (*a)[i] {\n\t\t\tif (*a)[i][j] == Inf && b[i][j] == Inf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !almostEqual((*a)[i][j], b[i][j]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc TestFloydWarshall(t *testing.T) {\n\tvar floydWarshallTestData = []struct {\n\t\tdescription string\n\t\tgraph       [][]float64\n\t\texpected    [][]float64\n\t}{\n\t\t{\n\t\t\tdescription: \"test empty graph\",\n\t\t\tgraph:       nil,\n\t\t\texpected:    nil,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with wrong dimensions\",\n\t\t\tgraph: [][]float64{\n\t\t\t\t{1, 2},\n\t\t\t\t{Inf},\n\t\t\t},\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with no edges\",\n\t\t\tgraph: [][]float64{\n\t\t\t\t{Inf, Inf},\n\t\t\t\t{Inf, Inf},\n\t\t\t},\n\t\t\texpected: [][]float64{\n\t\t\t\t{Inf, Inf},\n\t\t\t\t{Inf, Inf},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with only negative edges\",\n\t\t\tgraph: [][]float64{\n\t\t\t\t{-3, -2},\n\t\t\t\t{-3, -2},\n\t\t\t},\n\t\t\texpected: [][]float64{\n\t\t\t\t{-17, -25},\n\t\t\t\t{-26, -34},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test graph with 5 vertices and self-loops\",\n\t\t\tgraph: [][]float64{\n\t\t\t\t{1, 2, Inf, Inf, Inf},\n\t\t\t\t{Inf, Inf, 3, -4, Inf},\n\t\t\t\t{Inf, Inf, Inf, Inf, 5},\n\t\t\t\t{1, Inf, Inf, Inf, Inf},\n\t\t\t\t{Inf, Inf, Inf, 2, Inf},\n\t\t\t},\n\t\t\texpected: [][]float64{\n\t\t\t\t{-1, 1, 4, -3, 8},\n\t\t\t\t{-3, -1, 2, -5, 6},\n\t\t\t\t{7, 9, 12, 5, 5},\n\t\t\t\t{0, 2, 5, -2, 9},\n\t\t\t\t{2, 4, 7, 0, 9},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range floydWarshallTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tresult := FloydWarshall(test.graph)\n\n\t\t\tif !result.IsAlmostEqualTo(test.expected) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expected result:%f\\nFound: %f\", test.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/graph.go",
    "content": "// This file contains the simple structural implementation of\n// directed & undirected graphs used within the graph package\n// Author(s): [Shivam](https://github.com/Shivam010), [Tahmeed](https://github.com/Tahmeed156)\n\npackage graph\n\n// Graph provides a structure to store the graph.\n// It is safe to use its empty object.\ntype Graph struct {\n\tvertices int\n\tedges    map[int]map[int]int // Stores weight of an edge\n\tDirected bool                // Differentiate directed/undirected graphs\n}\n\n// Constructor functions for graphs (undirected by default)\nfunc New(v int) *Graph {\n\treturn &Graph{\n\t\tvertices: v,\n\t}\n}\n\n// AddVertex will add a new vertex in the graph.\n// If the vertex already exists it will do nothing.\nfunc (g *Graph) AddVertex(v int) {\n\tif g.edges == nil {\n\t\tg.edges = make(map[int]map[int]int)\n\t}\n\n\t// Check if vertex is present or not\n\tif _, ok := g.edges[v]; !ok {\n\t\tg.edges[v] = make(map[int]int)\n\t}\n}\n\n// AddEdge will add a new edge between the provided vertices in the graph\nfunc (g *Graph) AddEdge(one, two int) {\n\t// Add an edge with 0 weight\n\tg.AddWeightedEdge(one, two, 0)\n}\n\n// AddWeightedEdge will add a new weighted edge between the provided vertices in the graph\nfunc (g *Graph) AddWeightedEdge(one, two, weight int) {\n\t// Add vertices: one and two to the graph if they are not present\n\tg.AddVertex(one)\n\tg.AddVertex(two)\n\n\t// And finally add the edges\n\t// one->two and two->one for undirected graph\n\t// one->two for directed graphs\n\tg.edges[one][two] = weight\n\tif !g.Directed {\n\t\tg.edges[two][one] = weight\n\t}\n}\n"
  },
  {
    "path": "graph/graph_test.go",
    "content": "// Tests for directed and undirected graphs\n\npackage graph\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar graphTestCases = []struct {\n\tname     string\n\tedges    [][]int\n\tvertices int\n}{\n\t{\n\t\t\"single edge\",\n\t\t[][]int{\n\t\t\t{0, 1, 1},\n\t\t},\n\t\t2,\n\t},\n\t{\n\t\t\"many edges\",\n\t\t[][]int{\n\t\t\t{0, 1, 1},\n\t\t\t{0, 2, 2},\n\t\t\t{1, 3, 4},\n\t\t\t{3, 4, 3},\n\t\t\t{4, 8, 3},\n\t\t\t{4, 9, 1},\n\t\t\t{7, 8, 2},\n\t\t\t{8, 9, 2},\n\t\t},\n\t\t10,\n\t},\n\t{\n\t\t\"cycles\",\n\t\t[][]int{\n\t\t\t{0, 1, 1},\n\t\t\t{0, 2, 2},\n\t\t\t{1, 3, 4},\n\t\t\t{3, 4, 3},\n\t\t\t{4, 2, 1},\n\t\t},\n\t\t5,\n\t},\n\t{\n\t\t\"disconnected graphs\",\n\t\t[][]int{\n\t\t\t{0, 1, 5},\n\t\t\t{2, 4, 5},\n\t\t\t{3, 8, 5},\n\t\t},\n\t\t2,\n\t},\n}\n\nfunc TestDirectedGraph(t *testing.T) {\n\n\t// Testing self-loops separately only for directed graphs.\n\t// For undirected graphs each edge already creates a self-loop.\n\tdirectedGraphTestCases := append(graphTestCases, struct {\n\t\tname     string\n\t\tedges    [][]int\n\t\tvertices int\n\t}{\n\t\t\"self-loops\",\n\t\t[][]int{\n\t\t\t{0, 1, 1},\n\t\t\t{1, 2, 2},\n\t\t\t{2, 1, 3},\n\t\t},\n\t\t3,\n\t})\n\n\tfor _, test := range directedGraphTestCases {\n\t\tt.Run(fmt.Sprint(test.name), func(t *testing.T) {\n\t\t\t// Initializing graph, adding edges\n\t\t\tgraph := New(test.vertices)\n\t\t\tgraph.Directed = true\n\t\t\tfor _, edge := range test.edges {\n\t\t\t\tgraph.AddWeightedEdge(edge[0], edge[1], edge[2])\n\t\t\t}\n\n\t\t\tif graph.vertices != test.vertices {\n\t\t\t\tt.Errorf(\"Number of vertices, Expected: %d, Computed: %d\", test.vertices, graph.vertices)\n\t\t\t}\n\t\t\tedgeCount := 0\n\t\t\tfor _, e := range graph.edges {\n\t\t\t\tedgeCount += len(e)\n\t\t\t}\n\t\t\tif edgeCount != len(test.edges) {\n\t\t\t\tt.Errorf(\"Number of edges, Expected: %d, Computed: %d\", len(test.edges), edgeCount)\n\t\t\t}\n\t\t\tfor _, edge := range test.edges {\n\t\t\t\tif val, found := graph.edges[edge[0]][edge[1]]; !found || val != edge[2] {\n\t\t\t\t\tt.Errorf(\"Edge {%d->%d (%d)} not found\", edge[0], edge[1], edge[2])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUndirectedGraph(t *testing.T) {\n\n\tfor _, test := range graphTestCases {\n\t\tt.Run(fmt.Sprint(test.name), func(t *testing.T) {\n\t\t\t// Initializing graph, adding edges\n\t\t\tgraph := New(test.vertices)\n\t\t\tfor _, edge := range test.edges {\n\t\t\t\tgraph.AddWeightedEdge(edge[0], edge[1], edge[2])\n\t\t\t}\n\n\t\t\tif graph.vertices != test.vertices {\n\t\t\t\tt.Errorf(\"Number of vertices, Expected: %d, Computed: %d\", test.vertices, graph.vertices)\n\t\t\t}\n\t\t\tedgeCount := 0\n\t\t\tfor _, e := range graph.edges {\n\t\t\t\tedgeCount += len(e)\n\t\t\t}\n\t\t\tif edgeCount != len(test.edges)*2 {\n\t\t\t\tt.Errorf(\"Number of edges, Expected: %d, Computed: %d\", len(test.edges)*2, edgeCount)\n\t\t\t}\n\t\t\tfor _, edge := range test.edges {\n\t\t\t\tif val, found := graph.edges[edge[0]][edge[1]]; !found || val != edge[2] {\n\t\t\t\t\tt.Errorf(\"Edge {%d->%d (%d)} not found\", edge[0], edge[1], edge[2])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/kahn.go",
    "content": "// Kahn's algorithm computes a topological ordering of a directed acyclic graph (DAG).\n// Time Complexity: O(V + E)\n// Space Complexity: O(V + E)\n// Reference: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm\n// see graph.go, topological.go, kahn_test.go\n\npackage graph\n\n// Kahn's algorithm computes a topological ordering of a directed acyclic graph (DAG).\n// `n` is the number of vertices,\n// `dependencies` is a list of directed edges, where each pair [a, b] represents\n// a directed edge from a to b (i.e. b depends on a).\n// Vertices are assumed to be labelled 0, 1, ..., n-1.\n// If the graph is not a DAG, the function returns nil.\nfunc Kahn(n int, dependencies [][]int) []int {\n\tg := Graph{vertices: n, Directed: true}\n\t// track the in-degree (number of incoming edges) of each vertex\n\tinDegree := make([]int, n)\n\n\t// populate g with edges, increase the in-degree counts accordingly\n\tfor _, d := range dependencies {\n\t\t// make sure we don't add the same edge twice\n\t\tif _, ok := g.edges[d[0]][d[1]]; !ok {\n\t\t\tg.AddEdge(d[0], d[1])\n\t\t\tinDegree[d[1]]++\n\t\t}\n\t}\n\n\t// queue holds all vertices with in-degree 0\n\t// these vertices have no dependency and thus can be ordered first\n\tqueue := make([]int, 0, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tif inDegree[i] == 0 {\n\t\t\tqueue = append(queue, i)\n\t\t}\n\t}\n\n\t// order holds a valid topological order\n\torder := make([]int, 0, n)\n\n\t// process the dependency-free vertices\n\t// every time we process a vertex, we \"remove\" it from the graph\n\tfor len(queue) > 0 {\n\t\t// pop the first vertex from the queue\n\t\tvtx := queue[0]\n\t\tqueue = queue[1:]\n\t\t// add the vertex to the topological order\n\t\torder = append(order, vtx)\n\t\t// \"remove\" all the edges coming out of this vertex\n\t\t// every time we remove an edge, the corresponding in-degree reduces by 1\n\t\t// if all dependencies on a vertex is removed, enqueue the vertex\n\t\tfor neighbour := range g.edges[vtx] {\n\t\t\tinDegree[neighbour]--\n\t\t\tif inDegree[neighbour] == 0 {\n\t\t\t\tqueue = append(queue, neighbour)\n\t\t\t}\n\t\t}\n\t}\n\n\t// if the graph is a DAG, order should contain all the certices\n\tif len(order) != n {\n\t\treturn nil\n\t}\n\treturn order\n}\n"
  },
  {
    "path": "graph/kahn_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestKahn(t *testing.T) {\n\ttestCases := []struct {\n\t\tname         string\n\t\tn            int\n\t\tdependencies [][]int\n\t\twantNil      bool\n\t}{\n\t\t{\n\t\t\t\"linear graph\",\n\t\t\t3,\n\t\t\t[][]int{{0, 1}, {1, 2}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"diamond graph\",\n\t\t\t4,\n\t\t\t[][]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"star graph\",\n\t\t\t5,\n\t\t\t[][]int{{0, 1}, {0, 2}, {0, 3}, {0, 4}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"disconnected graph\",\n\t\t\t5,\n\t\t\t[][]int{{0, 1}, {0, 2}, {3, 4}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"cycle graph 1\",\n\t\t\t4,\n\t\t\t[][]int{{0, 1}, {1, 2}, {2, 3}, {3, 0}},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"cycle graph 2\",\n\t\t\t4,\n\t\t\t[][]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}},\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"single node graph\",\n\t\t\t1,\n\t\t\t[][]int{},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"empty graph\",\n\t\t\t0,\n\t\t\t[][]int{},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"redundant dependencies\",\n\t\t\t4,\n\t\t\t[][]int{{0, 1}, {1, 2}, {1, 2}, {2, 3}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"island vertex\",\n\t\t\t4,\n\t\t\t[][]int{{0, 1}, {0, 2}},\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"more complicated graph\",\n\t\t\t14,\n\t\t\t[][]int{{1, 9}, {2, 0}, {3, 2}, {4, 5}, {4, 6}, {4, 7}, {6, 7},\n\t\t\t\t{7, 8}, {9, 4}, {10, 0}, {10, 1}, {10, 12}, {11, 13},\n\t\t\t\t{12, 0}, {12, 11}, {13, 5}},\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Kahn(tc.n, tc.dependencies)\n\t\t\tif tc.wantNil {\n\t\t\t\tif actual != nil {\n\t\t\t\t\tt.Errorf(\"Kahn(%d, %v) = %v; want nil\", tc.n, tc.dependencies, actual)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif actual == nil {\n\t\t\t\t\tt.Errorf(\"Kahn(%d, %v) = nil; want valid order\", tc.n, tc.dependencies)\n\t\t\t\t} else {\n\t\t\t\t\tseen := make([]bool, tc.n)\n\t\t\t\t\tpositions := make([]int, tc.n)\n\t\t\t\t\tfor i, v := range actual {\n\t\t\t\t\t\tseen[v] = true\n\t\t\t\t\t\tpositions[v] = i\n\t\t\t\t\t}\n\t\t\t\t\tfor i, v := range seen {\n\t\t\t\t\t\tif !v {\n\t\t\t\t\t\t\tt.Errorf(\"missing vertex %v\", i)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor _, d := range tc.dependencies {\n\t\t\t\t\t\tif positions[d[0]] > positions[d[1]] {\n\t\t\t\t\t\t\tt.Errorf(\"dependency %v not satisfied\", d)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/kosaraju.go",
    "content": "// kosaraju.go\n// description: Implementation of Kosaraju's algorithm to find Strongly Connected Components (SCCs) in a directed graph.\n// details: The algorithm consists of three steps:\n// 1. Perform DFS and fill the stack with vertices in the order of their finish times.\n// 2. Create a transposed graph by reversing all edges.\n// 3. Perform DFS on the transposed graph in the order defined by the stack to find SCCs.\n// time: O(V + E), where V is the number of vertices and E is the number of edges in the graph.\n// space: O(V), where V is the number of vertices in the graph.\n// ref link: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm\n// author: mapcrafter2048\n\npackage graph\n\n// Kosaraju returns a list of Strongly Connected Components (SCCs).\nfunc (g *Graph) Kosaraju() [][]int {\n\tstack := []int{}\n\tvisited := make([]bool, g.vertices)\n\n\t// Step 1: Perform DFS and fill stack based on finish times.\n\tfor i := 0; i < g.vertices; i++ {\n\t\tif !visited[i] {\n\t\t\tg.fillOrder(i, visited, &stack)\n\t\t}\n\t}\n\n\t// Step 2: Create a transposed graph.\n\ttransposed := g.transpose()\n\n\t// Step 3: Perform DFS on the transposed graph in the order defined by the stack.\n\tvisited = make([]bool, g.vertices)\n\tvar sccs [][]int\n\n\tfor len(stack) > 0 {\n\t\t// Pop vertex from stack\n\t\tv := stack[len(stack)-1]\n\t\tstack = stack[:len(stack)-1]\n\n\t\t// Perform DFS if not already visited.\n\t\tif !visited[v] {\n\t\t\tscc := []int{}\n\t\t\ttransposed.dfs(v, visited, &scc)\n\t\t\tsccs = append(sccs, scc)\n\t\t}\n\t}\n\n\treturn sccs\n}\n\n// Helper function to fill the stack with vertices in the order of their finish times.\nfunc (g *Graph) fillOrder(v int, visited []bool, stack *[]int) {\n\tvisited[v] = true\n\n\tfor neighbor := range g.edges[v] {\n\t\tif !visited[neighbor] {\n\t\t\tg.fillOrder(neighbor, visited, stack)\n\t\t}\n\t}\n\n\t// Push the current vertex to the stack after exploring all neighbors.\n\t*stack = append(*stack, v)\n}\n\n// Helper function to create a transposed (reversed) graph.\nfunc (g *Graph) transpose() *Graph {\n\ttransposed := &Graph{\n\t\tvertices: g.vertices,\n\t\tedges:    make(map[int]map[int]int),\n\t}\n\n\tfor v, neighbors := range g.edges {\n\t\tfor neighbor := range neighbors {\n\t\t\tif transposed.edges[neighbor] == nil {\n\t\t\t\ttransposed.edges[neighbor] = make(map[int]int)\n\t\t\t}\n\t\t\ttransposed.edges[neighbor][v] = 1 // Add the reversed edge\n\t\t}\n\t}\n\n\treturn transposed\n}\n\n// Helper DFS function used in the transposed graph to collect SCCs.\nfunc (g *Graph) dfs(v int, visited []bool, scc *[]int) {\n\tvisited[v] = true\n\t*scc = append(*scc, v)\n\n\tfor neighbor := range g.edges[v] {\n\t\tif !visited[neighbor] {\n\t\t\tg.dfs(neighbor, visited, scc)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "graph/kosaraju_test.go",
    "content": "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     string\n\t\tvertices int\n\t\tedges    map[int][]int\n\t\texpected [][]int\n\t}{\n\t\t{\n\t\t\tname:     \"Single SCC\",\n\t\t\tvertices: 5,\n\t\t\tedges: map[int][]int{\n\t\t\t\t0: {1},\n\t\t\t\t1: {2},\n\t\t\t\t2: {0, 3},\n\t\t\t\t3: {4},\n\t\t\t\t4: {},\n\t\t\t},\n\t\t\texpected: [][]int{{4}, {3}, {0, 2, 1}},\n\t\t},\n\t\t{\n\t\t\tname:     \"Multiple SCCs\",\n\t\t\tvertices: 8,\n\t\t\tedges: map[int][]int{\n\t\t\t\t0: {1},\n\t\t\t\t1: {2},\n\t\t\t\t2: {0, 3},\n\t\t\t\t3: {4},\n\t\t\t\t4: {5},\n\t\t\t\t5: {3, 6},\n\t\t\t\t6: {7},\n\t\t\t\t7: {6},\n\t\t\t},\n\t\t\texpected: [][]int{{6, 7}, {3, 4, 5}, {0, 2, 1}},\n\t\t},\n\t\t{\n\t\t\tname:     \"Disconnected graph\",\n\t\t\tvertices: 4,\n\t\t\tedges: map[int][]int{\n\t\t\t\t0: {1},\n\t\t\t\t1: {},\n\t\t\t\t2: {3},\n\t\t\t\t3: {},\n\t\t\t},\n\t\t\texpected: [][]int{{1}, {0}, {3}, {2}},\n\t\t},\n\t\t{\n\t\t\tname:     \"No edges\",\n\t\t\tvertices: 3,\n\t\t\tedges: map[int][]int{\n\t\t\t\t0: {},\n\t\t\t\t1: {},\n\t\t\t\t2: {},\n\t\t\t},\n\t\t\texpected: [][]int{{0}, {1}, {2}},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Initializing graph\n\t\t\tgraph := &Graph{\n\t\t\t\tvertices: tt.vertices,\n\t\t\t\tedges:    make(map[int]map[int]int),\n\t\t\t}\n\t\t\tfor v, neighbors := range tt.edges {\n\t\t\t\tgraph.edges[v] = make(map[int]int)\n\t\t\t\tfor _, neighbor := range neighbors {\n\t\t\t\t\tgraph.edges[v][neighbor] = 1\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Running Kosaraju's algorithm to get the SCCs\n\t\t\tresult := graph.Kosaraju()\n\n\t\t\t// Sort the expected and result SCCs to ensure order doesn't matter\n\t\t\tsortSlices(tt.expected)\n\t\t\tsortSlices(result)\n\n\t\t\t// Compare the sorted SCCs\n\t\t\tif !reflect.DeepEqual(result, tt.expected) {\n\t\t\t\tt.Errorf(\"expected %v, got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Utility function to sort the slices and their contents\nfunc sortSlices(s [][]int) {\n\tfor _, inner := range s {\n\t\tsort.Ints(inner)\n\t}\n\tsort.Slice(s, func(i, j int) bool {\n\t\tif len(s[i]) == 0 || len(s[j]) == 0 {\n\t\t\treturn len(s[i]) < len(s[j])\n\t\t}\n\t\treturn s[i][0] < s[j][0]\n\t})\n}\n"
  },
  {
    "path": "graph/kruskal.go",
    "content": "// KRUSKAL'S ALGORITHM\n// Reference: Kruskal's Algorithm: https://www.scaler.com/topics/data-structures/kruskal-algorithm/\n// Reference: Union Find Algorithm: https://www.scaler.com/topics/data-structures/disjoint-set/\n// Author: Author: Mugdha Behere[https://github.com/MugdhaBehere]\n// Worst Case Time Complexity: O(E log E), where E is the number of edges.\n// Worst Case Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges.\n// see kruskal.go, kruskal_test.go\n\npackage graph\n\nimport (\n\t\"sort\"\n)\n\ntype Vertex int\n\ntype Edge struct {\n\tStart  Vertex\n\tEnd    Vertex\n\tWeight int\n}\n\nfunc KruskalMST(n int, edges []Edge) ([]Edge, int) {\n\t// Initialize variables to store the minimum spanning tree and its total cost\n\tvar mst []Edge\n\tvar cost int\n\n\t// Create a new UnionFind data structure with 'n' nodes\n\tu := NewUnionFind(n)\n\n\t// Sort the edges in non-decreasing order based on their weights\n\tsort.SliceStable(edges, func(i, j int) bool {\n\t\treturn edges[i].Weight < edges[j].Weight\n\t})\n\n\t// Iterate through the sorted edges\n\tfor _, edge := range edges {\n\t\t// Check if adding the current edge forms a cycle or not\n\t\tif u.Find(int(edge.Start)) != u.Find(int(edge.End)) {\n\t\t\t// Add the edge to the minimum spanning tree\n\t\t\tmst = append(mst, edge)\n\t\t\t// Add the weight of the edge to the total cost\n\t\t\tcost += edge.Weight\n\t\t\t// Merge the sets containing the start and end vertices of the current edge\n\t\t\tu.Union(int(edge.Start), int(edge.End))\n\t\t}\n\t}\n\n\t// Return the minimum spanning tree and its total cost\n\treturn mst, cost\n}\n"
  },
  {
    "path": "graph/kruskal_test.go",
    "content": "package graph\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestKruskalMST(t *testing.T) {\n\t// Define test cases with inputs, expected outputs, and sample graphs\n\tvar testCases = []struct {\n\t\tn     int\n\t\tgraph []Edge\n\t\tcost  int\n\t}{\n\t\t// Test Case 1\n\t\t{\n\t\t\tn: 5,\n\t\t\tgraph: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 4},\n\t\t\t\t{Start: 0, End: 2, Weight: 13},\n\t\t\t\t{Start: 0, End: 3, Weight: 7},\n\t\t\t\t{Start: 0, End: 4, Weight: 7},\n\t\t\t\t{Start: 1, End: 2, Weight: 9},\n\t\t\t\t{Start: 1, End: 3, Weight: 3},\n\t\t\t\t{Start: 1, End: 4, Weight: 7},\n\t\t\t\t{Start: 2, End: 3, Weight: 10},\n\t\t\t\t{Start: 2, End: 4, Weight: 14},\n\t\t\t\t{Start: 3, End: 4, Weight: 4},\n\t\t\t},\n\t\t\tcost: 20,\n\t\t},\n\t\t// Test Case 2\n\t\t{\n\t\t\tn: 3,\n\t\t\tgraph: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 12},\n\t\t\t\t{Start: 0, End: 2, Weight: 18},\n\t\t\t\t{Start: 1, End: 2, Weight: 6},\n\t\t\t},\n\t\t\tcost: 18,\n\t\t},\n\t\t// Test Case 3\n\t\t{\n\t\t\tn: 4,\n\t\t\tgraph: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 2},\n\t\t\t\t{Start: 0, End: 2, Weight: 1},\n\t\t\t\t{Start: 0, End: 3, Weight: 2},\n\t\t\t\t{Start: 1, End: 2, Weight: 1},\n\t\t\t\t{Start: 1, End: 3, Weight: 2},\n\t\t\t\t{Start: 2, End: 3, Weight: 3},\n\t\t\t},\n\t\t\tcost: 4,\n\t\t},\n\t\t// Test Case 4\n\t\t{\n\t\t\tn: 2,\n\t\t\tgraph: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 4000000},\n\t\t\t},\n\t\t\tcost: 4000000,\n\t\t},\n\t\t// Test Case 5\n\t\t{\n\t\t\tn: 1,\n\t\t\tgraph: []Edge{\n\t\t\t\t{Start: 0, End: 0, Weight: 0},\n\t\t\t},\n\t\t\tcost: 0,\n\t\t},\n\t}\n\n\t// Iterate through the test cases and run the tests\n\tfor i, testCase := range testCases {\n\t\tt.Run(fmt.Sprintf(\"Test Case %d\", i), func(t *testing.T) {\n\t\t\t// Execute KruskalMST for the current test case\n\t\t\t_, computed := KruskalMST(testCase.n, testCase.graph)\n\n\t\t\t// Compare the computed result with the expected result\n\t\t\tif computed != testCase.cost {\n\t\t\t\tt.Errorf(\"Test Case %d, Expected: %d, Computed: %d\", i, testCase.cost, computed)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/lowestcommonancestor.go",
    "content": "// lowestcommonancestor.go\n// description: Implementation of Lowest common ancestor (LCA) algorithm.\n// detail:\n// Let `T` be a tree. The LCA of `u` and `v` in T is the shared ancestor of `u` and `v`\n// that is located farthest from the root.\n// time complexity: O(n log n) where n is the number of vertices in the tree\n// space complexity: O(n log n) where n is the number of vertices in the tree\n// references: [cp-algorithms](https://cp-algorithms.com/graph/lca_binary_lifting.html)\n// author(s) [Dat](https://github.com/datbeohbbh)\n// see lowestcommonancestor_test.go for a test implementation.\n\npackage graph\n\ntype TreeEdge struct {\n\tfrom int\n\tto   int\n}\n\ntype ITree interface {\n\tdfs(int, int)\n\taddEdge(int, int)\n\tGetDepth(int) int\n\tGetDad(int) int\n\tGetLCA(int, int) int\n}\n\ntype Tree struct {\n\tnumbersVertex int\n\troot          int\n\tMAXLOG        int\n\tdepth         []int\n\tdad           []int\n\tjump          [][]int\n\tedges         [][]int\n}\n\nfunc (tree *Tree) addEdge(u, v int) {\n\ttree.edges[u] = append(tree.edges[u], v)\n\ttree.edges[v] = append(tree.edges[v], u)\n}\n\nfunc (tree *Tree) dfs(u, par int) {\n\ttree.jump[0][u] = par\n\ttree.dad[u] = par\n\tfor _, v := range tree.edges[u] {\n\t\tif v != par {\n\t\t\ttree.depth[v] = tree.depth[u] + 1\n\t\t\ttree.dfs(v, u)\n\t\t}\n\t}\n}\n\nfunc (tree *Tree) GetDepth(u int) int {\n\treturn tree.depth[u]\n}\n\nfunc (tree *Tree) GetDad(u int) int {\n\treturn tree.dad[u]\n}\n\nfunc (tree *Tree) GetLCA(u, v int) int {\n\tif tree.GetDepth(u) < tree.GetDepth(v) {\n\t\tu, v = v, u\n\t}\n\n\tfor j := tree.MAXLOG - 1; j >= 0; j-- {\n\t\tif tree.GetDepth(tree.jump[j][u]) >= tree.GetDepth(v) {\n\t\t\tu = tree.jump[j][u]\n\t\t}\n\t}\n\n\tif u == v {\n\t\treturn u\n\t}\n\n\tfor j := tree.MAXLOG - 1; j >= 0; j-- {\n\t\tif tree.jump[j][u] != tree.jump[j][v] {\n\t\t\tu = tree.jump[j][u]\n\t\t\tv = tree.jump[j][v]\n\t\t}\n\t}\n\n\treturn tree.jump[0][u]\n}\n\nfunc NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {\n\ttree = new(Tree)\n\ttree.numbersVertex, tree.root, tree.MAXLOG = numbersVertex, root, 0\n\ttree.depth = make([]int, numbersVertex)\n\ttree.dad = make([]int, numbersVertex)\n\n\tfor (1 << tree.MAXLOG) <= numbersVertex {\n\t\t(tree.MAXLOG) += 1\n\t}\n\t(tree.MAXLOG) += 1\n\n\ttree.jump = make([][]int, tree.MAXLOG)\n\tfor j := 0; j < tree.MAXLOG; j++ {\n\t\ttree.jump[j] = make([]int, numbersVertex)\n\t}\n\n\ttree.edges = make([][]int, numbersVertex)\n\tfor _, e := range edges {\n\t\ttree.addEdge(e.from, e.to)\n\t}\n\n\treturn tree\n}\n\n// For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc.\n// 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)`.\n// These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time.\nfunc LowestCommonAncestor(tree *Tree) {\n\t// call dfs to compute depth from the root to each node and the parent of each node.\n\ttree.dfs(tree.root, tree.root)\n\n\t// compute jump[j][u]\n\tfor j := 1; j < tree.MAXLOG; j++ {\n\t\tfor u := 0; u < tree.numbersVertex; u++ {\n\t\t\ttree.jump[j][u] = tree.jump[j-1][tree.jump[j-1][u]]\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "graph/lowestcommonancestor_test.go",
    "content": "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\n}\n\nfunc TestLCA(t *testing.T) {\n\ttestSuites := []struct {\n\t\tnumbersVertex int\n\t\troot          int\n\t\tedges         []TreeEdge\n\t\tqueries       []Query\n\t}{\n\t\t{\n\t\t\tnumbersVertex: 2,\n\t\t\troot:          0,\n\t\t\tedges: []TreeEdge{\n\t\t\t\t{\n\t\t\t\t\tfrom: 0,\n\t\t\t\t\tto:   1,\n\t\t\t\t},\n\t\t\t},\n\t\t\tqueries: []Query{\n\t\t\t\t{\n\t\t\t\t\tu:        0,\n\t\t\t\t\tv:        0,\n\t\t\t\t\texpected: 0,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        0,\n\t\t\t\t\tv:        1,\n\t\t\t\t\texpected: 0,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        1,\n\t\t\t\t\tv:        1,\n\t\t\t\t\texpected: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tnumbersVertex: 1,\n\t\t\troot:          0,\n\t\t\tedges:         []TreeEdge{},\n\t\t\tqueries: []Query{\n\t\t\t\t{\n\t\t\t\t\tu:        0,\n\t\t\t\t\tv:        0,\n\t\t\t\t\texpected: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tnumbersVertex: 9,\n\t\t\troot:          7,\n\t\t\tedges: []TreeEdge{\n\t\t\t\t{\n\t\t\t\t\tfrom: 0,\n\t\t\t\t\tto:   1,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 0,\n\t\t\t\t\tto:   2,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 2,\n\t\t\t\t\tto:   3,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 2,\n\t\t\t\t\tto:   4,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 2,\n\t\t\t\t\tto:   6,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 3,\n\t\t\t\t\tto:   5,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 6,\n\t\t\t\t\tto:   7,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: 6,\n\t\t\t\t\tto:   8,\n\t\t\t\t},\n\t\t\t},\n\t\t\tqueries: []Query{\n\t\t\t\t{\n\t\t\t\t\tu:        1,\n\t\t\t\t\tv:        0,\n\t\t\t\t\texpected: 0,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        8,\n\t\t\t\t\tv:        2,\n\t\t\t\t\texpected: 6,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        1,\n\t\t\t\t\tv:        5,\n\t\t\t\t\texpected: 2,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        4,\n\t\t\t\t\tv:        7,\n\t\t\t\t\texpected: 7,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tu:        0,\n\t\t\t\t\tv:        8,\n\t\t\t\t\texpected: 6,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t// Test #2:\n\t//\t\t\t\t\t\t\t7\n\t//\t\t\t\t\t\t /\n\t//\t\t\t\t\t\t6\n\t//\t\t\t\t\t/  \\\n\t//\t\t\t\t2    8\n\t//\t\t\t/ | \\\n\t//\t\t 0  3  4\n\t//\t\t/   |\n\t//\t 1    5\n\tfor idx, test := range testSuites {\n\t\ttree := NewTree(test.numbersVertex, test.root, test.edges)\n\t\tLowestCommonAncestor(tree)\n\n\t\tfor qi, query := range test.queries {\n\t\t\tactual := tree.GetLCA(query.u, query.v)\n\t\t\texpected := query.expected\n\t\t\tif actual != expected {\n\t\t\t\tt.Errorf(\"\\nTest #%d:\\nQuery #%d: u = %d, v = %d\\nExpected %d, but actual %d\", idx, qi, query.u, query.v, expected, actual)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc generateTree() *Tree {\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\tconst MAXVERTEX int = 2000\n\tvar numbersVertex int = rnd.Intn(MAXVERTEX) + 1\n\tvar root int = rnd.Intn(numbersVertex)\n\tvar edges []TreeEdge\n\n\tvar fullGraph []TreeEdge\n\tfor u := 0; u < numbersVertex; u++ {\n\t\tfor v := 0; v < numbersVertex; v++ {\n\t\t\tfullGraph = append(fullGraph, TreeEdge{\n\t\t\t\tfrom: u,\n\t\t\t\tto:   v,\n\t\t\t})\n\t\t}\n\t}\n\trnd.Shuffle(len(fullGraph), func(i, j int) {\n\t\tfullGraph[i], fullGraph[j] = fullGraph[j], fullGraph[i]\n\t})\n\n\tpar := make([]int, numbersVertex)\n\tfor u := 0; u < numbersVertex; u++ {\n\t\tpar[u] = u\n\t}\n\n\tvar findp func(int) int\n\tfindp = func(u int) int {\n\t\tif u == par[u] {\n\t\t\treturn u\n\t\t} else {\n\t\t\tpar[u] = findp(par[u])\n\t\t\treturn par[u]\n\t\t}\n\t}\n\n\tjoin := func(u, v int) bool {\n\t\tu, v = findp(u), findp(v)\n\t\tif u == v {\n\t\t\treturn false\n\t\t}\n\t\tpar[v] = u\n\t\treturn true\n\t}\n\n\tfor _, e := range fullGraph {\n\t\tif join(e.from, e.to) == true {\n\t\t\tedges = append(edges, e)\n\t\t}\n\t}\n\n\treturn NewTree(numbersVertex, root, edges)\n}\n\nfunc generateQuery(tree *Tree) []Query {\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tconst MAXQUERY = 50\n\tvar queries []Query\n\n\tbruteforceLCA := func(u, v int) int {\n\t\tfor u != v {\n\t\t\tif tree.GetDepth(u) > tree.GetDepth(v) {\n\t\t\t\tu = tree.GetDad(u)\n\t\t\t} else {\n\t\t\t\tv = tree.GetDad(v)\n\t\t\t}\n\t\t}\n\t\treturn u\n\t}\n\n\tfor q := 1; q <= MAXQUERY; q++ {\n\t\tu := rnd.Intn(tree.numbersVertex)\n\t\tv := rnd.Intn(tree.numbersVertex)\n\t\tqueries = append(queries, Query{\n\t\t\tu:        u,\n\t\t\tv:        v,\n\t\t\texpected: bruteforceLCA(u, v),\n\t\t})\n\t}\n\n\treturn queries\n}\n\n// Test with the tree with up to 2000 vertices.\nfunc TestLCAWithLargeTree(t *testing.T) {\n\tconst MAXTEST int = 20\n\n\tfor test := 1; test <= MAXTEST; test++ {\n\t\ttree := generateTree()\n\t\tLowestCommonAncestor(tree)\n\n\t\tqueries := generateQuery(tree)\n\n\t\tfor qi, query := range queries {\n\t\t\tactual := tree.GetLCA(query.u, query.v)\n\t\t\texpected := query.expected\n\t\t\tif actual != expected {\n\t\t\t\tt.Errorf(\"\\nTest #%d:\\nQuery #%d: u = %d, v = %d\\nExpected %d, but actual %d\", test, qi, query.u, query.v, expected, actual)\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "graph/prim.go",
    "content": "// The Prim's algorithm computes the minimum spanning tree for a weighted undirected graph\n// Worst Case Time Complexity: O(E log V) using Binary heap, where V is the number of vertices and E is the number of edges\n// Space Complexity: O(V + E)\n// Implementation is based on the book 'Introduction to Algorithms' (CLRS)\n\npackage graph\n\nimport (\n\t\"container/heap\"\n)\n\ntype minEdge []Edge\n\nfunc (h minEdge) Len() int           { return len(h) }\nfunc (h minEdge) Less(i, j int) bool { return h[i].Weight < h[j].Weight }\nfunc (h minEdge) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }\n\nfunc (h *minEdge) Push(x interface{}) {\n\t*h = append(*h, x.(Edge))\n}\n\nfunc (h *minEdge) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\nfunc (g *Graph) PrimMST(start Vertex) ([]Edge, int) {\n\tvar mst []Edge\n\tmarked := make([]bool, g.vertices)\n\th := &minEdge{}\n\t// Pushing neighbors of the start node to the binary heap\n\tfor neighbor, weight := range g.edges[int(start)] {\n\t\theap.Push(h, Edge{start, Vertex(neighbor), weight})\n\t}\n\tmarked[start] = true\n\tcost := 0\n\tfor h.Len() > 0 {\n\t\te := heap.Pop(h).(Edge)\n\t\tend := int(e.End)\n\t\t// To avoid cycles\n\t\tif marked[end] {\n\t\t\tcontinue\n\t\t}\n\t\tmarked[end] = true\n\t\tcost += e.Weight\n\t\tmst = append(mst, e)\n\t\t// Check for neighbors of the newly added edge's End vertex\n\t\tfor neighbor, weight := range g.edges[end] {\n\t\t\tif !marked[neighbor] {\n\t\t\t\theap.Push(h, Edge{e.End, Vertex(neighbor), weight})\n\t\t\t}\n\t\t}\n\t}\n\treturn mst, cost\n}\n"
  },
  {
    "path": "graph/prim_test.go",
    "content": "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\tedges    []Edge\n\t\tvertices int\n\t\tstart    int\n\t\tcost     int\n\t\tmst      []Edge\n\t}{\n\t\t{\n\t\t\tedges: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 4},\n\t\t\t\t{Start: 0, End: 2, Weight: 13},\n\t\t\t\t{Start: 0, End: 3, Weight: 7},\n\t\t\t\t{Start: 0, End: 4, Weight: 7},\n\t\t\t\t{Start: 1, End: 2, Weight: 9},\n\t\t\t\t{Start: 1, End: 3, Weight: 3},\n\t\t\t\t{Start: 1, End: 4, Weight: 7},\n\t\t\t\t{Start: 2, End: 3, Weight: 10},\n\t\t\t\t{Start: 2, End: 4, Weight: 14},\n\t\t\t\t{Start: 3, End: 4, Weight: 4},\n\t\t\t},\n\t\t\tvertices: 5,\n\t\t\tstart:    0,\n\t\t\tcost:     20,\n\t\t\tmst: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 4},\n\t\t\t\t{Start: 1, End: 3, Weight: 3},\n\t\t\t\t{Start: 3, End: 4, Weight: 4},\n\t\t\t\t{Start: 1, End: 2, Weight: 9},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tedges: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 4},\n\t\t\t\t{Start: 0, End: 7, Weight: 8},\n\t\t\t\t{Start: 1, End: 2, Weight: 8},\n\t\t\t\t{Start: 1, End: 7, Weight: 11},\n\t\t\t\t{Start: 2, End: 3, Weight: 7},\n\t\t\t\t{Start: 2, End: 5, Weight: 4},\n\t\t\t\t{Start: 2, End: 8, Weight: 2},\n\t\t\t\t{Start: 3, End: 4, Weight: 9},\n\t\t\t\t{Start: 3, End: 5, Weight: 14},\n\t\t\t\t{Start: 4, End: 5, Weight: 10},\n\t\t\t\t{Start: 5, End: 6, Weight: 2},\n\t\t\t\t{Start: 6, End: 7, Weight: 1},\n\t\t\t\t{Start: 6, End: 8, Weight: 6},\n\t\t\t\t{Start: 7, End: 8, Weight: 7},\n\t\t\t},\n\t\t\tvertices: 9,\n\t\t\tstart:    3,\n\t\t\tcost:     37,\n\t\t\tmst: []Edge{\n\t\t\t\t{Start: 3, End: 2, Weight: 7},\n\t\t\t\t{Start: 2, End: 8, Weight: 2},\n\t\t\t\t{Start: 2, End: 5, Weight: 4},\n\t\t\t\t{Start: 5, End: 6, Weight: 2},\n\t\t\t\t{Start: 6, End: 7, Weight: 1},\n\t\t\t\t{Start: 2, End: 1, Weight: 8},\n\t\t\t\t{Start: 1, End: 0, Weight: 4},\n\t\t\t\t{Start: 3, End: 4, Weight: 9},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tedges: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 2},\n\t\t\t\t{Start: 0, End: 3, Weight: 6},\n\t\t\t\t{Start: 1, End: 2, Weight: 3},\n\t\t\t\t{Start: 1, End: 3, Weight: 8},\n\t\t\t\t{Start: 1, End: 4, Weight: 5},\n\t\t\t\t{Start: 2, End: 4, Weight: 7},\n\t\t\t\t{Start: 3, End: 4, Weight: 9},\n\t\t\t},\n\t\t\tvertices: 5,\n\t\t\tstart:    2,\n\t\t\tcost:     16,\n\t\t\tmst: []Edge{\n\t\t\t\t{Start: 2, End: 1, Weight: 3},\n\t\t\t\t{Start: 1, End: 0, Weight: 2},\n\t\t\t\t{Start: 1, End: 4, Weight: 5},\n\t\t\t\t{Start: 0, End: 3, Weight: 6},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tedges: []Edge{\n\t\t\t\t{Start: 0, End: 0, Weight: 0},\n\t\t\t},\n\t\t\tvertices: 1,\n\t\t\tstart:    0,\n\t\t\tcost:     0,\n\t\t\tmst:      nil,\n\t\t},\n\t\t{\n\t\t\tedges: []Edge{\n\t\t\t\t{Start: 0, End: 1, Weight: 1},\n\t\t\t\t{Start: 0, End: 2, Weight: 6},\n\t\t\t\t{Start: 0, End: 3, Weight: 5},\n\t\t\t\t{Start: 1, End: 2, Weight: 2},\n\t\t\t\t{Start: 1, End: 4, Weight: 4},\n\t\t\t\t{Start: 2, End: 4, Weight: 9},\n\t\t\t},\n\t\t\tvertices: 5,\n\t\t\tstart:    4,\n\t\t\tcost:     12,\n\t\t\tmst: []Edge{\n\t\t\t\t{Start: 4, End: 1, Weight: 4},\n\t\t\t\t{Start: 1, End: 0, Weight: 1},\n\t\t\t\t{Start: 1, End: 2, Weight: 2},\n\t\t\t\t{Start: 0, End: 3, Weight: 5},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tt.Run(fmt.Sprintf(\"Test Case %d\", i), func(t *testing.T) {\n\t\t\t// Initializing graph, adding edges\n\t\t\tgraph := New(testCase.vertices)\n\t\t\tgraph.Directed = false\n\t\t\tfor _, edge := range testCase.edges {\n\t\t\t\tgraph.AddWeightedEdge(int(edge.Start), int(edge.End), edge.Weight)\n\t\t\t}\n\n\t\t\tcomputedMST, computedCost := graph.PrimMST(Vertex(testCase.start))\n\n\t\t\t// Compare the computed result with the expected result\n\t\t\tif computedCost != testCase.cost {\n\t\t\t\tt.Errorf(\"Test Case %d, Expected Cost: %d, Computed: %d\", i, testCase.cost, computedCost)\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(testCase.mst, computedMST) {\n\t\t\t\tt.Errorf(\"Test Case %d, Expected MST: %v, Computed: %v\", i, testCase.mst, computedMST)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/topological.go",
    "content": "// topological.go\n// description: Topological sort\n// details: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.\n// time complexity: O(V+E) where V is the number of vertices and E is the number of edges in the graph\n// space complexity: O(V) where V is the number of vertices in the graph\n// reference: https://en.wikipedia.org/wiki/Topological_sorting\n\npackage graph\n\n// Topological assumes that graph given is valid and that its\n// possible to get a topological ordering.\n// constraints are array of []int{a, b}, representing\n// an edge going from a to b\nfunc Topological(N int, constraints [][]int) []int {\n\tdependencies := make([]int, N)\n\tnodes := make([]int, N)\n\tfor i := range nodes {\n\t\tnodes[i] = i\n\t}\n\tedges := make([][]bool, N)\n\tfor i := range edges {\n\t\tedges[i] = make([]bool, N)\n\t}\n\n\tfor _, c := range constraints {\n\t\ta := c[0]\n\t\tb := c[1]\n\t\tdependencies[b]++\n\t\tedges[a][b] = true\n\t}\n\n\tvar answer []int\n\tfor s := 0; s < N; s++ {\n\t\t// Only start walking from top level nodes\n\t\tif dependencies[s] == 0 {\n\t\t\troute, _ := DepthFirstSearchHelper(s, N, nodes, edges, true)\n\t\t\tanswer = append(answer, route...)\n\t\t}\n\t}\n\n\treturn answer\n}\n"
  },
  {
    "path": "graph/topological_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname        string\n\tN           int\n\tconstraints [][]int\n}{\n\t{\n\t\t\"basic test\", 2,\n\t\t[][]int{{1, 0}},\n\t},\n\t{\n\t\t\"double path\", 7,\n\t\t[][]int{\n\t\t\t{0, 1}, {1, 3}, {3, 5},\n\t\t\t{0, 2}, {2, 4}, {4, 6}},\n\t},\n\t{\n\t\t\"star shape\", 7,\n\t\t[][]int{\n\t\t\t{0, 1}, {0, 3}, {0, 5},\n\t\t\t{0, 2}, {0, 4}, {0, 6}},\n\t},\n\t{\n\t\t\"tree shape\", 7,\n\t\t[][]int{\n\t\t\t{0, 1}, {1, 3}, {1, 5},\n\t\t\t{0, 2}, {2, 4}, {2, 6}},\n\t},\n}\n\nfunc TestTopological(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Topological(tc.N, tc.constraints)\n\n\t\t\tvisited := make([]bool, tc.N)\n\t\t\tpositions := make([]int, tc.N)\n\t\t\tfor i := 0; i < tc.N; i++ {\n\t\t\t\tpositions[actual[i]] = i\n\t\t\t\tvisited[actual[i]] = true\n\t\t\t}\n\t\t\tfor _, v := range visited {\n\t\t\t\tif !v {\n\t\t\t\t\tt.Errorf(\"nodes not all visited, %v\", visited)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, c := range tc.constraints {\n\t\t\t\tif positions[c[0]] > positions[c[1]] {\n\t\t\t\t\tt.Errorf(\"%v dun satisfy %v\", actual, c)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "graph/unionfind.go",
    "content": "// Union Find Algorithm or Dynamic Connectivity algorithm, often implemented with the help\n//of the union find data structure,\n// is used to efficiently maintain connected components in a graph that undergoes dynamic changes,\n// such as edges being added or removed over time\n// Worst Case Time Complexity: The time complexity of find operation is nearly constant or\n//O(α(n)), where α(n) is the inverse Ackermann function\n// practically, this is a very slowly growing function making the time complexity for find\n//operation nearly constant.\n// The time complexity of the union operation is also nearly constant or O(α(n))\n// Worst Case Space Complexity: O(n), where n is the number of nodes or element in the structure\n// Reference: https://www.scaler.com/topics/data-structures/disjoint-set/\n// https://en.wikipedia.org/wiki/Disjoint-set_data_structure\n// Author: Mugdha Behere[https://github.com/MugdhaBehere]\n// see: unionfind.go, unionfind_test.go\n\npackage graph\n\n// Defining the union-find data structure\ntype UnionFind struct {\n\tparent []int\n\trank   []int\n}\n\n// Initialise a new union find data structure with s nodes\nfunc NewUnionFind(s int) UnionFind {\n\tparent := make([]int, s)\n\trank := make([]int, s)\n\tfor i := 0; i < s; i++ {\n\t\tparent[i] = i\n\t\trank[i] = 1\n\t}\n\treturn UnionFind{parent, rank}\n}\n\n// Find finds the root of the set to which the given element belongs.\n// It performs path compression to make future Find operations faster.\nfunc (u *UnionFind) Find(q int) int {\n\tif q != u.parent[q] {\n\t\tu.parent[q] = u.Find(u.parent[q])\n\t}\n\treturn u.parent[q]\n}\n\n// Union merges the sets, if not already merged, to which the given elements belong.\n// It performs union by rank to keep the tree as flat as possible.\nfunc (u *UnionFind) Union(p, q int) {\n\trootP := u.Find(p)\n\trootQ := u.Find(q)\n\n\tif rootP == rootQ {\n\t\treturn\n\t}\n\n\tif u.rank[rootP] < u.rank[rootQ] {\n\t\tu.parent[rootP] = rootQ\n\t} else if u.rank[rootP] > u.rank[rootQ] {\n\t\tu.parent[rootQ] = rootP\n\t} else {\n\t\tu.parent[rootQ] = rootP\n\t\tu.rank[rootP]++\n\t}\n}\n"
  },
  {
    "path": "graph/unionfind_test.go",
    "content": "package graph\n\nimport (\n\t\"testing\"\n)\n\nfunc TestUnionFind(t *testing.T) {\n\tu := NewUnionFind(10) // Creating a Union-Find data structure with 10 elements\n\n\t//union operations\n\tu.Union(0, 1)\n\tu.Union(2, 3)\n\tu.Union(4, 5)\n\tu.Union(6, 7)\n\n\t// Testing the parent of specific elements\n\tt.Run(\"Test Find\", func(t *testing.T) {\n\t\tif u.Find(0) != u.Find(1) || u.Find(2) != u.Find(3) || u.Find(4) != u.Find(5) || u.Find(6) != u.Find(7) {\n\t\t\tt.Error(\"Union operation not functioning correctly\")\n\t\t}\n\t})\n\n\tu.Union(1, 5) // Additional union operation\n\tu.Union(3, 7) // Additional union operation\n\n\t// Testing the parent of specific elements after more union operations\n\tt.Run(\"Test Find after Union\", func(t *testing.T) {\n\t\tif u.Find(0) != u.Find(5) || u.Find(1) != u.Find(4) || u.Find(2) != u.Find(7) || u.Find(3) != u.Find(6) {\n\t\t\tt.Error(\"Union operation not functioning correctly\")\n\t\t}\n\t})\n\n\tu.Union(3, 7) // Repeated union operation\n\n\t// Testing that repeated union operations are idempotent\n\tt.Run(\"Test Find after repeated Union\", func(t *testing.T) {\n\t\tif u.Find(2) != u.Find(6) || u.Find(2) != u.Find(7) || u.Find(3) != u.Find(6) || u.Find(3) != u.Find(7) {\n\t\t\tt.Error(\"Union operation not functioning correctly\")\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "hashing/doc.go",
    "content": "// Package hashing containing different implementation of certain hashing\npackage hashing\n"
  },
  {
    "path": "hashing/hashing_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage hashing\n"
  },
  {
    "path": "hashing/md5/md5.go",
    "content": "// md5.go\n// description: The MD5 hashing function as defined in RFC 1321.\n// author: Simon Waldherr\n// ref: https://datatracker.ietf.org/doc/html/rfc1321\n// see md5_test.go for testing\n\npackage md5\n\nimport (\n\t\"encoding/binary\"\n)\n\n// Constants for MD5\nvar (\n\ts = [64]uint32{\n\t\t7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n\t\t5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n\t\t4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n\t\t6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n\t}\n\n\tK = [64]uint32{\n\t\t0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n\t\t0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n\t\t0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n\t\t0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n\t\t0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n\t\t0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n\t\t0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n\t\t0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n\t\t0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n\t\t0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n\t\t0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n\t\t0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n\t\t0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n\t\t0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n\t\t0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n\t\t0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n\t}\n)\n\n// leftRotate rotates x left by n bits\nfunc leftRotate(x, n uint32) uint32 {\n\treturn (x << n) | (x >> (32 - n))\n}\n\n// pad pads the input message so that its length is congruent to 448 modulo 512\nfunc pad(message []byte) []byte {\n\toriginalLength := len(message) * 8\n\tmessage = append(message, 0x80)\n\tfor (len(message)*8)%512 != 448 {\n\t\tmessage = append(message, 0x00)\n\t}\n\n\tlengthBytes := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(lengthBytes, uint64(originalLength))\n\tmessage = append(message, lengthBytes...)\n\n\treturn message\n}\n\n// Hash computes the MD5 hash of the input message\nfunc Hash(message []byte) [16]byte {\n\tmessage = pad(message)\n\n\t// Initialize MD5 state variables\n\ta0, b0, c0, d0 := uint32(0x67452301), uint32(0xefcdab89), uint32(0x98badcfe), uint32(0x10325476)\n\n\t// Process the message in successive 512-bit chunks\n\tfor i := 0; i < len(message); i += 64 {\n\t\tchunk := message[i : i+64]\n\t\tvar M [16]uint32\n\t\tfor j := 0; j < 16; j++ {\n\t\t\tM[j] = binary.LittleEndian.Uint32(chunk[j*4 : (j+1)*4])\n\t\t}\n\n\t\t// Initialize hash value for this chunk\n\t\tA, B, C, D := a0, b0, c0, d0\n\n\t\t// Main loop\n\t\tfor i := 0; i < 64; i++ {\n\t\t\tvar F, g uint32\n\t\t\tif i < 16 {\n\t\t\t\tF = (B & C) | ((^B) & D)\n\t\t\t\tg = uint32(i)\n\t\t\t} else if i < 32 {\n\t\t\t\tF = (D & B) | ((^D) & C)\n\t\t\t\tg = uint32((5*i + 1) % 16)\n\t\t\t} else if i < 48 {\n\t\t\t\tF = B ^ C ^ D\n\t\t\t\tg = uint32((3*i + 5) % 16)\n\t\t\t} else {\n\t\t\t\tF = C ^ (B | (^D))\n\t\t\t\tg = uint32((7 * i) % 16)\n\t\t\t}\n\t\t\tF = F + A + K[i] + M[g]\n\t\t\tA = D\n\t\t\tD = C\n\t\t\tC = B\n\t\t\tB = B + leftRotate(F, s[i])\n\t\t}\n\n\t\t// Add this chunk's hash to result so far\n\t\ta0 += A\n\t\tb0 += B\n\t\tc0 += C\n\t\td0 += D\n\t}\n\n\t// Produce the final hash value (digest)\n\tvar digest [16]byte\n\tbinary.LittleEndian.PutUint32(digest[0:4], a0)\n\tbinary.LittleEndian.PutUint32(digest[4:8], b0)\n\tbinary.LittleEndian.PutUint32(digest[8:12], c0)\n\tbinary.LittleEndian.PutUint32(digest[12:16], d0)\n\n\treturn digest\n}\n"
  },
  {
    "path": "hashing/md5/md5_test.go",
    "content": "// md5_test.go\n// description: Tests for the MD5 hashing function as defined in RFC 1321.\n// author: Simon Waldherr\n\npackage md5\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\n// Helper function to convert hash output to hex string for comparison\nfunc toHexString(hash [16]byte) string {\n\treturn hex.EncodeToString(hash[:])\n}\n\n// Test vectors for MD5 (from RFC 1321 and other known sources)\nvar tests = []struct {\n\tinput    string\n\texpected string\n}{\n\t{\"\", \"d41d8cd98f00b204e9800998ecf8427e\"},\n\t{\"a\", \"0cc175b9c0f1b6a831c399e269772661\"},\n\t{\"abc\", \"900150983cd24fb0d6963f7d28e17f72\"},\n\t{\"message digest\", \"f96b697d7cb7938d525a2f31aaf161d0\"},\n\t{\"abcdefghijklmnopqrstuvwxyz\", \"c3fcd3d76192e4007dfb496cca67e13b\"},\n\t{\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"d174ab98d277d9f5a5611c2c9f419d9f\"},\n\t{\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\", \"57edf4a22be3c955ac49da2e2107b67a\"},\n}\n\n// TestHash verifies that the Hash function produces the correct MD5 hash values\nfunc TestHash(t *testing.T) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.input, func(t *testing.T) {\n\t\t\tresult := Hash([]byte(tt.input))\n\t\t\tresultHex := toHexString(result)\n\t\t\tif resultHex != tt.expected {\n\t\t\t\tt.Errorf(\"MD5(%q) = %s; want %s\", tt.input, resultHex, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "hashing/sha1/sha1.go",
    "content": "// sha1.go\n// description: The SHA-1 hashing function as defined in RFC 3174.\n// author: Simon Waldherr\n// ref: https://datatracker.ietf.org/doc/html/rfc3174\n// see sha1_test.go for testing\n\npackage sha1\n\nimport (\n\t\"encoding/binary\" // Used for interacting with uint at the byte level\n)\n\n// Constants for SHA-1\nconst (\n\th0 uint32 = 0x67452301\n\th1 uint32 = 0xEFCDAB89\n\th2 uint32 = 0x98BADCFE\n\th3 uint32 = 0x10325476\n\th4 uint32 = 0xC3D2E1F0\n)\n\n// pad pads the input message so that its length is congruent to 448 modulo 512\nfunc pad(message []byte) []byte {\n\toriginalLength := len(message) * 8\n\tmessage = append(message, 0x80)\n\tfor (len(message)*8)%512 != 448 {\n\t\tmessage = append(message, 0x00)\n\t}\n\n\tlengthBytes := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(lengthBytes, uint64(originalLength))\n\tmessage = append(message, lengthBytes...)\n\n\treturn message\n}\n\n// leftRotate rotates x left by n bits\nfunc leftRotate(x, n uint32) uint32 {\n\treturn (x << n) | (x >> (32 - n))\n}\n\n// Hash computes the SHA-1 hash of the input message\nfunc Hash(message []byte) [20]byte {\n\tmessage = pad(message)\n\n\t// Initialize variables\n\ta, b, c, d, e := h0, h1, h2, h3, h4\n\n\t// Process the message in successive 512-bit chunks\n\tfor i := 0; i < len(message); i += 64 {\n\t\tvar w [80]uint32\n\t\tchunk := message[i : i+64]\n\n\t\t// Break chunk into sixteen 32-bit big-endian words\n\t\tfor j := 0; j < 16; j++ {\n\t\t\tw[j] = binary.BigEndian.Uint32(chunk[j*4 : (j+1)*4])\n\t\t}\n\n\t\t// Extend the sixteen 32-bit words into eighty 32-bit words\n\t\tfor j := 16; j < 80; j++ {\n\t\t\tw[j] = leftRotate(w[j-3]^w[j-8]^w[j-14]^w[j-16], 1)\n\t\t}\n\n\t\t// Initialize hash value for this chunk\n\t\tA, B, C, D, E := a, b, c, d, e\n\n\t\t// Main loop\n\t\tfor j := 0; j < 80; j++ {\n\t\t\tvar f, k uint32\n\t\t\tswitch {\n\t\t\tcase j < 20:\n\t\t\t\tf = (B & C) | ((^B) & D)\n\t\t\t\tk = 0x5A827999\n\t\t\tcase j < 40:\n\t\t\t\tf = B ^ C ^ D\n\t\t\t\tk = 0x6ED9EBA1\n\t\t\tcase j < 60:\n\t\t\t\tf = (B & C) | (B & D) | (C & D)\n\t\t\t\tk = 0x8F1BBCDC\n\t\t\tdefault:\n\t\t\t\tf = B ^ C ^ D\n\t\t\t\tk = 0xCA62C1D6\n\t\t\t}\n\n\t\t\ttemp := leftRotate(A, 5) + f + E + k + w[j]\n\t\t\tE = D\n\t\t\tD = C\n\t\t\tC = leftRotate(B, 30)\n\t\t\tB = A\n\t\t\tA = temp\n\t\t}\n\n\t\t// Add this chunk's hash to result so far\n\t\ta += A\n\t\tb += B\n\t\tc += C\n\t\td += D\n\t\te += E\n\t}\n\n\t// Produce the final hash value (digest)\n\tvar digest [20]byte\n\tbinary.BigEndian.PutUint32(digest[0:4], a)\n\tbinary.BigEndian.PutUint32(digest[4:8], b)\n\tbinary.BigEndian.PutUint32(digest[8:12], c)\n\tbinary.BigEndian.PutUint32(digest[12:16], d)\n\tbinary.BigEndian.PutUint32(digest[16:20], e)\n\n\treturn digest\n}\n"
  },
  {
    "path": "hashing/sha1/sha1_test.go",
    "content": "// sha1_test.go\n// description: Tests for the SHA-1 hashing function as defined in RFC 3174.\n// author: Simon Waldherr\n\npackage sha1\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\n// Helper function to convert hash output to hex string for comparison\nfunc toHexString(hash [20]byte) string {\n\treturn hex.EncodeToString(hash[:])\n}\n\n// Test vectors for SHA-1 (from RFC 3174 and other known sources)\nvar tests = []struct {\n\tinput    string\n\texpected string\n}{\n\t{\"\", \"da39a3ee5e6b4b0d3255bfef95601890afd80709\"},\n\t{\"a\", \"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8\"},\n\t{\"abc\", \"a9993e364706816aba3e25717850c26c9cd0d89d\"},\n\t{\"message digest\", \"c12252ceda8be8994d5fa0290a47231c1d16aae3\"},\n\t{\"abcdefghijklmnopqrstuvwxyz\", \"32d10c7b8cf96570ca04ce37f2a19d84240d3a89\"},\n\t{\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"761c457bf73b14d27e9e9265c46f4b4dda11f940\"},\n\t{\"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\", \"fecfd28bbc9345891a66d7c1b8ff46e60192d284\"},\n}\n\n// TestHash verifies that the Hash function produces the correct SHA-1 hash values\nfunc TestHash(t *testing.T) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.input, func(t *testing.T) {\n\t\t\tresult := Hash([]byte(tt.input))\n\t\t\tresultHex := toHexString(result)\n\t\t\tif resultHex != tt.expected {\n\t\t\t\tt.Errorf(\"SHA-1(%q) = %s; want %s\", tt.input, resultHex, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "hashing/sha256/sha256.go",
    "content": "// sha256.go\n// description: The sha256 cryptographic hash function as defined in the RFC6234 standard.\n// time complexity: O(n)\n// space complexity: O(n)\n// author: [Paul Leydier] (https://github.com/paul-leydier)\n// ref: https://datatracker.ietf.org/doc/html/rfc6234\n// ref: https://en.wikipedia.org/wiki/SHA-2\n// see sha256_test.go\n\npackage sha256\n\nimport (\n\t\"encoding/binary\" // Used for interacting with uint at the byte level\n\t\"math/bits\"       // Used for bits rotation operations\n)\n\nvar K = [64]uint32{\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n}\n\nconst chunkSize = 64\n\n// pad returns a padded version of the input message, such as the padded message's length is a multiple\n// of 512 bits.\n// The padding methodology is as follows:\n// A \"1\" bit is appended at the end of the input message, followed by m \"0\" bits such as the length is\n// 64 bits short of a 512 bits multiple. The remaining 64 bits are filled with the initial length of the\n// message, represented as a 64-bits unsigned integer.\n// For more details, see: https://datatracker.ietf.org/doc/html/rfc6234#section-4.1\nfunc pad(message []byte) []byte {\n\tL := make([]byte, 8)\n\tbinary.BigEndian.PutUint64(L, uint64(len(message)*8))\n\tmessage = append(message, 0x80) // \"1\" bit followed by 7 \"0\" bits\n\tfor (len(message)+8)%64 != 0 {\n\t\tmessage = append(message, 0x00) // 8 \"0\" bits\n\t}\n\tmessage = append(message, L...)\n\n\treturn message\n}\n\n// Hash hashes the input message using the sha256 hashing function, and return a 32 byte array.\n// The implementation follows the RGC6234 standard, which is documented\n// at https://datatracker.ietf.org/doc/html/rfc6234\nfunc Hash(message []byte) [32]byte {\n\tmessage = pad(message)\n\n\t// Initialize round constants\n\th0, h1, h2, h3, h4, h5, h6, h7 := uint32(0x6a09e667), uint32(0xbb67ae85), uint32(0x3c6ef372), uint32(0xa54ff53a),\n\t\tuint32(0x510e527f), uint32(0x9b05688c), uint32(0x1f83d9ab), uint32(0x5be0cd19)\n\n\t// Iterate through 512-bit chunks\n\tfor chunkStart := 0; chunkStart < len(message); chunkStart += chunkSize {\n\t\t// Message schedule\n\t\tvar w [64]uint32\n\t\tfor i := 0; i*4 < chunkSize; i++ {\n\t\t\tw[i] = binary.BigEndian.Uint32(message[chunkStart+i*4 : chunkStart+(i+1)*4])\n\t\t}\n\n\t\t// Extend the 16 bytes chunk to the whole 64 bytes message schedule\n\t\tfor i := 16; i < 64; i++ {\n\t\t\ts0 := bits.RotateLeft32(w[i-15], -7) ^ bits.RotateLeft32(w[i-15], -18) ^ (w[i-15] >> 3)\n\t\t\ts1 := bits.RotateLeft32(w[i-2], -17) ^ bits.RotateLeft32(w[i-2], -19) ^ (w[i-2] >> 10)\n\t\t\tw[i] = w[i-16] + s0 + w[i-7] + s1\n\t\t}\n\n\t\t// Actual hashing loop\n\t\ta, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7\n\t\tfor i := 0; i < 64; i++ {\n\t\t\tS1 := bits.RotateLeft32(e, -6) ^ bits.RotateLeft32(e, -11) ^ bits.RotateLeft32(e, -25)\n\t\t\tch := (e & f) ^ ((^e) & g)\n\t\t\ttmp1 := h + S1 + ch + K[i] + w[i]\n\t\t\tS0 := bits.RotateLeft32(a, -2) ^ bits.RotateLeft32(a, -13) ^ bits.RotateLeft32(a, -22)\n\t\t\tmaj := (a & b) ^ (a & c) ^ (b & c)\n\t\t\ttmp2 := S0 + maj\n\t\t\th = g\n\t\t\tg = f\n\t\t\tf = e\n\t\t\te = d + tmp1\n\t\t\td = c\n\t\t\tc = b\n\t\t\tb = a\n\t\t\ta = tmp1 + tmp2\n\t\t}\n\t\th0 += a\n\t\th1 += b\n\t\th2 += c\n\t\th3 += d\n\t\th4 += e\n\t\th5 += f\n\t\th6 += g\n\t\th7 += h\n\t}\n\n\t// Export digest\n\tdigest := [32]byte{}\n\tbinary.BigEndian.PutUint32(digest[:4], h0)\n\tbinary.BigEndian.PutUint32(digest[4:8], h1)\n\tbinary.BigEndian.PutUint32(digest[8:12], h2)\n\tbinary.BigEndian.PutUint32(digest[12:16], h3)\n\tbinary.BigEndian.PutUint32(digest[16:20], h4)\n\tbinary.BigEndian.PutUint32(digest[20:24], h5)\n\tbinary.BigEndian.PutUint32(digest[24:28], h6)\n\tbinary.BigEndian.PutUint32(digest[28:], h7)\n\n\treturn digest\n}\n"
  },
  {
    "path": "hashing/sha256/sha256_test.go",
    "content": "package sha256\n\nimport (\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\nfunc TestHash(t *testing.T) {\n\ttestCases := []struct {\n\t\tin       string\n\t\texpected string\n\t}{\n\t\t{\"hello world\", \"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\"},\n\t\t{\"\", \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"},\n\t\t{\"a\", \"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb\"},\n\t\t{\"The quick brown fox jumps over the lazy dog\", \"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592\"},\n\t\t{\"The quick brown fox jumps over the lazy dog.\", \"ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c\"},\n\t\t{\"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.\", \"2d8c2f6d978ca21712b5f6de36c9d31fa8e96a4fa5d8ff8b0188dfb9e7c171bb\"},\n\t}\n\tfor _, tc := range testCases {\n\t\tres := Hash([]byte(tc.in))\n\t\tresult := hex.EncodeToString(res[:])\n\t\tif result != tc.expected {\n\t\t\tt.Fatalf(\"Hash(%s) = %s, expected %s\", tc.in, result, tc.expected)\n\t\t}\n\t}\n}\n\nfunc BenchmarkHash(b *testing.B) {\n\ttestCases := []struct {\n\t\tname string\n\t\tin   string\n\t}{\n\t\t{\"hello world\", \"hello world\"},\n\t\t{\"empty\", \"\"},\n\t\t{\"a\", \"a\"},\n\t\t{\"The quick brown fox jumps over the lazy dog\", \"The quick brown fox jumps over the lazy dog\"},\n\t\t{\"The quick brown fox jumps over the lazy dog.\", \"The quick brown fox jumps over the lazy dog.\"},\n\t\t{\"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.\"},\n\t}\n\tfor _, testCase := range testCases {\n\t\tb.Run(testCase.name, func(b *testing.B) {\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tHash([]byte(testCase.in))\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/abs.go",
    "content": "// abs.go\n// description: Absolute value\n// details:\n// In mathematics, the absolute value or modulus of a real number x, denoted |x|, is the non-negative value of x without regard to its sign. [Absolute value](https://en.wikipedia.org/wiki/Average#Arithmetic_mean)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see abs_test.go\n\npackage math\n\n// Abs returns absolute value\nfunc Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}\n"
  },
  {
    "path": "math/abs_test.go",
    "content": "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\ttests := getTests()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := Abs(test.n); got != test.want {\n\t\t\t\tt.Errorf(\"Abs() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc getTests() []struct {\n\tname string\n\tn    int\n\twant int\n} {\n\ttests := []struct {\n\t\tname string\n\t\tn    int\n\t\twant int\n\t}{\n\t\t{\"-1 = |1| \", -1, 1},\n\t\t{\"-255 = |255| \", -255, 255},\n\t\t{\"0 = |0| \", 0, 0},\n\t\t{\"5 = |5| \", 5, 5},\n\t\t{\"-5 = |5| \", -5, 5},\n\t\t{\"-98368972 = |98368972| \", -98368972, 98368972},\n\t}\n\treturn tests\n}\n\nfunc BenchmarkSimpleAbs(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tAbs(-1024)\n\t}\n}\nfunc BenchmarkBinaryAbs32(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbinary.Abs(32, -1024)\n\t}\n}\n\nfunc BenchmarkBinaryAbs64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbinary.Abs(64, -1024)\n\t}\n}\n\nfunc BenchmarkStdLibAbs(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.Abs(-1024)\n\t}\n}\n"
  },
  {
    "path": "math/aliquot_test.go",
    "content": "// aliquotsum_test.go\n// description: Returns s(n)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see aliquotsum.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestAliquotSum(t *testing.T) {\n\tvar tests = []struct {\n\t\tname          string\n\t\tn             int\n\t\texpectedValue int\n\t\texpectedError error\n\t}{\n\t\t{\"n = 10\", 10, 8, nil},\n\t\t{\"n = 11\", 11, 1, nil},\n\t\t{\"n = 1\", 1, 0, nil},\n\t\t{\"n = -1\", -1, 0, math.ErrPosArgsOnly},\n\t\t{\"n = 0\", 0, 0, math.ErrNonZeroArgsOnly},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult, err := math.AliquotSum(test.n)\n\t\t\tif result != test.expectedValue || test.expectedError != err {\n\t\t\t\tt.Errorf(\"expected error: %s, got: %s; expected value: %v, got: %v\", test.expectedError, err, test.expectedValue, result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc BenchmarkAliquotSum(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = math.AliquotSum(65536)\n\t}\n}\n"
  },
  {
    "path": "math/aliquotsum.go",
    "content": "// aliquotsum.go\n// description: Returns s(n)\n// details:\n// the aliquot sum s(n) of a positive integer n\n// is the sum of all proper divisors of n,\n// that is, all divisors of n other than n itself\n// wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum\n// time complexity: O(n)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see aliquotsum_test.go\n\npackage math\n\n// This function returns s(n) for given number\nfunc AliquotSum(n int) (int, error) {\n\tswitch {\n\tcase n < 0:\n\t\treturn 0, ErrPosArgsOnly\n\tcase n == 0:\n\t\treturn 0, ErrNonZeroArgsOnly\n\tdefault:\n\t\tvar sum int\n\t\tfor i := 1; i <= n/2; i++ {\n\t\t\tif n%i == 0 {\n\t\t\t\tsum += i\n\t\t\t}\n\t\t}\n\t\treturn sum, nil\n\t}\n}\n"
  },
  {
    "path": "math/armstrong/isarmstrong.go",
    "content": "// isarmstrong.go\n// description: Checks if the given number is armstrong number or not\n// details: An Armstrong number is a n-digit number that is equal to the sum of each of its digits taken to the nth power.\n// time complexity: O(log(n))\n// space complexity: O(1)\n// ref: https://mathlair.allfunandgames.ca/armstrong.php\n// author: Kavitha J\n\npackage armstrong\n\nimport (\n\t\"math\"\n\t\"strconv\"\n)\n\nfunc IsArmstrong(number int) bool {\n\tvar rightMost int\n\tvar sum int = 0\n\tvar tempNum int = number\n\n\t// to get the number of digits in the number\n\tlength := float64(len(strconv.Itoa(number)))\n\n\t// get the right most digit and break the loop once all digits are iterated\n\tfor tempNum > 0 {\n\t\trightMost = tempNum % 10\n\t\tsum += int(math.Pow(float64(rightMost), length))\n\n\t\t// update the input digit minus the processed rightMost\n\t\ttempNum /= 10\n\t}\n\n\treturn number == sum\n}\n"
  },
  {
    "path": "math/armstrong/isarmstrong_test.go",
    "content": "// isarmstrong_test.go\n\npackage armstrong\n\nimport \"testing\"\n\nvar testCases = []struct {\n\tname     string // test description\n\tinput    int    // user input\n\texpected bool   // expected return\n}{\n\t{\n\t\t\"negative number: Not an armstrong number\",\n\t\t-140,\n\t\tfalse,\n\t},\n\t{\n\t\t\"positive number: Not an armstrong number\",\n\t\t23,\n\t\tfalse,\n\t},\n\t{\n\t\t\"smallest armstrong number\",\n\t\t0,\n\t\ttrue,\n\t},\n\t{\n\t\t\"smallest armstrong number with more than one digit\",\n\t\t153,\n\t\ttrue,\n\t},\n\t{\n\t\t\"random armstrong number\",\n\t\t407,\n\t\ttrue,\n\t},\n\t{\n\t\t\"random armstrong number\",\n\t\t9474,\n\t\ttrue,\n\t},\n}\n\nfunc TestIsArmstrong(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfuncResult := IsArmstrong(test.input)\n\t\t\tif test.expected != funcResult {\n\t\t\t\tt.Errorf(\"Expected answer '%t' for the number '%d' but answer given was %t\", test.expected, test.input, funcResult)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/binary/abs.go",
    "content": "// abs.go\n// description: returns absolute value using binary operation\n// time complexity: O(1)\n// space complexity: O(1)\n\npackage binary\n\n// Abs returns absolute value using binary operation\n// Principle of operation:\n// 1) Get the mask by right shift by the base\n// 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\n// 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.\n// 4) Add the mask to the given number.\n// 5) XOR of mask + n and mask gives the absolute value.\nfunc Abs(base, n int) int {\n\tm := n >> (base - 1)\n\treturn (n + m) ^ m\n}\n"
  },
  {
    "path": "math/binary/abs_test.go",
    "content": "package binary\n\nimport \"testing\"\n\nfunc TestAbs(t *testing.T) {\n\ttests := getAbsTests()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := Abs(test.base, test.n); got != test.want {\n\t\t\t\tt.Errorf(\"Abs() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc getAbsTests() []struct {\n\tname string\n\tbase int\n\tn    int\n\twant int\n} {\n\ttests := []struct {\n\t\tname string\n\t\tbase int\n\t\tn    int\n\t\twant int\n\t}{\n\t\t{\"-1 = |1| \", 32, -1, 1},\n\t\t{\"-255 = |255| \", 32, -255, 255},\n\t\t{\"0 = |0| \", 64, 0, 0},\n\t\t{\"5 = |5| \", 16, 5, 5},\n\t\t{\"-5 = |5| \", 32, -5, 5},\n\t\t{\"-98368972 = |98368972| \", 64, -98368972, 98368972},\n\t\t{\"-110298368972 = |110298368972| \", 64, -98368972, 98368972},\n\t}\n\treturn tests\n}\n"
  },
  {
    "path": "math/binary/arithmeticmean.go",
    "content": "// arithmeticmean.go\n// description: Arithmetic mean\n// details:\n// The most common type of average is the arithmetic mean. If n numbers are given, each number denoted by ai (where i = 1,2, ..., n), the arithmetic mean is the sum of the as divided by n or - [Arithmetic mean](https://en.wikipedia.org/wiki/Average#Arithmetic_mean)\n// time complexity: O(1)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see arithmeticmean_test.go\n\n// Package binary describes algorithms that use binary operations for different calculations.\npackage binary\n\n// MeanUsingAndXor This function finds arithmetic mean using \"AND\" and \"XOR\" operations\nfunc MeanUsingAndXor(a int, b int) int {\n\treturn ((a ^ b) >> 1) + (a & b)\n}\n\n// MeanUsingRightShift This function finds arithmetic mean using right shift\nfunc MeanUsingRightShift(a int, b int) int {\n\treturn (a + b) >> 1\n}\n"
  },
  {
    "path": "math/binary/arithmeticmean_test.go",
    "content": "// arithmeticmean_test.go\n// description: Test for Arithmetic mean\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see arithmeticmean.go\n\npackage binary\n\nimport \"testing\"\n\nfunc TestMeanUsingAndXor(t *testing.T) {\n\ttests := getTests()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := MeanUsingAndXor(tv.a, tv.b)\n\t\t\tif result != tv.result {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%d, returned:%d \", tv.result, result)\n\t\t\t}\n\t\t})\n\t}\n\n}\n\nfunc TestMeanUsingRightShift(t *testing.T) {\n\ttests := getTests()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := MeanUsingRightShift(tv.a, tv.b)\n\t\t\tif result != tv.result {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%d, returned:%d \", tv.result, result)\n\t\t\t}\n\t\t})\n\t}\n\n}\nfunc getTests() []struct {\n\tname   string\n\ta      int\n\tb      int\n\tresult int\n} {\n\tvar tests = []struct {\n\t\tname   string\n\t\ta      int\n\t\tb      int\n\t\tresult int\n\t}{\n\t\t{\"Average of 2 and 4\", 2, 4, 3},\n\t\t{\"Average of 5 and 5\", 5, 5, 5},\n\t\t{\"Average of 1000 and 1002\", 1000, 1002, 1001},\n\t\t{\"Average of 80 and 40\", 80, 40, 60},\n\t\t{\"Average of 7 and 4\", 7, 4, 5},\n\t}\n\treturn tests\n}\nfunc BenchmarkMeanUsingAndXor(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tMeanUsingAndXor(222, 888)\n\t}\n}\n\nfunc BenchmarkMeanUsingRightShift(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tMeanUsingRightShift(222, 888)\n\t}\n}\n"
  },
  {
    "path": "math/binary/bitcounter.go",
    "content": "// bitcounter.go\n// description: Counts the number of set bits in a number\n// details:\n// For unsigned integer number N, return the number of bits set to 1 - [Bit numbering](https://en.wikipedia.org/wiki/Bit_numbering)\n// time complexity: O(log(n))\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see bitcounter_test.go\n\npackage binary\n\n// BitCounter - The function returns the number of set bits for an unsigned integer number\nfunc BitCounter(n uint) int {\n\tcounter := 0\n\tfor n != 0 {\n\t\tif n&1 == 1 {\n\t\t\tcounter++\n\t\t}\n\t\tn >>= 1\n\t}\n\treturn counter\n}\n"
  },
  {
    "path": "math/binary/bitcounter_test.go",
    "content": "// bitcounter_test.go\n// description: Test for counts the number of set bits in a number\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see bitcounter.go\n\npackage binary\n\nimport \"testing\"\n\nfunc TestBitCounter(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tnumber uint\n\t\twant   int\n\t}{\n\t\t{\"Number of bits in a number 0\", 0, 0},\n\t\t{\"Number of bits in a number 1\", 1, 1},\n\t\t{\"Number of bits in a number 255\", 255, 8},\n\t\t{\"Number of bits in a number 7\", 7, 3},\n\t\t{\"Number of bits in a number 8\", 8, 1},\n\t\t{\"Number of bits in a number 9223372036854775807\", 9223372036854775807, 63},\n\t\t{\"Number of bits in a number 2147483647\", 2147483647, 31},\n\t\t{\"Number of bits in a number 15\", 15, 4},\n\t\t{\"Number of bits in a number 16\", 16, 1},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := BitCounter(test.number); got != test.want {\n\t\t\t\tt.Errorf(\"BitCounter() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/binary/checkisnumberpoweroftwo.go",
    "content": "// checkisnumberpoweroftwo.go\n// description: Is the number a power of two\n// details:\n// Checks if a number is a power of two- [Power of two](https://en.wikipedia.org/wiki/Power_of_two)\n// time complexity: O(1)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see checkisnumberpoweroftwo_test.go\n\npackage binary\n\n// IsPowerOfTwo This function uses the fact that powers of 2 are represented\n// like 10...0 in binary, and numbers one less than the power of 2\n// are represented like 11...1.\n// Therefore, using the and function:\n//\n//\t  10...0\n//\t& 01...1\n//\t  00...0 -> 0\n//\n// This is also true for 0, which is not a power of 2, for which we\n// have to add and extra condition.\nfunc IsPowerOfTwo(x int) bool {\n\treturn x > 0 && (x&(x-1)) == 0\n}\n\n// IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number\n// by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000,\n// which in decimal system is 8 or = 2 * 2 * 2\nfunc IsPowerOfTwoLeftShift(number uint) bool {\n\tfor p := uint(1); p <= number; p = p << 1 {\n\t\tif number == p {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "math/binary/checkisnumberpoweroftwo_test.go",
    "content": "// checkisnumberpoweroftwo_test.go\n// description: Test for Is the number a power of two\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see checkisnumberpoweroftwo.go\n\npackage binary\n\nimport (\n\tmath2 \"github.com/TheAlgorithms/Go/math\"\n\t\"math\"\n\t\"testing\"\n)\n\nfunc getTestsForPowerOfTwo() []struct {\n\tname    string\n\ta       int\n\tmissing bool\n} {\n\tvar tests = []struct {\n\t\tname    string\n\t\ta       int\n\t\tmissing bool\n\t}{\n\t\t{\"Is 64 a power of 2? - YES\", 64, true},\n\t\t{\"Is 1 a power of 2? - YES\", 1, true},\n\t\t{\"Is 2 a power of 2? - YES\", 2, true},\n\t\t{\"Is 5 a power of 2? - NO\", 5, false},\n\t\t{\"Is 1023 a power of 2? - NO\", 1023, false},\n\t\t{\"Is 1024 a power of 2? - YES\", 1024, true},\n\t\t{\"Is 0 a power of 2? - NO\", 0, false},\n\t\t{\"Is 9223372036854775807 a power of 2? - NO\", math.MaxInt64, false},\n\t\t{\"Is 9223372036854775806 a power of 2? - NO\", math.MaxInt64, false},\n\t\t{\"Is 4611686018427387904 a power of 2? - YES\", 4611686018427387904, true},\n\t}\n\treturn tests\n}\n\nfunc TestIsPowerOfTwo(t *testing.T) {\n\ttests := getTestsForPowerOfTwo()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := IsPowerOfTwo(tv.a)\n\t\t\tt.Log(tv.a, \" \", result)\n\t\t\tif result != tv.missing {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", tv.missing, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsPowerOfTwoLeftShift(t *testing.T) {\n\ttests := getTestsForPowerOfTwo()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := IsPowerOfTwoLeftShift(uint(tv.a))\n\t\t\tt.Log(tv.a, \" \", result)\n\t\t\tif result != tv.missing {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", tv.missing, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsPowOfTwoUseLog(t *testing.T) {\n\ttests := getTestsForPowerOfTwo()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := math2.IsPowOfTwoUseLog(float64(tv.a))\n\t\t\tt.Log(tv.a, \" \", result)\n\t\t\tif result != tv.missing {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", tv.missing, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkIsPowerOfTwoBinaryMethod(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsPowerOfTwo(1024)\n\t}\n}\n\nfunc BenchmarkIsPowerOfTwoUseCycleAndLeftShift(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsPowerOfTwoLeftShift(1024)\n\t}\n}\n\nfunc BenchmarkIsPowerOfTwoUseLog(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath2.IsPowOfTwoUseLog(1024)\n\t}\n}\n"
  },
  {
    "path": "math/binary/fast_inverse_sqrt.go",
    "content": "// Calculating the inverse square root\n// time complexity: O(1)\n// space complexity: O(1)\n// [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root)\n\npackage binary\n\nimport (\n\t\"math\"\n)\n\n// FastInverseSqrt assumes that argument is always positive,\n// and it does not deal with negative numbers.\n// The \"magic\" number 0x5f3759df is hex for 1597463007 in decimals.\n// The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f))\n// and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)).\nfunc FastInverseSqrt(number float32) float32 {\n\tvar i uint32\n\tvar y, x2 float32\n\tconst threehalfs float32 = 1.5\n\n\tx2 = number * float32(0.5)\n\ty = number\n\ti = math.Float32bits(y)   // evil floating point bit level hacking\n\ti = 0x5f3759df - (i >> 1) // magic number and bitshift hacking\n\ty = math.Float32frombits(i)\n\n\ty = y * (threehalfs - (x2 * y * y)) // 1st iteration of Newton's method\n\ty = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed\n\treturn y\n}\n"
  },
  {
    "path": "math/binary/logarithm.go",
    "content": "// author(s) [red_byte](https://github.com/i-redbyte)\n// time complexity: O(1)\n// space complexity: O(1)\n// see logarithm_test.go\n\npackage binary\n\n// 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)\nfunc LogBase2(n uint32) uint32 {\n\tbase := [5]uint32{0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}\n\texponents := [5]uint32{1, 2, 4, 8, 16}\n\tvar result uint32\n\tfor i := 4; i >= 0; i-- {\n\t\tif n&base[i] != 0 {\n\t\t\tn >>= exponents[i]\n\t\t\tresult |= exponents[i]\n\t\t}\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/binary/logarithm_test.go",
    "content": "// logarithm_test.go\n// description: Test for finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see logarithm.go\n\npackage binary\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestLogBase2(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    uint32\n\t\twant uint32\n\t}{\n\t\t{\"log2(1) = 0\", 1, 0},\n\t\t{\"log2(2) = 1\", 2, 1},\n\t\t{\"log2(4) = 2\", 4, 2},\n\t\t{\"log2(8) = 3\", 8, 3},\n\t\t{\"log2(16) = 4\", 16, 4},\n\t\t{\"log2(32) = 5\", 32, 5},\n\t\t{\"log2(64) = 6\", 64, 6},\n\t\t{\"log2(128) = 7\", 128, 7},\n\t\t{\"log2(256) = 8\", 256, 8},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := LogBase2(test.n); got != test.want {\n\t\t\t\tt.Errorf(\"LogBase2() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkBitwiseLogBase2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tLogBase2(1024)\n\t}\n}\n\nfunc BenchmarkMathPAckageLogBase2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.Log2(1024)\n\t}\n}\n"
  },
  {
    "path": "math/binary/rbc.go",
    "content": "// rbc.go\n// description: Reflected binary code (RBC)\n// details:\n// The reflected binary code (RBC), also known just as reflected binary (RB) or Gray code after Frank Gray, is an ordering of the binary numeral system such that two successive values differ in only one bit (binary digit). - [RBC](https://en.wikipedia.org/wiki/Gray_code)\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see rbc_test.go\n\npackage binary\n\n// SequenceGrayCode The function generates an \"Gray code\" sequence of length n\nfunc SequenceGrayCode(n uint) []uint {\n\tresult := make([]uint, 0)\n\tvar i uint\n\tfor i = 0; i < 1<<n; i++ {\n\t\tresult = append(result, i^(i>>1))\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/binary/rbc_test.go",
    "content": "// rbc_test.go\n// description: Test for Reflected binary code\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see rbc.go\n\npackage binary\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSequenceGrayCode(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    uint\n\t\twant []uint\n\t}{\n\t\t{\"Sequence of values for 1\", 1, []uint{0, 1}},\n\t\t{\"Sequence of values for 2\", 2, []uint{0, 1, 3, 2}},\n\t\t{\"Sequence of values for 6\", 6, []uint{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, 24, 25, 27, 26, 30, 31, 29, 28, 20, 21, 23, 22, 18, 19, 17, 16, 48, 49, 51, 50, 54, 55, 53, 52, 60, 61, 63, 62, 58, 59, 57, 56, 40, 41, 43, 42, 46, 47, 45, 44, 36, 37, 39, 38, 34, 35, 33, 32}},\n\t\t{\"Sequence of values for 8\", 8, []uint{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, 24, 25, 27, 26, 30, 31, 29, 28, 20, 21, 23, 22, 18, 19, 17, 16, 48, 49, 51, 50, 54, 55, 53, 52, 60, 61, 63, 62, 58, 59, 57, 56, 40, 41, 43, 42, 46, 47, 45, 44, 36, 37, 39, 38, 34, 35, 33, 32, 96, 97, 99, 98, 102, 103, 101, 100, 108, 109, 111, 110, 106, 107, 105, 104, 120, 121, 123, 122, 126, 127, 125, 124, 116, 117, 119, 118, 114, 115, 113, 112, 80, 81, 83, 82, 86, 87, 85, 84, 92, 93, 95, 94, 90, 91, 89, 88, 72, 73, 75, 74, 78, 79, 77, 76, 68, 69, 71, 70, 66, 67, 65, 64, 192, 193, 195, 194, 198, 199, 197, 196, 204, 205, 207, 206, 202, 203, 201, 200, 216, 217, 219, 218, 222, 223, 221, 220, 212, 213, 215, 214, 210, 211, 209, 208, 240, 241, 243, 242, 246, 247, 245, 244, 252, 253, 255, 254, 250, 251, 249, 248, 232, 233, 235, 234, 238, 239, 237, 236, 228, 229, 231, 230, 226, 227, 225, 224, 160, 161, 163, 162, 166, 167, 165, 164, 172, 173, 175, 174, 170, 171, 169, 168, 184, 185, 187, 186, 190, 191, 189, 188, 180, 181, 183, 182, 178, 179, 177, 176, 144, 145, 147, 146, 150, 151, 149, 148, 156, 157, 159, 158, 154, 155, 153, 152, 136, 137, 139, 138, 142, 143, 141, 140, 132, 133, 135, 134, 130, 131, 129, 128}},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := SequenceGrayCode(test.n); !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"SequenceGrayCode() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkSequenceGrayCode(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSequenceGrayCode(6)\n\t}\n}\n"
  },
  {
    "path": "math/binary/reversebits.go",
    "content": "// reversebits.go\n// description: Reverse bits\n// details:\n// Reverse the bits of an integer number\n// time complexity: O(log(n))\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see reversebits_test.go\n\npackage binary\n\n// ReverseBits This function initialized the result by 0 (all bits 0) and process the given number starting\n// from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result\n// and finally move on to the next bit in the input number.\n// Repeat this till all its bits are processed.\nfunc ReverseBits(number uint) uint {\n\tresult := uint(0)\n\tintSize := 31\n\tfor number != 0 {\n\t\tresult += (number & 1) << intSize\n\t\tnumber = number >> 1\n\t\tintSize -= 1\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/binary/reversebits_test.go",
    "content": "// reversebits_test.go\n// description: Reverse bits\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see reversebits.go\n\npackage binary\n\nimport \"testing\"\n\nfunc TestReverseBits(t *testing.T) {\n\tvar tests = []struct {\n\t\tname   string\n\t\tnumber uint\n\t\tresult uint\n\t}{\n\t\t{\"43261596 (00000010100101000001111010011100) to 964176192 (00111001011110000010100101000000)\", 43261596, 964176192},\n\t\t{\"3758096384 (11100000000000000000000000000000) to 7 (00000000000000000000000000000111)\", 3758096384, 7},\n\t\t{\"7 (00000000000000000000000000000111) to 3758096384 (11100000000000000000000000000000)\", 7, 3758096384},\n\t\t{\"2684354560 (10100000000000000000000000000000) to 5 (00000000000000000000000000000101)\", 2684354560, 5},\n\t\t{\"2684354561 (10100000000000000000000000000001) to 5 (10000000000000000000000000000101)\", 2684354561, 2147483653},\n\t}\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := ReverseBits(tv.number)\n\t\t\tt.Log(result)\n\t\t\tif result != tv.result {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%d, returned:%d \", tv.result, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkReverseBits(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tReverseBits(2684354560)\n\t}\n}\n"
  },
  {
    "path": "math/binary/sqrt.go",
    "content": "// sqrt.go\n// description: Square root calculation\n// details:\n// Calculating the square root using binary operations and a magic number 0x5f3759df [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// time complexity: O(1)\n// space complexity: O(1)\n// see sqrt_test.go\n\npackage binary\n\nfunc Sqrt(n float32) float32 { return 1 / FastInverseSqrt(n) }\n"
  },
  {
    "path": "math/binary/sqrt_test.go",
    "content": "// sqrt_test.go\n// description: Test for square root calculation\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see sqrt.go\n\npackage binary\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nconst epsilon = 0.001\n\nfunc TestSquareRootCalculation(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tnumber float32\n\t\twant   float64\n\t}{\n\t\t{\"sqrt(1)\", 1, 1},\n\t\t{\"sqrt(9)\", 9, 3},\n\t\t{\"sqrt(25)\", 25, 5},\n\t\t{\"sqrt(121)\", 121, 11},\n\t\t{\"sqrt(10000)\", 10000, 100},\n\t\t{\"sqrt(169)\", 169, 13},\n\t\t{\"sqrt(0)\", 0, 0},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := Sqrt(test.number)\n\t\t\tdelta := math.Abs(test.want - float64(got))\n\t\t\tif delta > epsilon {\n\t\t\t\tt.Errorf(\"Sqrt() = %v, want %v delta %v\", got, test.want, delta)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkSquareRootCalculation(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSqrt(225)\n\t}\n}\n\nfunc BenchmarkMathSqrt(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.Sqrt(225)\n\t}\n}\n"
  },
  {
    "path": "math/binary/xorsearch.go",
    "content": "// xorsearch.go\n// description: Find a missing number in a sequence\n// details:\n// Given an array A containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. - [xor](https://en.wikipedia.org/wiki/Exclusive_or)\n// time complexity: O(n)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see xorsearch_test.go\n\npackage binary\n\n// XorSearchMissingNumber This function finds a missing number in a sequence\nfunc XorSearchMissingNumber(a []int) int {\n\tn := len(a)\n\tresult := len(a)\n\tfor i := 0; i < n; i++ {\n\t\tresult ^= i ^ a[i]\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/binary/xorsearch_test.go",
    "content": "// xorsearch_test.go\n// description: Test for Find a missing number in a sequence\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see xorsearch.go\n\npackage binary\n\nimport (\n\t\"testing\"\n)\n\nfunc TestXorSearchMissingNumber(t *testing.T) {\n\tvar tests = []struct {\n\t\tname    string\n\t\ta       []int\n\t\tmissing int\n\t}{\n\t\t{\"[3, 0, 1]/2\", []int{3, 0, 1}, 2},\n\t\t{\"[0, 1, 3, 4, 5, 6, 7]/2\", []int{0, 1, 3, 4, 5, 6, 7}, 2},\n\t\t{\"[0, 2, 3, 4, 5, 6, 7, 8, 9]/1\", []int{0, 2, 3, 4, 5, 6, 7, 8, 9}, 1},\n\t\t{\"[0, 10, 9, 7, 2, 1,  4, 3, 5, 6]/8\", []int{0, 10, 9, 7, 2, 1, 4, 3, 5, 6}, 8},\n\t}\n\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := XorSearchMissingNumber(tv.a)\n\t\t\tif result != tv.missing {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%d, returned:%d \", tv.missing, result)\n\t\t\t}\n\t\t})\n\t}\n\n}\n\nfunc BenchmarkTestXorSearchMissingNumber(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tXorSearchMissingNumber([]int{0, 10, 9, 7, 2, 1, 4, 3, 5, 6})\n\t}\n}\n"
  },
  {
    "path": "math/binomialcoefficient.go",
    "content": "// binomialcoefficient.go\n// description: Returns C(n, k)\n// details:\n// a binomial coefficient C(n,k) gives number ways\n// in which k objects can be chosen from n objects.\n// wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient\n// time complexity: O(k) or O(n-k) whichever is smaller (O(n) in worst case)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see binomialcoefficient_test.go\n\npackage math\n\nimport (\n\t\"errors\"\n)\n\nvar ErrPosArgsOnly error = errors.New(\"arguments must be positive\")\n\n// C is Binomial Coefficient function\n// This function returns C(n, k) for given n and k\nfunc Combinations(n int, k int) (int, error) {\n\tif n < 0 || k < 0 {\n\t\treturn -1, ErrPosArgsOnly\n\t}\n\tif k > (n - k) {\n\t\tk = n - k\n\t}\n\tres := 1\n\tfor i := 0; i < k; i++ {\n\t\tres *= (n - i)\n\t\tres /= (i + 1)\n\t}\n\treturn res, nil\n}\n"
  },
  {
    "path": "math/binomialcoefficient_test.go",
    "content": "// binomialcoefficient_test.go\n// description: Returns C(n, k)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see binomialcoefficient.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestCombinations(t *testing.T) {\n\tvar tests = []struct {\n\t\tname          string\n\t\tn             int\n\t\tk             int\n\t\texpectedValue int\n\t\texpectedError error\n\t}{\n\t\t{\"n = 5, k = 2\", 5, 2, 10, nil},\n\t\t{\"n = 7, k = 4\", 7, 4, 35, nil},\n\t\t{\"n = 0, k = 0\", 0, 0, 1, nil},\n\t\t{\"n = -1, k = 1\", -1, 1, -1, math.ErrPosArgsOnly},\n\t\t{\"n = 1, k = -1\", 1, -1, -1, math.ErrPosArgsOnly},\n\t\t{\"n = -1, k = -1\", -1, -1, -1, math.ErrPosArgsOnly},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult, err := math.Combinations(test.n, test.k)\n\t\t\tif result != test.expectedValue || test.expectedError != err {\n\t\t\t\tt.Errorf(\"expected error: %s, got: %s; expected value: %v, got: %v\", test.expectedError, err, test.expectedValue, result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc BenchmarkCombinations(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = math.Combinations(65536, 65536)\n\t}\n}\n"
  },
  {
    "path": "math/catalan/catalannumber.go",
    "content": "// catalannumber.go\n// description: Returns the Catalan number\n// details:\n// In combinatorial mathematics, the Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects. - [Catalan number](https://en.wikipedia.org/wiki/Catalan_number)\n// time complexity: O(n)\n// space complexity: O(1)\n// The input is the number of the Catalan number n, at the output we get the value of the number\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see catalannumber_test.go\n\npackage catalan\n\nimport (\n\tf \"github.com/TheAlgorithms/Go/math/factorial\"\n)\n\nfunc factorial(n int) int {\n\tresult, error := f.Iterative(n)\n\tif error != nil {\n\t\tpanic(error)\n\t}\n\treturn result\n}\n\n// CatalanNumber This function returns the `nth` Catalan number\nfunc CatalanNumber(n int) int {\n\treturn factorial(n*2) / (factorial(n) * factorial(n+1))\n}\n"
  },
  {
    "path": "math/catalan/catalannumber_test.go",
    "content": "// catalannumber_test.go\n// description: Test for returns the Catalan number\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see catalannumber.go\n\npackage catalan\n\nimport \"testing\"\n\nfunc TestCatalanNumber(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    int\n\t\twant int\n\t}{\n\t\t{\"zero Catalan number \", 0, 1},\n\t\t{\"second Catalan number \", 2, 2},\n\t\t{\"third Catalan number \", 3, 5},\n\t\t{\"fourth Catalan number \", 4, 14},\n\t\t{\"fifth Catalan number \", 5, 42},\n\t\t{\"sixth Catalan number \", 6, 132},\n\t\t{\"tenth Catalan number \", 10, 16796},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := CatalanNumber(test.n); got != test.want {\n\t\t\t\tt.Errorf(\"CatalanNumber() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkCatalanNumber(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tCatalanNumber(10)\n\t}\n}\n"
  },
  {
    "path": "math/checkisnumberpoweroftwo.go",
    "content": "package math\n\nimport (\n\t\"math\"\n)\n\n// IsPowOfTwoUseLog This function checks if a number is a power of two using the logarithm.\n// The limiting degree can be from 0 to 63.\n// See alternatives in the binary package.\nfunc IsPowOfTwoUseLog(number float64) bool {\n\tif number == 0 || math.Round(number) == math.MaxInt64 {\n\t\treturn false\n\t}\n\tlog := math.Log2(number)\n\treturn log == math.Round(log)\n}\n"
  },
  {
    "path": "math/checkisnumberpoweroftwo_test.go",
    "content": "// checkisnumberpoweroftwo_test.go\n// description: Test for Is the number a power of two\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see checkisnumberpoweroftwo.go\n\npackage math\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc getTestsForPowerOfTwo() []struct {\n\tname    string\n\ta       int\n\tmissing bool\n} {\n\tvar tests = []struct {\n\t\tname    string\n\t\ta       int\n\t\tmissing bool\n\t}{\n\t\t{\"Is 64 a power of 2? - YES\", 64, true},\n\t\t{\"Is 1 a power of 2? - YES\", 1, true},\n\t\t{\"Is 2 a power of 2? - YES\", 2, true},\n\t\t{\"Is 5 a power of 2? - NO\", 5, false},\n\t\t{\"Is 1023 a power of 2? - NO\", 1023, false},\n\t\t{\"Is 1024 a power of 2? - YES\", 1024, true},\n\t\t{\"Is 0 a power of 2? - NO\", 0, false},\n\t\t{\"Is 9223372036854775807 a power of 2? - NO\", math.MaxInt64, false},\n\t\t{\"Is 9223372036854775806 a power of 2? - NO\", math.MaxInt64, false},\n\t\t{\"Is 4611686018427387904 a power of 2? - YES\", 4611686018427387904, true},\n\t}\n\treturn tests\n}\n\nfunc TestIsPowOfTwoUseLog(t *testing.T) {\n\ttests := getTestsForPowerOfTwo()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.name, func(t *testing.T) {\n\t\t\tresult := IsPowOfTwoUseLog(float64(tv.a))\n\t\t\tt.Log(tv.a, \" \", result)\n\t\t\tif result != tv.missing {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", tv.missing, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkIsPowerOfTwoUseLog(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIsPowOfTwoUseLog(1024)\n\t}\n}\n"
  },
  {
    "path": "math/cos.go",
    "content": "// author(s) [red_byte](https://github.com/i-redbyte)\n// see cos_test.go\n\npackage math\n\nimport \"math\"\n\n// Cos  returns the cosine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine)\n// [Based on the idea of Bhaskara approximation of cos(x)](https://math.stackexchange.com/questions/3886552/bhaskara-approximation-of-cosx)\nfunc Cos(x float64) float64 {\n\ttp := 1.0 / (2.0 * math.Pi)\n\tx *= tp\n\tx -= 0.25 + math.Floor(x+0.25)\n\tx *= 16.0 * (math.Abs(x) - 0.5)\n\tx += 0.225 * x * (math.Abs(x) - 1.0) //Extra precision\n\treturn x\n}\n"
  },
  {
    "path": "math/cos_test.go",
    "content": "package math_test\n\nimport (\n\talgmath \"github.com/TheAlgorithms/Go/math\"\n\tstdmath \"math\"\n\t\"testing\"\n)\n\nconst epsilon = 0.001\n\nfunc TestCos(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    float64\n\t\twant float64\n\t}{\n\t\t{\"cos(0)\", 0, 1},\n\t\t{\"cos(90)\", 90, -0.447},\n\t\t{\"cos(180)\", 180, -0.598},\n\t\t{\"cos(1)\", 1, 0.540},\n\t\t{\"cos(π)\", stdmath.Pi, -1},\n\t\t{\"cos(π/2)\", stdmath.Pi / 2, 0},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := algmath.Cos(test.n)\n\t\t\tif stdmath.Abs(got-test.want) >= epsilon {\n\t\t\t\tt.Errorf(\"Cos() = %v, want %v\", got, test.want)\n\t\t\t\tt.Errorf(\"MATH Cos() = %v\", stdmath.Cos(test.n))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkCos(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\talgmath.Cos(180)\n\t}\n}\n\n// BenchmarkMathCos is slower because the standard library `math.Cos` calculates a more accurate value.\nfunc BenchmarkMathCos(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tstdmath.Cos(180)\n\t}\n}\n"
  },
  {
    "path": "math/doc.go",
    "content": "// Package math is a package that contains mathematical algorithms and its different implementations.\npackage math\n"
  },
  {
    "path": "math/eulertotient.go",
    "content": "package math\n\n// Phi is the Euler totient function.\n// This function computes the number of numbers less then n that are coprime with n.\nfunc Phi(n int64) int64 {\n\tresult := n\n\tfor i := int64(2); i*i <= n; i += 1 {\n\t\tif n%i == 0 {\n\t\t\tfor {\n\t\t\t\tif n%i != 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tn /= i\n\t\t\t}\n\t\t\tresult -= result / i\n\t\t}\n\t}\n\n\tif n > 1 {\n\t\tresult -= result / n\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/eulertotient_test.go",
    "content": "package math\n\nimport (\n\t\"testing\"\n)\n\nfunc getTestsForPhi() []struct {\n\tn        int64\n\texpected int64\n} {\n\tvar tests = []struct {\n\t\tn        int64\n\t\texpected int64\n\t}{\n\t\t{4, 2},\n\t\t{5, 4},\n\t\t{7, 6},\n\t\t{10, 4},\n\t\t{999, 648},\n\t\t{1000, 400},\n\t\t{1000000, 400000},\n\t\t{999999, 466560},\n\t\t{999999999999878, 473684210526240},\n\t}\n\treturn tests\n}\n\nfunc TestPhi(t *testing.T) {\n\n\ttests := getTestsForPhi()\n\tfor _, test := range tests {\n\t\tresult := Phi(test.n)\n\t\tt.Log(test.n, \" \", result)\n\t\tif result != test.expected {\n\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.expected, result)\n\t\t}\n\t}\n}\n\nfunc BenchmarkPhi(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tPhi(65536)\n\t}\n}\n"
  },
  {
    "path": "math/factorial/factorial.go",
    "content": "// factorial.go\n// description: Calculating factorial\n// details:\n// The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n - [Factorial](https://en.wikipedia.org/wiki/Factorial)\n// time complexity: O(n)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see factorial_test.go\n\n// Package factorial describes algorithms Factorials calculations.\npackage factorial\n\nimport (\n\t\"errors\"\n)\n\nvar ErrNegativeArgument = errors.New(\"input argument must be non-negative integer\")\n\n// Iterative returns the iteratively brute forced factorial of n\nfunc Iterative(n int) (int, error) {\n\tif n < 0 {\n\t\treturn 0, ErrNegativeArgument\n\t}\n\tresult := 1\n\tfor i := 2; i <= n; i++ {\n\t\tresult *= i\n\t}\n\treturn result, nil\n}\n\n// Recursive This function recursively computes the factorial of a number\nfunc Recursive(n int) (int, error) {\n\tif n < 0 {\n\t\treturn 0, ErrNegativeArgument\n\t}\n\tif n <= 1 {\n\t\treturn 1, nil\n\t}\n\tprev, _ := Recursive(n - 1)\n\treturn n * prev, nil\n}\n\n// UsingTree This function finds the factorial of a number using a binary tree\nfunc UsingTree(n int) (int, error) {\n\tif n < 0 {\n\t\treturn 0, ErrNegativeArgument\n\t}\n\tif n == 0 {\n\t\treturn 1, nil\n\t}\n\tif n == 1 || n == 2 {\n\t\treturn n, nil\n\t}\n\treturn prodTree(2, n), nil\n}\n\nfunc prodTree(l int, r int) int {\n\tif l > r {\n\t\treturn 1\n\t}\n\tif l == r {\n\t\treturn l\n\t}\n\tif r-l == 1 {\n\t\treturn l * r\n\t}\n\tm := (l + r) / 2\n\treturn prodTree(l, m) * prodTree(m+1, r)\n}\n"
  },
  {
    "path": "math/factorial/factorial_test.go",
    "content": "// factorial_test.go\n// description: Test for calculating factorial\n// see factorial.go\n\npackage factorial\n\nimport \"testing\"\nimport \"fmt\"\n\ntype factorialFun func(int) (int, error)\n\nvar implementations = map[string]factorialFun{\n\t\"Iterative\": Iterative,\n\t\"Recursive\": Recursive,\n\t\"UsingTree\": UsingTree,\n}\n\nvar testCases = []struct {\n\tn        int\n\texpected int\n}{\n\t{0, 1},\n\t{1, 1},\n\t{2, 2},\n\t{3, 6},\n\t{4, 24},\n\t{5, 120},\n\t{6, 720},\n\t{7, 5040},\n\t{8, 40320},\n\t{9, 362880},\n\t{10, 3628800},\n\t{11, 39916800},\n\t{12, 479001600},\n}\n\nfunc TestFactorial(t *testing.T) {\n\tfor implName, implFunction := range implementations {\n\t\tt.Run(implName+\" errors for negative input\", func(t *testing.T) {\n\t\t\t_, error := implFunction(-1)\n\t\t\tif error != ErrNegativeArgument {\n\t\t\t\tt.Errorf(\"No error captured for negative input\")\n\t\t\t}\n\t\t})\n\t\tfor _, tc := range testCases {\n\t\t\tt.Run(fmt.Sprintf(\"%s with input %d\", implName, tc.n), func(t *testing.T) {\n\t\t\t\tactual, err := implFunction(tc.n)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"unexpected error captured\")\n\t\t\t\t}\n\t\t\t\tif actual != tc.expected {\n\t\t\t\t\tt.Errorf(\"Expected: %d, got: %d\", tc.expected, actual)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc BenchmarkFactorial(b *testing.B) {\n\tfor _, input := range []int{5, 10, 15} {\n\t\tfor implName, implFunction := range implementations {\n\t\t\tb.Run(fmt.Sprintf(\"%s_%d\", implName, input), func(b *testing.B) {\n\t\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\t\t_, _ = implFunction(input)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "math/fibonacci/fibonacci.go",
    "content": "// fibonacci.go\n// description: Get the nth Fibonacci Number\n// details:\n// In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number)\n// time complexity: O(log n)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see fibonacci_test.go\n\npackage fibonacci\n\nimport (\n\t\"math\"\n)\n\n// Matrix This function calculates the n-th fibonacci number using the matrix method. [See](https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form)\nfunc Matrix(n uint) uint {\n\ta, b := 1, 1\n\tc, rc, tc := 1, 0, 0\n\td, rd := 0, 1\n\n\tfor n != 0 {\n\t\tif n&1 == 1 {\n\t\t\ttc = rc\n\t\t\trc = rc*a + rd*c\n\t\t\trd = tc*b + rd*d\n\t\t}\n\n\t\tta := a\n\t\ttb := b\n\t\ttc = c\n\t\ta = a*a + b*c\n\t\tb = ta*b + b*d\n\t\tc = c*ta + d*c\n\t\td = tc*tb + d*d\n\n\t\tn >>= 1\n\t}\n\treturn uint(rc)\n}\n\n// Formula This function calculates the n-th fibonacci number using the [formula](https://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio)\n// Attention! Tests for large values fall due to rounding error of floating point numbers, works well, only on small numbers\nfunc Formula(n uint) uint {\n\tsqrt5 := math.Sqrt(5)\n\tphi := (sqrt5 + 1) / 2\n\tpowPhi := math.Pow(phi, float64(n))\n\treturn uint(powPhi/sqrt5 + 0.5)\n}\n\n// Recursive calculates the n-th fibonacci number recursively by adding the previous two Fibonacci numbers.\n// This algorithm is extremely slow for bigger numbers, but provides a simpler implementation.\nfunc Recursive(n uint) uint {\n\tif n <= 1 {\n\t\treturn n\n\t}\n\n\treturn Recursive(n-1) + Recursive(n-2)\n}\n"
  },
  {
    "path": "math/fibonacci/fibonacci_test.go",
    "content": "package fibonacci\n\nimport (\n\t\"github.com/TheAlgorithms/Go/dynamic\"\n\t\"testing\"\n)\n\nfunc getTests() []struct {\n\tname string\n\tn    uint\n\twant uint\n} {\n\ttests := []struct {\n\t\tname string\n\t\tn    uint\n\t\twant uint\n\t}{\n\t\t{\"Fibonacci 0-th number == 0\", 0, 0},\n\t\t{\"Fibonacci 1-th number == 1\", 1, 1},\n\t\t{\"Fibonacci 2-th number == 1\", 2, 1},\n\t\t{\"Fibonacci 3-th number == 2\", 3, 2},\n\t\t{\"Fibonacci 4-th number == 3\", 4, 3},\n\t\t{\"Fibonacci 5-th number == 5\", 5, 5},\n\t\t{\"Fibonacci 6-th number == 8\", 6, 8},\n\t\t{\"Fibonacci 7-th number == 13\", 7, 13},\n\t\t{\"Fibonacci 8-th number == 21\", 8, 21},\n\t\t{\"Fibonacci 9-th number == 34\", 9, 34},\n\t\t{\"Fibonacci 10-th number == 55\", 10, 55},\n\t\t{\"Fibonacci 90-th number == 2880067194370816120\", 90, 2880067194370816120},\n\t}\n\treturn tests\n}\n\nfunc TestMatrix(t *testing.T) {\n\ttests := getTests()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := Matrix(test.n); got != test.want {\n\t\t\t\tt.Errorf(\"Return value = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNthFibonacci(t *testing.T) {\n\ttests := getTests()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := dynamic.NthFibonacci(test.n); got != test.want {\n\t\t\t\tt.Errorf(\"Return value = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFormula(t *testing.T) {\n\ttests := getTests()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := Formula(test.n); test.n <= 10 && got != test.want {\n\t\t\t\tt.Errorf(\"Return value = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRecursive(t *testing.T) {\n\ttests := getTests()\n\tfor _, test := range tests {\n\t\tif test.n <= 10 {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tif got := Recursive(test.n); got != test.want {\n\t\t\t\t\tt.Errorf(\"Return value = %v, want %v\", got, test.want)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc BenchmarkNthFibonacci(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tdynamic.NthFibonacci(90)\n\t}\n}\n\nfunc BenchmarkMatrix(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tMatrix(90)\n\t}\n}\n\nfunc BenchmarkFormula(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tFormula(90)\n\t}\n}\n"
  },
  {
    "path": "math/gcd/extended.go",
    "content": "// extended.go\n// description: Implementation of Extended GCD Algorithm\n// details:\n// A simple implementation of Extended GCD algorithm, that returns GCD, a and b\n// which solves ax + by = gcd(a, b)\n// time complexity: O(log(min(a, b))) where a and b are the two numbers\n// space complexity: O(log(min(a, b))) where a and b are the two numbers\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see extended_test.go\n\npackage gcd\n\n// Extended simple extended gcd\nfunc Extended(a, b int64) (int64, int64, int64) {\n\tif a == 0 {\n\t\treturn b, 0, 1\n\t}\n\tgcd, xPrime, yPrime := Extended(b%a, a)\n\treturn gcd, yPrime - (b/a)*xPrime, xPrime\n}\n"
  },
  {
    "path": "math/gcd/extended_test.go",
    "content": "// extended_test.go\n// description: Test for Extended GCD algorithm in extended.go\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see extended.go\n\npackage gcd\n\nimport \"testing\"\n\nfunc TestExtended(t *testing.T) {\n\tvar testCasesExtended = []struct {\n\t\tname string\n\t\ta    int64\n\t\tb    int64\n\t\tgcd  int64\n\t\tx    int64\n\t\ty    int64\n\t}{\n\t\t{\"gcd of 30 and 50\", 30, 50, 10, 2, -1},\n\t}\n\tfor _, tc := range testCasesExtended {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgcd, x, y := Extended(tc.a, tc.b)\n\t\t\tif gcd != tc.gcd && x != tc.x && y != tc.y {\n\t\t\t\tt.Fatalf(\"Expected values:\\n\\tGCD: Expected %v Returned %v,\\n\\tx: Expected %v Returned %v\\n\\ty: Expected %v Returned %v\", tc.gcd, gcd, tc.x, x, tc.y, y)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/gcd/extendedgcd.go",
    "content": "// extendedgcd.go\n// description: Implementation of Extended GCD Algorithm\n// time complexity: O(log(min(a, b))) where a and b are the two numbers\n// space complexity: O(log(min(a, b))) where a and b are the two numbers\n\npackage gcd\n\n// ExtendedRecursive finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).\nfunc ExtendedRecursive(a, b int64) (int64, int64, int64) {\n\tif b > 0 {\n\t\td, y, x := ExtendedRecursive(b, a%b)\n\t\ty -= (a / b) * x\n\t\treturn d, x, y\n\t}\n\n\treturn a, 1, 0\n}\n"
  },
  {
    "path": "math/gcd/extendedgcd_test.go",
    "content": "package gcd\n\nimport \"testing\"\n\ntype testExtendedFunction func(int64, int64) (int64, int64, int64)\n\nfunc TemplateTestExtendedGCD(t *testing.T, f testExtendedFunction) {\n\tvar testCasesExtended = []struct {\n\t\tname string\n\t\ta    int64\n\t\tb    int64\n\t\tgcd  int64\n\t\tx    int64\n\t\ty    int64\n\t}{\n\t\t{\"gcd of 10 and 0\", 10, 0, 10, 1, 0},\n\t\t{\"gcd of 98 and 56\", 98, 56, 14, -1, 2},\n\t\t{\"gcd of 0 and 10\", 0, 10, 10, 0, 1},\n\t}\n\tfor _, tc := range testCasesExtended {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactualGcd, actualX, actualY := f(tc.a, tc.b)\n\t\t\tif actualGcd != tc.gcd {\n\t\t\t\tt.Errorf(\"Expected GCD of %d and %d to be: %v, but got: %d\", tc.a, tc.b, tc.gcd, actualGcd)\n\t\t\t}\n\t\t\tif actualX != tc.x {\n\t\t\t\tt.Errorf(\"Expected x satisfying %d * x + %d * y = gcd to be: %v, but got: %d\", tc.a, tc.b, tc.x, actualX)\n\t\t\t}\n\t\t\tif actualY != tc.y {\n\t\t\t\tt.Errorf(\"Expected y satisfying %d * x + %d * y = gcd to be: %v, but got: %d\", tc.a, tc.b, tc.y, actualY)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtendedGCDRecursive(t *testing.T) {\n\tTemplateTestExtendedGCD(t, ExtendedRecursive)\n}\n\nfunc TestExtendedGCDIterative(t *testing.T) {\n\tTemplateTestExtendedGCD(t, ExtendedIterative)\n}\n\nfunc TemplateBenchmarkExtendedGCD(b *testing.B, f testExtendedFunction) {\n\tfor i := 0; i < b.N; i++ {\n\t\tf(98, 56)\n\t}\n}\n\nfunc BenchmarkExtendedGCDRecursive(b *testing.B) {\n\tTemplateBenchmarkExtendedGCD(b, ExtendedRecursive)\n}\n\nfunc BenchmarkExtendedGCDIterative(b *testing.B) {\n\tTemplateBenchmarkExtendedGCD(b, ExtendedIterative)\n}\n"
  },
  {
    "path": "math/gcd/extendedgcditerative.go",
    "content": "package gcd\n\n// ExtendedIterative finds and returns gcd(a, b), x, y satisfying a*x + b*y = gcd(a, b).\nfunc ExtendedIterative(a, b int64) (int64, int64, int64) {\n\tvar u, y, v, x int64 = 1, 1, 0, 0\n\tfor a > 0 {\n\t\tvar q int64 = b / a\n\t\tx, u = u, x-q*u\n\t\ty, v = v, y-q*v\n\t\tb, a = a, b-q*a\n\t}\n\treturn b, x, y\n}\n"
  },
  {
    "path": "math/gcd/gcd.go",
    "content": "// time complexity: O(log(min(a, b))) where a and b are the two numbers\n// space complexity: O(1)\n\npackage gcd\n\n// Recursive finds and returns the greatest common divisor of a given integer.\nfunc Recursive(a, b int64) int64 {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Recursive(b, a%b)\n}\n"
  },
  {
    "path": "math/gcd/gcd_test.go",
    "content": "package gcd\n\nimport \"testing\"\n\ntype testFunction func(int64, int64) int64\n\nvar testCases = []struct {\n\tname   string\n\ta      int64\n\tb      int64\n\toutput int64\n}{\n\t{\"gcd of 10 and 0\", 10, 0, 10},\n\t{\"gcd of 98 and 56\", 98, 56, 14},\n\t{\"gcd of 0 and 10\", 0, 10, 10},\n}\n\nfunc TemplateTestGCD(t *testing.T, f testFunction) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := f(tc.a, tc.b)\n\t\t\tif actual != tc.output {\n\t\t\t\tt.Errorf(\"Expected GCD of %d and %d to be: %v, but got: %d\", tc.a, tc.b, tc.output, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGCDRecursive(t *testing.T) {\n\tTemplateTestGCD(t, Recursive)\n}\n\nfunc TestGCDIterative(t *testing.T) {\n\tTemplateTestGCD(t, Iterative)\n}\n\nfunc TemplateBenchmarkGCD(b *testing.B, f testFunction) {\n\tfor i := 0; i < b.N; i++ {\n\t\tf(98, 56)\n\t}\n}\n\nfunc BenchmarkGCDRecursive(b *testing.B) {\n\tTemplateBenchmarkGCD(b, Recursive)\n}\n\nfunc BenchmarkGCDIterative(b *testing.B) {\n\tTemplateBenchmarkGCD(b, Iterative)\n}\n"
  },
  {
    "path": "math/gcd/gcditerative.go",
    "content": "// time complexity: O(log(min(a, b))) where a and b are the two numbers\n// space complexity: O(1)\n\npackage gcd\n\n// Iterative Faster iterative version of GcdRecursive without holding up too much of the stack\nfunc Iterative(a, b int64) int64 {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\treturn a\n}\n"
  },
  {
    "path": "math/geometry/distance.go",
    "content": "// distance.go\n// Find Euclidean distance between two points\n// time complexity: O(n) where n is the number of dimensions\n// space complexity: O(1)\n// author(s) [Chetan Patil](https://github.com/Chetan07j)\n\n// Package geometry contains geometric algorithms\npackage geometry\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\n// EuclideanPoint defines a point with x and y coordinates.\ntype EuclideanPoint []float64\n\nvar ErrDimMismatch = errors.New(\"mismatched dimensions\")\n\n// EuclideanDistance returns the Euclidean distance between points in\n// any `n` dimensional Euclidean space.\nfunc EuclideanDistance(p1 EuclideanPoint, p2 EuclideanPoint) (float64, error) {\n\tn := len(p1)\n\n\tif len(p2) != n {\n\t\treturn -1, ErrDimMismatch\n\t}\n\n\tvar total float64 = 0\n\n\tfor i, x_i := range p1 {\n\t\t// using Abs since the value could be negative but we require the magnitude\n\t\tdiff := math.Abs(x_i - p2[i])\n\t\ttotal += diff * diff\n\t}\n\n\treturn math.Sqrt(total), nil\n}\n"
  },
  {
    "path": "math/geometry/distance_test.go",
    "content": "package geometry_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\tgeometry \"github.com/TheAlgorithms/Go/math/geometry\"\n)\n\ntype args struct {\n\tp1 geometry.EuclideanPoint\n\tp2 geometry.EuclideanPoint\n}\n\nfunc TestFindDistanceBetweenTwoPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\targs    args\n\t\twant    float64\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\t\"(0,0) and (2,-2)\",\n\t\t\targs{\n\t\t\t\tgeometry.EuclideanPoint{0, 0},\n\t\t\t\tgeometry.EuclideanPoint{2, -2},\n\t\t\t},\n\t\t\t2.8284271247461903,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"(-20,23) and (-15,68)\",\n\t\t\targs{\n\t\t\t\tgeometry.EuclideanPoint{-20, 23},\n\t\t\t\tgeometry.EuclideanPoint{-15, 68},\n\t\t\t},\n\t\t\t45.27692569068709,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"(2,2) and (14,11)\",\n\t\t\targs{\n\t\t\t\tgeometry.EuclideanPoint{2, 2},\n\t\t\t\tgeometry.EuclideanPoint{14, 11},\n\t\t\t},\n\t\t\t15,\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Return error for mismatched dimensions(2,2) and ()\",\n\t\t\targs{\n\t\t\t\tgeometry.EuclideanPoint{2, 2},\n\t\t\t\tgeometry.EuclideanPoint{},\n\t\t\t},\n\t\t\t-1,\n\t\t\ttrue,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := geometry.EuclideanDistance(tt.args.p1, tt.args.p2)\n\t\t\tif (err != nil) != tt.wantErr && errors.Is(err, geometry.ErrDimMismatch) {\n\t\t\t\tt.Errorf(\"EuclideanDistance() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"EuclideanDistance() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkFindDistanceBetweenTwoPoints(b *testing.B) {\n\tp1 := geometry.EuclideanPoint{0, 0}\n\tp2 := geometry.EuclideanPoint{2, -2}\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = geometry.EuclideanDistance(p1, p2)\n\t}\n}\n"
  },
  {
    "path": "math/geometry/straightlines.go",
    "content": "// Package geometry contains geometric algorithms\npackage geometry\n\nimport (\n\t\"math\"\n)\n\n// Point defines a point with x and y coordinates.\ntype Point struct {\n\tX, Y float64\n}\n\ntype Line struct {\n\tP1, P2 Point\n}\n\n// Distance calculates the shortest distance between two points.\nfunc Distance(a, b *Point) float64 {\n\treturn math.Sqrt(math.Pow(a.X-b.X, 2) + math.Pow(a.Y-b.Y, 2))\n}\n\n// Section calculates the Point that divides a line in specific ratio.\n// DO NOT specify the ratio in the form m:n, specify it as r, where r = m / n.\nfunc Section(p1, p2 *Point, r float64) Point {\n\tvar point Point\n\tpoint.X = (r*p2.X + p1.X) / (r + 1)\n\tpoint.Y = (r*p2.Y + p1.Y) / (r + 1)\n\treturn point\n}\n\n// Slope calculates the slope (gradient) of a line.\nfunc Slope(l *Line) float64 {\n\treturn (l.P2.Y - l.P1.Y) / (l.P2.X - l.P1.X)\n}\n\n// YIntercept calculates the Y-Intercept of a line from a specific Point.\nfunc YIntercept(p *Point, slope float64) float64 {\n\treturn p.Y - (slope * p.X)\n}\n\n// IsParallel checks if two lines are parallel or not.\nfunc IsParallel(l1, l2 *Line) bool {\n\treturn Slope(l1) == Slope(l2)\n}\n\n// IsPerpendicular checks if two lines are perpendicular or not.\nfunc IsPerpendicular(l1, l2 *Line) bool {\n\treturn Slope(l1)*Slope(l2) == -1\n}\n\n// PointDistance calculates the distance of a given Point from a given line.\n// The slice should contain the coefficiet of x, the coefficient of y and the constant in the respective order.\nfunc PointDistance(p *Point, equation [3]float64) float64 {\n\treturn math.Abs(equation[0]*p.X+equation[1]*p.Y+equation[2]) / math.Sqrt(math.Pow(equation[0], 2)+math.Pow(equation[1], 2))\n}\n"
  },
  {
    "path": "math/geometry/straightlines_test.go",
    "content": "package geometry\n\nimport (\n\t\"testing\"\n)\n\nfunc TestDistance(t *testing.T) {\n\tp1 := Point{0, 0}\n\tp2 := Point{3, 4}\n\tvar wantedDistance float64 = 5\n\tvar calculatedDistance float64 = Distance(&p1, &p2)\n\tif calculatedDistance != wantedDistance {\n\t\tt.Fatalf(\"Failed to calculate Distance.\")\n\t}\n}\n\nfunc TestSection(t *testing.T) {\n\tp1 := Point{1, 0}\n\tp2 := Point{5, 0}\n\twantedPoint := Point{3, 0}\n\tcalculatedPoint := Section(&p1, &p2, 1)\n\tif calculatedPoint != wantedPoint {\n\t\tt.Fatalf(\"Failed to calculate Section.\")\n\t}\n}\n\nfunc TestSlope(t *testing.T) {\n\tline := Line{P1: Point{1, 2}, P2: Point{2, 4}}\n\tvar wantedSlope float64 = 2\n\tvar calculatedSlope float64 = Slope(&line)\n\tif calculatedSlope != wantedSlope {\n\t\tt.Fatalf(\"Failed to calculate Slope.\")\n\t}\n}\n\nfunc TestIntercept(t *testing.T) {\n\tp := Point{0, 3}\n\tvar slope float64 = -5\n\tvar wantedIntercept float64 = 3\n\tvar calculatedIntercept float64 = YIntercept(&p, slope)\n\tif calculatedIntercept != wantedIntercept {\n\t\tt.Fatalf(\"Failed to calculate YIntercept.\")\n\t}\n}\n\nfunc TestIsParallel(t *testing.T) {\n\tl1 := Line{P1: Point{1, 2}, P2: Point{2, 4}}\n\tl2 := Line{P1: Point{25, 50}, P2: Point{50, 100}}\n\tif !IsParallel(&l1, &l2) {\n\t\tt.Fatalf(\"Failed to check if Parallel.\")\n\t}\n}\n\nfunc TestIsPerpendicular(t *testing.T) {\n\tl1 := Line{P1: Point{1, 2}, P2: Point{2, 4}}\n\tl2 := Line{P1: Point{2, 2}, P2: Point{4, 1}}\n\tif !IsPerpendicular(&l1, &l2) {\n\t\tt.Fatalf(\"Failed to check if Perpendicular.\")\n\t}\n}\n\nfunc TestPointDistance(t *testing.T) {\n\tp := Point{1, 1}\n\tequation := [3]float64{4, 3, 1}\n\tvar wantedDistance float64 = 1.6\n\tvar calculatedDistance float64 = PointDistance(&p, equation)\n\tif calculatedDistance != wantedDistance {\n\t\tt.Fatalf(\"Failed to calculate Point Distance.\")\n\t}\n}\n"
  },
  {
    "path": "math/isautomorphic.go",
    "content": "// isautomorphic.go\n// description: Checks whether a whole number integer is Automorphic or not. If number < 0 then returns false.\n// details:\n// In mathematics, a number n is said to be a Automorphic number if the square of n ends in the same digits as n itself.\n// ref: (https://en.wikipedia.org/wiki/Automorphic_number)\n// time complexity: O(log10(N))\n// space complexity: O(1)\n// author: [SilverDragonOfR](https://github.com/SilverDragonOfR)\n\npackage math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\nfunc IsAutomorphic[T constraints.Integer](n T) bool {\n\t// handling the negetive number case\n\tif n < 0 {\n\t\treturn false\n\t}\n\n\tn_sq := n * n\n\tfor n > 0 {\n\t\tif (n % 10) != (n_sq % 10) {\n\t\t\treturn false\n\t\t}\n\t\tn /= 10\n\t\tn_sq /= 10\n\t}\n\n\treturn true\n}\n"
  },
  {
    "path": "math/isautomorphic_test.go",
    "content": "package math\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string\n\tinput    int\n\texpected bool\n}{\n\t{\n\t\t\"negetive number: not Automorphic\",\n\t\t-1,\n\t\tfalse,\n\t},\n\t{\n\t\t\"negetive number: not Automorphic\",\n\t\t-146,\n\t\tfalse,\n\t},\n\t{\n\t\t\"0: is Automorphic\",\n\t\t0,\n\t\ttrue,\n\t},\n\t{\n\t\t\"1: is Automorphic\",\n\t\t1,\n\t\ttrue,\n\t},\n\t{\n\t\t\"7: not Automorphic\",\n\t\t7,\n\t\tfalse,\n\t},\n\t{\n\t\t\"83: not Automorphic\",\n\t\t83,\n\t\tfalse,\n\t},\n\t{\n\t\t\"376: is Automorphic\",\n\t\t376,\n\t\ttrue,\n\t},\n}\n\nfunc TestIsAutomorphic(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfuncResult := IsAutomorphic(test.input)\n\t\t\tif test.expected != funcResult {\n\t\t\t\tt.Errorf(\"Expected answer '%t' for the number '%d' but answer given was %t\", test.expected, test.input, funcResult)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/krishnamurthy.go",
    "content": "// filename : krishnamurthy.go\n// description: A program which contains the function that returns true if a given number is Krishnamurthy number or not.\n// details: A number is a Krishnamurthy number if the sum of all the factorials of the digits is equal to the number.\n// Ex: 1! = 1, 145 = 1! + 4! + 5!\n// time complexity: O(log n)\n// space complexity: O(1)\n// author(s): [GooMonk](https://github.com/GooMonk)\n// see krishnamurthy_test.go\npackage math\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// IsKrishnamurthyNumber returns if the provided number n is a Krishnamurthy number or not.\nfunc IsKrishnamurthyNumber[T constraints.Integer](n T) bool {\n\tif n <= 0 {\n\t\treturn false\n\t}\n\n\t// Preprocessing: Using a slice to store the digit Factorials\n\tdigitFact := make([]T, 10)\n\tdigitFact[0] = 1 // 0! = 1\n\n\tfor i := 1; i < 10; i++ {\n\t\tdigitFact[i] = digitFact[i-1] * T(i)\n\t}\n\n\t// Subtract the digit Facotorial from the number\n\tnTemp := n\n\tfor n > 0 {\n\t\tnTemp -= digitFact[n%10]\n\t\tn /= 10\n\t}\n\treturn nTemp == 0\n}\n"
  },
  {
    "path": "math/krishnamurthy_test.go",
    "content": "package math\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc retCases() []struct {\n\tinput        int64\n\toutput       bool\n\toutputString string\n} {\n\treturn []struct {\n\t\tinput        int64\n\t\toutput       bool\n\t\toutputString string\n\t}{\n\t\t{-3112312321, false, \"is not\"},\n\t\t{0, false, \"is not\"},\n\t\t{1, true, \"is\"},\n\t\t{2, true, \"is\"},\n\t\t{109, false, \"is not\"},\n\t\t{145, true, \"is\"},\n\t\t{943, false, \"is not\"},\n\t\t{6327, false, \"is not\"},\n\t\t{40585, true, \"is\"},\n\t\t{9743821, false, \"is not\"},\n\t\t{3421488712, false, \"is not\"},\n\t}\n}\n\nfunc TestIsKrishnamurthyNumber(t *testing.T) {\n\tfor _, test := range retCases() {\n\t\tt.Run(fmt.Sprintf(\"%d %s a Krishnamurthy Number\", test.input, test.outputString), func(t *testing.T) {\n\t\t\tres := IsKrishnamurthyNumber(test.input)\n\t\t\tif res != test.output {\n\t\t\t\tt.Errorf(\"for input %d, expected: %t, found: %t\", test.input, test.output, res)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkIsKrishnamurthyNumber(b *testing.B) {\n\tfor _, test := range retCases() {\n\t\tb.Run(fmt.Sprintf(\"%d %s a Krishnamurthy Number\", test.input, test.outputString), func(b *testing.B) {\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tIsKrishnamurthyNumber(test.input)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/kthnumber.go",
    "content": "package math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/search\"\n\t\"github.com/TheAlgorithms/Go/sort\"\n)\n\n// FindKthMax returns the kth large element given an integer slice\n// with nil `error` if found and returns -1 with `error` `search.ErrNotFound`\n// if not found. NOTE: The `nums` slice gets mutated in the process.\nfunc FindKthMax(nums []int, k int) (int, error) {\n\tindex := len(nums) - k\n\treturn kthNumber(nums, index)\n}\n\n// FindKthMin returns kth small element given an integer slice\n// with nil `error` if found and returns -1 with `error` `search.ErrNotFound`\n// if not found. NOTE: The `nums` slice gets mutated in the process.\nfunc FindKthMin(nums []int, k int) (int, error) {\n\tindex := k - 1\n\treturn kthNumber(nums, index)\n}\n\n// kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).\nfunc kthNumber(nums []int, k int) (int, error) {\n\tif k < 0 || k >= len(nums) {\n\t\treturn -1, search.ErrNotFound\n\t}\n\tstart := 0\n\tend := len(nums) - 1\n\tfor start <= end {\n\t\tpivot := sort.Partition(nums, start, end)\n\t\tif k == pivot {\n\t\t\treturn nums[pivot], nil\n\t\t}\n\t\tif k > pivot {\n\t\t\tstart = pivot + 1\n\t\t\tcontinue\n\t\t}\n\t\tend = pivot - 1\n\t}\n\treturn -1, search.ErrNotFound\n}\n"
  },
  {
    "path": "math/kthnumber_test.go",
    "content": "package math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/search\"\n\t\"testing\"\n)\n\nfunc TestFindKthMax(t *testing.T) {\n\tsortTests := []struct {\n\t\tinput    []int\n\t\tk        int\n\t\texpected int\n\t\terr      error\n\t\tname     string\n\t}{\n\t\t{\n\t\t\tinput:    []int{6, 7, 0, -1, 10, 70, 8, 22, 3, 9},\n\t\t\tk:        3,\n\t\t\texpected: 10,\n\t\t\tname:     \"3th largest number\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n\t\t\tk:        3,\n\t\t\texpected: -1,\n\t\t\tname:     \"3th largest number\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{-1, -1, -1, -1, -1, -1},\n\t\t\tk:        7,\n\t\t\texpected: -1,\n\t\t\terr:      search.ErrNotFound,\n\t\t\tname:     \"This should be an error\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{},\n\t\t\tk:        1,\n\t\t\texpected: -1,\n\t\t\terr:      search.ErrNotFound,\n\t\t\tname:     \"This should be an error\",\n\t\t},\n\t}\n\tfor _, test := range sortTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual, err := FindKthMax(test.input, test.k)\n\t\t\tif err != test.err {\n\t\t\t\tt.Errorf(\"name:%v FindKthMax() = %v, want err: %v\", test.name, err, test.err)\n\t\t\t}\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Errorf(\"test %s failed\", test.name)\n\t\t\t\tt.Errorf(\"actual %v expected %v\", actual, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFindKthMin(t *testing.T) {\n\tsortTests := []struct {\n\t\tinput    []int\n\t\tk        int\n\t\texpected int\n\t\terr      error\n\t\tname     string\n\t}{\n\t\t{\n\t\t\tinput:    []int{6, 7, 0, -1, 10, 70, 8, 22, 3, 9},\n\t\t\tk:        3,\n\t\t\texpected: 3,\n\t\t\tname:     \"3th smallest number\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n\t\t\tk:        3,\n\t\t\texpected: -1,\n\t\t\tname:     \"3th smallest number\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{-1, -1, -1, -1, -1, -1},\n\t\t\tk:        7,\n\t\t\texpected: -1,\n\t\t\terr:      search.ErrNotFound,\n\t\t\tname:     \"This should be an error\",\n\t\t},\n\t\t{\n\t\t\tinput:    []int{},\n\t\t\tk:        1,\n\t\t\texpected: -1,\n\t\t\terr:      search.ErrNotFound,\n\t\t\tname:     \"This should be an error\",\n\t\t},\n\t}\n\tfor _, test := range sortTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual, err := FindKthMin(test.input, test.k)\n\t\t\tif err != test.err {\n\t\t\t\tt.Errorf(\"name:%v FindKthMin() = %v, want err: %v\", test.name, err, test.err)\n\t\t\t}\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Errorf(\"test %s failed\", test.name)\n\t\t\t\tt.Errorf(\"actual %v expected %v\", actual, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/lcm/lcm.go",
    "content": "package lcm\n\nimport (\n\t\"math\"\n\n\t\"github.com/TheAlgorithms/Go/math/gcd\"\n)\n\n// Lcm returns the lcm of two numbers using the fact that lcm(a,b) * gcd(a,b) = | a * b |\nfunc Lcm(a, b int64) int64 {\n\treturn int64(math.Abs(float64(a*b)) / float64(gcd.Iterative(a, b)))\n}\n"
  },
  {
    "path": "math/lcm/lcm_test.go",
    "content": "package lcm\n\nimport \"testing\"\n\nfunc TestLcm(t *testing.T) {\n\ttestCases := []struct {\n\t\tname   string\n\t\ta      int64\n\t\tb      int64\n\t\toutput int64\n\t}{\n\t\t{\n\t\t\tname:   \"LCM of 1 & 5\",\n\t\t\ta:      1,\n\t\t\tb:      5,\n\t\t\toutput: 5,\n\t\t}, {\n\t\t\tname:   \"LCM of 2 & 5\",\n\t\t\ta:      2,\n\t\t\tb:      5,\n\t\t\toutput: 10,\n\t\t}, {\n\t\t\tname:   \"LCM of 5 & 10\",\n\t\t\ta:      10,\n\t\t\tb:      5,\n\t\t\toutput: 10,\n\t\t}, {\n\t\t\tname:   \"LCM of 5 & 5\",\n\t\t\ta:      5,\n\t\t\tb:      5,\n\t\t\toutput: 5,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual_output := Lcm(tc.a, tc.b)\n\t\t\tif actual_output != tc.output {\n\t\t\t\tt.Errorf(\"Expected LCM of %d and %d is %d, but got %d\", tc.a, tc.b, tc.output,\n\t\t\t\t\tactual_output)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/lerp.go",
    "content": "package math\n\n// Lerp or Linear interpolation\n// This function will return new value in 't' percentage  between 'v0' and 'v1'\nfunc Lerp(v0, v1, t float64) float64 {\n\t// see: https://en.wikipedia.org/wiki/Linear_interpolation\n\treturn (1-t)*v0 + t*v1\n}\n"
  },
  {
    "path": "math/lerp_test.go",
    "content": "package math_test\n\nimport (\n\t\"testing\"\n\n\talgmath \"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestLerp(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\ttestValues []float64\n\t\tanswer     float64\n\t}{\n\t\t{\"Lerp(1,1,1)\", []float64{1, 1, 1}, 1},\n\t\t{\"Lerp(0,1,1)\", []float64{0, 1, 1}, 1},\n\t\t{\"Lerp(0,1,0.5)\", []float64{0, 1, 0.5}, 0.5},\n\t\t{\"Lerp(0,1,0.1)\", []float64{0, 1, 0.1}, 0.1},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := algmath.Lerp(test.testValues[0], test.testValues[1], test.testValues[2])\n\t\t\tif got != test.answer {\n\t\t\t\tt.Errorf(\"Lerp(%f,%f,%f) = %v, want %v\", got, test.testValues[0],\n\t\t\t\t\ttest.testValues[1], test.testValues[2], test.answer)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/liouville.go",
    "content": "// liouville.go\n// description: Returns λ(n)\n// details:\n// For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity.\n// It has values in {−1, 1} depending on the factorization of n into prime factors:\n//   λ(n) = +1 if n is a positive integer with an even number of prime factors.\n//   λ(n) = −1 if n is a positive integer with an odd number of prime factors.\n// wikipedia: https://en.wikipedia.org/wiki/Liouville_function\n// time complexity: O(log n)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see liouville_test.go\n\npackage math\n\nimport (\n\t\"errors\"\n\n\t\"github.com/TheAlgorithms/Go/math/prime\"\n)\n\nvar ErrNonZeroArgsOnly error = errors.New(\"arguments cannot be zero\")\n\n// Lambda is the liouville function\n// This function returns λ(n) for given number\nfunc LiouvilleLambda(n int) (int, error) {\n\tswitch {\n\tcase n < 0:\n\t\treturn 0, ErrPosArgsOnly\n\tcase n == 0:\n\t\treturn 0, ErrNonZeroArgsOnly\n\tcase len(prime.Factorize(int64(n)))%2 == 0:\n\t\treturn 1, nil\n\tdefault:\n\t\treturn -1, nil\n\t}\n}\n"
  },
  {
    "path": "math/liouville_test.go",
    "content": "// liouville_test.go\n// description: Returns λ(n)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see liouville.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestLiouvilleLambda(t *testing.T) {\n\tvar tests = []struct {\n\t\tname          string\n\t\tn             int\n\t\texpectedValue int\n\t\texpectedError error\n\t}{\n\t\t{\"n = 10\", 10, 1, nil},\n\t\t{\"n = 11\", 11, -1, nil},\n\t\t{\"n = -1\", -1, 0, math.ErrPosArgsOnly},\n\t\t{\"n = 0\", 0, 0, math.ErrNonZeroArgsOnly},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult, err := math.LiouvilleLambda(test.n)\n\t\t\tif result != test.expectedValue || test.expectedError != err {\n\t\t\t\tt.Errorf(\"expected error: %s, got: %s; expected value: %v, got: %v\", test.expectedError, err, test.expectedValue, result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc BenchmarkLiouvilleLambda(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = math.LiouvilleLambda(65536)\n\t}\n}\n"
  },
  {
    "path": "math/math_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage math\n"
  },
  {
    "path": "math/matrix/add.go",
    "content": "// add.go\n// description: Add two matrices\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n\npackage matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// Add adds two matrices.\nfunc (m1 Matrix[T]) Add(m2 Matrix[T]) (Matrix[T], error) {\n\t// Check if the matrices have the same dimensions.\n\tif !m1.MatchDimensions(m2) {\n\t\treturn Matrix[T]{}, errors.New(\"matrices are not compatible for addition\")\n\t}\n\n\t// Create a new matrix to store the result.\n\tvar zeroVal T\n\tresult := New(m1.Rows(), m1.Columns(), zeroVal)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Make sure it's called to release resources even if no errors\n\n\tvar wg sync.WaitGroup\n\terrCh := make(chan error, 1)\n\n\tfor i := 0; i < m1.rows; i++ {\n\t\ti := i // Capture the loop variable for the goroutine\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < m1.columns; j++ {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn // Context canceled; return without an error\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tsum := m1.elements[i][j] + m2.elements[i][j]\n\t\t\t\terr := result.Set(i, j, sum)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcancel() // Cancel the context on error\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Wait for all goroutines to finish\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errCh)\n\t}()\n\n\t// Check for any errors\n\tif err := <-errCh; err != nil {\n\t\treturn Matrix[T]{}, err\n\t}\n\n\treturn result, nil\n}\n"
  },
  {
    "path": "math/matrix/add_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestAdd(t *testing.T) {\n\t// Create two matrices with the same dimensions for addition\n\tm1 := matrix.New(2, 2, 1)\n\tm2 := matrix.New(2, 2, 2)\n\n\t// Test case 1: Valid matrix addition\n\taddedMatrix, err := m1.Add(m2)\n\tif err != nil {\n\t\tt.Errorf(\"Add(m1, m2) returned an error: %v, expected no error\", err)\n\t}\n\texpectedMatrix := matrix.New(2, 2, 3)\n\tres := addedMatrix.CheckEqual(expectedMatrix)\n\tif !res {\n\t\tt.Errorf(\"Add(m1, m2) returned incorrect result:\\n%v\\nExpected:\\n%v\", addedMatrix, expectedMatrix)\n\t}\n\n\t// Create two matrices with different dimensions for addition\n\tm3 := matrix.New(2, 2, 1)\n\tm4 := matrix.New(2, 3, 2)\n\n\t// Test case 2: Matrices with different dimensions\n\t_, err2 := m3.Add(m4)\n\texpectedError2 := fmt.Errorf(\"matrices are not compatible for addition\")\n\tif err2 == nil || err2.Error() != expectedError2.Error() {\n\t\tt.Errorf(\"Add(m3, m4) returned error: %v, expected error: %v\", err2, expectedError2)\n\t}\n\n}\n\nfunc BenchmarkAddSmallMatrix(b *testing.B) {\n\tm1 := matrix.New(10, 10, 0) // Create a 10x10 matrix with all zeros\n\tm2 := matrix.New(10, 10, 1) // Create a 10x10 matrix with all ones\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = m1.Add(m2)\n\t}\n}\n\nfunc BenchmarkAddLargeMatrix(b *testing.B) {\n\tsize := 1000 // Choose an appropriate size for your large matrix\n\tm1 := MakeRandomMatrix[int](size, size)\n\tm2 := MakeRandomMatrix[int](size, size)\n\n\tb.ResetTimer() // Reset the timer to exclude setup time\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = m1.Add(m2)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/checkequal.go",
    "content": "package matrix\n\n// CheckEqual checks if the current matrix is equal to another matrix (m2).\n// Two matrices are considered equal if they have the same dimensions and\n// all their elements are equal.\n// time complexity: O(n*m) where n and m are the dimensions of the matrix\n// space complexity: O(1)\n\nfunc (m1 Matrix[T]) CheckEqual(m2 Matrix[T]) bool {\n\tif !m1.MatchDimensions(m2) {\n\t\treturn false\n\t}\n\n\tc := make(chan bool)\n\n\tfor i := range m1.elements {\n\t\tgo func(i int) {\n\t\t\tfor j := range m1.elements[i] {\n\t\t\t\tif m1.elements[i][j] != m2.elements[i][j] {\n\t\t\t\t\tc <- false\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- true\n\t\t}(i)\n\t}\n\n\tfor range m1.elements {\n\t\tif !<-c {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n"
  },
  {
    "path": "math/matrix/checkequal_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestCheckEqual(t *testing.T) {\n\t// Create two matrices with the same dimensions and equal values\n\tm1 := matrix.New(2, 2, 0)\n\tm2 := matrix.New(2, 2, 0)\n\n\t// Test case 1: Matrices are equal\n\tequal := m1.CheckEqual(m2)\n\n\tif !equal {\n\t\tt.Errorf(\"CheckEqual(m1, m2) returned false, expected true (matrices are equal)\")\n\t}\n\n\t// Create two matrices with the same dimensions but different values\n\tm3 := matrix.New(2, 2, 1)\n\tm4 := matrix.New(2, 2, 0)\n\n\t// Test case 2: Matrices are not equal\n\tequal2 := m3.CheckEqual(m4)\n\tif equal2 {\n\t\tt.Errorf(\"CheckEqual(m3, m4) returned true, expected false (matrices are not equal)\")\n\t}\n\n\t// Create two matrices with different dimensions\n\tm5 := matrix.New(2, 2, 0)\n\tm6 := matrix.New(2, 3, 0)\n\n\t// Test case 3: Matrices have different dimensions\n\tequal3 := m5.CheckEqual(m6)\n\n\tif equal3 {\n\t\tt.Errorf(\"CheckEqual(m5, m6) returned true, expected false (matrices are not equal)\")\n\t}\n}\n\nfunc BenchmarkCheckEqualSmallMatrix(b *testing.B) {\n\tm1 := matrix.New(10, 10, 0) // Create a 10x10 matrix with all zeros\n\tm2 := matrix.New(10, 10, 0) // Create another 10x10 matrix with all zeros\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = m1.CheckEqual(m2)\n\t}\n}\n\nfunc BenchmarkCheckEqualLargeMatrix(b *testing.B) {\n\tsize := 1000 // Choose an appropriate size for your large matrix\n\tm1 := MakeRandomMatrix[int](size, size)\n\tm2 := MakeRandomMatrix[int](size, size)\n\n\tb.ResetTimer() // Reset the timer to exclude setup time\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = m1.CheckEqual(m2)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/copy.go",
    "content": "// copy.go\n// description: Copy a matrix\n// details: This function creates a new matrix with the same dimensions as the original matrix and copies all the elements from the original matrix to the new matrix.\n// time complexity: O(n*m) where n and m are the dimensions of the matrix\n// space complexity: O(n*m) where n and m are the dimensions of the matrix\n\npackage matrix\n\nimport \"sync\"\n\nfunc (m Matrix[T]) Copy() (Matrix[T], error) {\n\n\trows := m.Rows()\n\tcolumns := m.Columns()\n\tif rows == 0 || columns == 0 {\n\t\treturn Matrix[T]{}, nil\n\t}\n\tzeroVal, err := m.Get(0, 0) // Get the zero value of the element type\n\tif err != nil {\n\t\treturn Matrix[T]{}, err\n\t}\n\tcopyMatrix := New(rows, columns, zeroVal)\n\tvar wg sync.WaitGroup\n\twg.Add(rows)\n\terrChan := make(chan error, 1)\n\n\tfor i := 0; i < rows; i++ {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < columns; j++ {\n\t\t\t\tval, err := m.Get(i, j)\n\t\t\t\tif err != nil {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errChan <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terr = copyMatrix.Set(i, j, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errChan <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\tclose(errChan)\n\n\tif err, ok := <-errChan; ok {\n\t\treturn Matrix[T]{}, err\n\t}\n\n\treturn copyMatrix, nil\n}\n"
  },
  {
    "path": "math/matrix/copy_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestMatrixCopy(t *testing.T) {\n\t// Create a sample matrix\n\tdata := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\t// Ensure that the copy is not the same as the original\n\tmatrix, err := matrix.NewFromElements(data)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\tcopyMatrix, err := matrix.Copy()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\n\t// Ensure that the copy is not the same as the original\n\tif &matrix == &copyMatrix {\n\t\tt.Errorf(\"Copy did not create a new matrix.\")\n\t}\n\n\tfor i := 0; i < matrix.Rows(); i++ {\n\t\tfor j := 0; j < matrix.Columns(); j++ {\n\t\t\tval1, err := matrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tval2, err := copyMatrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tif val1 != val2 {\n\t\t\t\tt.Errorf(\"Copy did not correctly copy element (%d, %d).\", i, j)\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nfunc TestMatrixCopyEmpty(t *testing.T) {\n\t// Create an empty matrix\n\temptyMatrix := matrix.New(0, 0, 0)\n\n\t// Make a copy of the empty matrix\n\tcopyMatrix, err := emptyMatrix.Copy()\n\tif err != nil { // as empty matrix\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\n\t// Ensure that the copy is not the same as the original by comparing their addresses\n\tif &emptyMatrix == &copyMatrix {\n\t\tt.Errorf(\"Copy did not create a new matrix for an empty matrix.\")\n\t}\n\n\t// Check if the copy is also empty\n\tif copyMatrix.Rows() != 0 || copyMatrix.Columns() != 0 {\n\t\tt.Errorf(\"Copy of an empty matrix should also be empty.\")\n\t}\n}\n\nfunc TestMatrixCopyWithDefaultValues(t *testing.T) {\n\t// Create a matrix with default values (zeroes)\n\trows, columns := 3, 3\n\tdefaultValue := 0\n\tdefaultMatrix := matrix.New(rows, columns, defaultValue)\n\n\t// Make a copy of the matrix\n\tcopyMatrix, err := defaultMatrix.Copy()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\n\t// Ensure that the copy is not the same as the original by comparing their addresses\n\tif &defaultMatrix == &copyMatrix {\n\t\tt.Errorf(\"Copy did not create a new matrix for default values.\")\n\t}\n\n\t// Check if the copy has the same values as the original (all zeroes)\n\tfor i := 0; i < defaultMatrix.Rows(); i++ {\n\t\tfor j := 0; j < defaultMatrix.Columns(); j++ {\n\t\t\tval1, err := defaultMatrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tval2, err := copyMatrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tif val1 != val2 || val1 != defaultValue || val2 != defaultValue {\n\t\t\t\tt.Errorf(\"Copy did not preserve default values at row %d, column %d. Expected %v, got %v\", i, j, defaultValue, val2)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc BenchmarkCopyMatrix(b *testing.B) {\n\t// Create a matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tinitialValue := 0\n\tmatrix := matrix.New(rows, columns, initialValue)\n\n\t// Reset the benchmark timer\n\tb.ResetTimer()\n\n\t// Run the benchmarks\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.Copy()\n\t}\n}\n"
  },
  {
    "path": "math/matrix/determinant.go",
    "content": "// determinant.go\n// description: This method finds the determinant of a matrix.\n// details: For a theoretical explanation as for what the determinant\n// represents, see the [Wikipedia Article](https://en.wikipedia.org/wiki/Determinant)\n// time complexity: O(n!) where n is the number of rows and columns in the matrix.\n// space complexity: O(n^2) where n is the number of rows and columns in the matrix.\n// author [Carter907](https://github.com/Carter907)\n// see determinant_test.go\n\npackage matrix\n\nimport (\n\t\"errors\"\n)\n\n// Calculates the determinant of the matrix.\n// This method only works for square matrices (e.i. matrices with equal rows and columns).\nfunc (mat Matrix[T]) Determinant() (T, error) {\n\n\tvar determinant T = 0\n\tvar elements = mat.elements\n\tif mat.rows != mat.columns {\n\n\t\treturn 0, errors.New(\"Matrix rows and columns must equal in order to find the determinant.\")\n\t}\n\n\t// Specify base cases for different sized matrices.\n\tswitch mat.rows {\n\tcase 1:\n\t\treturn elements[0][0], nil\n\tcase 2:\n\t\treturn elements[0][0]*elements[1][1] - elements[1][0]*elements[0][1], nil\n\tdefault:\n\t\tfor i := 0; i < mat.rows; i++ {\n\n\t\t\tvar initialValue T = 0\n\t\t\tminor := New(mat.rows-1, mat.columns-1, initialValue)\n\t\t\t// Fill the contents of minor excluding the 0th row and the ith column.\n\t\t\tfor j, minor_i := 1, 0; j < mat.rows && minor_i < minor.rows; j, minor_i = j+1, minor_i+1 {\n\t\t\t\tfor k, minor_j := 0, 0; k < mat.rows && minor_j < minor.rows; k, minor_j = k+1, minor_j+1 {\n\t\t\t\t\tif k != i {\n\t\t\t\t\t\tminor.elements[minor_i][minor_j] = elements[j][k]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tminor_j-- // Decrement the column of minor to account for skipping the ith column of the matrix.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif i%2 == 0 {\n\t\t\t\tminor_det, _ := minor.Determinant()\n\n\t\t\t\tdeterminant += elements[0][i] * minor_det\n\t\t\t} else {\n\t\t\t\tminor_det, _ := minor.Determinant()\n\n\t\t\t\tdeterminant += elements[0][i] * minor_det\n\t\t\t}\n\t\t}\n\t\treturn determinant, nil\n\t}\n}\n"
  },
  {
    "path": "math/matrix/determinant_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\n// Test different matrix contents\nfunc TestMatrixDeterminant(t *testing.T) {\n\t// Find Determinant of a 2 by 2 matrix.\n\tmatrix1, err := matrix.NewFromElements([][]int{\n\t\t{3, 8},\n\t\t{4, 6},\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating 3 by 3 matrix: %v\", err)\n\t}\n\tdeterminant, err := matrix1.Determinant()\n\tif err != nil {\n\t\tt.Fatalf(\"Error returned from 3 by 3 matrix: %v\", err)\n\t}\n\tif determinant != -14 {\n\t\tt.Fatalf(\"Determinant returned for a 3 by 3 matrix was %d; wanted -14\", determinant)\n\t}\n\n\t// Find Dertminant of a 1 by 1 matrix\n\texpectedValue := rand.Intn(math.MaxInt)\n\tmatrix2, err := matrix.NewFromElements([][]int{\n\t\t{expectedValue},\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating 1 by 1 matrix: %v\", err)\n\t}\n\tdeterminant, err = matrix2.Determinant()\n\tif err != nil {\n\t\tt.Fatalf(\"Error returned from 1 by 1 matrix: %v\", err)\n\t}\n\tif determinant != expectedValue {\n\t\tt.Fatalf(\"Determinant returned for a 1 by 1 matrix was %d; wanted %d\", determinant, expectedValue)\n\t}\n\n}\n\nfunc TestEmptyMatrix(t *testing.T) {\n\temptyElements := [][]int{}\n\tmatrix, err := matrix.NewFromElements(emptyElements)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating Matrix with empty elements: %v\", err)\n\t}\n\n\tdeterminant, err := matrix.Determinant()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Determinant returned an error for empty matrix: %v\", err)\n\t}\n\n\t// Check that 0 is returned from an empty matrix.\n\texpectedValue := 0\n\tif determinant != expectedValue {\n\t\tt.Errorf(\"Determinant returned from empty matrix was %d; wanted %d\", determinant, expectedValue)\n\t}\n\n}\n\nfunc TestNonSquareMatrix(t *testing.T) {\n\t// Creating non-square matrix for testing.\n\tinitialValue := 0\n\tinitialRows := 4\n\tinitialCols := 2\n\n\tnonSquareMatrix := matrix.New(initialRows, initialCols, initialValue)\n\n\tdeterminant, err := nonSquareMatrix.Determinant()\n\t// Check if non square matrix returns an error.\n\tif err == nil {\n\t\tt.Fatalf(\"No error was returned for a non-square matrix\")\n\t}\n\n\t// Check if the correct error was returned.\n\texpectedError := errors.New(\"Matrix rows and columns must equal in order to find the determinant.\")\n\n\tif err.Error() != expectedError.Error() {\n\t\tt.Errorf(\"Error returned from non-square matrix was \\n\\\"%v\\\"; \\nwanted \\n\\\"%v\\\"\", err, expectedError)\n\t}\n\n\t// Check if the determinant of the non-square matrix is 0.\n\tif determinant != 0 {\n\t\tt.Errorf(\"Determinant of non-square matrix was not 0 but was %d\", determinant)\n\t}\n\n}\n\n// Test matrix returned from matrix.New\nfunc TestDefaultMatrix(t *testing.T) {\n\tinitialValue := 0\n\tinitialRows := 3\n\tinitialCols := 3\n\tdefaultMatrix := matrix.New(initialRows, initialCols, initialValue)\n\n\tdeterminant, err := defaultMatrix.Determinant()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error finding the determinant of 3 by 3 default matrix: %v.\", err)\n\t}\n\texpectedValue := 0\n\tif determinant != expectedValue {\n\t\tt.Errorf(\"Determinant of the default matrix with an initial value 0 was %d; wanted %d.\", initialValue, expectedValue)\n\t}\n}\n\n// Benchmark a 3 by 3 matrix for computational throughput\nfunc BenchmarkSmallMatrixDeterminant(b *testing.B) {\n\t// Create a 3 by 3 matrix for benchmarking\n\trows := 3\n\tcolumns := 3\n\tinitialValue := 0\n\tmatrix := matrix.New(rows, columns, initialValue)\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.Determinant()\n\t}\n}\n\n// Benchmark a 10 by 10 matrix for computational throughput.\nfunc BenchmarkMatrixDeterminant(b *testing.B) {\n\t// Create a 10 by 10 matrix for benchmarking\n\trows := 10\n\tcolumns := 10\n\tinitialValue := 0\n\tmatrix := matrix.New(rows, columns, initialValue)\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.Determinant()\n\t}\n}\n"
  },
  {
    "path": "math/matrix/isvalid.go",
    "content": "package matrix\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// IsValid checks if the input matrix has consistent row lengths.\nfunc IsValid[T constraints.Integer](elements [][]T) bool {\n\tif len(elements) == 0 {\n\t\treturn true\n\t}\n\tcolumns := len(elements[0])\n\tfor _, row := range elements {\n\t\tif len(row) != columns {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "math/matrix/isvalid_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestIsValid(t *testing.T) {\n\t// Test case 1: Valid matrix with consistent row lengths\n\tvalidMatrix := [][]int{\n\t\t{1, 2, 3},\n\t\t{4, 5, 6},\n\t\t{7, 8, 9},\n\t}\n\tresult1 := matrix.IsValid(validMatrix)\n\tif !result1 {\n\t\tt.Errorf(\"IsValid(validMatrix) returned false, expected true (valid matrix)\")\n\t}\n\n\t// Test case 2: Valid matrix with empty rows (no inconsistency)\n\tvalidMatrixEmptyRows := [][]int{\n\t\t{},\n\t\t{},\n\t\t{},\n\t}\n\tresult2 := matrix.IsValid(validMatrixEmptyRows)\n\tif !result2 {\n\t\tt.Errorf(\"IsValid(validMatrixEmptyRows) returned false, expected true (valid matrix with empty rows)\")\n\t}\n\n\t// Test case 3: Invalid matrix with inconsistent row lengths\n\tinvalidMatrix := [][]int{\n\t\t{1, 2, 3},\n\t\t{4, 5},\n\t\t{6, 7, 8},\n\t}\n\tresult3 := matrix.IsValid(invalidMatrix)\n\tif result3 {\n\t\tt.Errorf(\"IsValid(invalidMatrix) returned true, expected false (invalid matrix with inconsistent row lengths)\")\n\t}\n\n}\n\nfunc BenchmarkIsValid(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\telements := make([][]int, rows)\n\tfor i := range elements {\n\t\telements[i] = make([]int, columns)\n\t\tfor j := range elements[i] {\n\t\t\telements[i][j] = i*columns + j // Some arbitrary values\n\t\t}\n\t}\n\n\t// Reset the benchmark timer\n\tb.ResetTimer()\n\n\t// Run the benchmark\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = matrix.IsValid(elements)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/matchdimensions.go",
    "content": "package matrix\n\n// MatchDimensions checks if two matrices have the same dimensions.\nfunc (m Matrix[T]) MatchDimensions(m1 Matrix[T]) bool {\n\tif m.rows == m1.rows && m.columns == m1.columns {\n\t\treturn true\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "math/matrix/matchdimensions_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestMatrixMatchDimensions(t *testing.T) {\n\t// Create two matrices with the same dimensions\n\tm1 := matrix.New(2, 3, 0)\n\tm2 := matrix.New(2, 3, 0)\n\n\t// Test case 1: Same dimensions\n\tif !m1.MatchDimensions(m2) {\n\t\tt.Errorf(\"m1.MatchDimensions(m2) returned %t, expected 1 (same dimensions)\", m1.MatchDimensions(m2))\n\t}\n\n\t// Create two matrices with different dimensions\n\tm3 := matrix.New(2, 3, 0)\n\tm4 := matrix.New(3, 2, 0)\n\n\t// Test case 2: Different dimensions\n\tif m3.MatchDimensions(m4) {\n\t\tt.Errorf(\"m3.MatchDimensions(m4) returned : %v, expected: %v\", m3.MatchDimensions(m4), false)\n\t}\n}\n\n// BenchmarkMatchDimensions benchmarks the MatchDimensions method.\nfunc BenchmarkMatchDimensions(b *testing.B) {\n\t// Create sample matrices for benchmarking\n\trows := 100\n\tcolumns := 100\n\tm1 := matrix.New(rows, columns, 0) // Replace with appropriate values\n\tm2 := matrix.New(rows, columns, 0) // Replace with appropriate values\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = m1.MatchDimensions(m2)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/matrix.go",
    "content": "package matrix\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\ntype Matrix[T constraints.Integer] struct {\n\telements [][]T\n\trows     int\n\tcolumns  int\n}\n\n// NewMatrix creates a new Matrix based on the provided arguments.\nfunc New[T constraints.Integer](rows, columns int, initial T) Matrix[T] {\n\tif rows < 0 || columns < 0 {\n\t\treturn Matrix[T]{} // Invalid dimensions, return an empty matrix\n\t}\n\n\t// Initialize the matrix with the specified dimensions and fill it with the initial value.\n\telements := make([][]T, rows)\n\tvar wg sync.WaitGroup\n\twg.Add(rows)\n\n\tfor i := range elements {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\telements[i] = make([]T, columns)\n\t\t\tfor j := range elements[i] {\n\t\t\t\telements[i][j] = initial\n\t\t\t}\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\n\treturn Matrix[T]{elements, rows, columns}\n}\n\n// NewFromElements creates a new Matrix from the given elements.\nfunc NewFromElements[T constraints.Integer](elements [][]T) (Matrix[T], error) {\n\tif !IsValid(elements) {\n\t\treturn Matrix[T]{}, errors.New(\"rows have different numbers of columns\")\n\t}\n\trows := len(elements)\n\tif rows == 0 {\n\t\treturn Matrix[T]{}, nil // Empty matrix\n\t}\n\n\tcolumns := len(elements[0])\n\tmatrix := Matrix[T]{\n\t\telements: make([][]T, rows),\n\t\trows:     rows,    // Set the rows field\n\t\tcolumns:  columns, // Set the columns field\n\t}\n\tfor i := range matrix.elements {\n\t\tmatrix.elements[i] = make([]T, columns)\n\t\tcopy(matrix.elements[i], elements[i])\n\t}\n\n\treturn matrix, nil\n}\n\nfunc (m Matrix[T]) Get(row, col int) (T, error) {\n\tif row < 0 || row >= m.rows || col < 0 || col >= m.columns {\n\t\tvar zeroVal T\n\t\treturn zeroVal, errors.New(\"index out of range\")\n\t}\n\treturn m.elements[row][col], nil\n}\n\nfunc (m Matrix[T]) Set(row, col int, val T) error {\n\tif row < 0 || row >= m.rows || col < 0 || col >= m.columns {\n\t\treturn errors.New(\"index out of bounds\")\n\t}\n\n\tm.elements[row][col] = val\n\treturn nil\n}\n\nfunc (m Matrix[T]) Rows() int {\n\treturn len(m.elements)\n}\n\nfunc (m Matrix[T]) Columns() int {\n\tif len(m.elements) == 0 {\n\t\treturn 0\n\t}\n\treturn len(m.elements[0])\n}\n"
  },
  {
    "path": "math/matrix/matrix_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestNewMatrix(t *testing.T) {\n\n\tnullMatrix := matrix.New(0, 0, 0)\n\tif nullMatrix.Rows() != 0 || nullMatrix.Columns() != 0 {\n\t\tt.Errorf(\"matrix.New( 0, 0, 0) returned nil, expected a matrix\")\n\t}\n\t// Test creating a matrix of integers\n\tintMatrix := matrix.New(3, 4, 0)\n\tif intMatrix.Rows() != 3 || intMatrix.Columns() != 4 {\n\t\tt.Errorf(\"matrix.New( 3, 4, 0) returned nil, expected a matrix\")\n\t}\n\n}\n\nfunc TestNewFromElements(t *testing.T) {\n\t// Test case 1: Valid matrix\n\tvalidElements := [][]int{\n\t\t{1, 2, 3},\n\t\t{4, 5, 6},\n\t}\n\texpectedm1 := matrix.New(2, 3, 0)\n\tfor i := 0; i < len(validElements); i++ {\n\t\tfor j := 0; j < len(validElements[0]); j++ {\n\t\t\terr := expectedm1.Set(i, j, validElements[i][j])\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"copyMatrix.Set error: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tm1, err1 := matrix.NewFromElements(validElements)\n\tif err1 != nil {\n\t\tt.Errorf(\"NewFromElements(validElements) returned an error: %v\", err1)\n\t}\n\tres := m1.CheckEqual(expectedm1)\n\tif res != true {\n\t\tt.Errorf(\"NewFromElements(validElements) returned %v, expected %v\", m1, expectedm1)\n\t}\n\n\t// Test case 2: Invalid matrix with different column counts\n\tinvalidElements := [][]int{\n\t\t{1, 2, 3},\n\t\t{4, 5},\n\t}\n\t_, err2 := matrix.NewFromElements(invalidElements)\n\texpectedError2 := errors.New(\"rows have different numbers of columns\")\n\tif err2 == nil || err2.Error() != expectedError2.Error() {\n\t\tt.Errorf(\"NewFromElements(invalidElements) returned error: %v, expected error: %v\", err2, expectedError2)\n\t}\n\n\t// Test case 3: Empty matrix\n\temptyElements := [][]int{}\n\tm3, err3 := matrix.NewFromElements(emptyElements)\n\tif err3 != nil {\n\t\tt.Errorf(\"NewFromElements(emptyElements) returned an error: %v\", err3)\n\t}\n\tif m3.Rows() != 0 || m3.Columns() != 0 {\n\t\tt.Errorf(\"NewFromElements(emptyElements) returned %v, expected nil\", m3)\n\t}\n}\n\nfunc TestMatrixGet(t *testing.T) {\n\t// Create a sample matrix for testing\n\tmatrix := matrix.New(3, 3, 0)\n\terr := matrix.Set(1, 1, 42) // Set a specific value for testing\n\tif err != nil {\n\t\tt.Errorf(\"copyMatrix.Set error: %s\", err.Error())\n\t}\n\t// Test case 1: Valid Get\n\tval1, err1 := matrix.Get(1, 1)\n\tif err1 != nil {\n\t\tt.Errorf(\"matrix.Get(1, 1) returned an error: %v, expected no error\", err1)\n\t}\n\tif val1 != 42 {\n\t\tt.Errorf(\"matrix.Get(1, 1) returned %v, expected 42\", val1)\n\t}\n\n\t// Test case 2: Get with invalid indices\n\t_, err2 := matrix.Get(10, 10)\n\texpectedError2 := errors.New(\"index out of range\")\n\tif err2 == nil || err2.Error() != expectedError2.Error() {\n\t\tt.Errorf(\"matrix.Get(10, 10) returned error: %v, expected error: %v\", err2, expectedError2)\n\t}\n\t// Test case 3: Get with invalid indices\n\t_, err3 := matrix.Get(-1, -3)\n\texpectedError3 := errors.New(\"index out of range\")\n\tif err3 == nil || err3.Error() != expectedError3.Error() {\n\t\tt.Errorf(\"matrix.Get(10, 10) returned error: %v, expected error: %v\", err3, expectedError3)\n\t}\n}\n\nfunc TestMatrixSet(t *testing.T) {\n\t// Create a sample matrix for testing\n\tmatrix := matrix.New(3, 3, 0)\n\n\t// Test case 1: Valid Set\n\terr1 := matrix.Set(1, 1, 42)\n\tif err1 != nil {\n\t\tt.Errorf(\"matrix.Set(1, 1, 42) returned an error: %v, expected no error\", err1)\n\t}\n\tval1, err := matrix.Get(1, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\tif val1 != 42 {\n\t\tt.Errorf(\"matrix.Set(1, 1, 42) did not set the value correctly, expected 42, got %v\", val1)\n\t}\n\n\t// Test case 2: Set with invalid indices\n\terr2 := matrix.Set(10, 10, 100)\n\texpectedError2 := errors.New(\"index out of bounds\")\n\tif err2 == nil || err2.Error() != expectedError2.Error() {\n\t\tt.Errorf(\"matrix.Set(10, 10, 100) returned error: %v, expected error: %v\", err2, expectedError2)\n\t}\n\t// Test case 3: Get with invalid indices\n\terr3 := matrix.Set(-13, -1, 100)\n\texpectedError3 := errors.New(\"index out of bounds\")\n\tif err3 == nil || err3.Error() != expectedError3.Error() {\n\t\tt.Errorf(\"matrix.Get(10, 10) returned error: %v, expected error: %v\", err3, expectedError3)\n\t}\n}\n\nfunc TestMatrixRows(t *testing.T) {\n\t// Create a sample matrix\n\tdata := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tmatrix, err := matrix.NewFromElements(data)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\t// Check the number of rows\n\texpectedRows := len(data)\n\trows := matrix.Rows()\n\tif rows != expectedRows {\n\t\tt.Errorf(\"Expected %d rows, but got %d\", expectedRows, rows)\n\t}\n}\n\nfunc TestMatrixColumns(t *testing.T) {\n\t// Create a sample matrix\n\tdata := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tmatrix, err := matrix.NewFromElements(data)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\t// Check the number of columns\n\texpectedColumns := len(data[0])\n\tcolumns := matrix.Columns()\n\tif columns != expectedColumns {\n\t\tt.Errorf(\"Expected %d columns, but got %d\", expectedColumns, columns)\n\t}\n}\n\nfunc TestMatrixEmptyRowsAndColumns(t *testing.T) {\n\t// Create an empty matrix\n\temptyMatrix := matrix.New(0, 0, 0)\n\n\t// Check the number of rows and columns for an empty matrix\n\trows := emptyMatrix.Rows()\n\tcolumns := emptyMatrix.Columns()\n\n\tif rows != 0 {\n\t\tt.Errorf(\"Expected 0 rows for an empty matrix, but got %d\", rows)\n\t}\n\n\tif columns != 0 {\n\t\tt.Errorf(\"Expected 0 columns for an empty matrix, but got %d\", columns)\n\t}\n}\n\n// BenchmarkNew benchmarks the New function.\nfunc BenchmarkNew(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = matrix.New(100, 100, 0) // Change the arguments to match your use case\n\t}\n}\n\n// BenchmarkNewFromElements benchmarks the NewFromElements function.\nfunc BenchmarkNewFromElements(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\telements := make([][]int, rows)\n\tfor i := range elements {\n\t\telements[i] = make([]int, columns)\n\t\tfor j := range elements[i] {\n\t\t\telements[i][j] = i*columns + j // Some arbitrary values\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.NewFromElements(elements)\n\t}\n}\n\n// BenchmarkGet benchmarks the Get method.\nfunc BenchmarkGet(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tmatrix := matrix.New(rows, columns, 0)\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.Get(50, 50) // Change the row and column indices as needed\n\t}\n}\n\n// BenchmarkSet benchmarks the Set method.\nfunc BenchmarkSet(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tmatrix := matrix.New(rows, columns, 0)\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = matrix.Set(50, 50, 42) // Change the row, column, and value as needed\n\t}\n}\n\n// BenchmarkRows benchmarks the Rows method.\nfunc BenchmarkRows(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tmatrix := matrix.New(rows, columns, 0)\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = matrix.Rows()\n\t}\n}\n\n// BenchmarkColumns benchmarks the Columns method.\nfunc BenchmarkColumns(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tmatrix := matrix.New(rows, columns, 0)\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = matrix.Columns()\n\t}\n}\n"
  },
  {
    "path": "math/matrix/multiply.go",
    "content": "// multiply.go\n// description: Implementation of matrix multiplication\n// time complexity: O(n^3) where n is the number of rows in the first matrix\n// space complexity: O(n^2) where n is the number of rows in the first matrix\n\npackage matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// Multiply multiplies the current matrix (m1) with another matrix (m2) and returns the result as a new matrix.\nfunc (m1 Matrix[T]) Multiply(m2 Matrix[T]) (Matrix[T], error) {\n\t// Check if the matrices can be multiplied.\n\tif m1.Columns() != m2.Rows() {\n\t\treturn Matrix[T]{}, errors.New(\"matrices cannot be multiplied: column count of the first matrix must match row count of the second matrix\")\n\t}\n\n\t// Create a new matrix to store the result.\n\tvar zeroVal T\n\tresult := New(m1.Rows(), m2.Columns(), zeroVal)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Make sure it's called to release resources even if no errors\n\n\tvar wg sync.WaitGroup\n\terrCh := make(chan error, 1)\n\n\tfor i := 0; i < m1.Rows(); i++ {\n\t\tfor j := 0; j < m2.Columns(); j++ {\n\t\t\ti, j := i, j // Capture the loop variable for the goroutine\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t// Compute the dot product of the row from the first matrix and the column from the second matrix.\n\t\t\t\tdotProduct := zeroVal\n\t\t\t\tfor k := 0; k < m1.Columns(); k++ {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\t\treturn // Context canceled; return without an error\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\n\t\t\t\t\tval1, err := m1.Get(i, k)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcancel()\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tval2, err := m2.Get(k, j)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcancel()\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tdotProduct += val1 * val2\n\t\t\t\t}\n\t\t\t\terr := result.Set(i, j, dotProduct)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcancel()\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\t// Wait for all goroutines to finish\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errCh)\n\t}()\n\n\t// Check for any errors\n\tif err := <-errCh; err != nil {\n\t\treturn Matrix[T]{}, err\n\t}\n\n\treturn result, nil\n}\n"
  },
  {
    "path": "math/matrix/multiply_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestMultiplyMatrix(t *testing.T) {\n\t// Test case with compatible NULL matrices\n\tt.Run(\"NULL Matrices\", func(t *testing.T) {\n\t\tmat1 := matrix.New(0, 0, 0)\n\t\tmat2 := matrix.New(0, 0, 0)\n\n\t\texpected := matrix.New(0, 0, 0)\n\t\tresult, err := mat1.Multiply(mat2)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected no error, got %v\", err)\n\t\t} else if !result.CheckEqual(expected) {\n\t\t\tt.Errorf(\"Result matrix does not match the expected result.\")\n\t\t}\n\n\t})\n\t// Test case with compatible matrices\n\tt.Run(\"Compatible Matrices\", func(t *testing.T) {\n\t\tmat1 := [][]int{{1, 2, 3}, {4, 5, 6}}\n\t\tmat2 := [][]int{{7, 8}, {9, 10}, {11, 12}}\n\t\tm1, err := matrix.NewFromElements(mat1)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\tm2, err := matrix.NewFromElements(mat2)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\texp := [][]int{{58, 64}, {139, 154}}\n\t\texpected, err := matrix.NewFromElements(exp)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\tresult, err := m1.Multiply(m2)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected no error, got %v\", err)\n\t\t} else if !result.CheckEqual(expected) {\n\t\t\tt.Errorf(\"Result matrix does not match the expected result.\")\n\t\t}\n\n\t})\n\n}\n\nfunc TestMultiplyIncompatibleMatrix(t *testing.T) {\n\t// Test case with incompatible matrices\n\tt.Run(\"Incompatible Matrices\", func(t *testing.T) {\n\t\tmat1 := [][]int{{1, 2, 3}, {4, 5, 6}}\n\t\tmat2 := [][]int{{7, 8}, {9, 10}}\n\t\tm1, err := matrix.NewFromElements(mat1)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\tm2, err := matrix.NewFromElements(mat2)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\n\t\t_, err = m1.Multiply(m2)\n\t\tif err == nil {\n\t\t\tt.Error(\"Expected an error, but got none\")\n\t\t}\n\t})\n\n\tt.Run(\"Incompatible Matrices\", func(t *testing.T) {\n\t\tmat1 := [][]int{{1, 2}}\n\t\tmat2 := [][]int{{}}\n\t\tm1, err := matrix.NewFromElements(mat1)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\tm2, err := matrix.NewFromElements(mat2)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t}\n\t\t_, err = m1.Multiply(m2)\n\n\t\tif err == nil {\n\t\t\tt.Error(\"Expected an error, but got none\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkMatrixMultiply(b *testing.B) {\n\t// Create sample matrices for benchmarking\n\trows := 10\n\tcolumns := 10\n\tm1 := matrix.New(rows, columns, 2) // Replace with appropriate values\n\tm2 := matrix.New(rows, columns, 3) // Replace with appropriate values\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = m1.Multiply(m2)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/strassenmatrixmultiply.go",
    "content": "// filename: strassenmatrixmultiply.go\n// description: Implements matrix multiplication using the Strassen algorithm.\n// details:\n// This program takes two matrices as input and performs matrix multiplication\n// using the Strassen algorithm, which is an optimized divide-and-conquer\n// approach. It allows for efficient multiplication of large matrices.\n// time complexity: O(n^2.81)\n// space complexity: O(n^2)\n// author(s): Mohit Raghav(https://github.com/mohit07raghav19)\n// See strassenmatrixmultiply_test.go for test cases\npackage matrix\n\n// Perform matrix multiplication using Strassen's algorithm\nfunc (A Matrix[T]) StrassenMatrixMultiply(B Matrix[T]) (Matrix[T], error) {\n\tn := A.rows\n\t// Check if matrices are 2x2 or smaller\n\tif n == 1 {\n\t\ta1, err := A.Get(0, 0)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tb1, err := B.Get(0, 0)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tresult := New(1, 1, a1*b1)\n\t\treturn result, nil\n\t} else {\n\t\t// Calculate the size of submatrices\n\t\tmid := n / 2\n\n\t\t// Create submatrices\n\t\tA11, err := A.SubMatrix(0, 0, mid, mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA12, err := A.SubMatrix(0, mid, mid, n-mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA21, err := A.SubMatrix(mid, 0, n-mid, mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA22, err := A.SubMatrix(mid, mid, n-mid, n-mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tB11, err := B.SubMatrix(0, 0, mid, mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tB12, err := B.SubMatrix(0, mid, mid, n-mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tB21, err := B.SubMatrix(mid, 0, n-mid, mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tB22, err := B.SubMatrix(mid, mid, n-mid, n-mid)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\t// Calculate result submatrices\n\t\tA1, err := A11.Add(A22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tA2, err := B11.Add(B22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tA3, err := A21.Add(A22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tA4, err := A11.Add(A12)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tA5, err := B11.Add(B12)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\tA6, err := B21.Add(B22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\t//\n\t\tS1, err := B12.Subtract(B22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tS2, err := B21.Subtract(B11)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tS3, err := A21.Subtract(A11)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tS4, err := A12.Subtract(A22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\t// Recursive steps\n\t\tM1, err := A1.StrassenMatrixMultiply(A2)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM2, err := A3.StrassenMatrixMultiply(B11)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM3, err := A11.StrassenMatrixMultiply(S1)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM4, err := A22.StrassenMatrixMultiply(S2)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM5, err := A4.StrassenMatrixMultiply(B22)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM6, err := S3.StrassenMatrixMultiply(A5)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tM7, err := S4.StrassenMatrixMultiply(A6)\n\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t} //\n\t\tA7, err := M1.Add(M4)\n\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA8, err := A7.Add(M7)\n\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA9, err := M1.Add(M3)\n\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tA10, err := A9.Add(M6)\n\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\t// Calculate result submatrices\n\t\tC11, err := A8.Subtract(M5)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tC12, err := M3.Add(M5)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tC21, err := M2.Add(M4)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\t\tC22, err := A10.Subtract(M2)\n\t\tif err != nil {\n\t\t\treturn Matrix[T]{}, err\n\t\t}\n\n\t\t// Combine subMatrices into the result matrix\n\t\tvar zeroVal T\n\t\tC := New(n, n, zeroVal)\n\n\t\tfor i := 0; i < mid; i++ {\n\t\t\tfor j := 0; j < mid; j++ {\n\t\t\t\tval, err := C11.Get(i, j)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Matrix[T]{}, err\n\t\t\t\t}\n\n\t\t\t\terr = C.Set(i, j, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Matrix[T]{}, err\n\t\t\t\t}\n\n\t\t\t\tval, err = C12.Get(i, j)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Matrix[T]{}, err\n\t\t\t\t}\n\n\t\t\t\terr1 := C.Set(i, j+mid, val)\n\t\t\t\tif err1 != nil {\n\t\t\t\t\treturn Matrix[T]{}, err1\n\t\t\t\t}\n\t\t\t\tval, err = C21.Get(i, j)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Matrix[T]{}, err\n\t\t\t\t}\n\n\t\t\t\terr2 := C.Set(i+mid, j, val)\n\t\t\t\tif err2 != nil {\n\t\t\t\t\treturn Matrix[T]{}, err2\n\t\t\t\t}\n\t\t\t\tval, err = C22.Get(i, j)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn Matrix[T]{}, err\n\t\t\t\t}\n\n\t\t\t\terr3 := C.Set(i+mid, j+mid, val)\n\t\t\t\tif err3 != nil {\n\t\t\t\t\treturn Matrix[T]{}, err3\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn C, nil\n\t}\n}\n"
  },
  {
    "path": "math/matrix/strassenmatrixmultiply_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestStrassenMatrixMultiply(t *testing.T) {\n\t// Create two sample matrices\n\tdataA := [][]int{{1, 2}, {4, 5}}\n\tdataB := [][]int{{9, 8}, {6, 5}}\n\tmatrixA, err := matrix.NewFromElements(dataA)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\tmatrixB, err := matrix.NewFromElements(dataB)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\n\t// Perform matrix multiplication using Strassen's algorithm\n\tresultMatrix, err := matrixA.StrassenMatrixMultiply(matrixB)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\n\t// Expected result\n\texpectedData, err := matrixA.Multiply(matrixB)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\n\t// Check the dimensions of the result matrix\n\texpectedRows := expectedData.Rows()\n\texpectedColumns := expectedData.Columns()\n\trows := resultMatrix.Rows()\n\tcolumns := resultMatrix.Columns()\n\n\tif rows != expectedRows {\n\t\tt.Errorf(\"Expected %d rows in result matrix, but got %d\", expectedRows, rows)\n\t}\n\n\tif columns != expectedColumns {\n\t\tt.Errorf(\"Expected %d columns in result matrix, but got %d\", expectedColumns, columns)\n\t}\n\n\t// Check the values in the result matrix\n\tfor i := 0; i < expectedRows; i++ {\n\t\tfor j := 0; j < expectedColumns; j++ {\n\t\t\tval, err := resultMatrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\texpVal, err := expectedData.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tif val != expVal {\n\t\t\t\tt.Errorf(\"Expected value %d at (%d, %d) in result matrix, but got %d\", expVal, i, j, val)\n\t\t\t}\n\t\t}\n\t}\n}\nfunc TestMatrixMultiplication(t *testing.T) {\n\trand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t// Generate random matrices for testing\n\tsize := 1 << (rand.Intn(8) + 1) // tests for matrix with n as power of 2\n\tmatrixA := MakeRandomMatrix[int](size, size)\n\tmatrixB := MakeRandomMatrix[int](size, size)\n\n\t// Calculate the expected result using the standard multiplication\n\texpected, err := matrixA.Multiply(matrixB)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\t// Calculate the result using the Strassen algorithm\n\tresult, err := matrixA.StrassenMatrixMultiply(matrixB)\n\tif err != nil {\n\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t}\n\n\t// Check if the result matches the expected result\n\tfor i := 0; i < size; i++ {\n\t\tfor j := 0; j < size; j++ {\n\t\t\tval, err := result.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t\t\t}\n\t\t\texp, err := expected.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"copyMatrix.Set error: \" + err.Error())\n\t\t\t}\n\t\t\tif val != exp {\n\t\t\t\tt.Errorf(\"Mismatch at position (%d, %d). Expected %d, but got %d.\", i, j, exp, val)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc MakeRandomMatrix[T constraints.Integer](rows, columns int) matrix.Matrix[T] {\n\trand.New(rand.NewSource(time.Now().UnixNano()))\n\n\tmatrixData := make([][]T, rows)\n\tfor i := 0; i < rows; i++ {\n\t\tmatrixData[i] = make([]T, columns)\n\t\tfor j := 0; j < columns; j++ {\n\t\t\tmatrixData[i][j] = T(rand.Intn(1000)) // Generate random integers between 0 and 1000\n\t\t}\n\t}\n\n\trandomMatrix, _ := matrix.NewFromElements(matrixData)\n\treturn randomMatrix\n}\n\n// BenchmarkStrassenMatrixMultiply benchmarks the StrassenMatrixMultiply function.\nfunc BenchmarkStrassenMatrixMultiply(b *testing.B) {\n\t// Create sample matrices for benchmarking\n\trows := 64 // it is large enough for multiplication\n\tcolumns := 64\n\tm1 := matrix.New(rows, columns, 2) // Replace with appropriate values\n\tm2 := matrix.New(rows, columns, 3) // Replace with appropriate values\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = m1.StrassenMatrixMultiply(m2)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/string.go",
    "content": "package matrix\n\nimport \"fmt\"\n\n// String implements the fmt.Stringer interface for Matrix.\nfunc (m Matrix[T]) String() string {\n\tvar result string\n\tfor i := range m.elements {\n\t\tfor j := range m.elements[i] {\n\t\t\tresult += fmt.Sprintf(\"%v \", m.elements[i][j])\n\t\t}\n\t\tresult += \"\\n\"\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/matrix/string_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestMatrixString(t *testing.T) {\n\t// Create a sample matrix for testing\n\tm1, err := matrix.NewFromElements([][]int{{1, 2}, {3, 4}})\n\tif err != nil {\n\t\tt.Errorf(\"Error creating matrix: %v\", err)\n\t}\n\n\t// Redirect stdout to capture Stringed output\n\told := os.Stdout\n\tr, w, err := os.Pipe()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\tos.Stdout = w\n\n\t// Call the String method\n\tfmt.Print(m1)\n\n\t// Reset stdout\n\tw.Close()\n\tos.Stdout = old\n\n\t// Read the captured output\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, r)\n\tif err != nil {\n\t\tt.Errorf(\"Error copying output: %v\", err)\n\t}\n\tcapturedOutput := buf.String()\n\n\t// Define the expected output\n\texpectedOutput := \"1 2 \\n3 4 \\n\"\n\n\t// Compare the captured output with the expected output\n\tif capturedOutput != expectedOutput {\n\t\tt.Errorf(\"Matrix.Print() produced incorrect output:\\n%s\\nExpected:\\n%s\", capturedOutput, expectedOutput)\n\t}\n}\n\nfunc TestNullMatrixString(t *testing.T) {\n\n\tm1 := matrix.New(0, 0, 0)\n\t// Redirect stdout to capture Stringed output\n\told := os.Stdout\n\tr, w, err := os.Pipe()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\tos.Stdout = w\n\n\t// Call the String method\n\tfmt.Print(m1)\n\n\t// Reset stdout\n\tw.Close()\n\tos.Stdout = old\n\n\t// Read the captured output\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, r)\n\tif err != nil {\n\t\tt.Errorf(\"Error copying output: %v\", err)\n\t}\n\tcapturedOutput := buf.String()\n\n\t// Define the expected output\n\texpectedOutput := \"\"\n\n\t// Compare the captured output with the expected output\n\tif capturedOutput != expectedOutput {\n\t\tt.Errorf(\"Matrix.Print() produced incorrect output:\\n%s\\nExpected:\\n%s\", capturedOutput, expectedOutput)\n\t}\n}\n\nfunc BenchmarkString(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tm := matrix.New(rows, columns, 0) // Replace with appropriate values\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = m.String()\n\t}\n}\n"
  },
  {
    "path": "math/matrix/submatrix.go",
    "content": "package matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// SubMatrix extracts a submatrix from the current matrix.\nfunc (m Matrix[T]) SubMatrix(rowStart, colStart, numRows, numCols int) (Matrix[T], error) {\n\tif rowStart < 0 || colStart < 0 || numRows < 0 || numCols < 0 {\n\t\treturn Matrix[T]{}, errors.New(\"negative dimensions are not allowed\")\n\t}\n\n\tif rowStart+numRows > m.rows || colStart+numCols > m.columns {\n\t\treturn Matrix[T]{}, errors.New(\"submatrix dimensions exceed matrix bounds\")\n\t}\n\n\tvar zeroVal T\n\tif numRows == 0 || numCols == 0 {\n\t\treturn New(numRows, numCols, zeroVal), nil // Return an empty matrix\n\t}\n\n\tsubMatrix := New(numRows, numCols, zeroVal)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Make sure it's called to release resources even if no errors\n\n\tvar wg sync.WaitGroup\n\terrCh := make(chan error, 1)\n\n\tfor i := 0; i < numRows; i++ {\n\t\ti := i // Capture the loop variable for the goroutine\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < numCols; j++ {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn // Context canceled; return without an error\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tval, err := m.Get(rowStart+i, colStart+j)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcancel()\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\terr = subMatrix.Set(i, j, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcancel()\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Wait for all goroutines to finish\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errCh)\n\t}()\n\n\t// Check for any errors\n\tif err := <-errCh; err != nil {\n\t\treturn Matrix[T]{}, err\n\t}\n\n\treturn subMatrix, nil\n}\n"
  },
  {
    "path": "math/matrix/submatrix_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestMatrixSubMatrix(t *testing.T) {\n\t// Create a sample matrix\n\tdata := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tmatrix, err := matrix.NewFromElements(data)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\t// Extract a submatrix\n\tsubMatrix, err := matrix.SubMatrix(1, 1, 2, 2)\n\tif err != nil {\n\t\tt.Errorf(\"Error extracting submatrix: %v\", err)\n\t}\n\n\t// Check the dimensions of the submatrix\n\texpectedRows := 2\n\texpectedColumns := 2\n\trows := subMatrix.Rows()\n\tcolumns := subMatrix.Columns()\n\n\tif rows != expectedRows {\n\t\tt.Errorf(\"Expected %d rows in submatrix, but got %d\", expectedRows, rows)\n\t}\n\n\tif columns != expectedColumns {\n\t\tt.Errorf(\"Expected %d columns in submatrix, but got %d\", expectedColumns, columns)\n\t}\n\n\t// Check the values in the submatrix\n\texpectedData := [][]int{{5, 6}, {8, 9}}\n\tfor i := 0; i < expectedRows; i++ {\n\t\tfor j := 0; j < expectedColumns; j++ {\n\t\t\tval, err := subMatrix.Get(i, j)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t\t\t}\n\t\t\tif val != expectedData[i][j] {\n\t\t\t\tt.Errorf(\"Expected value %d at (%d, %d) in submatrix, but got %d\", expectedData[i][j], i, j, val)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMatrixInvalidSubMatrix(t *testing.T) {\n\t// Create a sample matrix\n\tdata := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tmatrix, err := matrix.NewFromElements(data)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to copy matrix: %v\", err)\n\t}\n\t// Attempt to extract an invalid submatrix\n\t_, err = matrix.SubMatrix(1, 1, 3, 3)\n\n\t// Check if an error is returned\n\tif err == nil {\n\t\tt.Error(\"Expected an error for invalid submatrix dimensions, but got nil\")\n\t}\n\n\t// Check the error message\n\texpectedErrorMessage := \"submatrix dimensions exceed matrix bounds\"\n\tif err.Error() != expectedErrorMessage {\n\t\tt.Errorf(\"Expected error message '%s', but got '%s'\", expectedErrorMessage, err.Error())\n\t}\n}\n\n// BenchmarkSubMatrix benchmarks the SubMatrix function.\nfunc BenchmarkSubMatrix(b *testing.B) {\n\t// Create a sample matrix for benchmarking\n\trows := 100\n\tcolumns := 100\n\tmatrix := matrix.New(rows, columns, 2) // Replace with appropriate values\n\n\trowStart := 10\n\tcolStart := 10\n\tnumRows := 20\n\tnumCols := 20\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = matrix.SubMatrix(rowStart, colStart, numRows, numCols)\n\t}\n}\n"
  },
  {
    "path": "math/matrix/subtract.go",
    "content": "package matrix\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n)\n\n// Subtract subtracts two matrices.\nfunc (m1 Matrix[T]) Subtract(m2 Matrix[T]) (Matrix[T], error) {\n\t// Check if the matrices have the same dimensions.\n\tif !m1.MatchDimensions(m2) {\n\t\treturn Matrix[T]{}, errors.New(\"matrices are not compatible for subtraction\")\n\t}\n\n\t// Create a new matrix to store the result.\n\tvar zeroVal T\n\tresult := New(m1.Rows(), m1.Columns(), zeroVal)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Make sure it's called to release resources even if no errors\n\n\tvar wg sync.WaitGroup\n\terrCh := make(chan error, 1)\n\n\tfor i := 0; i < m1.rows; i++ {\n\t\ti := i // Capture the loop variable for the goroutine\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < m1.columns; j++ {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn // Context canceled; return without an error\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\tdiff := m1.elements[i][j] - m2.elements[i][j]\n\t\t\t\terr := result.Set(i, j, diff)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcancel() // Cancel the context on error\n\t\t\t\t\tselect {\n\t\t\t\t\tcase errCh <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Wait for all goroutines to finish\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errCh)\n\t}()\n\n\t// Check for any errors\n\tif err := <-errCh; err != nil {\n\t\treturn Matrix[T]{}, err\n\t}\n\n\treturn result, nil\n}\n"
  },
  {
    "path": "math/matrix/subtract_test.go",
    "content": "package matrix_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/matrix\"\n)\n\nfunc TestSubtract(t *testing.T) {\n\t// Create two matrices with the same dimensions for Subtraction\n\tm1 := matrix.New(2, 2, 1)\n\tm2 := matrix.New(2, 2, 2)\n\n\t// Test case 1: Valid matrix Subtraction\n\tsubMatrix, err := m1.Subtract(m2)\n\tif err != nil {\n\t\tt.Errorf(\"Add(m1, m2) returned an error: %v, expected no error\", err)\n\t}\n\texpectedMatrix := matrix.New(2, 2, -1)\n\tres := subMatrix.CheckEqual(expectedMatrix)\n\tif !res {\n\t\tt.Errorf(\"Add(m1, m2) returned incorrect result:\\n%v\\nExpected:\\n%v\", subMatrix, expectedMatrix)\n\t}\n\n\t// Create two matrices with different dimensions for Subtraction\n\tm3 := matrix.New(2, 2, 1)\n\tm4 := matrix.New(2, 3, 2)\n\n\t// Test case 2: Matrices with different dimensions\n\t_, err2 := m3.Subtract(m4)\n\texpectedError2 := fmt.Errorf(\"matrices are not compatible for subtraction\")\n\tif err2 == nil || err2.Error() != expectedError2.Error() {\n\t\tt.Errorf(\"m3.Subtract(m4) returned error: %v, expected error: %v\", err2, expectedError2)\n\t}\n\n}\n\n// BenchmarkSubtract benchmarks the Subtract function.\nfunc BenchmarkSubtract(b *testing.B) {\n\t// Create sample matrices for benchmarking\n\trows := 100\n\tcolumns := 100\n\tm1 := matrix.New(rows, columns, 2) // Replace with appropriate values\n\tm2 := matrix.New(rows, columns, 3) // Replace with appropriate values\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = m1.Subtract(m2)\n\t}\n}\n"
  },
  {
    "path": "math/max/bitwisemax.go",
    "content": "// bitwiseMax.go\n// description: Gives max of two integers\n// details:\n// implementation of finding the maximum of two numbers using only binary operations without using conditions\n// author(s) [red_byte](https://github.com/i-redbyte)\n// time complexity: O(1)\n// space complexity: O(1)\n// see bitwiseMax_test.go\n\npackage max\n\n// Bitwise computes using bitwise operator the maximum of all the integer input and returns it\nfunc Bitwise(a int, b int, base int) int {\n\tz := a - b\n\ti := (z >> base) & 1\n\treturn a - (i * z)\n}\n"
  },
  {
    "path": "math/max/bitwisemax_test.go",
    "content": "// bitwiseMax_test.go\n// description: Test for Bitwise\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see bitwiseMax.go\n\npackage max\n\nimport \"testing\"\n\nfunc TestBitwiseMax(t *testing.T) {\n\tbase32 := 31\n\n\tt.Run(\"Testing(32bit) a = 32 and m = 64: \", func(t *testing.T) {\n\t\tmax := Bitwise(32, 64, base32)\n\t\tif max != 64 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(32bit) a = 1024 and m = -9: \", func(t *testing.T) {\n\t\tmax := Bitwise(1024, -9, base32)\n\t\tif max != 1024 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(32bit) a = -6 and m = -6: \", func(t *testing.T) {\n\t\tmax := Bitwise(-6, -6, base32)\n\t\tif max != -6 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(32bit) a = -72 and m = -73: \", func(t *testing.T) {\n\t\tmax := Bitwise(-72, -73, base32)\n\t\tif max != -72 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tbase64 := 63\n\tt.Run(\"Testing(64bit) a = 32 and m = 9223372036854775807: \", func(t *testing.T) {\n\t\tmax := Bitwise(32, 9223372036854775807, base64)\n\t\tif max != 9223372036854775807 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(64bit) a = 1024 and m = -9223372036854770001: \", func(t *testing.T) {\n\t\tmax := Bitwise(1024, -9223372036854770001, base64)\n\t\tif max != 1024 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(64bit) a = -6 and m = -6: \", func(t *testing.T) {\n\t\tmax := Bitwise(-6, -6, base64)\n\t\tif max != -6 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tt.Run(\"Testing(64bit) a = -4223372036854775809 and m = -4223372036854775808: \", func(t *testing.T) {\n\t\tmax := Bitwise(-4223372036854775809, -4223372036854775808, base64)\n\t\tif max != -4223372036854775808 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n\n\tbase8 := 7\n\tt.Run(\"Testing(8bit) a = 257 and m = 256: \", func(t *testing.T) {\n\t\tmax := Bitwise(8, 16, base8)\n\t\tif max != 16 {\n\t\t\tt.Fatalf(\"Error: Bitwise returned bad value\")\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "math/max/max.go",
    "content": "package max\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Int is a function which returns the maximum of all the integers provided as arguments.\nfunc Int[T constraints.Integer](values ...T) T {\n\tmax := values[0]\n\tfor _, value := range values {\n\t\tif value > max {\n\t\t\tmax = value\n\t\t}\n\t}\n\treturn max\n}\n"
  },
  {
    "path": "math/max/max_test.go",
    "content": "package max\n\nimport \"testing\"\n\nfunc TestMax(t *testing.T) {\n\ttestCases := []struct {\n\t\tname  string\n\t\tleft  int\n\t\tright int\n\t\tmax   int\n\t}{\n\t\t{\n\t\t\tname:  \"Left is max\",\n\t\t\tleft:  10,\n\t\t\tright: 9,\n\t\t\tmax:   10,\n\t\t},\n\t\t{\n\t\t\tname:  \"right is max\",\n\t\t\tleft:  1,\n\t\t\tright: 10,\n\t\t\tmax:   10,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treturnedMax := Int(test.left, test.right)\n\t\t\tif returnedMax != test.max {\n\t\t\t\tt.Errorf(\"Failed test %s\\n\\tleft: %v, right: %v, max: %v but received: %v\",\n\t\t\t\t\ttest.name, test.left, test.right, test.max, returnedMax)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMaxOfThree(t *testing.T) {\n\ttestCases := []struct {\n\t\tname   string\n\t\tleft   int\n\t\tmiddle int\n\t\tright  int\n\t\tmax    int\n\t}{\n\t\t{\n\t\t\tname:   \"right is max\",\n\t\t\tleft:   1,\n\t\t\tmiddle: 5,\n\t\t\tright:  10,\n\t\t\tmax:    10,\n\t\t},\n\t\t{\n\t\t\tname:   \"left is max\",\n\t\t\tleft:   10,\n\t\t\tmiddle: 5,\n\t\t\tright:  9,\n\t\t\tmax:    10,\n\t\t},\n\t\t{\n\t\t\tname:   \"left is max\",\n\t\t\tleft:   10,\n\t\t\tmiddle: 8,\n\t\t\tright:  6,\n\t\t\tmax:    10,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactualMax := Int(test.left, test.middle, test.right)\n\t\t\tif actualMax != test.max {\n\t\t\t\tt.Errorf(\"Failed test %s\\n\\tleft: %v, middle: %v, right: %v, max: %v but received: %v\",\n\t\t\t\t\ttest.name, test.left, test.middle, test.right, test.max, actualMax)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/mean.go",
    "content": "package math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\nfunc Mean[T constraints.Number](values []T) float64 {\n\n\tif len(values) == 0 {\n\t\treturn 0\n\t}\n\n\tvar summation float64 = 0\n\n\tfor _, singleValue := range values {\n\t\tsummation += float64(singleValue)\n\t}\n\n\treturn summation / float64(len(values))\n\n}\n"
  },
  {
    "path": "math/mean_test.go",
    "content": "package math_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math\"\n\t\"testing\"\n)\n\nfunc TestMean(t *testing.T) {\n\ttestCases := []struct {\n\t\tname       string\n\t\ttestValues []float64\n\t\taverage    float64\n\t}{\n\t\t{\n\t\t\tname:       \"All 0s\",\n\t\t\ttestValues: []float64{0, 0, 0, 0, 0},\n\t\t\taverage:    0,\n\t\t},\n\t\t{\n\t\t\tname:       \"With integer values\",\n\t\t\ttestValues: []float64{1, 2, 3, 4, 5},\n\t\t\taverage:    3.0,\n\t\t},\n\t\t{\n\t\t\tname:       \"With negative values\",\n\t\t\ttestValues: []float64{-1, 2, -3, 4, 5},\n\t\t\taverage:    1.4,\n\t\t},\n\t\t{\n\t\t\tname:       \"With floating values\",\n\t\t\ttestValues: []float64{1.1, 2.2, 3.3, 4.4, 5.5},\n\t\t\taverage:    3.3,\n\t\t},\n\t\t{\n\t\t\tname:       \"With no values\",\n\t\t\ttestValues: []float64{},\n\t\t\taverage:    0,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treturnedAverage := math.Mean(test.testValues)\n\t\t\tif returnedAverage != test.average {\n\t\t\t\tt.Errorf(\"\\nFailed test: %s\\ntestValues: %v\\naverage: %v\\nbut received: %v\\n\",\n\t\t\t\t\ttest.name, test.testValues, test.average, returnedAverage)\n\t\t\t}\n\n\t\t})\n\t}\n\n}\n"
  },
  {
    "path": "math/median.go",
    "content": "// author(s) [jo3zeph](https://github.com/jo3zeph)\n// description: Find the median from a set of values\n// time complexity: O(n log n)\n// space complexity: O(1)\n// see median_test.go\n\npackage math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/sort\"\n)\n\nfunc Median[T constraints.Number](values []T) float64 {\n\n\tsort.Bubble(values)\n\n\tl := len(values)\n\n\tswitch {\n\tcase l == 0:\n\t\treturn 0\n\n\tcase l%2 == 0:\n\t\treturn float64((values[l/2-1] + values[l/2]) / 2)\n\n\tdefault:\n\t\treturn float64(values[l/2])\n\t}\n}\n"
  },
  {
    "path": "math/median_test.go",
    "content": "// author(s) [jo3zeph](https://github.com/jo3zeph)\n// median_test.go\n// see median.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestMedian(t *testing.T) {\n\ttestCases := []struct {\n\t\tname       string\n\t\ttestValues []float64\n\t\tanswer     float64\n\t}{\n\n\t\t{\n\t\t\tname:       \"Series of numbers in ascending order\",\n\t\t\ttestValues: []float64{12, 14, 16, 18, 19},\n\t\t\tanswer:     16,\n\t\t},\n\n\t\t{\n\t\t\tname:       \"Series of numbers in random order\",\n\t\t\ttestValues: []float64{21, 10, 22, 33, 11, 88},\n\t\t\tanswer:     21.5,\n\t\t},\n\n\t\t{\n\t\t\tname:       \"Series of decimals in random order\",\n\t\t\ttestValues: []float64{11.2, 32.5, 2.5, 37.8, 21.8, 5.2},\n\t\t\tanswer:     16.5,\n\t\t},\n\n\t\t{\n\t\t\ttestValues: []float64{},\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\n\t\t\treturnedMedian := math.Median(test.testValues)\n\n\t\t\tt.Log(test.testValues, \" \", returnedMedian)\n\n\t\t\tif returnedMedian != test.answer {\n\t\t\t\tt.Errorf(\"Test failed. Median should have been %v but received %v\",\n\t\t\t\t\ttest.answer, returnedMedian)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/min/bitwisemin.go",
    "content": "// bitwisemin.go\n// description: Gives min of two integers\n// details:\n// implementation of finding the minimum of two numbers using only binary operations without using conditions\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see bitwisemin_test.go\n\npackage min\n\n// Bitwise This function returns the minimum integer using bit operations\nfunc Bitwise(base int, value int, values ...int) int {\n\tmin := value\n\tfor _, val := range values {\n\t\tmin = min&((min-val)>>base) | val&(^(min-val)>>base)\n\t}\n\treturn min\n}\n"
  },
  {
    "path": "math/min/min.go",
    "content": "package min\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Int is a function which returns the minimum of all the integers provided as arguments.\nfunc Int[T constraints.Integer](values ...T) T {\n\tmin := values[0]\n\tfor _, value := range values {\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t}\n\treturn min\n}\n"
  },
  {
    "path": "math/min/min_test.go",
    "content": "package min\n\nimport (\n\t\"testing\"\n)\n\nfunc getTestCases() []struct {\n\tname    string\n\tbase    int\n\tnumbers []int\n\tmin     int\n} {\n\tvar tests = []struct {\n\t\tname    string\n\t\tbase    int\n\t\tnumbers []int\n\t\tmin     int\n\t}{\n\t\t{\"Minimum of [128, 127], min = 117\", 8, []int{128, 127}, 127},\n\t\t{\"Minimum of [5], min = 5\", 32, []int{5}, 5},\n\t\t{\"Minimum of [-8, 32, 64, -1, 0], min = -8\", 64, []int{-8, 32, 64, -1, 0}, -8},\n\t\t{\"Minimum of [1, 2, 3, 4, 5], min = 1\", 32, []int{1, 2, 3, 4, 5}, 1},\n\t\t{\"Minimum of [1024, 512, 256, 333, 777], min = 256\", 64, []int{1024, 512, 256, 333, 777}, 256},\n\t\t{\"Minimum of [-9223372036854770001, -9223372036854770000, 256, 333, 777], min = 256\", 64, []int{-9223372036854770001, -9223372036854770000, 256, 333, 777}, -9223372036854770001},\n\t}\n\treturn tests\n}\n\nfunc TestBitwiseMin(t *testing.T) {\n\ttests := getTestCases()\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult := Bitwise(test.base, 999, test.numbers...)\n\t\t\tif result != test.min {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.min, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMin(t *testing.T) {\n\tfor _, test := range getTestCases() {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactualMin := Int(test.numbers...)\n\t\t\tif actualMin != test.min {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.min, actualMin)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkTestMinInt(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tInt(0, 10, 9, 7, 2, 1, 4, 3, 5, 6)\n\t}\n}\n\nfunc BenchmarkTestBitwiseMin(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tBitwise(32, 10, 9, 7, 2, 1, 4, 3, 5, 6)\n\t}\n}\n"
  },
  {
    "path": "math/mobius.go",
    "content": "// mobius.go\n// description: Returns μ(n)\n// details:\n// For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity.\n// It has values in {−1, 0, 1} depending on the factorization of n into prime factors:\n//   μ(n) = +1 if n is a square-free positive integer with an even number of prime factors.\n//   μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.\n//   μ(n) = 0 if n has a squared prime factor.\n// wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function\n// time complexity: O(n)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see mobius_test.go\n\npackage math\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/prime\"\n)\n\n// Mu is the Mobius function\n// This function returns μ(n) for given number\nfunc Mu(n int) int {\n\tif n <= 1 {\n\t\treturn 1\n\t}\n\tvar primeFactorCount int\n\tfor i := 1; i <= n; i++ {\n\t\tif n%i == 0 && prime.OptimizedTrialDivision(int64(i)) {\n\t\t\tif n%(i*i) == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tprimeFactorCount += 1\n\t\t}\n\t}\n\tif primeFactorCount%2 == 0 {\n\t\treturn 1\n\t}\n\treturn -1\n}\n"
  },
  {
    "path": "math/mobius_test.go",
    "content": "// mobius_test.go\n// description: Returns μ(n)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see mobius.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\talgmath \"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestMu(t *testing.T) {\n\tvar tests = []struct {\n\t\tn        int\n\t\texpected int\n\t}{\n\t\t{-1, 1},\n\t\t{0, 1},\n\t\t{2, -1},\n\t\t{3, -1},\n\t\t{95, 1},\n\t\t{97, -1},\n\t\t{98, 0},\n\t\t{99, 0},\n\t\t{100, 0},\n\t}\n\tfor _, test := range tests {\n\t\tresult := algmath.Mu(test.n)\n\t\tt.Log(test.n, \" \", result)\n\t\tif result != test.expected {\n\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.expected, result)\n\t\t}\n\t}\n}\nfunc BenchmarkMu(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\talgmath.Mu(65536)\n\t}\n}\n"
  },
  {
    "path": "math/mode.go",
    "content": "// mode.go\n// author(s): [CalvinNJK] (https://github.com/CalvinNJK)\n// time complexity: O(n)\n// space complexity: O(n)\n// description: Finding Mode Value In an Array\n// see mode.go\n\npackage math\n\nimport (\n\t\"errors\"\n\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\n// ErrEmptySlice is the error returned by functions in math package when\n// an empty slice is provided to it as argument when the function expects\n// a non-empty slice.\nvar ErrEmptySlice = errors.New(\"empty slice provided\")\n\nfunc Mode[T constraints.Number](numbers []T) (T, error) {\n\n\tcountMap := make(map[T]int)\n\n\tn := len(numbers)\n\n\tif n == 0 {\n\t\treturn 0, ErrEmptySlice\n\t}\n\n\tfor _, number := range numbers {\n\t\tcountMap[number]++\n\t}\n\n\tvar mode T\n\tcount := 0\n\n\tfor k, v := range countMap {\n\t\tif v > count {\n\t\t\tcount = v\n\t\t\tmode = k\n\t\t}\n\t}\n\n\treturn mode, nil\n\n}\n"
  },
  {
    "path": "math/mode_test.go",
    "content": "// mode.go\n// author(s): [CalvinNJK] (https://github.com/CalvinNJK)\n// description: Test for Finding Mode Value In an Array\n\npackage math_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\ntype testCase[T constraints.Number] struct {\n\tname    string\n\tnumbers []T\n\tmode    T\n\terr     error\n}\n\nfunc testModeFramework[T constraints.Number](t *testing.T, testCases []testCase[T]) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treturnMode, err := math.Mode(test.numbers)\n\t\t\tif returnMode != test.mode {\n\t\t\t\tt.Errorf(\"\\n Failed test %s,\\n Numbers: %v,\\n Correct Mode: %v,\\n Returned Mode: %v\\n\",\n\t\t\t\t\ttest.name, test.numbers, test.mode, returnMode)\n\t\t\t}\n\t\t\tif !errors.Is(err, test.err) {\n\t\t\t\tt.Errorf(\"\\n Failed test %s,\\n Numbers: %v,\\n Correct Error: %v,\\n Returned Error: %v\\n\",\n\t\t\t\t\ttest.name, test.numbers, test.err, err)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc TestMode(t *testing.T) {\n\t// test cases for integer values\n\tintTestCases := []testCase[int]{\n\t\t{\n\t\t\tname:    \"An array of positive whole numbers\",\n\t\t\tnumbers: []int{10, 52, 10, 92, 10, 75, 60, 10, 44, 29},\n\t\t\tmode:    10,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"An array of negative whole numbers\",\n\t\t\tnumbers: []int{-19, -12, -74, -19, -22, -56, -19, -19, -68, -93},\n\t\t\tmode:    -19,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"An array of positive & negative whole numbers\",\n\t\t\tnumbers: []int{18, -28, 33, -28, 2, 39, 48, -49, -87, 78, -28},\n\t\t\tmode:    -28,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"If array has no value\",\n\t\t\tnumbers: []int{},\n\t\t\tmode:    0,\n\t\t\terr:     math.ErrEmptySlice,\n\t\t},\n\t}\n\ttestModeFramework(t, intTestCases)\n\t// test cases for float64 values\n\tfloatTestCases := []testCase[float64]{\n\t\t{\n\t\t\tname:    \"An array of positive real numbers\",\n\t\t\tnumbers: []float64{1.5, 2.88, 84.4, 77.2, 29.8, 46.2, 33.7, 88.4, 88.4},\n\t\t\tmode:    88.4,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"An array of negative real numbers\",\n\t\t\tnumbers: []float64{-98.1, -26.8, -54.45, -26.8, -1.5, -26.8, -33, -19.5, -26.8},\n\t\t\tmode:    -26.8,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"An array of positive and negative real numbers\",\n\t\t\tnumbers: []float64{-17, 28.9, -5.2, -19.5, 77.3, -5.2, 39.3, 28.5, -59.77, -5.2},\n\t\t\tmode:    -5.2,\n\t\t\terr:     nil,\n\t\t},\n\t\t{\n\t\t\tname:    \"If array has no value\",\n\t\t\tnumbers: []float64{},\n\t\t\tmode:    0,\n\t\t\terr:     math.ErrEmptySlice,\n\t\t},\n\t}\n\ttestModeFramework(t, floatTestCases)\n}\n"
  },
  {
    "path": "math/modular/exponentiation.go",
    "content": "// exponentiation.go\n// description: Implementation of Modular Exponentiation Algorithm\n// details:\n// A simple implementation of Modular Exponentiation - [Modular Exponenetation wiki](https://en.wikipedia.org/wiki/Modular_exponentiation)\n// time complexity: O(log(n)) where n is the exponent\n// space complexity: O(1)\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see exponentiation_test.go\n\npackage modular\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\n// ErrorIntOverflow For asserting that the values do not overflow in Int64\nvar ErrorIntOverflow = errors.New(\"integer overflow\")\n\n// ErrorNegativeExponent for asserting that the exponent we receive is positive\nvar ErrorNegativeExponent = errors.New(\"negative Exponent provided\")\n\n// Exponentiation returns base^exponent % mod\nfunc Exponentiation(base, exponent, mod int64) (int64, error) {\n\tif mod == 1 {\n\t\treturn 0, nil\n\t}\n\n\tif exponent < 0 {\n\t\treturn -1, ErrorNegativeExponent\n\t}\n\t_, err := Multiply64BitInt(mod-1, mod-1)\n\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tvar result int64 = 1\n\n\tbase = base % mod\n\n\tfor exponent > 0 {\n\t\tif exponent%2 == 1 {\n\t\t\tresult = (result * base) % mod\n\t\t}\n\t\texponent = exponent >> 1\n\t\tbase = (base * base) % mod\n\t}\n\treturn result, nil\n}\n\n// Multiply64BitInt Checking if the integer multiplication overflows\nfunc Multiply64BitInt(left, right int64) (int64, error) {\n\tif math.Abs(float64(left)) > float64(math.MaxInt64)/math.Abs(float64(right)) {\n\t\treturn 0, ErrorIntOverflow\n\t}\n\treturn left * right, nil\n}\n"
  },
  {
    "path": "math/modular/exponentiation_test.go",
    "content": "// exponentiation_test.go\n// description: Test for ModularExponentiation\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see exponentiation.go\n\npackage modular\n\nimport \"testing\"\n\ntype cases struct {\n\tname          string\n\tdescription   string\n\tbase          int64\n\texponent      int64\n\tmod           int64\n\texpected      int64\n\texpectedError error\n}\n\nvar testCases = []cases{\n\t{\n\t\tname:          \"Test 1\",\n\t\tdescription:   \"Test 1: 3^6 % 3 == 0\",\n\t\tbase:          3,\n\t\texponent:      6,\n\t\tmod:           3,\n\t\texpected:      0,\n\t\texpectedError: nil,\n\t},\n\t{\n\t\tname:          \"Test 2\",\n\t\tdescription:   \"Test 2: 33^60 % 25 == 1\",\n\t\tbase:          33,\n\t\texponent:      60,\n\t\tmod:           25,\n\t\texpected:      1,\n\t\texpectedError: nil,\n\t},\n\t{\n\t\tname:          \"Test 3\",\n\t\tdescription:   \"Test 3: 17^60 % 23 == 2\",\n\t\tbase:          17,\n\t\texponent:      60,\n\t\tmod:           23,\n\t\texpected:      2,\n\t\texpectedError: nil,\n\t},\n\t{\n\t\tname:          \"Test 4\",\n\t\tdescription:   \"Test 4: 17^60 % 1 == 0\", // handling result when we get mod = 1\n\t\tbase:          17,\n\t\texponent:      60,\n\t\tmod:           1,\n\t\texpected:      0,\n\t\texpectedError: nil,\n\t},\n\t{\n\t\tname:          \"Error test 1\",\n\t\tdescription:   \"Testing whether we receive the expected errors gracefully\",\n\t\tbase:          50,\n\t\texponent:      -1,\n\t\tmod:           2,\n\t\texpected:      -1,\n\t\texpectedError: ErrorNegativeExponent,\n\t},\n}\n\nfunc TestExponentiation(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult, err := Exponentiation(test.base, test.exponent, test.mod)\n\t\t\tif err != test.expectedError {\n\t\t\t\tt.Logf(\"Test Failed for %s\", test.name)\n\t\t\t\tt.Logf(\"Unexpected error occurred\")\n\t\t\t\tt.Errorf(\"Expected error: %v, Received error: %v\", test.expectedError, err)\n\t\t\t}\n\t\t\tif result != test.expected {\n\t\t\t\tt.Logf(\"Test Failed for %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expected: %d, Received: %d\", test.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkExponentiation(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Exponentiation(17, 60, 23)\n\t}\n}\n"
  },
  {
    "path": "math/modular/inverse.go",
    "content": "// inverse.go\n// description: Implementation of Modular Inverse Algorithm\n// details:\n// A simple implementation of Modular Inverse - [Modular Inverse wiki](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)\n// time complexity: O(log(min(a, b))) where a and b are the two numbers\n// space complexity: O(1)\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see inverse_test.go\n\npackage modular\n\nimport (\n\t\"errors\"\n\n\t\"github.com/TheAlgorithms/Go/math/gcd\"\n)\n\nvar ErrorInverse = errors.New(\"no Modular Inverse exists\")\n\n// Inverse Modular function\nfunc Inverse(a, m int64) (int64, error) {\n\tgcd, x, _ := gcd.Extended(a, m)\n\tif gcd != 1 || m == 0 {\n\t\treturn 0, ErrorInverse\n\t}\n\n\treturn ((m + (x % m)) % m), nil // this is necessary because of Go's use of architecture specific instruction for the % operator.\n}\n"
  },
  {
    "path": "math/modular/inverse_test.go",
    "content": "// inverse_test.go\n// description: Test for Modular Inverse\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see inverse.go\n\npackage modular\n\nimport \"testing\"\nimport \"fmt\"\n\nfunc TestInverse(t *testing.T) {\n\ttestCases := []struct {\n\t\ta             int64\n\t\tm             int64\n\t\texpectedValue int64\n\t\texpectedError error\n\t}{\n\t\t{3, 11, 4, nil},\n\t\t{10, 17, 12, nil},\n\t\t{2, 6, 0, ErrorInverse},\n\t\t{1, 0, 0, ErrorInverse},\n\t}\n\tfor _, tc := range testCases {\n\t\ttestName := fmt.Sprintf(\"Testing a = %d and m = %d: \", tc.a, tc.m)\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\tinv, err := Inverse(tc.a, tc.m)\n\t\t\tif err != tc.expectedError {\n\t\t\t\tif tc.expectedError == nil {\n\t\t\t\t\tt.Fatalf(\"Error was raised when it shouldn't: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tt.Fatalf(\"Error was not raised when it should\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif inv != tc.expectedValue {\n\t\t\t\tt.Fatalf(\"expected: %d, got: %d\", tc.expectedValue, inv)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/moserdebruijnsequence/sequence.go",
    "content": "// The Moser-de Bruijn sequence is the sequence obtained by\n// adding up the distinct powers of the number 4 (For example 1, 4, 16, 64, etc).\n// time complexity: O(n)\n// space complexity: O(n)\n// You can get more details on https://en.wikipedia.org/wiki/Moser%E2%80%93de_Bruijn_sequence.\n\npackage moserdebruijnsequence\n\nfunc MoserDeBruijnSequence(number int) []int {\n\tsequence := []int{}\n\n\tfor i := 0; i < number; i++ {\n\t\tres := generateNthTerm(i)\n\t\tsequence = append(sequence, res)\n\t}\n\n\treturn sequence\n}\n\nfunc generateNthTerm(num int) int {\n\tif num == 0 || num == 1 {\n\t\treturn num\n\t}\n\n\t//number is even\n\tif num%2 == 0 {\n\t\treturn 4 * generateNthTerm(num/2)\n\t}\n\n\t//number is odd\n\treturn 4*generateNthTerm(num/2) + 1\n}\n"
  },
  {
    "path": "math/moserdebruijnsequence/sequence_test.go",
    "content": "package moserdebruijnsequence\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string\n\tinputNum int\n\texpected []int\n}{\n\t{\"first 15 terms\", 15, []int{0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84}},\n}\n\nfunc TestMoserDeBruijnSequence(t *testing.T) {\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif output := MoserDeBruijnSequence(test.inputNum); !reflect.DeepEqual(output, test.expected) {\n\t\t\t\tt.Errorf(\"For input: %d, expected: %v, but got: %v\", test.inputNum, test.expected, output)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/pascal/pascaltriangle.go",
    "content": "// pascaltriangle.go\n// description: Pascal's triangle\n// details:\n// Pascal's triangle is a triangular array of the binomial coefficients that arises in probability theory, combinatorics, and algebra. - [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle)\n// example:\n//1\n//1 1\n//1 2 1\n//1 3 3 1\n//1 4 6 4 1\n//1 5 10 10 5 1\n//1 6 15 20 15 6 1\n//1 7 21 35 35 21 7 1\n//1 8 28 56 70 56 28 8 1\n//1 9 36 84 126 126 84 36 9 1\n//1 10 45 120 210 252 210 120 45 10 1\n//...\n// author(s) [red_byte](https://github.com/i-redbyte)\n// time complexity: O(n^2)\n// space complexity: O(n^2)\n// see pascaltriangle_test.go\n\npackage pascal\n\n// GenerateTriangle This function generates a Pascal's triangle of n lines\nfunc GenerateTriangle(n int) [][]int {\n\tvar triangle = make([][]int, n)\n\tfor i := 0; i < n; i++ {\n\t\ttriangle[i] = make([]int, i+1)\n\t\ttriangle[i][0], triangle[i][i] = 1, 1\n\t\tfor j := 1; j < i; j++ {\n\t\t\ttriangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1]\n\t\t}\n\t}\n\treturn triangle\n}\n"
  },
  {
    "path": "math/pascal/pascaltriangle_test.go",
    "content": "// pascaltriangle_test.go\n// description: Test for Pascal's triangle\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see pascaltriangle.go\n\npackage pascal\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestGenerateTriangle(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    int\n\t\twant [][]int\n\t}{\n\t\t{name: \"Pascal's three-line triangle\", n: 3, want: [][]int{{1}, {1, 1}, {1, 2, 1}}},\n\t\t{name: \"Pascal's 0-line triangle\", n: 0, want: [][]int{}},\n\t\t{name: \"Pascal's one-line triangle\", n: 1, want: [][]int{{1}}},\n\t\t{name: \"Pascal's 7-line triangle\", n: 7, want: [][]int{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}}},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := GenerateTriangle(test.n); !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"GenerateTriangle() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkGenerateTriangle(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tGenerateTriangle(10)\n\t}\n}\n"
  },
  {
    "path": "math/perfectnumber.go",
    "content": "// perfectnumber.go\n// description: provides the function IsPerfectNumber and related utilities\n// details:\n// provides the functions\n// - IsPerfectNumber which checks if the input is a perfect number,\n// - SumOfProperDivisors which returns the sum of proper divisors of the input.\n// A number is called perfect, if it is a sum of its proper divisors,\n// cf. https://en.wikipedia.org/wiki/Perfect_number,\n// https://mathworld.wolfram.com/PerfectNumber.html\n// time complexity: O(sqrt(n))\n// space complexity: O(1)\n// https://oeis.org/A000396\n// author(s) [Piotr Idzik](https://github.com/vil02)\n// see perfectnumber_test.go\n\npackage math\n\n// Returns the sum of proper divisors of inNumber.\nfunc SumOfProperDivisors(inNumber uint) uint {\n\tvar res = uint(0)\n\tif inNumber > 1 {\n\t\tres = uint(1)\n\t}\n\tfor curDivisor := uint(2); curDivisor*curDivisor <= inNumber; curDivisor++ {\n\t\tif inNumber%curDivisor == 0 {\n\t\t\tres += curDivisor\n\t\t\tif curDivisor*curDivisor != inNumber {\n\t\t\t\tres += inNumber / curDivisor\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}\n\n// Checks if inNumber is a perfect number\nfunc IsPerfectNumber(inNumber uint) bool {\n\treturn inNumber > 0 && SumOfProperDivisors(inNumber) == inNumber\n}\n"
  },
  {
    "path": "math/perfectnumber_test.go",
    "content": "package math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\ntype testCaseSumOfProperDivisors struct {\n\tinput    uint\n\texpected uint\n}\n\n// getSumOfProperDivisorsTestCases returns an array of test data\n// for the tests of the function SumOfProperDivisors.\n// Data was verified using [A001065].\n// [A001065]: https://oeis.org/A001065/b001065.txt\nfunc getSumOfProperDivisorsTestCases() []testCaseSumOfProperDivisors {\n\treturn []testCaseSumOfProperDivisors{\n\t\t{0, 0},\n\t\t{1, 0},\n\t\t{2, 1},\n\t\t{3, 1},\n\t\t{4, 3},\n\t\t{5, 1},\n\t\t{6, 6},\n\t\t{7, 1},\n\t\t{8, 7},\n\t\t{9, 4},\n\t\t{10, 8},\n\t\t{11, 1},\n\t\t{12, 16},\n\t\t{13, 1},\n\t\t{14, 10},\n\t\t{15, 9},\n\t\t{16, 15},\n\t\t{17, 1},\n\t\t{18, 21},\n\t\t{19, 1},\n\t\t{20, 22},\n\t\t{21, 11},\n\t\t{22, 14},\n\t\t{23, 1},\n\t\t{24, 36},\n\t\t{25, 6},\n\t\t{26, 16},\n\t\t{27, 13},\n\t\t{28, 28},\n\t\t{29, 1},\n\t\t{30, 42},\n\t\t{31, 1},\n\t\t{32, 31},\n\t\t{33, 15},\n\t\t{34, 20},\n\t\t{35, 13},\n\t\t{36, 55},\n\t\t{37, 1},\n\t\t{38, 22},\n\t\t{39, 17},\n\t\t{40, 50},\n\t\t{41, 1},\n\t\t{42, 54},\n\t\t{43, 1},\n\t\t{44, 40},\n\t\t{45, 33},\n\t\t{46, 26},\n\t\t{47, 1},\n\t\t{48, 76},\n\t\t{49, 8},\n\t\t{50, 43},\n\t\t{51, 21},\n\t\t{52, 46},\n\t\t{53, 1},\n\t\t{54, 66},\n\t\t{55, 17},\n\t\t{56, 64},\n\t\t{57, 23},\n\t\t{58, 32},\n\t\t{59, 1},\n\t\t{60, 108},\n\t\t{800, 1153},\n\t\t{8204, 8260},\n\t\t{9646, 8498},\n\t\t{9756, 14996},\n\t\t{9829, 1},\n\t\t{9954, 15006},\n\t\t{10000, 14211},\n\t}\n}\n\nfunc TestSumOfProperDivisors(t *testing.T) {\n\tfor _, tc := range getSumOfProperDivisorsTestCases() {\n\t\tactual := math.SumOfProperDivisors(tc.input)\n\t\tif actual != tc.expected {\n\t\t\tt.Errorf(\n\t\t\t\t\"Expected SumOfProperDivisors(%d) to be: %d, but got: %d\",\n\t\t\t\ttc.input, tc.expected, actual)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSumOfProperDivisors(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.SumOfProperDivisors(800)\n\t}\n}\n\ntype isPerfectNumberTestCase struct {\n\tnumber    uint\n\tisPerfect bool\n}\n\n// getIsPerfectNumberTestCases returns an array of test data\n// for the tests of the function IsPerfectNumber\n// Data was verified using [A000396].\n// [A000396]: https://oeis.org/A000396\nfunc getIsPerfectNumberTestCases() []isPerfectNumberTestCase {\n\treturn []isPerfectNumberTestCase{\n\t\t{6, true},\n\t\t{28, true},\n\t\t{496, true},\n\t\t{8128, true},\n\t\t{33550336, true},\n\t\t{0, false},\n\t\t{1, false},\n\t\t{2, false},\n\t\t{3, false},\n\t\t{4, false},\n\t\t{5, false},\n\t\t{7, false},\n\t\t{100, false},\n\t\t{219, false},\n\t\t{997, false},\n\t\t{33550335, false},\n\t\t{33550337, false},\n\t}\n}\n\nfunc TestIsPerfectNumber(t *testing.T) {\n\tfor _, tc := range getIsPerfectNumberTestCases() {\n\t\tif math.IsPerfectNumber(tc.number) != tc.isPerfect {\n\t\t\tt.Errorf(\"Unexpected output for %d\", tc.number)\n\t\t}\n\t}\n}\n\nfunc BenchmarkIsPerfectNumber(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.IsPerfectNumber(8128)\n\t}\n}\n"
  },
  {
    "path": "math/permutation/heaps.go",
    "content": "// heaps.go\n// description: Implementation of Heap's Algorithm for generating all permutations of n objects\n// time complexity: O(n!)\n// space complexity: O(n)\n\npackage permutation\n\nimport (\n\t\"strings\"\n)\n\n// Heap's Algorithm for generating all permutations of n objects\nfunc Heaps(out chan []string, n int) {\n\telementSetCh := make(chan []string)\n\tgo GenerateElementSet(elementSetCh, n)\n\telementSet := <-elementSetCh\n\n\tvar recursiveGenerate func([]string, int, []string)\n\tvar permutations []string\n\trecursiveGenerate = func(previousIteration []string, n int, elements []string) {\n\t\tif n == 1 {\n\t\t\tpermutations = append(permutations, strings.Join(elements, \"\"))\n\t\t} else {\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\trecursiveGenerate(previousIteration, n-1, elements)\n\t\t\t\tif n%2 == 1 {\n\t\t\t\t\ttmp := elements[i]\n\t\t\t\t\telements[i] = elements[n-1]\n\t\t\t\t\telements[n-1] = tmp\n\t\t\t\t} else {\n\t\t\t\t\ttmp := elements[0]\n\t\t\t\t\telements[0] = elements[n-1]\n\t\t\t\t\telements[n-1] = tmp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trecursiveGenerate(permutations, n, elementSet)\n\tout <- permutations\n}\n\nfunc GenerateElementSet(out chan []string, n int) {\n\telementSet := make([]string, n)\n\tfor i := range elementSet {\n\t\telementSet[i] = string(rune(i + 49)) // Adjust this if you want to change your charset\n\t}\n\tout <- elementSet\n}\n"
  },
  {
    "path": "math/permutation/heaps_test.go",
    "content": "package permutation\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestHeaps(t *testing.T) {\n\tt.Run(\"Should generate permutations for various size sets\", func(t *testing.T) {\n\t\texpectedValues := [][]string{\n\t\t\t{\"1\"},\n\t\t\t{\"12\", \"21\"},\n\t\t\t{\"123\", \"213\", \"321\", \"231\", \"312\", \"132\"},\n\t\t\t{\"1234\", \"1243\", \"1324\", \"1342\", \"1423\", \"1432\", \"2134\", \"2143\", \"2314\", \"2341\", \"2413\", \"2431\", \"3124\", \"3142\", \"3214\", \"3241\", \"3412\", \"3421\", \"4123\", \"4132\", \"4213\", \"4231\", \"4312\", \"4321\"},\n\t\t\t{\"12345\", \"12354\", \"12435\", \"12453\", \"12534\", \"12543\", \"13245\", \"13254\", \"13425\", \"13452\", \"13524\", \"13542\", \"14235\", \"14253\", \"14325\", \"14352\", \"14523\", \"14532\", \"15234\", \"15243\", \"15324\", \"15342\", \"15423\", \"15432\", \"21345\", \"21354\", \"21435\", \"21453\", \"21534\", \"21543\", \"23145\", \"23154\", \"23415\", \"23451\", \"23514\", \"23541\", \"24135\", \"24153\", \"24315\", \"24351\", \"24513\", \"24531\", \"25134\", \"25143\", \"25314\", \"25341\", \"25413\", \"25431\", \"31245\", \"31254\", \"31425\", \"31452\", \"31524\", \"31542\", \"32145\", \"32154\", \"32415\", \"32451\", \"32514\", \"32541\", \"34125\", \"34152\", \"34215\", \"34251\", \"34512\", \"34521\", \"35124\", \"35142\", \"35214\", \"35241\", \"35412\", \"35421\", \"41235\", \"41253\", \"41325\", \"41352\", \"41523\", \"41532\", \"42135\", \"42153\", \"42315\", \"42351\", \"42513\", \"42531\", \"43125\", \"43152\", \"43215\", \"43251\", \"43512\", \"43521\", \"45123\", \"45132\", \"45213\", \"45231\", \"45312\", \"45321\", \"51234\", \"51243\", \"51324\", \"51342\", \"51423\", \"51432\", \"52134\", \"52143\", \"52314\", \"52341\", \"52413\", \"52431\", \"53124\", \"53142\", \"53214\", \"53241\", \"53412\", \"53421\", \"54123\", \"54132\", \"54213\", \"54231\", \"54312\", \"54321\"},\n\t\t}\n\t\tpermutationsCh := make(chan []string)\n\t\tvar value []string\n\n\t\tfor i := 1; i <= 5; i++ {\n\t\t\tgo Heaps(permutationsCh, i)\n\t\t\tvalue = <-permutationsCh\n\t\t\tsort.Strings(value)\n\t\t\tsort.Strings(expectedValues[i-1])\n\t\t\tif !reflect.DeepEqual(value, expectedValues[i-1]) {\n\t\t\t\tt.Errorf(\"Permutation set is incorrect for element size of %v. Expected (%v) and received (%v)\", i, expectedValues[i-1], value)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "math/permutation/next_permutation.go",
    "content": "// A practice to find lexicographically next greater permutation of the given array of integers.\n// If there does not exist any greater permutation, then print the lexicographically smallest permutation of the given array.\n// The implementation below, finds the next permutation in linear time and constant memory and returns in place\n// time complexity: O(n)\n// space complexity: O(1)\n// Useful reference: https://www.geeksforgeeks.org/next-permutation/\n\npackage permutation\n\nfunc NextPermutation(nums []int) {\n\tpivot := 0\n\tfor pivot = len(nums) - 2; pivot >= 0; pivot-- {\n\t\tif nums[pivot] < nums[pivot+1] {\n\t\t\tbreak\n\t\t}\n\t}\n\tif pivot < 0 {\n\t\t// current permutation is the last and must be reversed totally\n\t\tfor l, r := 0, len(nums)-1; l < r; l, r = l+1, r-1 {\n\t\t\tnums[l], nums[r] = nums[r], nums[l]\n\t\t}\n\t} else {\n\t\tsucc := 0\n\t\tfor succ = len(nums) - 1; succ > pivot; succ = succ - 1 {\n\t\t\tif nums[succ] > nums[pivot] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Swap the pivot and successor\n\t\tnums[pivot], nums[succ] = nums[succ], nums[pivot]\n\n\t\t// Reverse the suffix part to minimize it\n\t\tfor l, r := pivot+1, len(nums)-1; l < r; l, r = l+1, r-1 {\n\t\t\tnums[l], nums[r] = nums[r], nums[l]\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "math/permutation/next_permutation_test.go",
    "content": "package permutation\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestNextPermutation(t *testing.T) {\n\tvar nextPermutationTestData = []struct {\n\t\tdescription string\n\t\tnumbers     []int\n\t\tnext        []int\n\t}{\n\t\t{\n\t\t\tdescription: \"Basic case\",\n\t\t\tnumbers:     []int{1, 2, 3},\n\t\t\tnext:        []int{1, 3, 2},\n\t\t},\n\t\t{\n\t\t\tdescription: \"Should reverse the whole slice\",\n\t\t\tnumbers:     []int{3, 2, 1},\n\t\t\tnext:        []int{1, 2, 3},\n\t\t},\n\t\t{\n\t\t\tdescription: \"A more complex test\",\n\t\t\tnumbers:     []int{2, 4, 1, 7, 5, 0},\n\t\t\tnext:        []int{2, 4, 5, 0, 1, 7},\n\t\t},\n\t}\n\tfor _, test := range nextPermutationTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tNextPermutation(test.numbers)\n\n\t\t\tif !reflect.DeepEqual(test.numbers, test.next) {\n\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\tt.Fatalf(\"Expected result:%v\\nFound: %v\", test.next, test.numbers)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/pi/montecarlopi.go",
    "content": "// montecarlopi.go\n// description: Calculating pi by the Monte Carlo method\n// details:\n// implementations of Monte Carlo Algorithm for the calculating of Pi - [Monte Carlo method](https://en.wikipedia.org/wiki/Monte_Carlo_method)\n// time complexity: O(n)\n// space complexity: O(1)\n// author(s): [red_byte](https://github.com/i-redbyte), [Paul Leydier] (https://github.com/paul-leydier)\n// see montecarlopi_test.go\n\npackage pi\n\nimport (\n\t\"fmt\"       // Used for error formatting\n\t\"math/rand\" // Used for random number generation in Monte Carlo method\n\t\"runtime\"   // Used to get information on available CPUs\n\t\"time\"      // Used for seeding the random number generation\n)\n\nfunc MonteCarloPi(randomPoints int) float64 {\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tinside := 0\n\tfor i := 0; i < randomPoints; i++ {\n\t\tx := rnd.Float64()\n\t\ty := rnd.Float64()\n\t\tif x*x+y*y <= 1 {\n\t\t\tinside += 1\n\t\t}\n\t}\n\tpi := float64(inside) / float64(randomPoints) * 4\n\treturn pi\n}\n\n// MonteCarloPiConcurrent approximates the value of pi using the Monte Carlo method.\n// Unlike the MonteCarloPi function (first version), this implementation uses\n// goroutines and channels to parallelize the computation.\n// More details on the Monte Carlo method available at https://en.wikipedia.org/wiki/Monte_Carlo_method.\n// More details on goroutines parallelization available at https://go.dev/doc/effective_go#parallel.\nfunc MonteCarloPiConcurrent(n int) (float64, error) {\n\tnumCPU := runtime.GOMAXPROCS(0)\n\tc := make(chan int, numCPU)\n\tpointsToDraw, err := splitInt(n, numCPU) // split the task in sub-tasks of approximately equal sizes\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// launch numCPU parallel tasks\n\tfor _, p := range pointsToDraw {\n\t\tgo drawPoints(p, c)\n\t}\n\n\t// collect the tasks results\n\tinside := 0\n\tfor i := 0; i < numCPU; i++ {\n\t\tinside += <-c\n\t}\n\treturn float64(inside) / float64(n) * 4, nil\n}\n\n// drawPoints draws n random two-dimensional points in the interval [0, 1), [0, 1) and sends through c\n// the number of points which where within the circle of center 0 and radius 1 (unit circle)\nfunc drawPoints(n int, c chan<- int) {\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tinside := 0\n\tfor i := 0; i < n; i++ {\n\t\tx, y := rnd.Float64(), rnd.Float64()\n\t\tif x*x+y*y <= 1 {\n\t\t\tinside++\n\t\t}\n\t}\n\tc <- inside\n}\n\n// splitInt takes an integer x and splits it within an integer slice of length n in the most uniform\n// way possible.\n// For example, splitInt(10, 3) will return []int{4, 3, 3}, nil\nfunc splitInt(x int, n int) ([]int, error) {\n\tif x < n {\n\t\treturn nil, fmt.Errorf(\"x must be < n - given values are x=%d, n=%d\", x, n)\n\t}\n\tsplit := make([]int, n)\n\tif x%n == 0 {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tsplit[i] = x / n\n\t\t}\n\t} else {\n\t\tlimit := x % n\n\t\tfor i := 0; i < limit; i++ {\n\t\t\tsplit[i] = x/n + 1\n\t\t}\n\t\tfor i := limit; i < n; i++ {\n\t\t\tsplit[i] = x / n\n\t\t}\n\t}\n\treturn split, nil\n}\n"
  },
  {
    "path": "math/pi/montecarlopi_test.go",
    "content": "// montecarlopi_test.go\n// description: Test for calculating pi by the Monte Carlo method\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see montecarlopi.go\n\npackage pi\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestMonteCarloPi(t *testing.T) {\n\tt.Run(\"Monte Carlo Pi\", func(t *testing.T) {\n\t\tresult := fmt.Sprintf(\"%.2f\", MonteCarloPi(100000000))\n\t\tt.Log(result)\n\t\tif result != \"3.14\" {\n\t\t\tt.Errorf(\"Wrong result! Expected:%f, returned:%s \", 3.1415, result)\n\t\t}\n\t})\n}\n\nfunc BenchmarkMonteCarloPi(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tMonteCarloPi(100000000)\n\t}\n}\n\nfunc TestSplitInt(t *testing.T) {\n\ttestCases := []struct {\n\t\tname           string\n\t\tx              int\n\t\tn              int\n\t\texpectedResult []int\n\t\texpectedError  bool\n\t}{\n\t\t{\"multiple\", 10, 5, []int{2, 2, 2, 2, 2}, false},\n\t\t{\"n=1\", 10, 1, []int{10}, false},\n\t\t{\"x=10, n=3\", 10, 3, []int{4, 3, 3}, false},\n\t\t{\"x=10, n=7\", 10, 7, []int{2, 2, 2, 1, 1, 1, 1}, false},\n\t\t{\"n>x\", 10, 11, nil, true},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tres, err := splitInt(testCase.x, testCase.n)\n\t\t\tfor i := 0; i < len(testCase.expectedResult); i++ {\n\t\t\t\tif res[i] != testCase.expectedResult[i] {\n\t\t\t\t\tt.Fatalf(\"unexpected result at index %d: %d - expected %d\", i, res[i], testCase.expectedResult[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif testCase.expectedError {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Fatal(\"expected an error, got nil\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"unexpected error - %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMonteCarloPi2(t *testing.T) {\n\tres, err := MonteCarloPiConcurrent(100000000)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error %s\", err)\n\t}\n\tresult := fmt.Sprintf(\"%.2f\", res)\n\tt.Log(result)\n\tif result != \"3.14\" {\n\t\tt.Errorf(\"Wrong result! Expected:%f, returned:%s \", 3.1415, result)\n\t}\n}\n\nfunc BenchmarkMonteCarloPi2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := MonteCarloPiConcurrent(100000000)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected error - %s\", err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "math/pi/spigotpi.go",
    "content": "// spigotpi.go\n// description: A Spigot Algorithm for the Digits of Pi\n// details:\n// implementation of Spigot Algorithm for the Digits of Pi - [Spigot algorithm](https://en.wikipedia.org/wiki/Spigot_algorithm)\n// time complexity: O(n)\n// space complexity: O(n)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see spigotpi_test.go\n\npackage pi\n\nimport \"strconv\"\n\nfunc Spigot(n int) string {\n\tpi := \"\"\n\tboxes := n * 10 / 3\n\tremainders := make([]int, boxes)\n\tfor i := 0; i < boxes; i++ {\n\t\tremainders[i] = 2\n\t}\n\tdigitsHeld := 0\n\tfor i := 0; i < n; i++ {\n\t\tcarriedOver := 0\n\t\tsum := 0\n\t\tfor j := boxes - 1; j >= 0; j-- {\n\t\t\tremainders[j] *= 10\n\t\t\tsum = remainders[j] + carriedOver\n\t\t\tquotient := sum / (j*2 + 1)\n\t\t\tremainders[j] = sum % (j*2 + 1)\n\t\t\tcarriedOver = quotient * j\n\t\t}\n\t\tremainders[0] = sum % 10\n\t\tq := sum / 10\n\t\tswitch q {\n\t\tcase 9:\n\t\t\tdigitsHeld++\n\t\tcase 10:\n\t\t\tq = 0\n\t\t\tfor k := 1; k <= digitsHeld; k++ {\n\t\t\t\treplaced, _ := strconv.Atoi(pi[i-k : i-k+1])\n\t\t\t\tif replaced == 9 {\n\t\t\t\t\treplaced = 0\n\t\t\t\t} else {\n\t\t\t\t\treplaced++\n\t\t\t\t}\n\t\t\t\tpi = delChar(pi, i-k)\n\t\t\t\tpi = pi[:i-k] + strconv.Itoa(replaced) + pi[i-k:]\n\t\t\t}\n\t\t\tdigitsHeld = 1\n\t\tdefault:\n\t\t\tdigitsHeld = 1\n\t\t}\n\t\tpi += strconv.Itoa(q)\n\t}\n\treturn pi\n}\n\nfunc delChar(s string, index int) string {\n\ttmp := []rune(s)\n\treturn string(append(tmp[0:index], tmp[index+1:]...))\n}\n"
  },
  {
    "path": "math/pi/spigotpi_test.go",
    "content": "// spigotpi_test.go\n// description: Test for Spigot Algorithm for the Digits of Pi\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see spigotpi.go\npackage pi\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestSpigot(t *testing.T) {\n\tvar tests = []struct {\n\t\tresult string\n\t\tn      int\n\t}{\n\t\t{\"314\", 3},\n\t\t{\"31415\", 5},\n\t\t{\"314159\", 6},\n\t\t{\"31415926535\", 11},\n\t\t{\"314159265358\", 12},\n\t\t{\"314159265358979323846\", 21},\n\t\t{\"3141592653589793238462643\", 25},\n\t\t{\"314159265358979323846264338327950\", 33},\n\t\t{\"31415926535897932384626433832795028841971693993751\" +\n\t\t\t\"05820974944592307816406286208998628034825342117067\" +\n\t\t\t\"98214808651328230664709384460955058223172535940812\" +\n\t\t\t\"84811174502841027019385211055596446229489549303819\" +\n\t\t\t\"64428810975665933446128475648233786783165271201909\" +\n\t\t\t\"14564856692346034861045432664821339360726024914127\" +\n\t\t\t\"37245870066063155881748815209209628292540917153643\" +\n\t\t\t\"678925903600\", 362},\n\t}\n\tfor _, tv := range tests {\n\t\tt.Run(strconv.Itoa(tv.n)+\":\"+tv.result, func(t *testing.T) {\n\t\t\tresult := Spigot(tv.n)\n\t\t\tif result != tv.result {\n\t\t\t\tt.Errorf(\"Bad result %d:%s\", tv.n, tv.result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkPiSpigotN10(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSpigot(10)\n\t}\n}\n\nfunc BenchmarkPiSpigotN100(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSpigot(100)\n\t}\n}\n\nfunc BenchmarkPiSpigotN1000(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tSpigot(1000)\n\t}\n}\n"
  },
  {
    "path": "math/pollard.go",
    "content": "// pollard.go\n// description: Pollard's rho algorithm\n// details:\n// implementation of Pollard's rho algorithm for integer factorization-[Pollard's rho algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm)\n// time complexity: O(n^(1/4))\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see pollard_test.go\n\npackage math\n\nimport (\n\t\"errors\"\n\t\"math/big\"\n)\n\n// DefaultPolynomial is the commonly used polynomial g(x) = (x^2 + 1) mod n\nfunc DefaultPolynomial(n *big.Int) func(*big.Int) *big.Int {\n\tbigOne := big.NewInt(1)\n\tbigTwo := big.NewInt(2)\n\treturn func(x *big.Int) *big.Int {\n\t\txSquared := new(big.Int).Exp(x, bigTwo, n) // see: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Core_ideas\n\t\txSquared.Add(xSquared, bigOne)\n\t\txSquared.Mod(xSquared, n)\n\t\treturn xSquared\n\t}\n}\n\n// PollardsRhoFactorization is an implementation of Pollard's rho factorization algorithm\n// using the default parameters x = y = 2\nfunc PollardsRhoFactorization(n *big.Int, f func(n *big.Int) func(x *big.Int) *big.Int) (*big.Int, error) {\n\tx, y, d := big.NewInt(2), big.NewInt(2), big.NewInt(1)\n\tbigOne := big.NewInt(1)\n\tg := f(n)\n\tfor d.Cmp(bigOne) == 0 {\n\t\tx = g(x)\n\t\ty = g(g(y))\n\t\tsub := new(big.Int).Sub(x, y)\n\t\td.GCD(nil, nil, sub.Abs(sub), n)\n\t}\n\tif d.Cmp(n) == 0 {\n\t\treturn nil, errors.New(\"factorization failed\")\n\t}\n\treturn d, nil\n}\n"
  },
  {
    "path": "math/pollard_test.go",
    "content": "// pollard_test.go\n// description: Test for Pollard's rho algorithm\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see pollard.go\n\npackage math\n\nimport (\n\t\"math/big\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDefaultPolynomial(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tx    *big.Int\n\t\tn    *big.Int\n\t\twant *big.Int\n\t}{\n\t\t{\"Polynomial for n = 1772; x = 535\", big.NewInt(535), big.NewInt(1772), big.NewInt(934)},\n\t\t{\"Polynomial for n = 666; x = 53135\", big.NewInt(53135), big.NewInt(666), big.NewInt(380)},\n\t\t{\"Polynomial for n = 666; x = 13\", big.NewInt(13), big.NewInt(666), big.NewInt(170)},\n\t\t{\"Polynomial for n = 1917; x = 2510\", big.NewInt(2510), big.NewInt(1917), big.NewInt(839)},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif got := DefaultPolynomial(test.n)(test.x); !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"DefaultPolynomial() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRho(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tn       *big.Int\n\t\tg       func(n *big.Int) func(*big.Int) *big.Int\n\t\twant    *big.Int\n\t\twantErr bool\n\t}{\n\t\t{\"Factor of n:  11235 \", big.NewInt(11235), DefaultPolynomial, big.NewInt(21), false},\n\t\t{\"Factor of n:  111155 \", big.NewInt(111155), DefaultPolynomial, big.NewInt(11), false},\n\t\t{\"Factor of n:  8080 \", big.NewInt(8080), DefaultPolynomial, big.NewInt(16), false},\n\t\t{\"Factor of n:  8536 \", big.NewInt(8536), DefaultPolynomial, big.NewInt(88), false},\n\t\t{\"Factor of n:  666 \", big.NewInt(666), DefaultPolynomial, big.NewInt(3), false},\n\t\t{\"Factor of n:  2 \", big.NewInt(2), DefaultPolynomial, big.NewInt(2), true},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot, err := PollardsRhoFactorization(test.n, test.g)\n\t\t\tif err != nil && !test.wantErr {\n\t\t\t\tt.Errorf(\"PollardsRhoFactorization() error = %v, wantErr %v\", err, test.wantErr)\n\t\t\t\treturn\n\t\t\t} else if err != nil && test.wantErr {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"PollardsRhoFactorization() got = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkDefaultPolynomial(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tDefaultPolynomial(big.NewInt(535))(big.NewInt(11235))\n\t}\n}\n\nfunc BenchmarkRho(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := PollardsRhoFactorization(big.NewInt(535), DefaultPolynomial)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "math/power/fastexponent.go",
    "content": "package power\n\n// IterativePower is iterative O(logn) function for pow(x, y)\nfunc IterativePower(n uint, power uint) uint {\n\tvar res uint = 1\n\tfor power > 0 {\n\t\tif (power & 1) != 0 {\n\t\t\tres = res * n\n\t\t}\n\n\t\tpower = power >> 1\n\t\tn *= n\n\t}\n\treturn res\n}\n\n// RecursivePower is recursive O(logn) function for pow(x, y)\nfunc RecursivePower(n uint, power uint) uint {\n\tif power == 0 {\n\t\treturn 1\n\t}\n\tvar temp = RecursivePower(n, power/2)\n\tif power%2 == 0 {\n\t\treturn temp * temp\n\t}\n\treturn n * temp * temp\n}\n\n// RecursivePower1 is recursive O(n) function for pow(x, y)\nfunc RecursivePower1(n uint, power uint) uint {\n\tif power == 0 {\n\t\treturn 1\n\t} else if power%2 == 0 {\n\t\treturn RecursivePower1(n, power/2) * RecursivePower1(n, power/2)\n\t} else {\n\t\treturn n * RecursivePower1(n, power/2) * RecursivePower1(n, power/2)\n\t}\n}\n"
  },
  {
    "path": "math/power/fastexponent_test.go",
    "content": "package power\n\nimport \"testing\"\n\nvar testCases = []struct {\n\tname     string\n\tbase     uint\n\tpower    uint\n\texpected uint\n}{\n\t{\"0^2\", 0, 2, 0},\n\t{\"2^0\", 2, 0, 1},\n\t{\"2^3\", 2, 3, 8},\n\t{\"8^3\", 8, 3, 512},\n\t{\"10^5\", 10, 5, 100000},\n}\n\nfunc TestIterativePower(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := IterativePower(tc.base, tc.power)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected %d to the power of %d to be: %d, but got: %d\", tc.base, tc.power, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRecursivePower(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := RecursivePower(tc.base, tc.power)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected %d to the power of %d to be: %d, but got: %d\", tc.base, tc.power, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRecursivePower1(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := RecursivePower1(tc.base, tc.power)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected %d to the power of %d to be: %d, but got: %d\", tc.base, tc.power, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkIterativePower(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tIterativePower(10, 5)\n\t}\n}\n\nfunc BenchmarkRecursivePower(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tRecursivePower(10, 5)\n\t}\n}\n\nfunc BenchmarkRecursivePower1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tRecursivePower1(10, 5)\n\t}\n}\n"
  },
  {
    "path": "math/power/powvialogarithm.go",
    "content": "// powvialogarithm.go\n// description: Powers in terms of logarithms\n// details:\n// implementation of exponentiation using exponent and logarithm, without using loops  - [Powers via logarithms wiki](https://en.wikipedia.org/wiki/Exponentiation#Powers_via_logarithms)\n// time complexity: O(1)\n// space complexity: O(1)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see powvialogarithm_test.go\n\npackage power\n\nimport (\n\t\"math\"\n)\n\nfunc UsingLog(a float64, b float64) float64 {\n\tvar p float64\n\tp = 1\n\tif a < 0 && int(b)&1 != 0 {\n\t\tp = -1\n\t}\n\tlog := math.Log(math.Abs(a))\n\texp := math.Exp(b * log)\n\tresult := exp * p\n\treturn math.Round(result)\n}\n"
  },
  {
    "path": "math/power/powvialogarithm_test.go",
    "content": "// powvialogarithm_test.go\n// description: Test for UsingLog\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see powvialogarithm.go\n\npackage power\n\nimport \"testing\"\n\nfunc TestUsingLog(t *testing.T) {\n\tvar tests = []struct {\n\t\tname     string\n\t\tbase     float64\n\t\tpower    float64\n\t\texpected float64\n\t}{\n\t\t{\"0^0\", 99, 1, 99},\n\t\t{\"-3^9\", -3, 9, -19683},\n\t\t{\"0^2\", 0, 2, 0},\n\t\t{\"2^0\", 2, 0, 1},\n\t\t{\"2^3\", 2, 3, 8},\n\t\t{\"8^3\", 8, 3, 512},\n\t\t{\"11^11\", 11, 11, 285311670611},\n\t\t{\"5^5\", 5, 5, 3125},\n\t\t{\"-7^2\", -7, 2, 49},\n\t\t{\"-6^3\", -6, 3, -216},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tresult := UsingLog(tc.base, tc.power)\n\t\t\tt.Log(result)\n\t\t\tif result != tc.expected {\n\t\t\t\tt.Errorf(\"Expected %.2f to the power of %.2f to be: %.2f, but got: %.2f\", tc.base, tc.power, tc.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkUsingLog(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tUsingLog(10, 5)\n\t}\n}\n"
  },
  {
    "path": "math/prime/millerrabintest.go",
    "content": "// This file implements two versions of the Miller-Rabin primality test.\n// One of the implementations is deterministic and the other is probabilistic.\n// The Miller-Rabin test is one of the simplest and fastest known primality\n// tests and is widely used.\n// time complexity: O(k * log(n)^3)\n// space complexity: O(1)\n// Authors:\n// [Taj](https://github.com/tjgurwara99)\n// [Rak](https://github.com/raklaptudirm)\n\npackage prime\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/TheAlgorithms/Go/math/modular\"\n)\n\n// formatNum accepts a number and returns the\n// odd number d such that num = 2^s * d + 1\nfunc formatNum(num int64) (d int64, s int64) {\n\td = num - 1\n\tfor num%2 == 0 {\n\t\td /= 2\n\t\ts++\n\t}\n\treturn\n}\n\n// isTrivial checks if num's primality is easy to determine.\n// If it is, it returns true and num's primality. Otherwise\n// it returns false and false.\nfunc isTrivial(num int64) (prime bool, trivial bool) {\n\tif num <= 4 {\n\t\t// 2 and 3 are primes\n\t\tprime = num == 2 || num == 3\n\t\ttrivial = true\n\t} else {\n\t\tprime = false\n\t\t// number is trivial prime if\n\t\t// it is divisible by 2\n\t\ttrivial = num%2 == 0\n\t}\n\n\treturn\n}\n\n// MillerTest tests whether num is a strong probable prime to a witness.\n// Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s\nfunc MillerTest(num, witness int64) (bool, error) {\n\td, _ := formatNum(num)\n\tres, err := modular.Exponentiation(witness, d, num)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// miller conditions checks\n\tif res == 1 || res == num-1 {\n\t\treturn true, nil\n\t}\n\n\tfor d != num-1 {\n\t\tres = (res * res) % num\n\t\td *= 2\n\t\tif res == 1 {\n\t\t\treturn false, nil\n\t\t}\n\t\tif res == num-1 {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n\n// MillerRandomTest This is the intermediate step that repeats within the\n// miller rabin primality test for better probabilitic chances of\n// receiving the correct result with random witnesses.\nfunc MillerRandomTest(num int64) (bool, error) {\n\trandom := rand.Int63n(num-2) + 2\n\treturn MillerTest(num, random)\n}\n\n// MillerTestMultiple is like MillerTest but runs the test for multiple\n// witnesses.\nfunc MillerTestMultiple(num int64, witnesses ...int64) (bool, error) {\n\tfor _, witness := range witnesses {\n\t\tprime, err := MillerTest(num, witness)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif !prime {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}\n\n// MillerRabinProbabilistic is a probabilistic test for primality\n// of an integer based of the algorithm devised by Miller and Rabin.\nfunc MillerRabinProbabilistic(num, rounds int64) (bool, error) {\n\tif prime, trivial := isTrivial(num); trivial {\n\t\t// num is a trivial number\n\t\treturn prime, nil\n\t}\n\n\tfor i := int64(0); i < rounds; i++ {\n\t\tval, err := MillerRandomTest(num)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !val {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\n// MillerRabinDeterministic is a Deterministic version of the Miller-Rabin\n// test, which returns correct results for all valid int64 numbers.\nfunc MillerRabinDeterministic(num int64) (bool, error) {\n\tif prime, trivial := isTrivial(num); trivial {\n\t\t// num is a trivial number\n\t\treturn prime, nil\n\t}\n\n\tswitch {\n\tcase num < 2047:\n\t\t// witness 2 can determine the primality of any number less than 2047\n\t\treturn MillerTest(num, 2)\n\tcase num < 1_373_653:\n\t\t// witnesses 2 and 3 can determine the primality\n\t\t// of any number less than 1,373,653\n\t\treturn MillerTestMultiple(num, 2, 3)\n\tcase num < 9_080_191:\n\t\t// witnesses 31 and 73 can determine the primality\n\t\t// of any number less than 9,080,191\n\t\treturn MillerTestMultiple(num, 31, 73)\n\tcase num < 25_326_001:\n\t\t// witnesses 2, 3, and 5 can determine the\n\t\t// primality of any number less than 25,326,001\n\t\treturn MillerTestMultiple(num, 2, 3, 5)\n\tcase num < 1_122_004_669_633:\n\t\t// witnesses 2, 13, 23, and 1,662,803 can determine the\n\t\t// primality of any number less than 1,122,004,669,633\n\t\treturn MillerTestMultiple(num, 2, 13, 23, 1_662_803)\n\tcase num < 2_152_302_898_747:\n\t\t// witnesses 2, 3, 5, 7, and 11 can determine the primality\n\t\t// of any number less than 2,152,302,898,747\n\t\treturn MillerTestMultiple(num, 2, 3, 5, 7, 11)\n\tcase num < 341_550_071_728_321:\n\t\t// witnesses 2, 3, 5, 7, 11, 13, and 17 can determine the\n\t\t// primality of any number less than 341,550,071,728,321\n\t\treturn MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17)\n\tdefault:\n\t\t// witnesses 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37 can determine\n\t\t// the primality of any number less than 318,665,857,834,031,151,167,461\n\t\t// which is well above the max int64 9,223,372,036,854,775,807\n\t\treturn MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37)\n\t}\n}\n"
  },
  {
    "path": "math/prime/prime_test.go",
    "content": "package prime\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar primeList = []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127}\nvar testLimit = 127\n\ntype primalityTest func(int64) bool\n\nfunc primalityTestTestingHelper(t *testing.T, name string, f primalityTest) {\n\tarrayIndex := 0\n\tfor i := 1; i <= testLimit; i++ {\n\t\tisPrime := i == primeList[arrayIndex]\n\n\t\ttestName := fmt.Sprintf(\"%s(%d)\", name, i)\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\tresult := f(int64(i))\n\n\t\t\tif isPrime {\n\t\t\t\tarrayIndex++\n\t\t\t}\n\n\t\t\tif result != isPrime {\n\t\t\t\tt.Errorf(\"%d: %s function returned %v\\n\", i, name, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc primalityTestBenchmarkHelper(b *testing.B, f primalityTest) {\n\tfor i := 0; i < b.N; i++ {\n\t\tf(104729)\n\t}\n}\n\n// Miller-Rabin Probabilistic test\n\nfunc millerRabinProbabilisticTester(n int64) bool {\n\tresult, err := MillerRabinProbabilistic(n, 40)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn result\n}\n\nfunc TestMillerRabinProbabilistic(t *testing.T) {\n\tprimalityTestTestingHelper(t, \"Miller-Rabin Probabilistic\", millerRabinProbabilisticTester)\n}\n\nfunc BenchmarkMillerRabinProbabilistic(b *testing.B) {\n\tprimalityTestBenchmarkHelper(b, millerRabinProbabilisticTester)\n}\n\n// Miller-Rabin deterministic test\n\nfunc millerRabinDeterministicTester(n int64) bool {\n\tresult, err := MillerRabinDeterministic(n)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn result\n}\n\nfunc TestMillerRabinDeterministic(t *testing.T) {\n\tprimalityTestTestingHelper(t, \"Miller-Rabin Deterministic\", millerRabinDeterministicTester)\n}\n\nfunc BenchmarkMillerRabinDeterministic(b *testing.B) {\n\tprimalityTestBenchmarkHelper(b, millerRabinDeterministicTester)\n}\n\n// Trial Division test\n\nfunc TestTrialDivision(t *testing.T) {\n\tprimalityTestTestingHelper(t, \"Trial Division\", TrialDivision)\n}\n\nfunc BenchmarkTrialDivision(b *testing.B) {\n\tprimalityTestBenchmarkHelper(b, TrialDivision)\n}\n\n// Trial Division (optimized)\n\nfunc TestOptimizedTrialDivision(t *testing.T) {\n\tprimalityTestTestingHelper(t, \"Trial Division (optimized)\", OptimizedTrialDivision)\n}\n\nfunc BenchmarkOptimizedTrialDivision(b *testing.B) {\n\tprimalityTestBenchmarkHelper(b, OptimizedTrialDivision)\n}\n"
  },
  {
    "path": "math/prime/primecheck.go",
    "content": "package prime\n\n// A primality test is an algorithm for determining whether an input number is prime. Among other\n// fields of mathematics, it is used for cryptography. Unlike integer factorization, primality\n// tests do not generally give prime factors, only stating whether the input number is prime or not.\n// time complexity: O(sqrt(n))\n// space complexity: O(1)\n// Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test\n\n// TrialDivision tests whether a number is prime by trying to divide it by the numbers less than it.\nfunc TrialDivision(n int64) bool {\n\tif n < 2 {\n\t\treturn false\n\t}\n\n\tfor i := int64(2); i < n; i++ {\n\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// OptimizedTrialDivision checks primality of an integer using an optimized trial division method.\n// The optimizations include not checking divisibility by the even numbers and only checking up to\n// the square root of the given number.\nfunc OptimizedTrialDivision(n int64) bool {\n\t// 0 and 1 are not prime\n\tif n < 2 {\n\t\treturn false\n\t}\n\n\t// 2 and 3 are prime\n\tif n < 4 {\n\t\treturn true\n\t}\n\n\t// all numbers divisible by 2 except 2 are not prime\n\tif n%2 == 0 {\n\t\treturn false\n\t}\n\n\tfor i := int64(3); i*i <= n; i += 2 {\n\t\tif n%i == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "math/prime/primefactorization.go",
    "content": "// primefactorization.go\n// description: Prime factorization of a number\n// time complexity: O(sqrt(n))\n// space complexity: O(sqrt(n))\n\npackage prime\n\n// Factorize is a function that computes the exponents\n// of each prime in the prime factorization of n\nfunc Factorize(n int64) map[int64]int64 {\n\tresult := make(map[int64]int64)\n\n\tfor i := int64(2); i*i <= n; i += 1 {\n\t\tfor {\n\t\t\tif n%i != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tresult[i] += 1\n\t\t\tn /= i\n\t\t}\n\n\t}\n\tif n > 1 {\n\t\tresult[n] += 1\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "math/prime/primefactorization_test.go",
    "content": "package prime\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestFactorize(t *testing.T) {\n\tvar tests = []struct {\n\t\tn        int64\n\t\texpected map[int64]int64\n\t}{\n\t\t{4, map[int64]int64{2: 2}},\n\t\t{5, map[int64]int64{5: 1}},\n\t\t{7, map[int64]int64{7: 1}},\n\t\t{10, map[int64]int64{2: 1, 5: 1}},\n\t\t{999, map[int64]int64{3: 3, 37: 1}},\n\t\t{999999999999878, map[int64]int64{2: 1, 19: 1, 26315789473681: 1}},\n\t}\n\tfor _, test := range tests {\n\t\tresult := Factorize(test.n)\n\t\tt.Log(test.n, \" \", result)\n\t\tif !reflect.DeepEqual(result, test.expected) {\n\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.expected, result)\n\t\t}\n\t}\n}\n\nfunc BenchmarkFactorize(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tFactorize(1000000007)\n\t}\n}\n"
  },
  {
    "path": "math/prime/sieve.go",
    "content": "// sieve.go\n// description: Algorithms for generating prime numbers efficiently\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see sieve_test.go\n\npackage prime\n\n// Generate generates the sequence of integers starting at 2 and sends it to the channel `ch`\nfunc GenerateChannel(ch chan<- int) {\n\tfor i := 2; ; i++ {\n\t\tch <- i\n\t}\n}\n\n// Sieve Sieving the numbers that are not prime from the channel - basically removing them from the channels\nfunc Sieve(in <-chan int, out chan<- int, prime int) {\n\tfor {\n\t\ti := <-in\n\t\tif i%prime != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n}\n\n// Generate returns a int slice of prime numbers up to the limit\nfunc Generate(limit int) []int {\n\tvar primes []int\n\n\tch := make(chan int)\n\tgo GenerateChannel(ch)\n\n\tfor i := 0; i < limit; i++ {\n\t\tprimes = append(primes, <-ch)\n\t\tch1 := make(chan int)\n\t\tgo Sieve(ch, ch1, primes[i])\n\t\tch = ch1\n\t}\n\n\treturn primes\n}\n"
  },
  {
    "path": "math/prime/sieve2.go",
    "content": "/* sieve2.go - Sieve of Eratosthenes\n * Algorithm to generate prime numbers up to a limit\n * time complexity: O(n log log n)\n * space complexity: O(n)\n * Author: ddaniel27\n */\npackage prime\n\nfunc SieveEratosthenes(limit int) []int {\n\tprimes := make([]int, 0)\n\tsieve := make([]int, limit+1) // make a slice of size limit+1\n\n\tfor i := 2; i <= limit; i++ {\n\t\tif sieve[i] == 0 { // if the number is not marked as composite\n\t\t\tprimes = append(primes, i)           // add it to the list of primes\n\t\t\tfor j := i * i; j <= limit; j += i { // mark all multiples of i as composite\n\t\t\t\tsieve[j] = 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn primes\n}\n"
  },
  {
    "path": "math/prime/sieve2_test.go",
    "content": "package prime_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/prime\"\n)\n\nfunc TestSieveEratosthenes(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tlimit int\n\t\twant  []int\n\t}{\n\t\t{\n\t\t\tname:  \"First 10 primes test\",\n\t\t\tlimit: 30,\n\t\t\twant:  []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29},\n\t\t},\n\t\t{\n\t\t\tname:  \"First 20 primes test\",\n\t\t\tlimit: 71,\n\t\t\twant:  []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := prime.SieveEratosthenes(tt.limit)\n\n\t\t\tif !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"SieveEratosthenes() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkSieveEratosthenes(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = prime.SieveEratosthenes(10)\n\t}\n}\n"
  },
  {
    "path": "math/prime/sieve_test.go",
    "content": "// sieve_test.go\n// description: Testing all the algorithms related to the generation of prime numbers in sieve.go\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see sieve.go\n\npackage prime\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSieve(t *testing.T) {\n\tfirstTenPrimes := [10]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}\n\n\tt.Run(\"First 10 primes test\", func(t *testing.T) {\n\t\tvar testTenPrimes [10]int\n\n\t\tch := make(chan int)\n\t\tgo GenerateChannel(ch)\n\n\t\tfor i := 0; i < 10; i++ {\n\t\t\ttestTenPrimes[i] = <-ch\n\t\t\tch1 := make(chan int)\n\t\t\tgo Sieve(ch, ch1, testTenPrimes[i])\n\t\t\tch = ch1\n\t\t}\n\n\t\tif firstTenPrimes != testTenPrimes {\n\t\t\tt.Errorf(\"The first 10 primes do not match\")\n\t\t}\n\n\t})\n}\n\nfunc TestGeneratePrimes(t *testing.T) {\n\tfirstTenPrimes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}\n\n\tt.Run(\"Testing GeneratePrimes Function\", func(t *testing.T) {\n\t\ttestPrimes := Generate(10)\n\n\t\tif !reflect.DeepEqual(firstTenPrimes, testPrimes) {\n\t\t\tt.Fatal(\"GeneratePrimes function failed\")\n\t\t}\n\t})\n}\n\nfunc BenchmarkSieve10(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Generate(10)\n\t}\n}\n"
  },
  {
    "path": "math/prime/twin.go",
    "content": "// twin.go\n// description: Returns Twin Prime of n\n// details:\n// For any integer n, twin prime is (n + 2)\n// if and only if both n and (n + 2) both are prime\n// wikipedia: https://en.wikipedia.org/wiki/Twin_prime\n// time complexity: O(log n)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see twin_test.go\n\npackage prime\n\n// This function returns twin prime for given number\n// returns (n + 2) if both n and (n + 2) are prime\n// -1 otherwise\nfunc Twin(n int) (int, bool) {\n\tif OptimizedTrialDivision(int64(n)) && OptimizedTrialDivision(int64(n+2)) {\n\t\treturn n + 2, true\n\t}\n\treturn -1, false\n}\n"
  },
  {
    "path": "math/prime/twin_test.go",
    "content": "// twin_test.go\n// description: Returns Twin Prime of n\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see twin.go\n\npackage prime_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math/prime\"\n)\n\nfunc TestTwin(t *testing.T) {\n\tvar tests = []struct {\n\t\tname          string\n\t\tn             int\n\t\texpectedValue int\n\t\thasTwin       bool\n\t}{\n\t\t{\"n = 3, should return 5\", 3, 5, true},\n\t\t{\"n = 4, should return -1\", 4, -1, false},\n\t\t{\"n = 5, should return 7\", 5, 7, true},\n\t\t{\"n = 17, should return 19\", 17, 19, true},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult, hasTwin := prime.Twin(test.n)\n\t\t\tif result != test.expectedValue || hasTwin != test.hasTwin {\n\t\t\t\tt.Errorf(\"expected value: %v and %v, got: %v and %v\", test.expectedValue, test.hasTwin, result, hasTwin)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc BenchmarkTwin(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = prime.Twin(65536)\n\t}\n}\n"
  },
  {
    "path": "math/pronicnumber.go",
    "content": "// pronicnumber.go\n// description: Returns true if the number is pronic and false otherwise\n// details:\n//  Pronic number: For any integer n, if there exists integer m\n//  such that n = m * (m + 1) then n is called a pronic number.\n// wikipedia: https://en.wikipedia.org/wiki/Pronic_number\n// time complexity: O(1)\n// space complexity: O(1)\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see pronicnumber_test.go\n\npackage math\n\nimport \"math\"\n\n// PronicNumber returns true if argument passed to the function is pronic and false otherwise.\nfunc PronicNumber(n int) bool {\n\tif n < 0 || n%2 == 1 {\n\t\treturn false\n\t}\n\tx := int(math.Sqrt(float64(n)))\n\treturn n == x*(x+1)\n}\n"
  },
  {
    "path": "math/pronicnumber_test.go",
    "content": "// pronicnumber_test.go\n// author: Akshay Dubey (https://github.com/itsAkshayDubey)\n// see pronicnumber.go\n\npackage math_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/math\"\n)\n\nfunc TestPronicNumber(t *testing.T) {\n\tvar tests = []struct {\n\t\tname          string\n\t\tn             int\n\t\texpectedValue bool\n\t}{\n\t\t{\"-12 is not pronic\", -12, false},\n\t\t{\"0 is pronic\", 0, true},\n\t\t{\"1 is not pronic\", 1, false},\n\t\t{\"2 is pronic\", 2, true},\n\t\t{\"3 is not pronic\", 3, false},\n\t\t{\"4 is not pronic\", 4, false},\n\t\t{\"5 is not pronic\", 5, false},\n\t\t{\"6 is pronic\", 6, true},\n\t\t{\"7 is not pronic\", 7, false},\n\t\t{\"8 is not pronic\", 8, false},\n\t\t{\"9 is not pronic\", 9, false},\n\t\t{\"10 is not pronic\", 10, false},\n\t\t{\"11 is not pronic\", 11, false},\n\t\t{\"12 is pronic\", 12, true},\n\t\t{\"13 is not pronic\", 13, false},\n\t\t{\"14 is not pronic\", 14, false},\n\t\t{\"15 is not pronic\", 15, false},\n\t\t{\"16 is not pronic\", 16, false},\n\t\t{\"17 is not pronic\", 17, false},\n\t\t{\"18 is not pronic\", 18, false},\n\t\t{\"19 is not pronic\", 19, false},\n\t\t{\"20 is pronic\", 20, true},\n\t\t{\"21 is not pronic\", 21, false},\n\t\t{\"22 is not pronic\", 22, false},\n\t\t{\"23 is not pronic\", 23, false},\n\t\t{\"24 is not pronic\", 24, false},\n\t\t{\"25 is not pronic\", 25, false},\n\t\t{\"26 is not pronic\", 26, false},\n\t\t{\"27 is not pronic\", 27, false},\n\t\t{\"28 is not pronic\", 28, false},\n\t\t{\"29 is not pronic\", 29, false},\n\t\t{\"30 is pronic\", 30, true},\n\t\t{\"31 is not pronic\", 31, false},\n\t\t{\"32 is not pronic\", 32, false},\n\t\t{\"33 is not pronic\", 33, false},\n\t\t{\"34 is not pronic\", 34, false},\n\t\t{\"35 is not pronic\", 35, false},\n\t\t{\"36 is not pronic\", 36, false},\n\t\t{\"37 is not pronic\", 37, false},\n\t\t{\"38 is not pronic\", 38, false},\n\t\t{\"39 is not pronic\", 39, false},\n\t\t{\"40 is not pronic\", 40, false},\n\t\t{\"41 is not pronic\", 41, false},\n\t\t{\"42 is pronic\", 42, true},\n\t\t{\"43 is not pronic\", 43, false},\n\t\t{\"44 is not pronic\", 44, false},\n\t\t{\"45 is not pronic\", 45, false},\n\t\t{\"46 is not pronic\", 46, false},\n\t\t{\"47 is not pronic\", 47, false},\n\t\t{\"48 is not pronic\", 48, false},\n\t\t{\"49 is not pronic\", 49, false},\n\t\t{\"50 is not pronic\", 50, false},\n\t\t{\"51 is not pronic\", 51, false},\n\t\t{\"52 is not pronic\", 52, false},\n\t\t{\"53 is not pronic\", 53, false},\n\t\t{\"54 is not pronic\", 54, false},\n\t\t{\"55 is not pronic\", 55, false},\n\t\t{\"56 is pronic\", 56, true},\n\t\t{\"57 is not pronic\", 57, false},\n\t\t{\"58 is not pronic\", 58, false},\n\t\t{\"59 is not pronic\", 59, false},\n\t\t{\"60 is not pronic\", 60, false},\n\t\t{\"61 is not pronic\", 61, false},\n\t\t{\"62 is not pronic\", 62, false},\n\t\t{\"63 is not pronic\", 63, false},\n\t\t{\"64 is not pronic\", 64, false},\n\t\t{\"65 is not pronic\", 65, false},\n\t\t{\"66 is not pronic\", 66, false},\n\t\t{\"67 is not pronic\", 67, false},\n\t\t{\"68 is not pronic\", 68, false},\n\t\t{\"69 is not pronic\", 69, false},\n\t\t{\"70 is not pronic\", 70, false},\n\t\t{\"71 is not pronic\", 71, false},\n\t\t{\"72 is pronic\", 72, true},\n\t\t{\"73 is not pronic\", 73, false},\n\t\t{\"74 is not pronic\", 74, false},\n\t\t{\"75 is not pronic\", 75, false},\n\t\t{\"76 is not pronic\", 76, false},\n\t\t{\"77 is not pronic\", 77, false},\n\t\t{\"78 is not pronic\", 78, false},\n\t\t{\"79 is not pronic\", 79, false},\n\t\t{\"80 is not pronic\", 80, false},\n\t\t{\"81 is not pronic\", 81, false},\n\t\t{\"82 is not pronic\", 82, false},\n\t\t{\"83 is not pronic\", 83, false},\n\t\t{\"84 is not pronic\", 84, false},\n\t\t{\"85 is not pronic\", 85, false},\n\t\t{\"86 is not pronic\", 86, false},\n\t\t{\"87 is not pronic\", 87, false},\n\t\t{\"88 is not pronic\", 88, false},\n\t\t{\"89 is not pronic\", 89, false},\n\t\t{\"90 is pronic\", 90, true},\n\t\t{\"91 is not pronic\", 91, false},\n\t\t{\"92 is not pronic\", 92, false},\n\t\t{\"93 is not pronic\", 93, false},\n\t\t{\"94 is not pronic\", 94, false},\n\t\t{\"95 is not pronic\", 95, false},\n\t\t{\"96 is not pronic\", 96, false},\n\t\t{\"97 is not pronic\", 97, false},\n\t\t{\"98 is not pronic\", 98, false},\n\t\t{\"99 is not pronic\", 99, false},\n\t\t{\"100 is not pronic\", 100, false},\n\t\t{\"101 is not pronic\", 101, false},\n\t\t{\"102 is not pronic\", 102, false},\n\t\t{\"103 is not pronic\", 103, false},\n\t\t{\"104 is not pronic\", 104, false},\n\t\t{\"105 is not pronic\", 105, false},\n\t\t{\"106 is not pronic\", 106, false},\n\t\t{\"107 is not pronic\", 107, false},\n\t\t{\"108 is not pronic\", 108, false},\n\t\t{\"109 is not pronic\", 109, false},\n\t\t{\"110 is pronic\", 110, true},\n\t\t{\"111 is not pronic\", 111, false},\n\t\t{\"112 is not pronic\", 112, false},\n\t\t{\"113 is not pronic\", 113, false},\n\t\t{\"114 is not pronic\", 114, false},\n\t\t{\"115 is not pronic\", 115, false},\n\t\t{\"116 is not pronic\", 116, false},\n\t\t{\"117 is not pronic\", 117, false},\n\t\t{\"118 is not pronic\", 118, false},\n\t\t{\"119 is not pronic\", 119, false},\n\t\t{\"120 is not pronic\", 120, false},\n\t\t{\"121 is not pronic\", 121, false},\n\t\t{\"122 is not pronic\", 122, false},\n\t\t{\"123 is not pronic\", 123, false},\n\t\t{\"124 is not pronic\", 124, false},\n\t\t{\"125 is not pronic\", 125, false},\n\t\t{\"126 is not pronic\", 126, false},\n\t\t{\"127 is not pronic\", 127, false},\n\t\t{\"128 is not pronic\", 128, false},\n\t\t{\"129 is not pronic\", 129, false},\n\t\t{\"130 is not pronic\", 130, false},\n\t\t{\"131 is not pronic\", 131, false},\n\t\t{\"132 is pronic\", 132, true},\n\t\t{\"133 is not pronic\", 133, false},\n\t\t{\"134 is not pronic\", 134, false},\n\t\t{\"135 is not pronic\", 135, false},\n\t\t{\"136 is not pronic\", 136, false},\n\t\t{\"137 is not pronic\", 137, false},\n\t\t{\"138 is not pronic\", 138, false},\n\t\t{\"139 is not pronic\", 139, false},\n\t\t{\"140 is not pronic\", 140, false},\n\t\t{\"141 is not pronic\", 141, false},\n\t\t{\"142 is not pronic\", 142, false},\n\t\t{\"143 is not pronic\", 143, false},\n\t\t{\"144 is not pronic\", 144, false},\n\t\t{\"145 is not pronic\", 145, false},\n\t\t{\"146 is not pronic\", 146, false},\n\t\t{\"147 is not pronic\", 147, false},\n\t\t{\"148 is not pronic\", 148, false},\n\t\t{\"149 is not pronic\", 149, false},\n\t\t{\"150 is not pronic\", 150, false},\n\t\t{\"151 is not pronic\", 151, false},\n\t\t{\"152 is not pronic\", 152, false},\n\t\t{\"153 is not pronic\", 153, false},\n\t\t{\"154 is not pronic\", 154, false},\n\t\t{\"155 is not pronic\", 155, false},\n\t\t{\"156 is pronic\", 156, true},\n\t\t{\"157 is not pronic\", 157, false},\n\t\t{\"158 is not pronic\", 158, false},\n\t\t{\"159 is not pronic\", 159, false},\n\t\t{\"160 is not pronic\", 160, false},\n\t\t{\"161 is not pronic\", 161, false},\n\t\t{\"162 is not pronic\", 162, false},\n\t\t{\"163 is not pronic\", 163, false},\n\t\t{\"164 is not pronic\", 164, false},\n\t\t{\"165 is not pronic\", 165, false},\n\t\t{\"166 is not pronic\", 166, false},\n\t\t{\"167 is not pronic\", 167, false},\n\t\t{\"168 is not pronic\", 168, false},\n\t\t{\"169 is not pronic\", 169, false},\n\t\t{\"170 is not pronic\", 170, false},\n\t\t{\"171 is not pronic\", 171, false},\n\t\t{\"172 is not pronic\", 172, false},\n\t\t{\"173 is not pronic\", 173, false},\n\t\t{\"174 is not pronic\", 174, false},\n\t\t{\"175 is not pronic\", 175, false},\n\t\t{\"176 is not pronic\", 176, false},\n\t\t{\"177 is not pronic\", 177, false},\n\t\t{\"178 is not pronic\", 178, false},\n\t\t{\"179 is not pronic\", 179, false},\n\t\t{\"180 is not pronic\", 180, false},\n\t\t{\"181 is not pronic\", 181, false},\n\t\t{\"182 is pronic\", 182, true},\n\t\t{\"183 is not pronic\", 183, false},\n\t\t{\"184 is not pronic\", 184, false},\n\t\t{\"185 is not pronic\", 185, false},\n\t\t{\"186 is not pronic\", 186, false},\n\t\t{\"187 is not pronic\", 187, false},\n\t\t{\"188 is not pronic\", 188, false},\n\t\t{\"189 is not pronic\", 189, false},\n\t\t{\"190 is not pronic\", 190, false},\n\t\t{\"191 is not pronic\", 191, false},\n\t\t{\"192 is not pronic\", 192, false},\n\t\t{\"193 is not pronic\", 193, false},\n\t\t{\"194 is not pronic\", 194, false},\n\t\t{\"195 is not pronic\", 195, false},\n\t\t{\"196 is not pronic\", 196, false},\n\t\t{\"197 is not pronic\", 197, false},\n\t\t{\"198 is not pronic\", 198, false},\n\t\t{\"199 is not pronic\", 199, false},\n\t\t{\"200 is not pronic\", 200, false},\n\t\t{\"201 is not pronic\", 201, false},\n\t\t{\"202 is not pronic\", 202, false},\n\t\t{\"203 is not pronic\", 203, false},\n\t\t{\"204 is not pronic\", 204, false},\n\t\t{\"205 is not pronic\", 205, false},\n\t\t{\"206 is not pronic\", 206, false},\n\t\t{\"207 is not pronic\", 207, false},\n\t\t{\"208 is not pronic\", 208, false},\n\t\t{\"209 is not pronic\", 209, false},\n\t\t{\"210 is pronic\", 210, true},\n\t\t{\"211 is not pronic\", 211, false},\n\t\t{\"212 is not pronic\", 212, false},\n\t\t{\"213 is not pronic\", 213, false},\n\t\t{\"214 is not pronic\", 214, false},\n\t\t{\"215 is not pronic\", 215, false},\n\t\t{\"216 is not pronic\", 216, false},\n\t\t{\"217 is not pronic\", 217, false},\n\t\t{\"218 is not pronic\", 218, false},\n\t\t{\"219 is not pronic\", 219, false},\n\t\t{\"220 is not pronic\", 220, false},\n\t\t{\"221 is not pronic\", 221, false},\n\t\t{\"222 is not pronic\", 222, false},\n\t\t{\"223 is not pronic\", 223, false},\n\t\t{\"224 is not pronic\", 224, false},\n\t\t{\"225 is not pronic\", 225, false},\n\t\t{\"226 is not pronic\", 226, false},\n\t\t{\"227 is not pronic\", 227, false},\n\t\t{\"228 is not pronic\", 228, false},\n\t\t{\"229 is not pronic\", 229, false},\n\t\t{\"230 is not pronic\", 230, false},\n\t\t{\"231 is not pronic\", 231, false},\n\t\t{\"232 is not pronic\", 232, false},\n\t\t{\"233 is not pronic\", 233, false},\n\t\t{\"234 is not pronic\", 234, false},\n\t\t{\"235 is not pronic\", 235, false},\n\t\t{\"236 is not pronic\", 236, false},\n\t\t{\"237 is not pronic\", 237, false},\n\t\t{\"238 is not pronic\", 238, false},\n\t\t{\"239 is not pronic\", 239, false},\n\t\t{\"240 is pronic\", 240, true},\n\t\t{\"241 is not pronic\", 241, false},\n\t\t{\"242 is not pronic\", 242, false},\n\t\t{\"243 is not pronic\", 243, false},\n\t\t{\"244 is not pronic\", 244, false},\n\t\t{\"245 is not pronic\", 245, false},\n\t\t{\"246 is not pronic\", 246, false},\n\t\t{\"247 is not pronic\", 247, false},\n\t\t{\"248 is not pronic\", 248, false},\n\t\t{\"249 is not pronic\", 249, false},\n\t\t{\"250 is not pronic\", 250, false},\n\t\t{\"251 is not pronic\", 251, false},\n\t\t{\"252 is not pronic\", 252, false},\n\t\t{\"253 is not pronic\", 253, false},\n\t\t{\"254 is not pronic\", 254, false},\n\t\t{\"255 is not pronic\", 255, false},\n\t\t{\"256 is not pronic\", 256, false},\n\t\t{\"257 is not pronic\", 257, false},\n\t\t{\"258 is not pronic\", 258, false},\n\t\t{\"259 is not pronic\", 259, false},\n\t\t{\"260 is not pronic\", 260, false},\n\t\t{\"261 is not pronic\", 261, false},\n\t\t{\"262 is not pronic\", 262, false},\n\t\t{\"263 is not pronic\", 263, false},\n\t\t{\"264 is not pronic\", 264, false},\n\t\t{\"265 is not pronic\", 265, false},\n\t\t{\"266 is not pronic\", 266, false},\n\t\t{\"267 is not pronic\", 267, false},\n\t\t{\"268 is not pronic\", 268, false},\n\t\t{\"269 is not pronic\", 269, false},\n\t\t{\"270 is not pronic\", 270, false},\n\t\t{\"271 is not pronic\", 271, false},\n\t\t{\"272 is pronic\", 272, true},\n\t\t{\"273 is not pronic\", 273, false},\n\t\t{\"274 is not pronic\", 274, false},\n\t\t{\"275 is not pronic\", 275, false},\n\t\t{\"276 is not pronic\", 276, false},\n\t\t{\"277 is not pronic\", 277, false},\n\t\t{\"278 is not pronic\", 278, false},\n\t\t{\"279 is not pronic\", 279, false},\n\t\t{\"280 is not pronic\", 280, false},\n\t\t{\"281 is not pronic\", 281, false},\n\t\t{\"282 is not pronic\", 282, false},\n\t\t{\"283 is not pronic\", 283, false},\n\t\t{\"284 is not pronic\", 284, false},\n\t\t{\"285 is not pronic\", 285, false},\n\t\t{\"286 is not pronic\", 286, false},\n\t\t{\"287 is not pronic\", 287, false},\n\t\t{\"288 is not pronic\", 288, false},\n\t\t{\"289 is not pronic\", 289, false},\n\t\t{\"290 is not pronic\", 290, false},\n\t\t{\"291 is not pronic\", 291, false},\n\t\t{\"292 is not pronic\", 292, false},\n\t\t{\"293 is not pronic\", 293, false},\n\t\t{\"294 is not pronic\", 294, false},\n\t\t{\"295 is not pronic\", 295, false},\n\t\t{\"296 is not pronic\", 296, false},\n\t\t{\"297 is not pronic\", 297, false},\n\t\t{\"298 is not pronic\", 298, false},\n\t\t{\"299 is not pronic\", 299, false},\n\t\t{\"300 is not pronic\", 300, false},\n\t\t{\"301 is not pronic\", 301, false},\n\t\t{\"302 is not pronic\", 302, false},\n\t\t{\"303 is not pronic\", 303, false},\n\t\t{\"304 is not pronic\", 304, false},\n\t\t{\"305 is not pronic\", 305, false},\n\t\t{\"306 is pronic\", 306, true},\n\t\t{\"307 is not pronic\", 307, false},\n\t\t{\"308 is not pronic\", 308, false},\n\t\t{\"309 is not pronic\", 309, false},\n\t\t{\"310 is not pronic\", 310, false},\n\t\t{\"311 is not pronic\", 311, false},\n\t\t{\"312 is not pronic\", 312, false},\n\t\t{\"313 is not pronic\", 313, false},\n\t\t{\"314 is not pronic\", 314, false},\n\t\t{\"315 is not pronic\", 315, false},\n\t\t{\"316 is not pronic\", 316, false},\n\t\t{\"317 is not pronic\", 317, false},\n\t\t{\"318 is not pronic\", 318, false},\n\t\t{\"319 is not pronic\", 319, false},\n\t\t{\"320 is not pronic\", 320, false},\n\t\t{\"321 is not pronic\", 321, false},\n\t\t{\"322 is not pronic\", 322, false},\n\t\t{\"323 is not pronic\", 323, false},\n\t\t{\"324 is not pronic\", 324, false},\n\t\t{\"325 is not pronic\", 325, false},\n\t\t{\"326 is not pronic\", 326, false},\n\t\t{\"327 is not pronic\", 327, false},\n\t\t{\"328 is not pronic\", 328, false},\n\t\t{\"329 is not pronic\", 329, false},\n\t\t{\"330 is not pronic\", 330, false},\n\t\t{\"331 is not pronic\", 331, false},\n\t\t{\"332 is not pronic\", 332, false},\n\t\t{\"333 is not pronic\", 333, false},\n\t\t{\"334 is not pronic\", 334, false},\n\t\t{\"335 is not pronic\", 335, false},\n\t\t{\"336 is not pronic\", 336, false},\n\t\t{\"337 is not pronic\", 337, false},\n\t\t{\"338 is not pronic\", 338, false},\n\t\t{\"339 is not pronic\", 339, false},\n\t\t{\"340 is not pronic\", 340, false},\n\t\t{\"341 is not pronic\", 341, false},\n\t\t{\"342 is pronic\", 342, true},\n\t\t{\"343 is not pronic\", 343, false},\n\t\t{\"344 is not pronic\", 344, false},\n\t\t{\"345 is not pronic\", 345, false},\n\t\t{\"346 is not pronic\", 346, false},\n\t\t{\"347 is not pronic\", 347, false},\n\t\t{\"348 is not pronic\", 348, false},\n\t\t{\"349 is not pronic\", 349, false},\n\t\t{\"350 is not pronic\", 350, false},\n\t\t{\"351 is not pronic\", 351, false},\n\t\t{\"352 is not pronic\", 352, false},\n\t\t{\"353 is not pronic\", 353, false},\n\t\t{\"354 is not pronic\", 354, false},\n\t\t{\"355 is not pronic\", 355, false},\n\t\t{\"356 is not pronic\", 356, false},\n\t\t{\"357 is not pronic\", 357, false},\n\t\t{\"358 is not pronic\", 358, false},\n\t\t{\"359 is not pronic\", 359, false},\n\t\t{\"360 is not pronic\", 360, false},\n\t\t{\"361 is not pronic\", 361, false},\n\t\t{\"362 is not pronic\", 362, false},\n\t\t{\"363 is not pronic\", 363, false},\n\t\t{\"364 is not pronic\", 364, false},\n\t\t{\"365 is not pronic\", 365, false},\n\t\t{\"366 is not pronic\", 366, false},\n\t\t{\"367 is not pronic\", 367, false},\n\t\t{\"368 is not pronic\", 368, false},\n\t\t{\"369 is not pronic\", 369, false},\n\t\t{\"370 is not pronic\", 370, false},\n\t\t{\"371 is not pronic\", 371, false},\n\t\t{\"372 is not pronic\", 372, false},\n\t\t{\"373 is not pronic\", 373, false},\n\t\t{\"374 is not pronic\", 374, false},\n\t\t{\"375 is not pronic\", 375, false},\n\t\t{\"376 is not pronic\", 376, false},\n\t\t{\"377 is not pronic\", 377, false},\n\t\t{\"378 is not pronic\", 378, false},\n\t\t{\"379 is not pronic\", 379, false},\n\t\t{\"380 is pronic\", 380, true},\n\t\t{\"381 is not pronic\", 381, false},\n\t\t{\"382 is not pronic\", 382, false},\n\t\t{\"383 is not pronic\", 383, false},\n\t\t{\"384 is not pronic\", 384, false},\n\t\t{\"385 is not pronic\", 385, false},\n\t\t{\"386 is not pronic\", 386, false},\n\t\t{\"387 is not pronic\", 387, false},\n\t\t{\"388 is not pronic\", 388, false},\n\t\t{\"389 is not pronic\", 389, false},\n\t\t{\"390 is not pronic\", 390, false},\n\t\t{\"391 is not pronic\", 391, false},\n\t\t{\"392 is not pronic\", 392, false},\n\t\t{\"393 is not pronic\", 393, false},\n\t\t{\"394 is not pronic\", 394, false},\n\t\t{\"395 is not pronic\", 395, false},\n\t\t{\"396 is not pronic\", 396, false},\n\t\t{\"397 is not pronic\", 397, false},\n\t\t{\"398 is not pronic\", 398, false},\n\t\t{\"399 is not pronic\", 399, false},\n\t\t{\"400 is not pronic\", 400, false},\n\t\t{\"2147441940 is pronic\", 2147441940, true},\n\t\t{\"9223372033963249500 is pronic\", 9223372033963249500, true},\n\t\t{\"9223372033963249664 is not pronic\", 9223372033963249664, false},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresult := math.PronicNumber(test.n)\n\t\t\tif result != test.expectedValue {\n\t\t\t\tt.Errorf(\"expected value: %v, got: %v\", test.expectedValue, result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc BenchmarkPronicNumber(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tmath.PronicNumber(65536)\n\t}\n}\n"
  },
  {
    "path": "math/pythagoras/pythagoras.go",
    "content": "package pythagoras\n\nimport (\n\t\"math\"\n)\n\n// Vector defines a tuple with 3 values in 3d-space\ntype Vector struct {\n\tx float64\n\ty float64\n\tz float64\n}\n\n// Distance calculates the distance between to vectors with the   Pythagoras theorem\nfunc Distance(a, b Vector) float64 {\n\tres := math.Pow(b.x-a.x, 2.0) + math.Pow(b.y-a.y, 2.0) + math.Pow(b.z-a.z, 2.0)\n\treturn math.Sqrt(res)\n}\n"
  },
  {
    "path": "math/pythagoras/pythagoras_test.go",
    "content": "package pythagoras\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// TableDrivenTest for checking multiple values against our Test Function\nvar distanceTest = []struct {\n\tname string\n\tv1   Vector\n\tv2   Vector\n\tres  float64\n}{\n\t{\"random negative vector\", Vector{2, -1, 7}, Vector{1, -3, 5}, 3.0},\n\t{\"random wide vectors\", Vector{4, 10, 9}, Vector{4, 3, 5}, 8.06},\n\t{\"random wide vectors\", Vector{8, 5, 5}, Vector{1, 1, 12}, 10.67},\n\t{\"random short vectors\", Vector{1, 1, 1}, Vector{2, 2, 2}, 1.73},\n}\n\n// TestDistance tests the Function Distance with 2 vectors\nfunc TestDistance(t *testing.T) {\n\tt.Parallel() // marks TestDistance as capable of running in parallel with other tests\n\tfor _, tt := range distanceTest {\n\t\ttt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tres := Distance(tt.v1, tt.v2)           // Calculate result for\n\t\t\troundRes := (math.Floor(res*100) / 100) // Round to 2 decimal places because we can't compare an infinite number of places\n\t\t\t// Check result\n\t\t\tif roundRes != tt.res {\n\t\t\t\tt.Errorf(\"Distance(%v, %v) = %f, expected %f\",\n\t\t\t\t\ttt.v1, tt.v2, roundRes, tt.res)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "math/sin.go",
    "content": "// author(s) [red_byte](https://github.com/i-redbyte)\n// see sin_test.go\n\npackage math\n\nimport \"math\"\n\n// Sin returns the sine of the radian argument x. [See more](https://en.wikipedia.org/wiki/Sine_and_cosine)\nfunc Sin(x float64) float64 {\n\treturn Cos((math.Pi / 2) - x)\n}\n"
  },
  {
    "path": "math/sin_test.go",
    "content": "package math_test\n\nimport (\n\talgmath \"github.com/TheAlgorithms/Go/math\"\n\tstdmath \"math\"\n\t\"testing\"\n)\n\nfunc TestSin(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tn    float64\n\t\twant float64\n\t}{\n\t\t{\"sin(0)\", 0, 0},\n\t\t{\"sin(3π/2)\", (3 * stdmath.Pi) / 2, -1},\n\t\t{\"sin(π/2)\", stdmath.Pi / 2, 1},\n\t\t{\"sin(π/6)\", stdmath.Pi / 6, 0.5},\n\t\t{\"sin(90)\", 90, 0.893996663600558},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := algmath.Sin(test.n)\n\t\t\tif stdmath.Abs(got-test.want) >= epsilon {\n\t\t\t\tt.Errorf(\"Sin() = %v, want %v\", got, test.want)\n\t\t\t\tt.Errorf(\"MATH Sin() = %v\", stdmath.Sin(test.n))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkSin(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\talgmath.Sin(180)\n\t}\n}\n\n// BenchmarkMathSin is slower because the standard library `math.Sin` calculates a more accurate value.\nfunc BenchmarkMathSin(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tstdmath.Sin(180)\n\t}\n}\n"
  },
  {
    "path": "other/doc.go",
    "content": "// Package other is dedicated to algorithms that\n// do not quite fit into any of the other subpackages in this repository.\npackage other\n"
  },
  {
    "path": "other/maxsubarraysum/maxsubarraysum.go",
    "content": "/* O(n) solution, for calculating\nmaximum contiguous sum in the given array. */\n\n// Package maxsubarraysum is a package containing a solution to a common\n// problem of finding max contiguous sum within a array of ints.\npackage maxsubarraysum\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/max\"\n)\n\n// MaxSubarraySum returns the maximum subarray sum\nfunc MaxSubarraySum(array []int) int {\n\tvar currentMax int\n\tvar maxTillNow int\n\tif len(array) != 0 {\n\t\tcurrentMax = array[0]\n\t\tmaxTillNow = array[0]\n\t}\n\tfor _, v := range array {\n\t\tcurrentMax = max.Int(v, currentMax+v)\n\t\tmaxTillNow = max.Int(maxTillNow, currentMax)\n\t}\n\treturn maxTillNow\n}\n"
  },
  {
    "path": "other/maxsubarraysum/maxsubarraysum_test.go",
    "content": "package maxsubarraysum\n\nimport (\n\t\"testing\"\n)\n\nfunc TestMaxSubarraySum(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\tslice    []int\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tname:     \"Empty slice\",\n\t\t\tslice:    []int{},\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname:     \"Max is 0\",\n\t\t\tslice:    []int{0, -1, -2, -4, -5},\n\t\t\texpected: 0,\n\t\t},\n\t\t{\n\t\t\tname:     \"Max is -1\",\n\t\t\tslice:    []int{-1, -3, -2, -5, -7},\n\t\t\texpected: -1,\n\t\t},\n\t\t{\n\t\t\tname:     \"Max is 7\",\n\t\t\tslice:    []int{-2, -5, 6, 0, -2, 0, -3, 1, 0, 5, -6},\n\t\t\texpected: 7,\n\t\t},\n\t}\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif result := MaxSubarraySum(test.slice); result != test.expected {\n\t\t\t\tt.Fatalf(\"%s\\n\\tslice: %v, expected: %v, returned: %v\", test.name, test.slice, test.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "other/nested/nestedbrackets.go",
    "content": "// Package nested provides functions for testing\n// strings proper brackets nesting.\npackage nested\n\n// IsBalanced returns true if provided input string is properly nested.\n//\n// Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'.\n//\n// A sequence of brackets `s` is considered properly nested\n// if any of the following conditions are true:\n//   - `s` is empty;\n//   - `s` has the form (U) or [U] or {U} where U is a properly nested string;\n//   - `s` has the form VW where V and W are properly nested strings.\n//\n// For example, the string \"()()[()]\" is properly nested but \"[(()]\" is not.\n//\n// **Note** Providing characters other then brackets would return false,\n// despite brackets sequence in the string. Make sure to filter\n// input before usage.\n// time complexity: O(n)\n// space complexity: O(n)\n\nfunc IsBalanced(input string) bool {\n\tif len(input) == 0 {\n\t\treturn true\n\t}\n\n\tif len(input)%2 != 0 {\n\t\treturn false\n\t}\n\n\t// Brackets such as '{', '[', '(' are valid UTF-8 characters,\n\t// which means that only one byte is required to code them,\n\t// so can be stored as bytes.\n\tvar stack []byte\n\n\tfor i := 0; i < len(input); i++ {\n\t\tif input[i] == '(' || input[i] == '{' || input[i] == '[' {\n\t\t\tstack = append(stack, input[i])\n\t\t} else {\n\t\t\tif len(stack) > 0 {\n\t\t\t\tpair := string(stack[len(stack)-1]) + string(input[i])\n\t\t\t\tstack = stack[:len(stack)-1]\n\n\t\t\t\tif pair != \"[]\" && pair != \"{}\" && pair != \"()\" {\n\t\t\t\t\t// This means that two types of brackets has\n\t\t\t\t\t// been mixed together, for example \"([)]\",\n\t\t\t\t\t// which makes seuqence invalid by definition.\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// This means that closing bracket is encountered\n\t\t\t\t// before opening one, which makes all sequence\n\t\t\t\t// invalid by definition.\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\t// If sequence is properly nested, all elements in stack\n\t// has been paired with closing elements. If even one\n\t// element has not been paired with a closing bracket,\n\t// means that sequence is invalid by definition.\n\treturn len(stack) == 0\n}\n"
  },
  {
    "path": "other/nested/nestedbrackets_test.go",
    "content": "package nested\n\nimport (\n\t\"testing\"\n)\n\nfunc TestIsBalancedSimple(t *testing.T) {\n\tinput := \"{[()]}\"\n\n\tgot := IsBalanced(input)\n\twant := true\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc TestIsBalancedFalty(t *testing.T) {\n\tinput := \"{([()]}\"\n\n\tgot := IsBalanced(input)\n\twant := false\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc TestIsBalancedHandlesEmpty(t *testing.T) {\n\tinput := \"\"\n\n\tgot := IsBalanced(input)\n\twant := true\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc TestIsBalancedHandlesOneChar(t *testing.T) {\n\tinput := \"{\"\n\n\tgot := IsBalanced(input)\n\twant := false\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc TestIsBalancedHandlesNonBracketsCorrectly(t *testing.T) {\n\tinput := \"aaaa\"\n\n\tgot := IsBalanced(input)\n\twant := false\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc TestIsBalancedHandlesOrdering(t *testing.T) {\n\tinput := \"([)]\"\n\n\tgot := IsBalanced(input)\n\twant := false\n\n\tif got != want {\n\t\tt.Errorf(\"\\nInput: %s\\nGot: %v\\nWant: %v\\n\", input, got, want)\n\t}\n}\n\nfunc BenchmarkIsBalanced(b *testing.B) {\n\tinput := \"{[()]}\"\n\n\tfor i := 0; i < b.N; i++ {\n\t\tIsBalanced(input)\n\t}\n}\n"
  },
  {
    "path": "other/other_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage other\n"
  },
  {
    "path": "other/password/generator.go",
    "content": "// This program generates a password from a list of possible chars\n// You must provide a minimum length and a maximum length\n// This length is not fixed if you generate multiple passwords for the same range\n\n// Package password contains functions to help generate random passwords\n// time complexity: O(n)\n// space complexity: O(n)\n\npackage password\n\nimport (\n\t\"crypto/rand\"\n\t\"io\"\n\t\"math/big\"\n)\n\n// Generate returns a newly generated password\nfunc Generate(minLength int, maxLength int) string {\n\tvar chars = []byte(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]`~\")\n\n\tlength, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))\n\tif err != nil {\n\t\tpanic(err) // handle this gracefully\n\t}\n\tlength.Add(length, big.NewInt(int64(minLength)))\n\n\tintLength := int(length.Int64())\n\n\tnewPassword := make([]byte, intLength)\n\trandomData := make([]byte, intLength+intLength/4)\n\tcharLen := byte(len(chars))\n\tmaxrb := byte(256 - (256 % len(chars)))\n\ti := 0\n\tfor {\n\t\tif _, err := io.ReadFull(rand.Reader, randomData); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, c := range randomData {\n\t\t\tif c >= maxrb {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewPassword[i] = chars[c%charLen]\n\t\t\ti++\n\t\t\tif i == intLength {\n\t\t\t\treturn string(newPassword)\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_1/problem1.go",
    "content": "/**\n * Problem 1 - Multiples of 3 and 5\n *\n * @see {@link https://projecteuler.net/problem=1}\n *\n * If we list all the natural numbers below 10 that are multiples of 3 or 5,\n * we get 3, 5, 6 and 9. The sum of these multiples is 23.\n * Find the sum of all the multiples of 3 or 5 below 1000.\n *\n * @author ddaniel27\n */\npackage problem1\n\nfunc Problem1(n uint) uint {\n\tsum := uint(0)\n\n\tfor i := uint(1); i < n; i++ {\n\t\tif i%3 == 0 || i%5 == 0 {\n\t\t\tsum += i\n\t\t}\n\t}\n\n\treturn sum\n}\n"
  },
  {
    "path": "project_euler/problem_1/problem1_test.go",
    "content": "package problem1\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem1_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tthreshold uint\n\t\twant      uint\n\t}{\n\t\t{\n\t\t\tname:      \"Testcase 1 - threshold 10\",\n\t\t\tthreshold: 10,\n\t\t\twant:      23,\n\t\t},\n\t\t{\n\t\t\tname:      \"Testcase 2 - threshold 100\",\n\t\t\tthreshold: 100,\n\t\t\twant:      2318,\n\t\t},\n\t\t{\n\t\t\tname:      \"Testcase 3 - threshold 1000\",\n\t\t\tthreshold: 1000,\n\t\t\twant:      233168,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem1(tt.threshold)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem1() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem1(1000)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_10/problem10.go",
    "content": "/**\n* Problem 10 - Summation of primes\n* @see {@link https://projecteuler.net/problem=10}\n*\n* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n* Find the sum of all the primes below two million.\n*\n* @author ddaniel27\n */\npackage problem10\n\nimport \"github.com/TheAlgorithms/Go/math/prime\"\n\nfunc Problem10(n int) uint {\n\tsum := uint(0)\n\tsieve := prime.SieveEratosthenes(n)\n\n\tfor _, v := range sieve {\n\t\tsum += uint(v)\n\t}\n\n\treturn sum\n}\n"
  },
  {
    "path": "project_euler/problem_10/problem10_test.go",
    "content": "package problem10\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem10_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput int\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 10\",\n\t\t\tinput: 10,\n\t\t\twant:  17,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 2000000\",\n\t\t\tinput: 2000000,\n\t\t\twant:  142913828922,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem10(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem10() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem10(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem10(2000000)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_11/problem11.go",
    "content": "/**\n* Problem 11 - Largest product in a grid\n* @see {@link https://projecteuler.net/problem=11}\n*\n* In the 20×20 grid below, four numbers along a diagonal line have been marked in red.\n*\n* The product of these numbers is 26 × 63 × 78 × 14 = 1788696.\n*\n* What is the greatest product of four adjacent numbers in the same direction\n* (up, down, left, right, or diagonally) in the 20×20 grid?\n*\n* @author ddaniel27\n */\npackage problem11\n\nvar grid = [20][20]uint{\n\t{8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8},\n\t{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0},\n\t{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65},\n\t{52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91},\n\t{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},\n\t{24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},\n\t{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},\n\t{67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21},\n\t{24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},\n\t{21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95},\n\t{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92},\n\t{16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57},\n\t{86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},\n\t{19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40},\n\t{4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},\n\t{88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},\n\t{4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36},\n\t{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16},\n\t{20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54},\n\t{1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48},\n}\n\nfunc Problem11() uint {\n\tmax := uint(0)\n\n\tfor i := 0; i < 20; i++ {\n\t\tfor j := 0; j < 20; j++ {\n\n\t\t\t// Vertical\n\t\t\tif i+3 < 20 {\n\t\t\t\tproduct := grid[i][j] * grid[i+1][j] * grid[i+2][j] * grid[i+3][j]\n\t\t\t\tif product > max {\n\t\t\t\t\tmax = product\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Horizontal\n\t\t\tif j+3 < 20 {\n\t\t\t\tproduct := grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3]\n\t\t\t\tif product > max {\n\t\t\t\t\tmax = product\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif i+3 < 20 && j+3 < 20 {\n\t\t\t\t// Diagonal\n\t\t\t\tproduct := grid[i][j] * grid[i+1][j+1] * grid[i+2][j+2] * grid[i+3][j+3]\n\t\t\t\tif product > max {\n\t\t\t\t\tmax = product\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif i+3 < 20 && j-3 >= 0 {\n\t\t\t\t// Diagonal\n\t\t\t\tproduct := grid[i][j] * grid[i+1][j-1] * grid[i+2][j-2] * grid[i+3][j-3]\n\t\t\t\tif product > max {\n\t\t\t\t\tmax = product\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn max\n}\n"
  },
  {
    "path": "project_euler/problem_11/problem11_test.go",
    "content": "package problem11\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem11_Func(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\texpected uint\n\t}{\n\t\t{\"Test Case 1\", 70600674},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Problem11()\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected: %v, but got %v\", tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmark\nfunc BenchmarkProblem11_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem11()\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_12/problem12.go",
    "content": "/**\n* Problem 12 - Highly divisible triangular number\n* @see {@link https://projecteuler.net/problem=12}\n*\n* The sequence of triangle numbers is generated by adding the natural numbers.\n* So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.\n* The first ten terms would be:\n*\n* 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n*\n* Let us list the factors of the first seven triangle numbers:\n*\n*  1: 1\n*  3: 1,3\n*  6: 1,2,3,6\n* 10: 1,2,5,10\n* 15: 1,3,5,15\n* 21: 1,3,7,21\n* 28: 1,2,4,7,14,28\n*\n* We can see that 28 is the first triangle number to have over five divisors.\n* What is the value of the first triangle number to have over five hundred divisors?\n*\n* @author ddaniel27\n */\npackage problem12\n\nfunc Problem12(limit uint) uint {\n\ttriangle := uint(0)\n\tfor i := uint(1); ; i++ {\n\t\ttriangle += i\n\t\tif numDivisors(triangle) >= limit {\n\t\t\treturn triangle\n\t\t}\n\t}\n}\n\nfunc numDivisors(n uint) uint {\n\tdivisors := uint(0)\n\tfor i := uint(1); i*i <= n; i++ {\n\t\tif n%i == 0 {\n\t\t\tdivisors += 2\n\t\t}\n\t}\n\treturn divisors\n}\n"
  },
  {
    "path": "project_euler/problem_12/problem12_test.go",
    "content": "package problem12\n\nimport \"testing\"\n\nfunc TestProblem12_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  uint\n\t}{\n\t\t{\"Test Case 1\", 6, 28},\n\t\t{\"Test Case 2\", 7, 36},\n\t\t{\"Test Case 3\", 11, 120},\n\t\t{\"Test Case 4\", 500, 76576500},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := Problem12(tt.input)\n\t\t\tif actual != tt.want {\n\t\t\t\tt.Errorf(\"Expected: %v, but got %v\", tt.want, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkProblem12_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem12(500)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_13/problem13.go",
    "content": "/**\n* Problem 13 - Large sum\n* @see {@link https://projecteuler.net/problem=13}\n*\n* Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.\n*\n* @author ddaniel27\n */\npackage problem13\n\nvar numbers = [100]string{\n\t\"37107287533902102798797998220837590246510135740250\",\n\t\"46376937677490009712648124896970078050417018260538\",\n\t\"74324986199524741059474233309513058123726617309629\",\n\t\"91942213363574161572522430563301811072406154908250\",\n\t\"23067588207539346171171980310421047513778063246676\",\n\t\"89261670696623633820136378418383684178734361726757\",\n\t\"28112879812849979408065481931592621691275889832738\",\n\t\"44274228917432520321923589422876796487670272189318\",\n\t\"47451445736001306439091167216856844588711603153276\",\n\t\"70386486105843025439939619828917593665686757934951\",\n\t\"62176457141856560629502157223196586755079324193331\",\n\t\"64906352462741904929101432445813822663347944758178\",\n\t\"92575867718337217661963751590579239728245598838407\",\n\t\"58203565325359399008402633568948830189458628227828\",\n\t\"80181199384826282014278194139940567587151170094390\",\n\t\"35398664372827112653829987240784473053190104293586\",\n\t\"86515506006295864861532075273371959191420517255829\",\n\t\"71693888707715466499115593487603532921714970056938\",\n\t\"54370070576826684624621495650076471787294438377604\",\n\t\"53282654108756828443191190634694037855217779295145\",\n\t\"36123272525000296071075082563815656710885258350721\",\n\t\"45876576172410976447339110607218265236877223636045\",\n\t\"17423706905851860660448207621209813287860733969412\",\n\t\"81142660418086830619328460811191061556940512689692\",\n\t\"51934325451728388641918047049293215058642563049483\",\n\t\"62467221648435076201727918039944693004732956340691\",\n\t\"15732444386908125794514089057706229429197107928209\",\n\t\"55037687525678773091862540744969844508330393682126\",\n\t\"18336384825330154686196124348767681297534375946515\",\n\t\"80386287592878490201521685554828717201219257766954\",\n\t\"78182833757993103614740356856449095527097864797581\",\n\t\"16726320100436897842553539920931837441497806860984\",\n\t\"48403098129077791799088218795327364475675590848030\",\n\t\"87086987551392711854517078544161852424320693150332\",\n\t\"59959406895756536782107074926966537676326235447210\",\n\t\"69793950679652694742597709739166693763042633987085\",\n\t\"41052684708299085211399427365734116182760315001271\",\n\t\"65378607361501080857009149939512557028198746004375\",\n\t\"35829035317434717326932123578154982629742552737307\",\n\t\"94953759765105305946966067683156574377167401875275\",\n\t\"88902802571733229619176668713819931811048770190271\",\n\t\"25267680276078003013678680992525463401061632866526\",\n\t\"36270218540497705585629946580636237993140746255962\",\n\t\"24074486908231174977792365466257246923322810917141\",\n\t\"91430288197103288597806669760892938638285025333403\",\n\t\"34413065578016127815921815005561868836468420090470\",\n\t\"23053081172816430487623791969842487255036638784583\",\n\t\"11487696932154902810424020138335124462181441773470\",\n\t\"63783299490636259666498587618221225225512486764533\",\n\t\"67720186971698544312419572409913959008952310058822\",\n\t\"95548255300263520781532296796249481641953868218774\",\n\t\"76085327132285723110424803456124867697064507995236\",\n\t\"37774242535411291684276865538926205024910326572967\",\n\t\"23701913275725675285653248258265463092207058596522\",\n\t\"29798860272258331913126375147341994889534765745501\",\n\t\"18495701454879288984856827726077713721403798879715\",\n\t\"38298203783031473527721580348144513491373226651381\",\n\t\"34829543829199918180278916522431027392251122869539\",\n\t\"40957953066405232632538044100059654939159879593635\",\n\t\"29746152185502371307642255121183693803580388584903\",\n\t\"41698116222072977186158236678424689157993532961922\",\n\t\"62467957194401269043877107275048102390895523597457\",\n\t\"23189706772547915061505504953922979530901129967519\",\n\t\"86188088225875314529584099251203829009407770775672\",\n\t\"11306739708304724483816533873502340845647058077308\",\n\t\"82959174767140363198008187129011875491310547126581\",\n\t\"97623331044818386269515456334926366572897563400500\",\n\t\"42846280183517070527831839425882145521227251250327\",\n\t\"55121603546981200581762165212827652751691296897789\",\n\t\"32238195734329339946437501907836945765883352399886\",\n\t\"75506164965184775180738168837861091527357929701337\",\n\t\"62177842752192623401942399639168044983993173312731\",\n\t\"32924185707147349566916674687634660915035914677504\",\n\t\"99518671430235219628894890102423325116913619626622\",\n\t\"73267460800591547471830798392868535206946944540724\",\n\t\"76841822524674417161514036427982273348055556214818\",\n\t\"97142617910342598647204516893989422179826088076852\",\n\t\"87783646182799346313767754307809363333018982642090\",\n\t\"10848802521674670883215120185883543223812876952786\",\n\t\"71329612474782464538636993009049310363619763878039\",\n\t\"62184073572399794223406235393808339651327408011116\",\n\t\"66627891981488087797941876876144230030984490851411\",\n\t\"60661826293682836764744779239180335110989069790714\",\n\t\"85786944089552990653640447425576083659976645795096\",\n\t\"66024396409905389607120198219976047599490197230297\",\n\t\"64913982680032973156037120041377903785566085089252\",\n\t\"16730939319872750275468906903707539413042652315011\",\n\t\"94809377245048795150954100921645863754710598436791\",\n\t\"78639167021187492431995700641917969777599028300699\",\n\t\"15368713711936614952811305876380278410754449733078\",\n\t\"40789923115535562561142322423255033685442488917353\",\n\t\"44889911501440648020369068063960672322193204149535\",\n\t\"41503128880339536053299340368006977710650566631954\",\n\t\"81234880673210146739058568557934581403627822703280\",\n\t\"82616570773948327592232845941706525094512325230608\",\n\t\"22918802058777319719839450180888072429661980811197\",\n\t\"77158542502016545090413245809786882778948721859617\",\n\t\"72107838435069186155435662884062257473692284509516\",\n\t\"20849603980134001723930671666823555245252804609722\",\n\t\"53503534226472524250874054075591789781264330331690\",\n}\n\nfunc Problem13() string {\n\tsum := \"0\"\n\n\tfor _, n := range numbers {\n\t\tsum = add(sum, n)\n\t}\n\n\treturn sum[:10]\n}\n\nfunc add(a, b string) string {\n\tif len(a) < len(b) {\n\t\ta, b = b, a\n\t}\n\n\tcarry := 0\n\tsum := make([]byte, len(a)+1)\n\n\tfor i := 0; i < len(a); i++ {\n\t\td := int(a[len(a)-1-i] - '0')\n\t\tif i < len(b) {\n\t\t\td += int(b[len(b)-1-i] - '0')\n\t\t}\n\t\td += carry\n\n\t\tsum[len(sum)-1-i] = byte(d%10) + '0'\n\t\tcarry = d / 10\n\t}\n\n\tif carry > 0 {\n\t\tsum[0] = byte(carry) + '0'\n\t} else {\n\t\tsum = sum[1:]\n\t}\n\n\treturn string(sum)\n}\n"
  },
  {
    "path": "project_euler/problem_13/problem13_test.go",
    "content": "package problem13\n\nimport \"testing\"\n\nfunc TestProblem13_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texpected string\n\t}{\n\t\t{\"Test Case 1\", \"5537376230\"},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := Problem13()\n\t\t\tif actual != tt.expected {\n\t\t\t\tt.Errorf(\"Expected: %v, but got %v\", tt.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkProblem13_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem13()\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_14/problem14.go",
    "content": "/**\n* Problem 14 - Longest Collatz sequence\n* @see {@link https://projecteuler.net/problem=14}\n*\n* The following iterative sequence is defined for the set of positive integers:\n* n → n/2 (n is even)\n* n → 3n + 1 (n is odd)\n*\n* Using the rule above and starting with 13, we generate the following sequence:\n* 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n*\n* Which starting number, under one million, produces the longest chain?\n*\n* NOTE: Once the chain starts the terms are allowed to go above one million.\n*\n* @author ddaniel27\n */\npackage problem14\n\ntype dict map[uint64]uint64\n\nvar dictionary = dict{\n\t1: 1,\n}\n\nfunc Problem14(limit uint64) uint64 {\n\tfor i := uint64(2); i <= limit; i++ {\n\t\tweightNextNode(i)\n\t}\n\n\tvar max, maxWeight uint64\n\tfor k, v := range dictionary {\n\t\tif v > maxWeight {\n\t\t\tmax = k\n\t\t\tmaxWeight = v\n\t\t}\n\t}\n\n\treturn max\n}\n\nfunc weightNextNode(current uint64) uint64 {\n\tvar next, weight uint64\n\tif current%2 == 0 {\n\t\tnext = current / 2\n\t} else {\n\t\tnext = (3 * current) + 1\n\t}\n\tif v, ok := dictionary[next]; !ok {\n\t\tweight = weightNextNode(next) + 1\n\t} else {\n\t\tweight = v + 1\n\t}\n\tdictionary[current] = weight\n\treturn weight\n}\n"
  },
  {
    "path": "project_euler/problem_14/problem14_test.go",
    "content": "package problem14\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem14_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint64\n\t\twant  uint64\n\t}{\n\t\t{\"Input 30\", 30, 27},\n\t\t{\"Input 1e6\", 1e6, 837799},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := Problem14(tt.input)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"Problem14() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem14_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem14(1e6)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_15/problem15.go",
    "content": "/**\n* Problem 15 - Lattice paths\n* @see {@link https://projecteuler.net/problem=15}\n*\n* Starting in the top left corner of a 2×2 grid,\n* and only being able to move to the right and down,\n* there are exactly 6 routes to the bottom right corner.\n*\n* How many such routes are there through a 20×20 grid?\n*\n* @author ddaniel27\n */\npackage problem15\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/factorial\"\n)\n\nfunc Problem15(gridSize int) int {\n\t/**\n\tAuthor note:\n\tWe can solve this problem using combinatorics.\n\tHere is a good blog post that explains the solution:\n\n\t[link](https://stemhash.com/counting-lattice-paths/)\n\n\tBtw, I'm not related to the author of the blog post.\n\n\tAfter some simplification, we can see that the solution is:\n\t(2n)! / (n!)^2\n\n\tWe can use the factorial package to calculate the factorials.\n\t*/\n\n\tn := gridSize\n\n\tnumerator, _ := factorial.Iterative(2 * n)\n\tdenominator, _ := factorial.Iterative(n)\n\tdenominator *= denominator\n\n\treturn numerator / denominator\n}\n"
  },
  {
    "path": "project_euler/problem_15/problem15_test.go",
    "content": "package problem15\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem15_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput int\n\t\twant  int\n\t}{\n\t\t{\"Input 2\", 2, 6},\n\t\t// This test case is disabled\n\t\t// because it needs a big integer to run successfully\n\t\t// and factorial package doesn't support it\n\t\t// {\"Input 20\", 20, 137846528820},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := Problem15(tt.input)\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"Problem15() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem15_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem15(20)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_16/problem16.go",
    "content": "/**\n* Problem 16 - Power digit sum\n* @see {@link https://projecteuler.net/problem=16}\n*\n* 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.\n*\n* What is the sum of the digits of the number 2^1000?\n*\n* @author ddaniel27\n */\npackage problem16\n\nimport (\n\t\"math/big\"\n)\n\nfunc Problem16(exponent int64) int64 {\n\tvar result big.Int\n\n\tbigTwo := big.NewInt(2)\n\tbigExponent := big.NewInt(exponent)\n\n\tresult.Exp(bigTwo, bigExponent, nil)\n\n\tresultStr := result.String()\n\n\tvar sum int64\n\tfor _, digit := range resultStr {\n\t\tsum += int64(digit - '0')\n\t}\n\n\treturn sum\n}\n"
  },
  {
    "path": "project_euler/problem_16/problem16_test.go",
    "content": "package problem16\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem16_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texponent int64\n\t\twant     int64\n\t}{\n\t\t{\"2^15\", 15, 26},\n\t\t{\"2^1000\", 1000, 1366},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := Problem16(tt.exponent); got != tt.want {\n\t\t\t\tt.Errorf(\"Problem16() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmark\nfunc BenchmarkProblem16_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem16(1000)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_17/input.go",
    "content": "/**\n* I put this code in a separate file because it is too long.\n* Also it took me a lot of time to parsing this input from\n* a random html page, so, I don't want to lose it.\n */\npackage problem17\n\nconst INPUT = \"One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen Twenty Twenty one Twenty two Twenty three Twenty four Twenty five Twenty six Twenty seven Twenty eight Twenty nine Thirty Thirty one Thirty two Thirty three Thirty four Thirty five Thirty six Thirty seven Thirty eight Thirty nine Forty Forty one Forty two Forty three Forty four Forty five Forty six Forty seven Forty eight Forty nine Fifty Fifty one Fifty two Fifty three Fifty four Fifty five Fifty six Fifty seven Fifty eight Fifty nine Sixty Sixty one Sixty two Sixty three Sixty four Sixty five Sixty six Sixty seven Sixty eight Sixty nine Seventy Seventy one Seventy two Seventy three Seventy four Seventy five Seventy six Seventy seven Seventy eight Seventy nine Eighty Eighty one Eighty two Eighty three Eighty four Eighty five Eighty six Eighty seven Eighty eight Eighty nine Ninety Ninety one Ninety two Ninety three Ninety four Ninety five Ninety six Ninety seven Ninety eight Ninety nine One hundred One hundred and one One hundred and two One hundred and three One hundred and four One hundred and five One hundred and six One hundred and seven One hundred and eight One hundred and nine One hundred and ten One hundred and eleven One hundred and twelve One hundred and thirteen One hundred and fourteen One hundred and fifteen One hundred and sixteen One hundred and seventeen One hundred and eighteen One hundred and nineteen One hundred and twenty One hundred and twenty one One hundred and twenty two One hundred and twenty three One hundred and twenty four One hundred and twenty five One hundred and twenty six One hundred and twenty seven One hundred and twenty eight One hundred and twenty nine One hundred and thirty One hundred and thirty one One hundred and thirty two One hundred and thirty three One hundred and thirty four One hundred and thirty five One hundred and thirty six One hundred and thirty seven One hundred and thirty eight One hundred and thirty nine One hundred and forty One hundred and forty one One hundred and forty two One hundred and forty three One hundred and forty four One hundred and forty five One hundred and forty six One hundred and forty seven One hundred and forty eight One hundred and forty nine One hundred and fifty One hundred and fifty one One hundred and fifty two One hundred and fifty three One hundred and fifty four One hundred and fifty five One hundred and fifty six One hundred and fifty seven One hundred and fifty eight One hundred and fifty nine One hundred and sixty One hundred and sixty one One hundred and sixty two One hundred and sixty three One hundred and sixty four One hundred and sixty five One hundred and sixty six One hundred and sixty seven One hundred and sixty eight One hundred and sixty nine One hundred and seventy One hundred and seventy one One hundred and seventy two One hundred and seventy three One hundred and seventy four One hundred and seventy five One hundred and seventy six One hundred and seventy seven One hundred and seventy eight One hundred and seventy nine One hundred and eighty One hundred and eighty one One hundred and eighty two One hundred and eighty three One hundred and eighty four One hundred and eighty five One hundred and eighty six One hundred and eighty seven One hundred and eighty eight One hundred and eighty nine One hundred and ninety One hundred and ninety one One hundred and ninety two One hundred and ninety three One hundred and ninety four One hundred and ninety five One hundred and ninety six One hundred and ninety seven One hundred and ninety eight One hundred and ninety nine Two hundred Two hundred and one Two hundred and two Two hundred and three Two hundred and four Two hundred and five Two hundred and six Two hundred and seven Two hundred and eight Two hundred and nine Two hundred and ten Two hundred and eleven Two hundred and twelve Two hundred and thirteen Two hundred and fourteen Two hundred and fifteen Two hundred and sixteen Two hundred and seventeen Two hundred and eighteen Two hundred and nineteen Two hundred and twenty Two hundred and twenty one Two hundred and twenty two Two hundred and twenty three Two hundred and twenty four Two hundred and twenty five Two hundred and twenty six Two hundred and twenty seven Two hundred and twenty eight Two hundred and twenty nine Two hundred and thirty Two hundred and thirty one Two hundred and thirty two Two hundred and thirty three Two hundred and thirty four Two hundred and thirty five Two hundred and thirty six Two hundred and thirty seven Two hundred and thirty eight Two hundred and thirty nine Two hundred and forty Two hundred and forty one Two hundred and forty two Two hundred and forty three Two hundred and forty four Two hundred and forty five Two hundred and forty six Two hundred and forty seven Two hundred and forty eight Two hundred and forty nine Two hundred and fifty Two hundred and fifty one Two hundred and fifty two Two hundred and fifty three Two hundred and fifty four Two hundred and fifty five Two hundred and fifty six Two hundred and fifty seven Two hundred and fifty eight Two hundred and fifty nine Two hundred and sixty Two hundred and sixty one Two hundred and sixty two Two hundred and sixty three Two hundred and sixty four Two hundred and sixty five Two hundred and sixty six Two hundred and sixty seven Two hundred and sixty eight Two hundred and sixty nine Two hundred and seventy Two hundred and seventy one Two hundred and seventy two Two hundred and seventy three Two hundred and seventy four Two hundred and seventy five Two hundred and seventy six Two hundred and seventy seven Two hundred and seventy eight Two hundred and seventy nine Two hundred and eighty Two hundred and eighty one Two hundred and eighty two Two hundred and eighty three Two hundred and eighty four Two hundred and eighty five Two hundred and eighty six Two hundred and eighty seven Two hundred and eighty eight Two hundred and eighty nine Two hundred and ninety Two hundred and ninety one Two hundred and ninety two Two hundred and ninety three Two hundred and ninety four Two hundred and ninety five Two hundred and ninety six Two hundred and ninety seven Two hundred and ninety eight Two hundred and ninety nine Three hundred Three hundred and one Three hundred and two Three hundred and three Three hundred and four Three hundred and five Three hundred and six Three hundred and seven Three hundred and eight Three hundred and nine Three hundred and ten Three hundred and eleven Three hundred and twelve Three hundred and thirteen Three hundred and fourteen Three hundred and fifteen Three hundred and sixteen Three hundred and seventeen Three hundred and eighteen Three hundred and nineteen Three hundred and twenty Three hundred and twenty one Three hundred and twenty two Three hundred and twenty three Three hundred and twenty four Three hundred and twenty five Three hundred and twenty six Three hundred and twenty seven Three hundred and twenty eight Three hundred and twenty nine Three hundred and thirty Three hundred and thirty one Three hundred and thirty two Three hundred and thirty three Three hundred and thirty four Three hundred and thirty five Three hundred and thirty six Three hundred and thirty seven Three hundred and thirty eight Three hundred and thirty nine Three hundred and forty Three hundred and forty one Three hundred and forty two Three hundred and forty three Three hundred and forty four Three hundred and forty five Three hundred and forty six Three hundred and forty seven Three hundred and forty eight Three hundred and forty nine Three hundred and fifty Three hundred and fifty one Three hundred and fifty two Three hundred and fifty three Three hundred and fifty four Three hundred and fifty five Three hundred and fifty six Three hundred and fifty seven Three hundred and fifty eight Three hundred and fifty nine Three hundred and sixty Three hundred and sixty one Three hundred and sixty two Three hundred and sixty three Three hundred and sixty four Three hundred and sixty five Three hundred and sixty six Three hundred and sixty seven Three hundred and sixty eight Three hundred and sixty nine Three hundred and seventy Three hundred and seventy one Three hundred and seventy two Three hundred and seventy three Three hundred and seventy four Three hundred and seventy five Three hundred and seventy six Three hundred and seventy seven Three hundred and seventy eight Three hundred and seventy nine Three hundred and eighty Three hundred and eighty one Three hundred and eighty two Three hundred and eighty three Three hundred and eighty four Three hundred and eighty five Three hundred and eighty six Three hundred and eighty seven Three hundred and eighty eight Three hundred and eighty nine Three hundred and ninety Three hundred and ninety one Three hundred and ninety two Three hundred and ninety three Three hundred and ninety four Three hundred and ninety five Three hundred and ninety six Three hundred and ninety seven Three hundred and ninety eight Three hundred and ninety nine Four hundred Four hundred and one Four hundred and two Four hundred and three Four hundred and four Four hundred and five Four hundred and six Four hundred and seven Four hundred and eight Four hundred and nine Four hundred and ten Four hundred and eleven Four hundred and twelve Four hundred and thirteen Four hundred and fourteen Four hundred and fifteen Four hundred and sixteen Four hundred and seventeen Four hundred and eighteen Four hundred and nineteen Four hundred and twenty Four hundred and twenty one Four hundred and twenty two Four hundred and twenty three Four hundred and twenty four Four hundred and twenty five Four hundred and twenty six Four hundred and twenty seven Four hundred and twenty eight Four hundred and twenty nine Four hundred and thirty Four hundred and thirty one Four hundred and thirty two Four hundred and thirty three Four hundred and thirty four Four hundred and thirty five Four hundred and thirty six Four hundred and thirty seven Four hundred and thirty eight Four hundred and thirty nine Four hundred and forty Four hundred and forty one Four hundred and forty two Four hundred and forty three Four hundred and forty four Four hundred and forty five Four hundred and forty six Four hundred and forty seven Four hundred and forty eight Four hundred and forty nine Four hundred and fifty Four hundred and fifty one Four hundred and fifty two Four hundred and fifty three Four hundred and fifty four Four hundred and fifty five Four hundred and fifty six Four hundred and fifty seven Four hundred and fifty eight Four hundred and fifty nine Four hundred and sixty Four hundred and sixty one Four hundred and sixty two Four hundred and sixty three Four hundred and sixty four Four hundred and sixty five Four hundred and sixty six Four hundred and sixty seven Four hundred and sixty eight Four hundred and sixty nine Four hundred and seventy Four hundred and seventy one Four hundred and seventy two Four hundred and seventy three Four hundred and seventy four Four hundred and seventy five Four hundred and seventy six Four hundred and seventy seven Four hundred and seventy eight Four hundred and seventy nine Four hundred and eighty Four hundred and eighty one Four hundred and eighty two Four hundred and eighty three Four hundred and eighty four Four hundred and eighty five Four hundred and eighty six Four hundred and eighty seven Four hundred and eighty eight Four hundred and eighty nine Four hundred and ninety Four hundred and ninety one Four hundred and ninety two Four hundred and ninety three Four hundred and ninety four Four hundred and ninety five Four hundred and ninety six Four hundred and ninety seven Four hundred and ninety eight Four hundred and ninety nine Five hundred Five hundred and one Five hundred and two Five hundred and three Five hundred and four Five hundred and five Five hundred and six Five hundred and seven Five hundred and eight Five hundred and nine Five hundred and ten Five hundred and eleven Five hundred and twelve Five hundred and thirteen Five hundred and fourteen Five hundred and fifteen Five hundred and sixteen Five hundred and seventeen Five hundred and eighteen Five hundred and nineteen Five hundred and twenty Five hundred and twenty one Five hundred and twenty two Five hundred and twenty three Five hundred and twenty four Five hundred and twenty five Five hundred and twenty six Five hundred and twenty seven Five hundred and twenty eight Five hundred and twenty nine Five hundred and thirty Five hundred and thirty one Five hundred and thirty two Five hundred and thirty three Five hundred and thirty four Five hundred and thirty five Five hundred and thirty six Five hundred and thirty seven Five hundred and thirty eight Five hundred and thirty nine Five hundred and forty Five hundred and forty one Five hundred and forty two Five hundred and forty three Five hundred and forty four Five hundred and forty five Five hundred and forty six Five hundred and forty seven Five hundred and forty eight Five hundred and forty nine Five hundred and fifty Five hundred and fifty one Five hundred and fifty two Five hundred and fifty three Five hundred and fifty four Five hundred and fifty five Five hundred and fifty six Five hundred and fifty seven Five hundred and fifty eight Five hundred and fifty nine Five hundred and sixty Five hundred and sixty one Five hundred and sixty two Five hundred and sixty three Five hundred and sixty four Five hundred and sixty five Five hundred and sixty six Five hundred and sixty seven Five hundred and sixty eight Five hundred and sixty nine Five hundred and seventy Five hundred and seventy one Five hundred and seventy two Five hundred and seventy three Five hundred and seventy four Five hundred and seventy five Five hundred and seventy six Five hundred and seventy seven Five hundred and seventy eight Five hundred and seventy nine Five hundred and eighty Five hundred and eighty one Five hundred and eighty two Five hundred and eighty three Five hundred and eighty four Five hundred and eighty five Five hundred and eighty six Five hundred and eighty seven Five hundred and eighty eight Five hundred and eighty nine Five hundred and ninety Five hundred and ninety one Five hundred and ninety two Five hundred and ninety three Five hundred and ninety four Five hundred and ninety five Five hundred and ninety six Five hundred and ninety seven Five hundred and ninety eight Five hundred and ninety nine Six hundred Six hundred and one Six hundred and two Six hundred and three Six hundred and four Six hundred and five Six hundred and six Six hundred and seven Six hundred and eight Six hundred and nine Six hundred and ten Six hundred and eleven Six hundred and twelve Six hundred and thirteen Six hundred and fourteen Six hundred and fifteen Six hundred and sixteen Six hundred and seventeen Six hundred and eighteen Six hundred and nineteen Six hundred and twenty Six hundred and twenty one Six hundred and twenty two Six hundred and twenty three Six hundred and twenty four Six hundred and twenty five Six hundred and twenty six Six hundred and twenty seven Six hundred and twenty eight Six hundred and twenty nine Six hundred and thirty Six hundred and thirty one Six hundred and thirty two Six hundred and thirty three Six hundred and thirty four Six hundred and thirty five Six hundred and thirty six Six hundred and thirty seven Six hundred and thirty eight Six hundred and thirty nine Six hundred and forty Six hundred and forty one Six hundred and forty two Six hundred and forty three Six hundred and forty four Six hundred and forty five Six hundred and forty six Six hundred and forty seven Six hundred and forty eight Six hundred and forty nine Six hundred and fifty Six hundred and fifty one Six hundred and fifty two Six hundred and fifty three Six hundred and fifty four Six hundred and fifty five Six hundred and fifty six Six hundred and fifty seven Six hundred and fifty eight Six hundred and fifty nine Six hundred and sixty Six hundred and sixty one Six hundred and sixty two Six hundred and sixty three Six hundred and sixty four Six hundred and sixty five Six hundred and sixty six Six hundred and sixty seven Six hundred and sixty eight Six hundred and sixty nine Six hundred and seventy Six hundred and seventy one Six hundred and seventy two Six hundred and seventy three Six hundred and seventy four Six hundred and seventy five Six hundred and seventy six Six hundred and seventy seven Six hundred and seventy eight Six hundred and seventy nine Six hundred and eighty Six hundred and eighty one Six hundred and eighty two Six hundred and eighty three Six hundred and eighty four Six hundred and eighty five Six hundred and eighty six Six hundred and eighty seven Six hundred and eighty eight Six hundred and eighty nine Six hundred and ninety Six hundred and ninety one Six hundred and ninety two Six hundred and ninety three Six hundred and ninety four Six hundred and ninety five Six hundred and ninety six Six hundred and ninety seven Six hundred and ninety eight Six hundred and ninety nine Seven hundred Seven hundred and one Seven hundred and two Seven hundred and three Seven hundred and four Seven hundred and five Seven hundred and six Seven hundred and seven Seven hundred and eight Seven hundred and nine Seven hundred and ten Seven hundred and eleven Seven hundred and twelve Seven hundred and thirteen Seven hundred and fourteen Seven hundred and fifteen Seven hundred and sixteen Seven hundred and seventeen Seven hundred and eighteen Seven hundred and nineteen Seven hundred and twenty Seven hundred and twenty one Seven hundred and twenty two Seven hundred and twenty three Seven hundred and twenty four Seven hundred and twenty five Seven hundred and twenty six Seven hundred and twenty seven Seven hundred and twenty eight Seven hundred and twenty nine Seven hundred and thirty Seven hundred and thirty one Seven hundred and thirty two Seven hundred and thirty three Seven hundred and thirty four Seven hundred and thirty five Seven hundred and thirty six Seven hundred and thirty seven Seven hundred and thirty eight Seven hundred and thirty nine Seven hundred and forty Seven hundred and forty one Seven hundred and forty two Seven hundred and forty three Seven hundred and forty four Seven hundred and forty five Seven hundred and forty six Seven hundred and forty seven Seven hundred and forty eight Seven hundred and forty nine Seven hundred and fifty Seven hundred and fifty one Seven hundred and fifty two Seven hundred and fifty three Seven hundred and fifty four Seven hundred and fifty five Seven hundred and fifty six Seven hundred and fifty seven Seven hundred and fifty eight Seven hundred and fifty nine Seven hundred and sixty Seven hundred and sixty one Seven hundred and sixty two Seven hundred and sixty three Seven hundred and sixty four Seven hundred and sixty five Seven hundred and sixty six Seven hundred and sixty seven Seven hundred and sixty eight Seven hundred and sixty nine Seven hundred and seventy Seven hundred and seventy one Seven hundred and seventy two Seven hundred and seventy three Seven hundred and seventy four Seven hundred and seventy five Seven hundred and seventy six Seven hundred and seventy seven Seven hundred and seventy eight Seven hundred and seventy nine Seven hundred and eighty Seven hundred and eighty one Seven hundred and eighty two Seven hundred and eighty three Seven hundred and eighty four Seven hundred and eighty five Seven hundred and eighty six Seven hundred and eighty seven Seven hundred and eighty eight Seven hundred and eighty nine Seven hundred and ninety Seven hundred and ninety one Seven hundred and ninety two Seven hundred and ninety three Seven hundred and ninety four Seven hundred and ninety five Seven hundred and ninety six Seven hundred and ninety seven Seven hundred and ninety eight Seven hundred and ninety nine Eight hundred Eight hundred and one Eight hundred and two Eight hundred and three Eight hundred and four Eight hundred and five Eight hundred and six Eight hundred and seven Eight hundred and eight Eight hundred and nine Eight hundred and ten Eight hundred and eleven Eight hundred and twelve Eight hundred and thirteen Eight hundred and fourteen Eight hundred and fifteen Eight hundred and sixteen Eight hundred and seventeen Eight hundred and eighteen Eight hundred and nineteen Eight hundred and twenty Eight hundred and twenty one Eight hundred and twenty two Eight hundred and twenty three Eight hundred and twenty four Eight hundred and twenty five Eight hundred and twenty six Eight hundred and twenty seven Eight hundred and twenty eight Eight hundred and twenty nine Eight hundred and thirty Eight hundred and thirty one Eight hundred and thirty two Eight hundred and thirty three Eight hundred and thirty four Eight hundred and thirty five Eight hundred and thirty six Eight hundred and thirty seven Eight hundred and thirty eight Eight hundred and thirty nine Eight hundred and forty Eight hundred and forty one Eight hundred and forty two Eight hundred and forty three Eight hundred and forty four Eight hundred and forty five Eight hundred and forty six Eight hundred and forty seven Eight hundred and forty eight Eight hundred and forty nine Eight hundred and fifty Eight hundred and fifty one Eight hundred and fifty two Eight hundred and fifty three Eight hundred and fifty four Eight hundred and fifty five Eight hundred and fifty six Eight hundred and fifty seven Eight hundred and fifty eight Eight hundred and fifty nine Eight hundred and sixty Eight hundred and sixty one Eight hundred and sixty two Eight hundred and sixty three Eight hundred and sixty four Eight hundred and sixty five Eight hundred and sixty six Eight hundred and sixty seven Eight hundred and sixty eight Eight hundred and sixty nine Eight hundred and seventy Eight hundred and seventy one Eight hundred and seventy two Eight hundred and seventy three Eight hundred and seventy four Eight hundred and seventy five Eight hundred and seventy six Eight hundred and seventy seven Eight hundred and seventy eight Eight hundred and seventy nine Eight hundred and eighty Eight hundred and eighty one Eight hundred and eighty two Eight hundred and eighty three Eight hundred and eighty four Eight hundred and eighty five Eight hundred and eighty six Eight hundred and eighty seven Eight hundred and eighty eight Eight hundred and eighty nine Eight hundred and ninety Eight hundred and ninety one Eight hundred and ninety two Eight hundred and ninety three Eight hundred and ninety four Eight hundred and ninety five Eight hundred and ninety six Eight hundred and ninety seven Eight hundred and ninety eight Eight hundred and ninety nine Nine hundred Nine hundred and one Nine hundred and two Nine hundred and three Nine hundred and four Nine hundred and five Nine hundred and six Nine hundred and seven Nine hundred and eight Nine hundred and nine Nine hundred and ten Nine hundred and eleven Nine hundred and twelve Nine hundred and thirteen Nine hundred and fourteen Nine hundred and fifteen Nine hundred and sixteen Nine hundred and seventeen Nine hundred and eighteen Nine hundred and nineteen Nine hundred and twenty Nine hundred and twenty one Nine hundred and twenty two Nine hundred and twenty three Nine hundred and twenty four Nine hundred and twenty five Nine hundred and twenty six Nine hundred and twenty seven Nine hundred and twenty eight Nine hundred and twenty nine Nine hundred and thirty Nine hundred and thirty one Nine hundred and thirty two Nine hundred and thirty three Nine hundred and thirty four Nine hundred and thirty five Nine hundred and thirty six Nine hundred and thirty seven Nine hundred and thirty eight Nine hundred and thirty nine Nine hundred and forty Nine hundred and forty one Nine hundred and forty two Nine hundred and forty three Nine hundred and forty four Nine hundred and forty five Nine hundred and forty six Nine hundred and forty seven Nine hundred and forty eight Nine hundred and forty nine Nine hundred and fifty Nine hundred and fifty one Nine hundred and fifty two Nine hundred and fifty three Nine hundred and fifty four Nine hundred and fifty five Nine hundred and fifty six Nine hundred and fifty seven Nine hundred and fifty eight Nine hundred and fifty nine Nine hundred and sixty Nine hundred and sixty one Nine hundred and sixty two Nine hundred and sixty three Nine hundred and sixty four Nine hundred and sixty five Nine hundred and sixty six Nine hundred and sixty seven Nine hundred and sixty eight Nine hundred and sixty nine Nine hundred and seventy Nine hundred and seventy one Nine hundred and seventy two Nine hundred and seventy three Nine hundred and seventy four Nine hundred and seventy five Nine hundred and seventy six Nine hundred and seventy seven Nine hundred and seventy eight Nine hundred and seventy nine Nine hundred and eighty Nine hundred and eighty one Nine hundred and eighty two Nine hundred and eighty three Nine hundred and eighty four Nine hundred and eighty five Nine hundred and eighty six Nine hundred and eighty seven Nine hundred and eighty eight Nine hundred and eighty nine Nine hundred and ninety Nine hundred and ninety one Nine hundred and ninety two Nine hundred and ninety three Nine hundred and ninety four Nine hundred and ninety five Nine hundred and ninety six Nine hundred and ninety seven Nine hundred and ninety eight Nine hundred and ninety nine One thousand\"\n"
  },
  {
    "path": "project_euler/problem_17/problem17.go",
    "content": "/**\n* Problem 17 - Number letter counts\n* @see {@link https://projecteuler.net/problem=17}\n*\n* If the numbers 1 to 5 are written out in words: one, two, three, four, five,\n* then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n*\n* If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,\n* how many letters would be used?\n*\n* NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)\n* contains 23 letters and 115 (one hundred and fifteen) contains 20 letters.\n* The use of \"and\" when writing out numbers is in compliance with British usage.\n*\n* @author ddaniel27\n */\npackage problem17\n\nimport \"strings\"\n\nfunc Problem17(input string) int {\n\tvar sum int\n\n\tparsed := strings.Split(input, \" \")\n\n\tfor _, word := range parsed {\n\t\tsum += len(word)\n\t}\n\n\treturn sum\n}\n"
  },
  {
    "path": "project_euler/problem_17/problem17_test.go",
    "content": "package problem17\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem17_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput string\n\t\twant  int\n\t}{\n\t\t{\"1 to 5\", \"one two three four five\", 19},\n\t\t{\"1 to 1000\", INPUT, 21124},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := Problem17(tt.input); got != tt.want {\n\t\t\t\tt.Errorf(\"Problem17() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmark\nfunc BenchmarkProblem17_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem17(INPUT)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_18/edge.go",
    "content": "package problem18\n\ntype Edge struct {\n\tID        int\n\tNodeValue NodeValue\n\tNodeLeft  Node\n\tNodeRight Node\n\tParent    Node\n}\n\nfunc (n *Edge) Value() NodeValue {\n\treturn n.NodeValue\n}\n\nfunc (n *Edge) Left() Node {\n\treturn n.NodeLeft\n}\n\nfunc (n *Edge) Right() Node {\n\treturn n.NodeRight\n}\n\nfunc (n *Edge) Kind() string {\n\treturn \"edge\"\n}\n\nfunc (n *Edge) CreateChild(value NodeValue, id int) Node {\n\t// When the left child is nil, it's a left edge\n\tif n.NodeLeft == nil {\n\t\treturn &Edge{\n\t\t\tID:        id,\n\t\t\tNodeValue: value,\n\t\t\tParent:    n,\n\t\t\tNodeLeft:  nil,\n\t\t\tNodeRight: nil,\n\t\t}\n\t}\n\n\t// When the left child is a leaf, it's a right edge\n\tif n.NodeLeft.Kind() == \"leaf\" {\n\t\treturn &Edge{\n\t\t\tID:        id,\n\t\t\tNodeValue: value,\n\t\t\tParent:    n,\n\t\t\tNodeLeft:  nil,\n\t\t\tNodeRight: nil,\n\t\t}\n\t}\n\n\treturn &Leaf{\n\t\tID:        id,\n\t\tNodeValue: value,\n\t\tParent:    n,\n\t\tNodeLeft:  nil,\n\t\tNodeRight: nil,\n\t}\n}\n\nfunc (n *Edge) GetID() int {\n\treturn n.ID\n}\n\nfunc (n *Edge) Insert(node Node) {\n\t// If Left is nil, always simply insert the node\n\tif n.NodeLeft == nil {\n\t\tnode.SetParent(n)\n\t\tn.NodeLeft = node\n\n\t\treturn\n\t}\n\n\t// If Right is nil, insert the node\n\tn.NodeRight = node\n\n\t// If the node to insert is an edge, set the parent\n\tif node.Kind() == \"edge\" {\n\t\tnode.SetParent(n)\n\n\t\treturn\n\t}\n\n\t// If the node to insert is a leaf, send it to the sibling right\n\tn.Parent.Right().Insert(node)\n}\n\nfunc (n *Edge) HasSpace() bool {\n\treturn n.NodeLeft == nil || n.NodeRight == nil\n}\n\nfunc (n *Edge) LeftIsNil() bool {\n\treturn n.NodeLeft == nil\n}\n\nfunc (n *Edge) RightIsNil() bool {\n\treturn n.NodeRight == nil\n}\n\nfunc (n *Edge) SetParent(node Node) {\n\tn.Parent = node\n}\n"
  },
  {
    "path": "project_euler/problem_18/input.go",
    "content": "package problem18\n\nimport \"strings\"\n\nconst problem18_input_string = `\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n`\n\nvar problem18_input_parsed_string []string = strings.Split(\n\tstrings.Trim(\n\t\tstrings.ReplaceAll(problem18_input_string, \"\\n\", \" \"),\n\t\t\" \",\n\t),\n\t\" \")\n\nconst problem18_test_string = `\n3\n7 4\n2 4 6\n8 5 9 3\n`\n\nvar problem18_test_parsed_string []string = strings.Split(\n\tstrings.Trim(\n\t\tstrings.ReplaceAll(problem18_test_string, \"\\n\", \" \"),\n\t\t\" \",\n\t),\n\t\" \")\n"
  },
  {
    "path": "project_euler/problem_18/leaf.go",
    "content": "package problem18\n\ntype Leaf struct {\n\tID        int\n\tNodeValue NodeValue\n\tNodeLeft  *Leaf\n\tNodeRight *Leaf\n\tParent    Node\n}\n\nfunc (n *Leaf) Value() NodeValue {\n\treturn n.NodeValue\n}\n\nfunc (n *Leaf) Left() Node {\n\tif n.NodeLeft != nil {\n\t\tn.NodeLeft.Parent = n // Leaf is the parent of its left child always\n\t}\n\n\treturn n.NodeLeft\n}\n\nfunc (n *Leaf) Right() Node {\n\treturn n.NodeRight\n}\n\nfunc (n *Leaf) Kind() string {\n\treturn \"leaf\"\n}\n\nfunc (n *Leaf) CreateChild(value NodeValue, id int) Node {\n\t// Leafs only have leaf children\n\treturn &Leaf{\n\t\tID:        id,\n\t\tNodeValue: value,\n\t\tParent:    n,\n\t\tNodeLeft:  nil,\n\t\tNodeRight: nil,\n\t}\n}\n\nfunc (n *Leaf) GetID() int {\n\treturn n.ID\n}\n\nfunc (n *Leaf) Insert(node Node) {\n\t// If Left is nil, always simply insert the node\n\tif n.NodeLeft == nil {\n\t\tnode.SetParent(n)\n\t\tn.NodeLeft = node.(*Leaf)\n\n\t\treturn\n\t}\n\n\t// If Right is nil, insert the node\n\tn.NodeRight = node.(*Leaf)\n\t// Send it to the sibling right\n\tn.Parent.Right().Insert(node)\n}\n\nfunc (n *Leaf) HasSpace() bool {\n\treturn n.NodeLeft == nil || n.NodeRight == nil\n}\n\nfunc (n *Leaf) LeftIsNil() bool {\n\treturn n.NodeLeft == nil\n}\n\nfunc (n *Leaf) RightIsNil() bool {\n\treturn n.NodeRight == nil\n}\n\nfunc (n *Leaf) SetParent(node Node) {\n\tn.Parent = node\n}\n"
  },
  {
    "path": "project_euler/problem_18/problem18.go",
    "content": "/**\n* Problem 18 - Maximum path sum I\n* @see {@link https://projecteuler.net/problem=18}\n*\n* By starting at the top of the triangle below and\n* moving to adjacent numbers on the row below,\n* the maximum total from top to bottom is 23.\n*\n* 3\n* 7 4\n* 2 4 6\n* 8 5 9 3\n*\n* That is, 3 + 7 + 4 + 9 = 23.\n*\n* Find the maximum total from top to bottom of the triangle below:\n* [refer to the problem link]\n*\n* NOTE: As there are only 16384 routes, it is possible\n* to solve this problem by trying every route.\n* However, Problem 67, is the same challenge with a triangle\n* containing one-hundred rows; it cannot be solved by brute force,\n* and requires a clever method! ;o)\n*\n* @author ddaniel27\n */\npackage problem18\n\nimport \"strconv\"\n\ntype (\n\tNodeValue int\n\tNodeType  string\n\n\tNode interface {\n\t\tValue() NodeValue\n\t\tGetID() int\n\t\tLeft() Node\n\t\tRight() Node\n\t\tLeftIsNil() bool\n\t\tRightIsNil() bool\n\t\tHasSpace() bool\n\t\tKind() string\n\t\tSetParent(Node)\n\t\tCreateChild(NodeValue, int) Node\n\t\tInsert(Node)\n\t}\n)\n\nfunc Problem18(input []string, deep int) int {\n\ttree := &Tree{}\n\n\tfor _, num := range input {\n\t\tv, err := strconv.Atoi(num)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\ttree.BFSInsert(NodeValue(v))\n\t}\n\n\treturn tree.MaxPathValueSearch(deep)\n}\n"
  },
  {
    "path": "project_euler/problem_18/problem18_test.go",
    "content": "package problem18\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem18_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    []string\n\t\tdeep     int\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tname:     \"Test case 1\",\n\t\t\tinput:    problem18_test_parsed_string,\n\t\t\tdeep:     2,\n\t\t\texpected: 23,\n\t\t},\n\t\t{\n\t\t\tname:     \"Test case 2\",\n\t\t\tinput:    problem18_input_parsed_string,\n\t\t\tdeep:     2,\n\t\t\texpected: 1074,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual := Problem18(test.input, test.deep)\n\t\t\tif actual != test.expected {\n\t\t\t\tt.Errorf(\"Expected %d, but got %d\", test.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem18_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem18(problem18_input_parsed_string, 2)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_18/root.go",
    "content": "package problem18\n\ntype Root struct {\n\tID        int\n\tNodeValue NodeValue\n\tNodeLeft  *Edge\n\tNodeRight *Edge\n}\n\nfunc (n *Root) Value() NodeValue {\n\treturn n.NodeValue\n}\n\nfunc (n *Root) Left() Node {\n\treturn n.NodeLeft\n}\n\nfunc (n *Root) Right() Node {\n\treturn n.NodeRight\n}\n\nfunc (n *Root) Kind() string {\n\treturn \"root\"\n}\n\nfunc (n *Root) CreateChild(value NodeValue, id int) Node {\n\treturn &Edge{\n\t\tID:        id,\n\t\tNodeValue: value,\n\t\tParent:    n,\n\t\tNodeLeft:  nil,\n\t\tNodeRight: nil,\n\t}\n}\n\nfunc (n *Root) GetID() int {\n\treturn n.ID\n}\n\nfunc (n *Root) Insert(node Node) {\n\tif n.NodeLeft == nil {\n\t\tn.NodeLeft = node.(*Edge)\n\t} else {\n\t\tn.NodeRight = node.(*Edge)\n\t}\n}\n\nfunc (n *Root) HasSpace() bool {\n\treturn n.NodeLeft == nil || n.NodeRight == nil\n}\n\nfunc (n *Root) LeftIsNil() bool {\n\treturn n.NodeLeft == nil\n}\n\nfunc (n *Root) RightIsNil() bool {\n\treturn n.NodeRight == nil\n}\n\nfunc (n *Root) SetParent(node Node) {\n\tpanic(\"Root node cannot have a parent\")\n}\n"
  },
  {
    "path": "project_euler/problem_18/tree.go",
    "content": "package problem18\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Tree struct {\n\tRoot  *Root\n\tNodes map[int]struct{}\n\tID    int\n}\n\nfunc (t *Tree) BFSInsert(value NodeValue) {\n\tt.Nodes = make(map[int]struct{}) // Reset the nodes map\n\n\tif t.Root == nil {\n\t\tt.Root = &Root{NodeValue: value, ID: 0}\n\t\tt.ID = 1\n\t\treturn\n\t}\n\n\tqueue := make([]Node, 0)\n\tqueue = append(queue, t.Root)\n\tt.isInQueue(t.Root.GetID())\n\n\thead := 0\n\n\tfor head < len(queue) {\n\t\tcurrent := queue[head]\n\t\thead++\n\t\tchildNode := current.CreateChild(value, t.ID)\n\n\t\tif current.HasSpace() {\n\t\t\tcurrent.Insert(childNode)\n\t\t\tt.ID++\n\t\t\treturn\n\t\t}\n\n\t\tif !t.isInQueue(current.Left().GetID()) { // Avoid duplicates\n\t\t\tqueue = append(queue, current.Left())\n\t\t}\n\t\tif !t.isInQueue(current.Right().GetID()) {\n\t\t\tqueue = append(queue, current.Right())\n\t\t}\n\t}\n}\n\n// MaxPathValueSearch is a method that searches the maximum path value in a tree\n// given a certain depth\nfunc (r *Tree) MaxPathValueSearch(deep int) int {\n\tif r.Root == nil {\n\t\treturn 0\n\t}\n\n\ttype DFSNode struct {\n\t\tNode      Node\n\t\tStepsLeft int\n\t\tSum       int\n\t}\n\n\tvar pivot Node = r.Root\n\tpivotEnded := false\n\tmaxPathValue := int(pivot.Value())\n\n\tstack := make([]DFSNode, 0)\n\n\tfor !pivotEnded {\n\t\tstack = append(stack, DFSNode{Node: pivot, StepsLeft: deep, Sum: maxPathValue})\n\n\t\tfor len(stack) > 0 {\n\t\t\tcurrent := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\n\t\t\t// If we run out of steps, we check the sum of the path,\n\t\t\t// update the maxPathValue if necessary and continue\n\t\t\tif current.StepsLeft == 0 {\n\t\t\t\tif current.Sum > maxPathValue {\n\t\t\t\t\tmaxPathValue = current.Sum\n\t\t\t\t\tpivot = current.Node\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !current.Node.RightIsNil() {\n\t\t\t\tstack = append(stack, DFSNode{\n\t\t\t\t\tNode:      current.Node.Right(),\n\t\t\t\t\tStepsLeft: current.StepsLeft - 1,\n\t\t\t\t\tSum:       current.Sum + int(current.Node.Right().Value()),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// If the left child is nil, we have reached the end of the path\n\t\t\tif !current.Node.LeftIsNil() {\n\t\t\t\tstack = append(stack, DFSNode{\n\t\t\t\t\tNode:      current.Node.Left(),\n\t\t\t\t\tStepsLeft: current.StepsLeft - 1,\n\t\t\t\t\tSum:       current.Sum + int(current.Node.Left().Value()),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tif current.Sum > maxPathValue {\n\t\t\t\t\tmaxPathValue = current.Sum\n\t\t\t\t\tpivot = current.Node\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If we don't have reached the end of the left side of the tree,\n\t\t// we continue with the search using the pivot node\n\t\t// We use the left child only because how the tree is built\n\t\tif pivot.LeftIsNil() {\n\t\t\tpivotEnded = true\n\t\t}\n\t}\n\n\treturn maxPathValue\n}\n\n// PrintReport is a method that prints a report of the tree\n// Node by node\nfunc (t *Tree) PrintReport() {\n\tt.Nodes = make(map[int]struct{})\n\tif t.Root == nil {\n\t\treturn\n\t}\n\n\tqueue := make([]Node, 0)\n\tqueue = append(queue, t.Root)\n\n\thead := 0\n\n\tfor head < len(queue) {\n\t\tcurrent := queue[head]\n\t\thead++\n\n\t\tprint(\"ID:\", current.GetID())\n\t\tprint(\", Current node:\", current.Value())\n\n\t\tif !current.LeftIsNil() {\n\t\t\tprint(\", Left Child:\", current.Left().Value())\n\n\t\t\tif !t.isInQueue(current.Left().GetID()) {\n\t\t\t\tqueue = append(queue, current.Left())\n\t\t\t}\n\t\t}\n\n\t\tif !current.RightIsNil() {\n\t\t\tprint(\", Right Child:\", current.Right().Value())\n\n\t\t\tif !t.isInQueue(current.Right().GetID()) {\n\t\t\t\tqueue = append(queue, current.Right())\n\t\t\t}\n\t\t}\n\n\t\tprintln()\n\t}\n}\n\n// PrintPyramid is a method that prints the tree as a pyramid\nfunc (t *Tree) PrintPyramid() {\n\tt.Nodes = make(map[int]struct{})\n\tif t.Root == nil {\n\t\treturn\n\t}\n\n\tqueue := []Node{t.Root}\n\tlevels := []int{0}\n\toutputByLevel := []string{}\n\n\thead := 0\n\tcurrentLevel := 0\n\n\toutput := \"\"\n\n\tfor head < len(queue) {\n\t\tcurrent := queue[head]\n\t\tlevel := levels[head]\n\t\thead++\n\n\t\t// Level change\n\t\tif level > currentLevel {\n\t\t\tcurrentLevel = level\n\t\t\toutputByLevel = append(outputByLevel, output+\"\\n\")\n\t\t\toutput = \"\"\n\t\t}\n\n\t\t// Add current node to the output\n\t\tif current.Value() < 10 {\n\t\t\toutput += fmt.Sprintf(\"0%d  \", current.Value())\n\t\t} else {\n\t\t\toutput += fmt.Sprintf(\"%d  \", current.Value())\n\t\t}\n\n\t\t// Add children to the queue\n\t\tif !current.LeftIsNil() {\n\t\t\tif !t.isInQueue(current.Left().GetID()) {\n\t\t\t\tqueue = append(queue, current.Left())\n\t\t\t\tlevels = append(levels, level+1)\n\t\t\t}\n\t\t}\n\n\t\tif !current.RightIsNil() {\n\t\t\tif !t.isInQueue(current.Right().GetID()) {\n\t\t\t\tqueue = append(queue, current.Right())\n\t\t\t\tlevels = append(levels, level+1)\n\t\t\t}\n\t\t}\n\t}\n\t// Add the last level\n\toutputByLevel = append(outputByLevel, output+\"\\n\")\n\n\ttotalLevels := len(outputByLevel)\n\n\t// Print the pyramid\n\tfor i, level := range outputByLevel {\n\t\tstr := strings.Repeat(\" \", 2*(totalLevels-i)) + level\n\t\tprint(str)\n\t}\n}\n\n// isInQueue is a method that avoids duplicates in the tree\nfunc (n *Tree) isInQueue(nv int) bool {\n\tif _, ok := n.Nodes[nv]; ok {\n\t\treturn true\n\t}\n\n\tn.Nodes[nv] = struct{}{}\n\treturn false\n}\n"
  },
  {
    "path": "project_euler/problem_19/problem19.go",
    "content": "package problem19\n\n/**\n* Problem 19 - Counting Sundays\n* @see {@link https://projecteuler.net/problem=19}\n*\n* You are given the following information,\n* but you may prefer to do some research for yourself.\n*\n* 1 Jan 1900 was a Monday.\n* Thirty days has September,\n* April, June and November.\n* All the rest have thirty-one,\n* Saving February alone,\n* Which has twenty-eight, rain or shine.\n* And on leap years, twenty-nine.\n* A leap year occurs on any year evenly divisible by 4,\n* but not on a century unless it is divisible by 400.\n*\n* How many Sundays fell on the first of the month during\n* the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n*\n* @author ddaniel27\n */\n\nfunc Problem19() int {\n\tcount := 0\n\tdayOfWeek := 2 // 1 Jan 1901 was a Tuesday\n\n\tfor year := 1901; year <= 2000; year++ {\n\t\tfor month := 1; month <= 12; month++ {\n\t\t\tif dayOfWeek == 0 {\n\t\t\t\tcount++\n\t\t\t}\n\n\t\t\tdaysInMonth := 31\n\t\t\tswitch month {\n\t\t\tcase 4, 6, 9, 11:\n\t\t\t\tdaysInMonth = 30\n\t\t\tcase 2:\n\t\t\t\tif IsLeapYear(year) {\n\t\t\t\t\tdaysInMonth = 29\n\t\t\t\t} else {\n\t\t\t\t\tdaysInMonth = 28\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdayOfWeek = (dayOfWeek + daysInMonth) % 7\n\t\t}\n\t}\n\n\treturn count\n}\n\nfunc IsLeapYear(year int) bool {\n\tif year%4 == 0 {\n\t\tif year%100 == 0 {\n\t\t\treturn year%400 == 0\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "project_euler/problem_19/problem19_test.go",
    "content": "package problem19\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem19_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\texpected int\n\t}{\n\t\t{\"Problem 19 - Counting Sundays\", 171},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := Problem19()\n\t\t\tif got != test.expected {\n\t\t\t\tt.Errorf(\"Problem19() = got %v, want %v\", got, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem19_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem19()\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_2/problem2.go",
    "content": "/**\n* Problem 2 - Even Fibonacci numbers\n* @see {@link https://projecteuler.net/problem=2}\n*\n* Each new term in the Fibonacci sequence is generated by adding the previous two terms.\n* By starting with 1 and 2, the first 10 terms will be:\n*\n* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n*\n* By considering the terms in the Fibonacci sequence whose values do not exceed four million,\n* find the sum of the even-valued terms.\n*\n* @author ddaniel27\n */\npackage problem2\n\nfunc Problem2(n uint) uint {\n\tsum := uint(0)\n\ta, b := uint(1), uint(2)\n\n\tfor b < n {\n\t\tif b%2 == 0 {\n\t\t\tsum += b\n\t\t}\n\n\t\ta, b = b, a+b\n\t}\n\n\treturn sum\n}\n"
  },
  {
    "path": "project_euler/problem_2/problem2_test.go",
    "content": "package problem2\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem2_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 10\",\n\t\t\tinput: 10,\n\t\t\twant:  10,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 100\",\n\t\t\tinput: 100,\n\t\t\twant:  44,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 3 - input 4e6\",\n\t\t\tinput: 4e6,\n\t\t\twant:  4613732,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem2(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem2() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem2(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem2(4e6)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_20/problem20.go",
    "content": "/**\n* Problem 20 - Factorial digit sum\n* @see {@link https://projecteuler.net/problem=20}\n*\n* n! means n × (n − 1) × ... × 3 × 2 × 1\n*\n* For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\n* and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n*\n* Find the sum of the digits in the number 100!\n*\n* @author ddaniel27\n */\npackage problem20\n\nimport \"math/big\"\n\nfunc Problem20(input int) int {\n\tfactorial := bigFactorial(input)\n\tsum := 0\n\tfor _, digit := range factorial.String() {\n\t\tsum += int(digit - '0')\n\t}\n\treturn sum\n}\n\n// bigFactorial returns the factorial of n as a big.Int\n// Use big package to handle large numbers\nfunc bigFactorial(n int) *big.Int {\n\tif n < 0 {\n\t\treturn big.NewInt(0)\n\t}\n\tif n == 0 {\n\t\treturn big.NewInt(1)\n\t}\n\treturn big.NewInt(0).Mul(big.NewInt(int64(n)), bigFactorial(n-1))\n}\n"
  },
  {
    "path": "project_euler/problem_20/problem20_test.go",
    "content": "package problem20\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem20_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    int\n\t\texpected int\n\t}{\n\t\t{\"Problem 20 - Factorial digit sum\", 10, 27},\n\t\t{\"Problem 20 - Factorial digit sum\", 100, 648},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot := Problem20(test.input)\n\t\t\tif got != test.expected {\n\t\t\t\tt.Errorf(\"Problem20() = got %v, want %v\", got, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem20_Func(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tProblem20(100)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_3/problem3.go",
    "content": "/**\n* Problem 3 - Largest prime factor\n* @see {@link https://projecteuler.net/problem=3}\n*\n* The prime factors of 13195 are 5, 7, 13 and 29.\n* What is the largest prime factor of the number 600851475143 ?\n*\n* @author ddaniel27\n */\npackage problem3\n\nfunc Problem3(n uint) uint {\n\ti := uint(2)\n\n\tfor n > 1 {\n\t\tif n%i == 0 {\n\t\t\tn /= i\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn i\n}\n"
  },
  {
    "path": "project_euler/problem_3/problem3_test.go",
    "content": "package problem3\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem3_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 13195\",\n\t\t\tinput: 13195,\n\t\t\twant:  29,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 600851475143\",\n\t\t\tinput: 600851475143,\n\t\t\twant:  6857,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem3(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem3() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem3(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem3(600851475143)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_4/problem4.go",
    "content": "/**\n* Problem 4 - Largest palindrome product\n* @see {@link https://projecteuler.net/problem=4}\n*\n* A palindromic number reads the same both ways.\n* The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n* Find the largest palindrome made from the product of two 3-digit numbers.\n*\n* @author ddaniel27\n */\npackage problem4\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TheAlgorithms/Go/strings/palindrome\"\n)\n\nfunc Problem4() uint {\n\tmax := uint(0)\n\n\tfor i := 999; i >= 100; i-- {\n\t\tfor j := 999; j >= 100; j-- {\n\t\t\tn := uint(i * j)\n\n\t\t\tif palindrome.IsPalindrome(fmt.Sprintf(\"%d\", n)) && n > max {\n\t\t\t\tmax = n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn max\n}\n"
  },
  {
    "path": "project_euler/problem_4/problem4_test.go",
    "content": "package problem4\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem4_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant uint\n\t}{\n\t\t{\n\t\t\tname: \"Testcase 1\",\n\t\t\twant: 906609,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem4()\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem4() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem4(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem4()\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_5/problem5.go",
    "content": "/**\n* Problem 5 - Smallest multiple\n* @see {@link https://projecteuler.net/problem=5}\n*\n* 2520 is the smallest number that can be divided by\n* each of the numbers from 1 to 10 without any remainder.\n* What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n*\n* @author ddaniel27\n */\npackage problem5\n\nfunc Problem5(limit uint) uint {\n\tn := limit * limit\n\n\tfor {\n\t\tif isDivisible(n, limit) {\n\t\t\treturn n\n\t\t}\n\n\t\tn++\n\t}\n}\n\nfunc isDivisible(n, limit uint) bool {\n\tfor i := uint(1); i <= limit; i++ {\n\t\tif n%i != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n"
  },
  {
    "path": "project_euler/problem_5/problem5_test.go",
    "content": "package problem5\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem5_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 10\",\n\t\t\tinput: 10,\n\t\t\twant:  2520,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 20\",\n\t\t\tinput: 20,\n\t\t\twant:  232792560,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 3 - input 5\",\n\t\t\tinput: 5,\n\t\t\twant:  60,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem5(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem5() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem5(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem5(20)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_6/problem6.go",
    "content": "/**\n* Problem 6 - Sum square difference\n* @see {@link https://projecteuler.net/problem=6}\n*\n* The sum of the squares of the first ten natural numbers is,\n* 1^2 + 2^2 + ... + 10^2 = 385\n*\n* The square of the sum of the first ten natural numbers is,\n* (1 + 2 + ... + 10)^2 = 55^2 = 3025\n*\n* Hence the difference between the sum of the squares of the first ten natural numbers\n* and the square of the sum is 3025 − 385 = 2640.\n*\n* Find the difference between the sum of the squares of the first one hundred natural numbers\n* and the square of the sum.\n*\n* @author ddaniel27\n */\npackage problem6\n\nfunc Problem6(n uint) uint {\n\tsumOfSquares := uint(0)\n\tsquareOfSum := uint(0)\n\n\tfor i := uint(1); i <= n; i++ {\n\t\tsumOfSquares += i * i\n\t\tsquareOfSum += i\n\t}\n\n\tsquareOfSum *= squareOfSum\n\n\treturn squareOfSum - sumOfSquares\n}\n"
  },
  {
    "path": "project_euler/problem_6/problem6_test.go",
    "content": "package problem6\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem6_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 10\",\n\t\t\tinput: 10,\n\t\t\twant:  2640,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 100\",\n\t\t\tinput: 100,\n\t\t\twant:  25164150,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem6(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem6() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem6(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem6(100)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_7/problem7.go",
    "content": "/**\n* Problem 7 - 10001st prime\n* @see {@link https://projecteuler.net/problem=7}\n*\n* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,\n* we can see that the 6th prime is 13.\n*\n* What is the 10 001st prime number?\n*\n* @author ddaniel27\n */\npackage problem7\n\nimport \"github.com/TheAlgorithms/Go/math/prime\"\n\nfunc Problem7(n uint) int64 {\n\tcount, i := uint(0), int64(1)\n\n\tfor count < n {\n\t\ti++\n\t\tif prime.OptimizedTrialDivision(i) {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn i\n}\n"
  },
  {
    "path": "project_euler/problem_7/problem7_test.go",
    "content": "package problem7\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem7_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput uint\n\t\twant  int64\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 6\",\n\t\t\tinput: 6,\n\t\t\twant:  13,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 10001\",\n\t\t\tinput: 10001,\n\t\t\twant:  104743,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem7(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem7() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem7(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem7(10001)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_8/problem8.go",
    "content": "/**\n* Problem 8 - Largest product in a series\n* @see {@link https://projecteuler.net/problem=8}\n*\n* The four adjacent digits in the 1000-digit number that\n* have the greatest product are 9 × 9 × 8 × 9 = 5832.\n* Find the thirteen adjacent digits in the 1000-digit number\n* that have the greatest product. What is the value of this product?\n*\n* @author ddaniel27\n */\npackage problem8\n\nconst number = \"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450\"\n\nfunc Problem8(window int) uint {\n\tmax := uint(0)\n\n\tfor i := 0; i < len(number)-window; i++ {\n\t\tproduct := uint(1)\n\n\t\tfor j := 0; j < window; j++ {\n\t\t\tn := uint(number[i+j] - '0')\n\t\t\tproduct *= n\n\t\t}\n\n\t\tif product > max {\n\t\t\tmax = product\n\t\t}\n\t}\n\n\treturn max\n}\n"
  },
  {
    "path": "project_euler/problem_8/problem8_test.go",
    "content": "package problem8\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem8_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput int\n\t\twant  uint\n\t}{\n\t\t{\n\t\t\tname:  \"Testcase 1 - input 4\",\n\t\t\tinput: 4,\n\t\t\twant:  5832,\n\t\t},\n\t\t{\n\t\t\tname:  \"Testcase 2 - input 13\",\n\t\t\tinput: 13,\n\t\t\twant:  23514624000,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem8(tt.input)\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem8() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem8(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem8(13)\n\t}\n}\n"
  },
  {
    "path": "project_euler/problem_9/problem9.go",
    "content": "/**\n* Problem 9 - Special Pythagorean triplet\n* @see {@link https://projecteuler.net/problem=9}\n*\n* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n* a^2 + b^2 = c^2\n*\n* For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.\n*\n* There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n* Find the product abc.\n*\n* @author ddaniel27\n */\npackage problem9\n\nfunc Problem9() uint {\n\tfor a := uint(1); a < 1000; a++ {\n\t\tfor b := a + 1; b < 1000; b++ {\n\t\t\tc := 1000 - a - b\n\n\t\t\tif a*a+b*b == c*c {\n\t\t\t\treturn a * b * c\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0\n}\n"
  },
  {
    "path": "project_euler/problem_9/problem9_test.go",
    "content": "package problem9\n\nimport \"testing\"\n\n// Tests\nfunc TestProblem9_Func(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant uint\n\t}{\n\t\t{\n\t\t\tname: \"Testcase 1\",\n\t\t\twant: 31875000,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tn := Problem9()\n\n\t\t\tif n != tt.want {\n\t\t\t\tt.Errorf(\"Problem9() = %v, want %v\", n, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Benchmarks\nfunc BenchmarkProblem9(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = Problem9()\n\t}\n}\n"
  },
  {
    "path": "search/binary.go",
    "content": "package search\n\n// Binary search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.\n// This function uses recursive call to itself.\n// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.\nfunc Binary(array []int, target int, lowIndex int, highIndex int) (int, error) {\n\tif highIndex < lowIndex || len(array) == 0 {\n\t\treturn -1, ErrNotFound\n\t}\n\tmid := int(lowIndex + (highIndex-lowIndex)/2)\n\tif array[mid] > target {\n\t\treturn Binary(array, target, lowIndex, mid-1)\n\t} else if array[mid] < target {\n\t\treturn Binary(array, target, mid+1, highIndex)\n\t} else {\n\t\treturn mid, nil\n\t}\n}\n\n// BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target.\n// Unlike Binary, this function uses iterative method and not recursive.\n// If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.\nfunc BinaryIterative(array []int, target int) (int, error) {\n\tstartIndex := 0\n\tendIndex := len(array) - 1\n\tvar mid int\n\tfor startIndex <= endIndex {\n\t\tmid = int(startIndex + (endIndex-startIndex)/2)\n\t\tif array[mid] > target {\n\t\t\tendIndex = mid - 1\n\t\t} else if array[mid] < target {\n\t\t\tstartIndex = mid + 1\n\t\t} else {\n\t\t\treturn mid, nil\n\t\t}\n\t}\n\treturn -1, ErrNotFound\n}\n\n// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.\n// return -1 and ErrNotFound if no such element is found.\nfunc LowerBound(array []int, target int) (int, error) {\n\tstartIndex := 0\n\tendIndex := len(array) - 1\n\tvar mid int\n\tfor startIndex <= endIndex {\n\t\tmid = int(startIndex + (endIndex-startIndex)/2)\n\t\tif array[mid] < target {\n\t\t\tstartIndex = mid + 1\n\t\t} else {\n\t\t\tendIndex = mid - 1\n\t\t}\n\t}\n\n\t//when target greater than every element in array, startIndex will out of bounds\n\tif startIndex >= len(array) {\n\t\treturn -1, ErrNotFound\n\t}\n\treturn startIndex, nil\n}\n\n// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.\n// return -1 and ErrNotFound if no such element is found.\nfunc UpperBound(array []int, target int) (int, error) {\n\tstartIndex := 0\n\tendIndex := len(array) - 1\n\tvar mid int\n\tfor startIndex <= endIndex {\n\t\tmid = int(startIndex + (endIndex-startIndex)/2)\n\t\tif array[mid] > target {\n\t\t\tendIndex = mid - 1\n\t\t} else {\n\t\t\tstartIndex = mid + 1\n\t\t}\n\t}\n\n\t//when target greater or equal than every element in array, startIndex will out of bounds\n\tif startIndex >= len(array) {\n\t\treturn -1, ErrNotFound\n\t}\n\treturn startIndex, nil\n}\n"
  },
  {
    "path": "search/binary_test.go",
    "content": "package search\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestBinary(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := Binary(test.data, test.key, 0, len(test.data)-1)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif !errors.Is(test.expectedError, actualError) {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc TestBinaryIterative(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := BinaryIterative(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif !errors.Is(test.expectedError, actualError) {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc TestLowerBound(t *testing.T) {\n\tfor _, test := range lowerBoundTests {\n\t\tactualValue, actualError := LowerBound(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif !errors.Is(test.expectedError, actualError) {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc TestUpperBound(t *testing.T) {\n\tfor _, test := range upperBoundTests {\n\t\tactualValue, actualError := UpperBound(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif !errors.Is(test.expectedError, actualError) {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc BenchmarkBinary(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Binary(testCase, i, 0, len(testCase)-1)\n\t}\n}\n\nfunc BenchmarkBinaryIterative(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = BinaryIterative(testCase, i)\n\t}\n}\n\nfunc BenchmarkLowerBound(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = LowerBound(testCase, i)\n\t}\n}\n\nfunc BenchmarkUpperBound(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // this is important because the generateBenchmarkTestCase() is expensive\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = UpperBound(testCase, i)\n\t}\n}\n"
  },
  {
    "path": "search/doc.go",
    "content": "// Package search is a subpackage dedicated to all searching algorithms related to slices/arrays.\npackage search\n"
  },
  {
    "path": "search/errors.go",
    "content": "package search\n\nimport \"errors\"\n\n// ErrNotFound is returned by search functions when target is not found\nvar ErrNotFound = errors.New(\"target not found in array\")\n"
  },
  {
    "path": "search/interpolation.go",
    "content": "package search\n\n// Interpolation searches for the entity in the given sortedData.\n// if the entity is present, it will return the index of the entity, if not -1 will be returned.\n// see: https://en.wikipedia.org/wiki/Interpolation_search\n// Complexity\n//\n//\tWorst: O(N)\n//\tAverage: O(log(log(N))  if the elements are uniformly distributed\n//\tBest: O(1)\n//\n// Example\n//\n//\tfmt.Println(InterpolationSearch([]int{1, 2, 9, 20, 31, 45, 63, 70, 100},100))\nfunc Interpolation(sortedData []int, guess int) (int, error) {\n\tif len(sortedData) == 0 {\n\t\treturn -1, ErrNotFound\n\t}\n\n\tvar (\n\t\tlow, high       = 0, len(sortedData) - 1\n\t\tlowVal, highVal = sortedData[low], sortedData[high]\n\t)\n\n\tfor lowVal != highVal && (lowVal <= guess) && (guess <= highVal) {\n\t\tmid := low + int(float64(float64((guess-lowVal)*(high-low))/float64(highVal-lowVal)))\n\n\t\t// if guess is found, array can also have duplicate values, so scan backwards and find the first index\n\t\tif sortedData[mid] == guess {\n\t\t\tfor mid > 0 && sortedData[mid-1] == guess {\n\t\t\t\tmid--\n\t\t\t}\n\t\t\treturn mid, nil\n\n\t\t}\n\n\t\t// adjust our guess and continue\n\t\tif sortedData[mid] > guess {\n\t\t\thigh, highVal = mid-1, sortedData[high]\n\n\t\t} else {\n\t\t\tlow, lowVal = mid+1, sortedData[low]\n\t\t}\n\n\t}\n\n\tif guess == lowVal {\n\t\treturn low, nil\n\t}\n\treturn -1, ErrNotFound\n}\n"
  },
  {
    "path": "search/interpolation_test.go",
    "content": "package search\n\nimport \"testing\"\n\nfunc TestInterpolation(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := Interpolation(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif actualError != test.expectedError {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc BenchmarkInterpolation(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // exclude time taken to generate test case\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Interpolation(testCase, i)\n\t}\n}\n"
  },
  {
    "path": "search/jump.go",
    "content": "// jump.go\n// description: Implementation of jump search\n// details:\n// A search algorithm for ordered list that jump through the list to narrow down the range\n// before performing a linear search\n// reference: https://en.wikipedia.org/wiki/Jump_search\n// see jump_test.go for a test implementation, test function TestJump\n// time complexity: O(sqrt(n))\n// space complexity: O(1)\n\npackage search\n\nimport \"math\"\n\n// Jump search works by jumping multiple steps ahead in sorted list until it find an item larger than target,\n// then create a sublist of item from the last searched item up to the current item and perform a linear search.\nfunc Jump(array []int, target int) (int, error) {\n\tn := len(array)\n\tif n == 0 {\n\t\treturn -1, ErrNotFound\n\t}\n\n\t// the optimal value of step is square root of the length of list\n\tstep := int(math.Round(math.Sqrt(float64(n))))\n\n\tprev := 0    // previous index\n\tcurr := step // current index\n\tfor array[curr-1] < target {\n\t\tprev = curr\n\t\tif prev >= len(array) {\n\t\t\treturn -1, ErrNotFound\n\t\t}\n\n\t\tcurr += step\n\n\t\t// prevent jumping over list range\n\t\tif curr > n {\n\t\t\tcurr = n\n\t\t}\n\t}\n\n\t// perform linear search from index prev to index curr\n\tfor array[prev] < target {\n\t\tprev++\n\n\t\t// if reach end of range, indicate target not found\n\t\tif prev == curr {\n\t\t\treturn -1, ErrNotFound\n\t\t}\n\t}\n\tif array[prev] == target {\n\t\treturn prev, nil\n\t}\n\n\treturn -1, ErrNotFound\n\n}\n"
  },
  {
    "path": "search/jump2.go",
    "content": "package search\n\nimport \"math\"\n\nfunc Jump2(arr []int, target int) (int, error) {\n\tstep := int(math.Round(math.Sqrt(float64(len(arr)))))\n\trbound := len(arr)\n\tfor i := step; i < len(arr); i += step {\n\t\tif arr[i] > target {\n\t\t\trbound = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i := rbound - step; i < rbound; i++ {\n\t\tif arr[i] == target {\n\t\t\treturn i, nil\n\t\t}\n\t\tif arr[i] > target {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn -1, ErrNotFound\n}\n"
  },
  {
    "path": "search/jump2_test.go",
    "content": "package search\n\nimport \"testing\"\n\nfunc TestJump2(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := Jump2(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif actualError != test.expectedError {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc BenchmarkJump2(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // exclude time taken to generate test case\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Jump2(testCase, i)\n\t}\n}\n"
  },
  {
    "path": "search/jump_test.go",
    "content": "package search\n\nimport \"testing\"\n\nfunc TestJump(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := Jump(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif actualError != test.expectedError {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc BenchmarkJump(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // exclude time taken to generate test case\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Jump(testCase, i)\n\t}\n}\n"
  },
  {
    "path": "search/linear.go",
    "content": "package search\n\n// Linear Simple linear search algorithm that iterates over all elements of an array in the worst case scenario\nfunc Linear(array []int, query int) (int, error) {\n\tfor i, item := range array {\n\t\tif item == query {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn -1, ErrNotFound\n}\n"
  },
  {
    "path": "search/linear_test.go",
    "content": "package search\n\nimport (\n\t\"testing\"\n)\n\nfunc TestLinear(t *testing.T) {\n\tfor _, test := range searchTests {\n\t\tactualValue, actualError := Linear(test.data, test.key)\n\t\tif actualValue != test.expected {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected '%d', get '%d'\", test.name, test.data, test.key, test.expected, actualValue)\n\t\t}\n\t\tif actualError != test.expectedError {\n\t\t\tt.Errorf(\"test '%s' failed: input array '%v' with key '%d', expected error '%s', get error '%s'\", test.name, test.data, test.key, test.expectedError, actualError)\n\t\t}\n\t}\n}\n\nfunc BenchmarkLinear(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\tb.ResetTimer() // exclude time taken to generate test case\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = Linear(testCase, i)\n\t}\n}\n"
  },
  {
    "path": "search/selectk.go",
    "content": "package search\n\nfunc SelectK(array []int, k int) (int, error) {\n\tif k > len(array) {\n\t\treturn -1, ErrNotFound\n\t}\n\treturn selectK(array, 0, len(array), len(array)-k), nil\n}\n\n// search the element which index is idx\nfunc selectK(array []int, l, r, idx int) int {\n\tindex := partition(array, l, r)\n\tif index == idx {\n\t\treturn array[index]\n\t}\n\tif index < idx {\n\t\treturn selectK(array, index+1, r, idx)\n\t}\n\treturn selectK(array, l, index, idx)\n}\n\nfunc partition(array []int, l, r int) int {\n\telem, j := array[l], l+1\n\tfor i := l + 1; i < r; i++ {\n\t\tif array[i] <= elem {\n\t\t\tarray[i], array[j] = array[j], array[i]\n\t\t\tj++\n\t\t}\n\t}\n\tarray[l], array[j-1] = array[j-1], array[l]\n\treturn j - 1\n}\n"
  },
  {
    "path": "search/selectk_test.go",
    "content": "package search\n\nimport (\n\t\"testing\"\n)\n\nfunc TestSelectK(t *testing.T) {\n\ttests := []struct {\n\t\tdata     []int\n\t\tk        int\n\t\texpected int\n\t\terr      error\n\t\tname     string\n\t}{\n\t\t{[]int{1, 2, 3, 4, 5}, 1, 5, nil, \"sorted data\"},\n\t\t{[]int{5, 4, 3, 2, 1}, 2, 4, nil, \"reversed data\"},\n\t\t{[]int{3, 1, 2, 5, 4}, 3, 3, nil, \"random data\"},\n\t\t{[]int{3, 2, 1, 5, 4}, 10, -1, ErrNotFound, \" absent data\"},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\telem, err := SelectK(tc.data, tc.k)\n\t\t\tif err != tc.err {\n\t\t\t\tt.Errorf(\"name:%v SelectK() = _, %v, want err: %v\", tc.name, err, tc.err)\n\t\t\t}\n\t\t\tif elem != tc.expected {\n\t\t\t\tt.Errorf(\"name:%v SelectK() = %v,_ , want: %v\", tc.name, elem, tc.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkSelectK(b *testing.B) {\n\ttestCase := generateBenchmarkTestCase()\n\ttestCase = append(testCase, 1) // make sure len(testCase)/2+1 is valid\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = SelectK(testCase, len(testCase)/2)\n\t}\n}\n"
  },
  {
    "path": "search/ternary.go",
    "content": "package search\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// TernaryMax is a function to search for maximum value of a uni-modal function `f`\n// in the interval [a, b]. a and b should be finit numbers\nfunc TernaryMax(a, b, epsilon float64, f func(x float64) float64) (float64, error) {\n\tif a == math.Inf(-1) || b == math.Inf(1) {\n\t\treturn -1, fmt.Errorf(\"interval boundaries should be finite numbers\")\n\t}\n\tif math.Abs(a-b) <= epsilon {\n\t\treturn f((a + b) / 2), nil\n\t}\n\tleft := (2*a + b) / 3\n\tright := (a + 2*b) / 3\n\tif f(left) < f(right) {\n\t\treturn TernaryMax(left, b, epsilon, f)\n\t}\n\treturn TernaryMax(a, right, epsilon, f)\n}\n\n// TernaryMin is a function to search for minimum value of a uni-modal function `f`\n// in the interval [a, b]. a and b should be finit numbers.\nfunc TernaryMin(a, b, epsilon float64, f func(x float64) float64) (float64, error) {\n\tif a == math.Inf(-1) || b == math.Inf(1) {\n\t\treturn -1, fmt.Errorf(\"interval boundaries should be finite numbers\")\n\t}\n\tif math.Abs(a-b) <= epsilon {\n\t\treturn f((a + b) / 2), nil\n\t}\n\tleft := (2*a + b) / 3\n\tright := (a + 2*b) / 3\n\tif f(left) > f(right) {\n\t\treturn TernaryMin(left, b, epsilon, f)\n\t}\n\treturn TernaryMin(a, right, epsilon, f)\n}\n"
  },
  {
    "path": "search/ternary_test.go",
    "content": "package search\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nconst EPS = 1e-6\n\nfunc equal(a, b float64) bool {\n\treturn math.Abs(a-b) <= EPS\n}\n\nfunc TestTernaryMax(t *testing.T) {\n\n\tvar tests = []struct {\n\t\tf        func(x float64) float64\n\t\ta        float64\n\t\tb        float64\n\t\texpected float64\n\t}{\n\t\t{f: func(x float64) float64 { return -x * x }, a: 1, b: -1, expected: 0},\n\t\t{f: func(x float64) float64 { return -2*x*x - x + 1 }, a: -1, b: 1, expected: 1.125},\n\t}\n\tfor _, test := range tests {\n\t\tresult, err := TernaryMax(test.a, test.b, EPS, test.f)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"error occurred: %v\", err)\n\t\t}\n\t\tif !equal(result, test.expected) {\n\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.expected, result)\n\t\t}\n\t}\n}\n\nfunc TestTernaryMin(t *testing.T) {\n\n\tvar tests = []struct {\n\t\tf        func(x float64) float64\n\t\ta        float64\n\t\tb        float64\n\t\texpected float64\n\t}{\n\t\t{f: func(x float64) float64 { return x * x }, a: -1, b: 1, expected: 0},\n\t\t{f: func(x float64) float64 { return 2*x*x + x + 1 }, a: -1, b: 1, expected: 0.875},\n\t}\n\tfor _, test := range tests {\n\t\tresult, err := TernaryMin(test.a, test.b, EPS, test.f)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"error occurred: %v\", err)\n\t\t}\n\t\tif !equal(result, test.expected) {\n\t\t\tt.Errorf(\"Wrong result! Expected:%v, returned:%v \", test.expected, result)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "search/testcases.go",
    "content": "package search\n\ntype searchTest struct {\n\tdata          []int\n\tkey           int\n\texpected      int\n\texpectedError error\n\tname          string\n}\n\n// Note that these are immutable therefore they are shared among all the search tests.\n// If your algorithm is mutating these then it is advisable to create separate test cases.\nvar searchTests = []searchTest{\n\t//Sanity\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, 9, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 9, 8, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 8, 7, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 7, 6, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 6, 5, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 4, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 4, 3, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 3, 2, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 2, 1, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 0, nil, \"Sanity\"},\n\t//Absent\n\t{[]int{1, 4, 5, 6, 7, 10}, -25, -1, ErrNotFound, \"Absent\"},\n\t{[]int{1, 4, 5, 6, 7, 10}, 25, -1, ErrNotFound, \"Absent\"},\n\t//Empty slice\n\t{[]int{}, 2, -1, ErrNotFound, \"Empty\"},\n}\n\nvar lowerBoundTests = []searchTest{\n\t//Sanity\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, -25, 0, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 0, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 4, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, 9, nil, \"Sanity\"},\n\t{[]int{1, 2, 2, 2, 2, 6, 7, 8, 9, 10}, 2, 1, nil, \"Sanity\"},\n\t{[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 2, 0, nil, \"Sanity\"},\n\t//Absent\n\t{[]int{1, 4, 5, 6, 7, 10}, 25, -1, ErrNotFound, \"Absent\"},\n\t//Empty slice\n\t{[]int{}, 2, -1, ErrNotFound, \"Empty\"},\n}\n\nvar upperBoundTests = []searchTest{\n\t//Sanity\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, -25, 0, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 1, nil, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 5, nil, \"Sanity\"},\n\t{[]int{1, 2, 2, 2, 2, 6, 7, 8, 9, 10}, 2, 5, nil, \"Sanity\"},\n\t//Absent\n\t{[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, 2, -1, ErrNotFound, \"Sanity\"},\n\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, -1, ErrNotFound, \"Sanity\"},\n\t{[]int{1, 4, 5, 6, 7, 10}, 25, -1, ErrNotFound, \"Absent\"},\n\t//Empty slice\n\t{[]int{}, 2, -1, ErrNotFound, \"Empty\"},\n}\n\n// This function generate consistent testcase for benchmark test.\nfunc generateBenchmarkTestCase() []int {\n\tvar testCase []int\n\tfor i := 0; i < 1000; i++ {\n\t\ttestCase = append(testCase, i)\n\t}\n\treturn testCase\n}\n"
  },
  {
    "path": "sort/binaryinsertionsort.go",
    "content": "// Binary Insertion Sort\n// description: Implementation of binary insertion sort in Go\n// details: Binary Insertion Sort is a variation of\n// Insertion sort in which proper location to\n// insert the selected element is found using the\n// Binary search algorithm.\n// ref: https://www.geeksforgeeks.org/binary-insertion-sort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc BinaryInsertion[T constraints.Ordered](arr []T) []T {\n\tfor currentIndex := 1; currentIndex < len(arr); currentIndex++ {\n\t\ttemporary := arr[currentIndex]\n\t\tlow := 0\n\t\thigh := currentIndex - 1\n\n\t\tfor low <= high {\n\t\t\tmid := low + (high-low)/2\n\t\t\tif arr[mid] > temporary {\n\t\t\t\thigh = mid - 1\n\t\t\t} else {\n\t\t\t\tlow = mid + 1\n\t\t\t}\n\t\t}\n\n\t\tfor itr := currentIndex; itr > low; itr-- {\n\t\t\tarr[itr] = arr[itr-1]\n\t\t}\n\n\t\tarr[low] = temporary\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/bogosort.go",
    "content": "// This is a pure Go implementation of the bogosort algorithm,\n// also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.\n// Bogosort generates random permutations until it guesses the correct one.\n// worst-case time complexity: O((n+1)!)\n// best-case time complexity: O(n)\n// More info on: https://en.wikipedia.org/wiki/Bogosort\n\npackage sort\n\nimport (\n\t\"math/rand\"\n\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\nfunc isSorted[T constraints.Number](arr []T) bool {\n\tfor i := 0; i < len(arr)-1; i++ {\n\t\tif arr[i] > arr[i+1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc shuffle[T constraints.Number](arr []T) {\n\tfor i := range arr {\n\t\tj := rand.Intn(i + 1)\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n}\n\nfunc Bogo[T constraints.Number](arr []T) []T {\n\tfor !isSorted(arr) {\n\t\tshuffle(arr)\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/bubblesort.go",
    "content": "// Implementation of basic bubble sort algorithm\n// Reference: https://en.wikipedia.org/wiki/Bubble_sort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Bubble is a simple generic definition of Bubble sort algorithm.\nfunc Bubble[T constraints.Ordered](arr []T) []T {\n\tswapped := true\n\tfor swapped {\n\t\tswapped = false\n\t\tfor i := 0; i < len(arr)-1; i++ {\n\t\t\tif arr[i+1] < arr[i] {\n\t\t\t\tarr[i+1], arr[i] = arr[i], arr[i+1]\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/bucketsort.go",
    "content": "package sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Bucket sorts a slice. It is mainly useful\n// when input is uniformly distributed over a range.\nfunc Bucket[T constraints.Number](arr []T) []T {\n\t// early return if the array too small\n\tif len(arr) <= 1 {\n\t\treturn arr\n\t}\n\n\t// find the maximum and minimum elements in arr\n\tmax := arr[0]\n\tmin := arr[0]\n\tfor _, v := range arr {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\t// create an empty bucket for each element in arr\n\tbucket := make([][]T, len(arr))\n\n\t// put each element in the appropriate bucket\n\tfor _, v := range arr {\n\t\tbucketIndex := int((v - min) / (max - min) * T(len(arr)-1))\n\t\tbucket[bucketIndex] = append(bucket[bucketIndex], v)\n\t}\n\n\t// use insertion sort to sort each bucket\n\tfor i := range bucket {\n\t\tbucket[i] = Insertion(bucket[i])\n\t}\n\n\t// concatenate the sorted buckets\n\tsorted := make([]T, 0, len(arr))\n\tfor _, v := range bucket {\n\t\tsorted = append(sorted, v...)\n\t}\n\n\treturn sorted\n}\n"
  },
  {
    "path": "sort/circlesort.go",
    "content": "// Package sort implements various sorting algorithms.\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Circle sorts an array using the circle sort algorithm.\nfunc Circle[T constraints.Ordered](arr []T) []T {\n\tif len(arr) == 0 {\n\t\treturn arr\n\t}\n\tfor doSort(arr, 0, len(arr)-1) {\n\t}\n\treturn arr\n}\n\n// doSort is the recursive function that implements the circle sort algorithm.\nfunc doSort[T constraints.Ordered](arr []T, left, right int) bool {\n\tif left == right {\n\t\treturn false\n\t}\n\tswapped := false\n\tlow := left\n\thigh := right\n\n\tfor low < high {\n\t\tif arr[low] > arr[high] {\n\t\t\tarr[low], arr[high] = arr[high], arr[low]\n\t\t\tswapped = true\n\t\t}\n\t\tlow++\n\t\thigh--\n\t}\n\n\tif low == high && arr[low] > arr[high+1] {\n\t\tarr[low], arr[high+1] = arr[high+1], arr[low]\n\t\tswapped = true\n\t}\n\n\tmid := left + (right-left)/2\n\tleftHalf := doSort(arr, left, mid)\n\trightHalf := doSort(arr, mid+1, right)\n\n\treturn swapped || leftHalf || rightHalf\n}\n"
  },
  {
    "path": "sort/cocktailsort.go",
    "content": "// Implementation of Cocktail sorting\n// reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)\nfunc Cocktail[T constraints.Ordered](arr []T) []T {\n\tif len(arr) == 0 { // ignore 0 length arrays\n\t\treturn arr\n\t}\n\n\tswapped := true // true if swapped two or more elements in the last loop\n\t// if it loops through the array without swapping, the array is sorted\n\n\t// start and end indexes, this will be updated excluding already sorted elements\n\tstart := 0\n\tend := len(arr) - 1\n\n\tfor swapped {\n\t\tswapped = false\n\t\tvar new_start int\n\t\tvar new_end int\n\n\t\tfor i := start; i < end; i++ { // first loop, from start to end\n\t\t\tif arr[i] > arr[i+1] { // if current and next elements are unordered\n\t\t\t\tarr[i], arr[i+1] = arr[i+1], arr[i] // swap two elements\n\t\t\t\tnew_end = i\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\n\t\tend = new_end\n\n\t\tif !swapped { // early exit, skipping the second loop\n\t\t\tbreak\n\t\t}\n\n\t\tswapped = false\n\n\t\tfor i := end; i > start; i-- { // second loop, from end to start\n\t\t\tif arr[i] < arr[i-1] { // same process of the first loop, now going 'backwards'\n\t\t\t\tarr[i], arr[i-1] = arr[i-1], arr[i]\n\t\t\t\tnew_start = i\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\n\t\tstart = new_start\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/combSort.go",
    "content": "// Implementation of comb sort algorithm, an improvement of bubble sort\n// average time complexity: O(n^2 / 2^p) where p is the number of increments\n// worst time complexity: O(n^2)\n// space complexity: O(1)\n// Reference: https://www.geeksforgeeks.org/comb-sort/\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc getNextGap(gap int) int {\n\tgap = (gap * 10) / 13\n\tif gap < 1 {\n\t\treturn 1\n\t}\n\treturn gap\n}\n\n// Comb is a simple sorting algorithm which is an improvement of the bubble sorting algorithm.\nfunc Comb[T constraints.Ordered](data []T) []T {\n\tn := len(data)\n\tgap := n\n\tswapped := true\n\n\tfor gap != 1 || swapped {\n\t\tgap = getNextGap(gap)\n\t\tswapped = false\n\t\tfor i := 0; i < n-gap; i++ {\n\t\t\tif data[i] > data[i+gap] {\n\t\t\t\tdata[i], data[i+gap] = data[i+gap], data[i]\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\t}\n\treturn data\n}\n"
  },
  {
    "path": "sort/countingsort.go",
    "content": "// countingsort.go\n// description: Implementation of counting sort algorithm\n// details: A simple counting sort algorithm implementation\n// worst-case time complexity: O(n + k) where n is the number of elements in the input array and k is the range of the input\n// average-case time complexity: O(n + k) where n is the number of elements in the input array and k is the range of the input\n// space complexity: O(n + k)\n// author [Phil](https://github.com/pschik)\n// see sort_test.go for a test implementation, test function TestQuickSort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Count[T constraints.Integer](data []T) []T {\n\tif len(data) == 0 {\n\t\treturn data\n\t}\n\tvar aMin, aMax = data[0], data[0]\n\tfor _, x := range data {\n\t\tif x < aMin {\n\t\t\taMin = x\n\t\t}\n\t\tif x > aMax {\n\t\t\taMax = x\n\t\t}\n\t}\n\tcount := make([]int, aMax-aMin+1)\n\tfor _, x := range data {\n\t\tcount[x-aMin]++ // this is the reason for having only Integer constraint instead of Ordered.\n\t}\n\tz := 0\n\tfor i, c := range count {\n\t\tfor c > 0 {\n\t\t\tdata[z] = T(i) + aMin\n\t\t\tz++\n\t\t\tc--\n\t\t}\n\t}\n\treturn data\n}\n"
  },
  {
    "path": "sort/cyclesort.go",
    "content": "package sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\n// Cycle sort is an in-place, unstable sorting algorithm that is particularly useful\n// when sorting arrays containing elements with a small range of values. It is theoretically\n// optimal in terms of the total number of writes to the original array.\nfunc Cycle[T constraints.Number](arr []T) []T {\n\tcounter, cycle, len := 0, 0, len(arr)\n\t// Early return if the array too small\n\tif len <= 1 {\n\t\treturn arr\n\t}\n\n\tfor cycle = 0; cycle < len-1; cycle++ {\n\t\telem := arr[cycle]\n\t\t// Find total smaller elements to right\n\t\tpos := cycle\n\t\tfor counter = cycle + 1; counter < len; counter++ {\n\t\t\tif arr[counter] < elem {\n\t\t\t\tpos++\n\t\t\t}\n\t\t}\n\t\t// In case this element is already in correct position, let's skip processing\n\t\tif pos == cycle {\n\t\t\tcontinue\n\t\t}\n\t\t// In case we have same elements, we want to skip to the end of that list as well, ignoring order\n\t\t// This makes the algorithm unstable for composite elements\n\t\tfor elem == arr[pos] {\n\t\t\tpos++\n\t\t}\n\t\t// Now let us put the item to it's right position\n\t\tarr[pos], elem = elem, arr[pos]\n\n\t\t//We need to rotate the array till we have reached the start of the cycle again\n\t\tfor pos != cycle {\n\t\t\tpos = cycle\n\t\t\t// Find smaller elements to right again\n\t\t\tfor counter = cycle + 1; counter < len; counter++ {\n\t\t\t\tif arr[counter] < elem {\n\t\t\t\t\tpos++\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor elem == arr[pos] {\n\t\t\t\tpos++\n\t\t\t}\n\t\t\t//We can do this unconditionally, but the check helps prevent redundant writes to the array\n\t\t\tif elem != arr[pos] {\n\t\t\t\tarr[pos], elem = elem, arr[pos]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/doc.go",
    "content": "// Package sort a package for demonstrating sorting algorithms in Go\npackage sort\n"
  },
  {
    "path": "sort/exchangesort.go",
    "content": "// Implementation of exchange sort algorithm, a variant of bubble sort\n// average time complexity: O(n^2)\n// worst time complexity: O(n^2)\n// space complexity: O(1)\n// Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Exchange[T constraints.Ordered](arr []T) []T {\n\tfor i := 0; i < len(arr)-1; i++ {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[i] > arr[j] {\n\t\t\t\tarr[i], arr[j] = arr[j], arr[i]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/heapsort.go",
    "content": "// heapsort.go\n// description: Implementation of heap sort algorithm\n// worst-case time complexity: O(n log n)\n// average-case time complexity: O(n log n)\n// space complexity: O(1)\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\ntype MaxHeap struct {\n\tslice    []Comparable\n\theapSize int\n\tindices  map[int]int\n}\n\nfunc (h *MaxHeap) Init(slice []Comparable) {\n\tif slice == nil {\n\t\tslice = make([]Comparable, 0)\n\t}\n\n\th.slice = slice\n\th.heapSize = len(slice)\n\th.indices = make(map[int]int)\n\th.Heapify()\n}\n\nfunc (h MaxHeap) Heapify() {\n\tfor i, v := range h.slice {\n\t\th.indices[v.Idx()] = i\n\t}\n\tfor i := h.heapSize / 2; i >= 0; i-- {\n\t\th.heapifyDown(i)\n\t}\n}\n\nfunc (h *MaxHeap) Pop() Comparable {\n\tif h.heapSize == 0 {\n\t\treturn nil\n\t}\n\n\ti := h.slice[0]\n\th.heapSize--\n\n\th.slice[0] = h.slice[h.heapSize]\n\th.updateidx(0)\n\th.heapifyDown(0)\n\n\th.slice = h.slice[0:h.heapSize]\n\treturn i\n}\n\nfunc (h *MaxHeap) Push(i Comparable) {\n\th.slice = append(h.slice, i)\n\th.updateidx(h.heapSize)\n\th.heapifyUp(h.heapSize)\n\th.heapSize++\n}\n\nfunc (h MaxHeap) Size() int {\n\treturn h.heapSize\n}\n\nfunc (h MaxHeap) Update(i Comparable) {\n\th.slice[h.indices[i.Idx()]] = i\n\th.heapifyUp(h.indices[i.Idx()])\n\th.heapifyDown(h.indices[i.Idx()])\n}\n\nfunc (h MaxHeap) updateidx(i int) {\n\th.indices[h.slice[i].Idx()] = i\n}\n\nfunc (h *MaxHeap) swap(i, j int) {\n\th.slice[i], h.slice[j] = h.slice[j], h.slice[i]\n\th.updateidx(i)\n\th.updateidx(j)\n}\n\nfunc (h MaxHeap) more(i, j int) bool {\n\treturn h.slice[i].More(h.slice[j])\n}\n\nfunc (h MaxHeap) heapifyUp(i int) {\n\tif i == 0 {\n\t\treturn\n\t}\n\tp := i / 2\n\n\tif h.slice[i].More(h.slice[p]) {\n\t\th.swap(i, p)\n\t\th.heapifyUp(p)\n\t}\n}\n\nfunc (h MaxHeap) heapifyDown(i int) {\n\theapifyDown(h.slice, h.heapSize, i, h.more, h.swap)\n}\n\nfunc heapifyDown[T any](slice []T, N, i int, moreFunc func(i, j int) bool, swapFunc func(i, j int)) {\n\tl, r := 2*i+1, 2*i+2\n\tmax := i\n\n\tif l < N && moreFunc(l, max) {\n\t\tmax = l\n\t}\n\tif r < N && moreFunc(r, max) {\n\t\tmax = r\n\t}\n\tif max != i {\n\t\tswapFunc(i, max)\n\n\t\theapifyDown(slice, N, max, moreFunc, swapFunc)\n\t}\n}\n\ntype Comparable interface {\n\tIdx() int\n\tMore(any) bool\n}\n\nfunc HeapSort[T constraints.Ordered](slice []T) []T {\n\tN := len(slice)\n\n\tmoreFunc := func(i, j int) bool {\n\t\treturn slice[i] > slice[j]\n\t}\n\tswapFunc := func(i, j int) {\n\t\tslice[i], slice[j] = slice[j], slice[i]\n\t}\n\n\t// build a maxheap\n\tfor i := N/2 - 1; i >= 0; i-- {\n\t\theapifyDown(slice, N, i, moreFunc, swapFunc)\n\t}\n\n\tfor i := N - 1; i > 0; i-- {\n\t\tslice[i], slice[0] = slice[0], slice[i]\n\t\theapifyDown(slice, i, 0, moreFunc, swapFunc)\n\t}\n\n\treturn slice\n}\n"
  },
  {
    "path": "sort/insertionsort.go",
    "content": "// insertionsort.go\n// description: Implementation of insertion sort algorithm\n// worst-case time complexity: O(n^2)\n// average-case time complexity: O(n^2)\n// space complexity: O(1)\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Insertion[T constraints.Ordered](arr []T) []T {\n\tfor currentIndex := 1; currentIndex < len(arr); currentIndex++ {\n\t\ttemporary := arr[currentIndex]\n\t\titerator := currentIndex\n\t\tfor ; iterator > 0 && arr[iterator-1] > temporary; iterator-- {\n\t\t\tarr[iterator] = arr[iterator-1]\n\t\t}\n\t\tarr[iterator] = temporary\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/mergesort.go",
    "content": "// mergesort.go\n// description: Implementation of merge sort algorithm\n// worst-case time complexity: O(n log n)\n// average-case time complexity: O(n log n)\n// space complexity: O(n)\n\npackage sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/min\"\n\t\"sync\"\n)\n\nfunc merge[T constraints.Ordered](a []T, b []T) []T {\n\n\tvar r = make([]T, len(a)+len(b))\n\tvar i = 0\n\tvar j = 0\n\n\tfor i < len(a) && j < len(b) {\n\n\t\tif a[i] <= b[j] {\n\t\t\tr[i+j] = a[i]\n\t\t\ti++\n\t\t} else {\n\t\t\tr[i+j] = b[j]\n\t\t\tj++\n\t\t}\n\n\t}\n\n\tfor i < len(a) {\n\t\tr[i+j] = a[i]\n\t\ti++\n\t}\n\tfor j < len(b) {\n\t\tr[i+j] = b[j]\n\t\tj++\n\t}\n\n\treturn r\n\n}\n\n// Merge Perform merge sort on a slice\nfunc Merge[T constraints.Ordered](items []T) []T {\n\n\tif len(items) < 2 {\n\t\treturn items\n\n\t}\n\n\tvar middle = len(items) / 2\n\tvar a = Merge(items[:middle])\n\tvar b = Merge(items[middle:])\n\treturn merge(a, b)\n\n}\n\nfunc MergeIter[T constraints.Ordered](items []T) []T {\n\tfor step := 1; step < len(items); step += step {\n\t\tfor i := 0; i+step < len(items); i += 2 * step {\n\t\t\ttmp := merge(items[i:i+step], items[i+step:min.Int(i+2*step, len(items))])\n\t\t\tcopy(items[i:], tmp)\n\t\t}\n\t}\n\treturn items\n}\n\n// ParallelMerge Perform merge sort on a slice using goroutines\nfunc ParallelMerge[T constraints.Ordered](items []T) []T {\n\tif len(items) < 2 {\n\t\treturn items\n\t}\n\n\tif len(items) < 2048 {\n\t\treturn Merge(items)\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\tvar middle = len(items) / 2\n\tvar a []T\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ta = ParallelMerge(items[:middle])\n\t}()\n\tvar b = ParallelMerge(items[middle:])\n\n\twg.Wait()\n\treturn merge(a, b)\n}\n"
  },
  {
    "path": "sort/oddevensort.go",
    "content": "// oddevensort.go\n// Implementation of Odd-Even Sort (Brick Sort)\n// Reference: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// OddEvenSort performs the odd-even sort algorithm on the given array.\n// It is a variation of bubble sort that compares adjacent pairs, alternating\n// between odd and even indexed elements in each pass until the array is sorted.\nfunc OddEvenSort[T constraints.Ordered](arr []T) []T {\n\tif len(arr) == 0 { // handle empty array\n\t\treturn arr\n\t}\n\n\tswapped := true\n\tfor swapped {\n\t\tswapped = false\n\n\t\t// Perform \"odd\" indexed pass\n\t\tfor i := 1; i < len(arr)-1; i += 2 {\n\t\t\tif arr[i] > arr[i+1] {\n\t\t\t\tarr[i], arr[i+1] = arr[i+1], arr[i]\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\n\t\t// Perform \"even\" indexed pass\n\t\tfor i := 0; i < len(arr)-1; i += 2 {\n\t\t\tif arr[i] > arr[i+1] {\n\t\t\t\tarr[i], arr[i+1] = arr[i+1], arr[i]\n\t\t\t\tswapped = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/pancakesort.go",
    "content": "package sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Pancake sorts a slice using flip operations,\n// where flip refers to the idea of reversing the\n// slice from index `0` to `i`.\nfunc Pancake[T constraints.Ordered](arr []T) []T {\n\t// early return if the array too small\n\tif len(arr) <= 1 {\n\t\treturn arr\n\t}\n\n\t// start from the end of the array\n\tfor i := len(arr) - 1; i > 0; i-- {\n\t\t// find the index of the maximum element in arr\n\t\tmax := 0\n\t\tfor j := 1; j <= i; j++ {\n\t\t\tif arr[j] > arr[max] {\n\t\t\t\tmax = j\n\t\t\t}\n\t\t}\n\n\t\t// if the maximum element is not at the end of the array\n\t\tif max != i {\n\t\t\t// flip the maximum element to the beginning of the array\n\t\t\tarr = flip(arr, max)\n\n\t\t\t// flip the maximum element to the end of the array by flipping the whole array\n\t\t\tarr = flip(arr, i)\n\t\t}\n\t}\n\n\treturn arr\n}\n\n// flip reverses the input slice from `0` to `i`.\nfunc flip[T constraints.Ordered](arr []T, i int) []T {\n\tfor j := 0; j < i; j++ {\n\t\tarr[j], arr[i] = arr[i], arr[j]\n\t\ti--\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/patiencesort.go",
    "content": "// Patience sorting is a sorting algorithm inspired by the card game patience.\n//\n// For more details check out those links below here:\n// GeeksForGeeks article : https://www.geeksforgeeks.org/patience-sorting/\n// Wikipedia article: https://en.wikipedia.org/wiki/Patience_sorting\n// authors [guuzaa](https://github.com/guuzaa)\n// worst-case time complexity: O(n log n)\n// average time complexity: O(n log n)\n// space complexity: O(n)\n// see patiencesort.go\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Patience[T constraints.Ordered](arr []T) []T {\n\tif len(arr) <= 1 {\n\t\treturn arr\n\t}\n\n\tvar piles [][]T\n\n\tfor _, card := range arr {\n\t\tleft, right := 0, len(piles)\n\t\tfor left < right {\n\t\t\tmid := left + (right-left)/2\n\t\t\tif piles[mid][len(piles[mid])-1] >= card {\n\t\t\t\tright = mid\n\t\t\t} else {\n\t\t\t\tleft = mid + 1\n\t\t\t}\n\t\t}\n\n\t\tif left == len(piles) {\n\t\t\tpiles = append(piles, []T{card})\n\t\t} else {\n\t\t\tpiles[left] = append(piles[left], card)\n\t\t}\n\t}\n\n\treturn mergePiles(piles)\n}\n\nfunc mergePiles[T constraints.Ordered](piles [][]T) []T {\n\tvar ret []T\n\n\tfor len(piles) > 0 {\n\t\tminID := 0\n\t\tminValue := piles[minID][len(piles[minID])-1]\n\n\t\tfor i := 1; i < len(piles); i++ {\n\t\t\tif minValue <= piles[i][len(piles[i])-1] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tminValue = piles[i][len(piles[i])-1]\n\t\t\tminID = i\n\t\t}\n\n\t\tret = append(ret, minValue)\n\n\t\tpiles[minID] = piles[minID][:len(piles[minID])-1]\n\n\t\tif len(piles[minID]) == 0 {\n\t\t\tpiles = append(piles[:minID], piles[minID+1:]...)\n\t\t}\n\t}\n\n\treturn ret\n}\n"
  },
  {
    "path": "sort/pigeonholesort.go",
    "content": "// Pigeonhole algorithm's working at wikipedia.\n// https://en.wikipedia.org/wiki/Pigeonhole_sort\n// time complexity: O(n + N) where n is the number of elements in the array and N is the range of input\n// space complexity: O(N)\n\npackage sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/max\"\n\t\"github.com/TheAlgorithms/Go/math/min\"\n)\n\n// Pigeonhole sorts a slice using pigeonhole sorting algorithm.\n// NOTE: To maintain time complexity O(n + N), this is the reason for having\n// only Integer constraint instead of Ordered.\nfunc Pigeonhole[T constraints.Integer](arr []T) []T {\n\tif len(arr) == 0 {\n\t\treturn arr\n\t}\n\n\tmax := max.Int(arr...)\n\tmin := min.Int(arr...)\n\n\tsize := max - min + 1\n\n\tholes := make([]T, size)\n\n\tfor _, element := range arr {\n\t\tholes[element-min]++\n\t}\n\n\ti := 0\n\n\tfor j := T(0); j < size; j++ {\n\t\tfor holes[j] > 0 {\n\t\t\tholes[j]--\n\t\t\tarr[i] = j + min\n\t\t\ti++\n\t\t}\n\t}\n\n\treturn arr\n}\n"
  },
  {
    "path": "sort/quicksort.go",
    "content": "// quicksort.go\n// description: Implementation of in-place quicksort algorithm\n// details:\n// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)\n// worst time complexity: O(n^2)\n// average time complexity: O(n log n)\n// space complexity: O(log n)\n// author(s) [Taj](https://github.com/tjgurwara99)\n// see sort_test.go for a test implementation, test function TestQuickSort.\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Partition[T constraints.Ordered](arr []T, low, high int) int {\n\tindex := low - 1\n\tpivotElement := arr[high]\n\tfor i := low; i < high; i++ {\n\t\tif arr[i] <= pivotElement {\n\t\t\tindex += 1\n\t\t\tarr[index], arr[i] = arr[i], arr[index]\n\t\t}\n\t}\n\tarr[index+1], arr[high] = arr[high], arr[index+1]\n\treturn index + 1\n}\n\n// QuicksortRange Sorts the specified range within the array\nfunc QuicksortRange[T constraints.Ordered](arr []T, low, high int) {\n\tif len(arr) <= 1 {\n\t\treturn\n\t}\n\n\tif low < high {\n\t\tpivot := Partition(arr, low, high)\n\t\tQuicksortRange(arr, low, pivot-1)\n\t\tQuicksortRange(arr, pivot+1, high)\n\t}\n}\n\n// Quicksort Sorts the entire array\nfunc Quicksort[T constraints.Ordered](arr []T) []T {\n\tQuicksortRange(arr, 0, len(arr)-1)\n\treturn arr\n}\n"
  },
  {
    "path": "sort/radixsort.go",
    "content": "// radixsort.go\n// description: Implementation of in-place radixsort algorithm\n// details:\n// A simple in-place quicksort algorithm implementation. [Wikipedia](https://en.wikipedia.org/wiki/Radix_sort)\n// worst time complexity: O(n * k) where n is the number of elements in the input array and k is the number of digits in the largest number\n// average time complexity: O(n * k) where n is the number of elements in the input array and k is the number of digits in the largest number\n// space complexity: O(n)\n\npackage sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/max\"\n)\n\nfunc countSort[T constraints.Integer](arr []T, exp T) []T {\n\tvar digits [10]int\n\tvar output = make([]T, len(arr))\n\n\tfor _, item := range arr {\n\t\tdigits[(item/exp)%10]++\n\t}\n\tfor i := 1; i < 10; i++ {\n\t\tdigits[i] += digits[i-1]\n\t}\n\n\tfor i := len(arr) - 1; i >= 0; i-- {\n\t\toutput[digits[(arr[i]/exp)%10]-1] = arr[i]\n\t\tdigits[(arr[i]/exp)%10]--\n\t}\n\n\treturn output\n}\n\nfunc unsignedRadixSort[T constraints.Integer](arr []T) []T {\n\tif len(arr) == 0 {\n\t\treturn arr\n\t}\n\tmaxElement := max.Int(arr...)\n\tfor exp := T(1); maxElement/exp > 0; exp *= 10 {\n\t\tarr = countSort(arr, exp)\n\t}\n\treturn arr\n}\n\nfunc RadixSort[T constraints.Integer](arr []T) []T {\n\tif len(arr) < 1 {\n\t\treturn arr\n\t}\n\tvar negatives, nonNegatives []T\n\n\tfor _, item := range arr {\n\t\tif item < 0 {\n\t\t\tnegatives = append(negatives, -item)\n\t\t} else {\n\t\t\tnonNegatives = append(nonNegatives, item)\n\t\t}\n\t}\n\tnegatives = unsignedRadixSort(negatives)\n\n\t// Reverse the negative array and restore signs\n\tfor i, j := 0, len(negatives)-1; i <= j; i, j = i+1, j-1 {\n\t\tnegatives[i], negatives[j] = -negatives[j], -negatives[i]\n\t}\n\treturn append(negatives, unsignedRadixSort(nonNegatives)...)\n}\n"
  },
  {
    "path": "sort/selectionsort.go",
    "content": "package sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Selection[T constraints.Ordered](arr []T) []T {\n\tfor i := 0; i < len(arr); i++ {\n\t\tmin := i\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[j] < arr[min] {\n\t\t\t\tmin = j\n\t\t\t}\n\t\t}\n\n\t\tarr[i], arr[min] = arr[min], arr[i]\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/shellsort.go",
    "content": "package sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Shell[T constraints.Ordered](arr []T) []T {\n\tfor d := int(len(arr) / 2); d > 0; d /= 2 {\n\t\tfor i := d; i < len(arr); i++ {\n\t\t\tfor j := i; j >= d && arr[j-d] > arr[j]; j -= d {\n\t\t\t\tarr[j], arr[j-d] = arr[j-d], arr[j]\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/simplesort.go",
    "content": "// simplesort.go\n// description: Implementation of a simple sorting algorithm\n// details:\n// A simple sorting algorithm that look counter intuitive at first glance and very similar to Exchange Sort\n// An improved version is included with slight changes to make the sort slightly more efficient\n// reference: https://arxiv.org/abs/2110.01111v1\n// see sort_test.go for a test implementation, test function TestSimple and TestImprovedSimple\n// worst-case time complexity: O(n^2)\n// average-case time complexity: O(n^2)\n// space complexity: O(1)\n\npackage sort\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\nfunc Simple[T constraints.Ordered](arr []T) []T {\n\tfor i := 0; i < len(arr); i++ {\n\t\tfor j := 0; j < len(arr); j++ {\n\t\t\tif arr[i] < arr[j] {\n\t\t\t\t// swap arr[i] and arr[j]\n\t\t\t\tarr[i], arr[j] = arr[j], arr[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n\n// ImprovedSimple is a improve SimpleSort by skipping an unnecessary comparison of the first and last.\n// This improved version is more similar to implementation of insertion sort\nfunc ImprovedSimple[T constraints.Ordered](arr []T) []T {\n\tfor i := 1; i < len(arr); i++ {\n\t\tfor j := 0; j < len(arr)-1; j++ {\n\t\t\tif arr[i] < arr[j] {\n\t\t\t\t// swap arr[i] and arr[j]\n\t\t\t\tarr[i], arr[j] = arr[j], arr[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n"
  },
  {
    "path": "sort/sorts_test.go",
    "content": "package sort_test\n\nimport (\n\t\"math/rand\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/TheAlgorithms/Go/sort\"\n)\n\nfunc testFramework(t *testing.T, sortingFunction func([]int) []int) {\n\tsortTests := []struct {\n\t\tinput    []int\n\t\texpected []int\n\t\tname     string\n\t}{\n\t\t//Sorted slice\n\t\t{\n\t\t\tinput:    []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\texpected: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\tname:     \"Sorted Unsigned\",\n\t\t},\n\t\t//Reversed slice\n\t\t{\n\t\t\tinput:    []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1},\n\t\t\texpected: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\tname:     \"Reversed Unsigned\",\n\t\t},\n\t\t//Sorted slice\n\t\t{\n\t\t\tinput:    []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\texpected: []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\tname:     \"Sorted Signed\",\n\t\t},\n\t\t//Reversed slice\n\t\t{\n\t\t\tinput:    []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10},\n\t\t\texpected: []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\tname:     \"Reversed Signed\",\n\t\t},\n\t\t//Reversed slice, even length\n\t\t{\n\t\t\tinput:    []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10},\n\t\t\texpected: []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\tname:     \"Reversed Signed #2\",\n\t\t},\n\t\t//Random order with repetitions\n\t\t{\n\t\t\tinput:    []int{-5, 7, 4, -2, 6, 5, 8, 3, 2, -7, -1, 0, -3, 9, -6, -4, 10, 9, 1, -8, -9, -10},\n\t\t\texpected: []int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10},\n\t\t\tname:     \"Random order Signed\",\n\t\t},\n\t\t//Single-entry slice\n\t\t{\n\t\t\tinput:    []int{1},\n\t\t\texpected: []int{1},\n\t\t\tname:     \"Singleton\",\n\t\t},\n\t\t// Empty slice\n\t\t{\n\t\t\tinput:    []int{},\n\t\t\texpected: []int{},\n\t\t\tname:     \"Empty Slice\",\n\t\t},\n\t}\n\tfor _, test := range sortTests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactual := sortingFunction(test.input)\n\t\t\tsorted := reflect.DeepEqual(actual, test.expected)\n\t\t\tif !sorted {\n\t\t\t\tt.Errorf(\"test %s failed\", test.name)\n\t\t\t\tt.Errorf(\"actual %v expected %v\", actual, test.expected)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// BEGIN TESTS\nfunc TestBinaryInsertion(t *testing.T) {\n\ttestFramework(t, sort.BinaryInsertion[int])\n}\n\nfunc TestBubble(t *testing.T) {\n\ttestFramework(t, sort.Bubble[int])\n}\n\nfunc TestBogo(t *testing.T) {\n\tt.Skip(\"Skipping test for Bogo Sort, as it uses a lot of resource.\")\n\ttestFramework(t, sort.Bogo[int])\n}\n\nfunc TestBucketSort(t *testing.T) {\n\ttestFramework(t, sort.Bucket[int])\n}\n\nfunc TestCocktailSort(t *testing.T) {\n\ttestFramework(t, sort.Cocktail[int])\n}\n\nfunc TestExchange(t *testing.T) {\n\ttestFramework(t, sort.Exchange[int])\n}\n\nfunc TestInsertion(t *testing.T) {\n\ttestFramework(t, sort.Insertion[int])\n}\n\nfunc TestMerge(t *testing.T) {\n\ttestFramework(t, sort.Merge[int])\n}\n\nfunc TestMergeIter(t *testing.T) {\n\ttestFramework(t, sort.MergeIter[int])\n}\n\nfunc TestMergeParallel(t *testing.T) {\n\ttestFramework(t, sort.ParallelMerge[int])\n\n\t// Test parallel merge sort with a large slice\n\tt.Run(\"ParallelMerge on large slice\", func(t *testing.T) {\n\t\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\tsize := 100000\n\t\trandomLargeSlice := make([]int, size)\n\t\tfor i := range randomLargeSlice {\n\t\t\trandomLargeSlice[i] = rnd.Intn(size)\n\t\t}\n\t\tsortedSlice := sort.ParallelMerge[int](randomLargeSlice)\n\t\tfor i := 0; i < len(sortedSlice)-1; i++ {\n\t\t\tif sortedSlice[i] > sortedSlice[i+1] {\n\t\t\t\tt.Errorf(\"ParallelMerge failed\")\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestHeap(t *testing.T) {\n\ttestFramework(t, sort.HeapSort[int])\n}\n\nfunc TestCount(t *testing.T) {\n\ttestFramework(t, sort.Count[int])\n}\n\nfunc TestQuick(t *testing.T) {\n\ttestFramework(t, sort.Quicksort[int])\n}\n\nfunc TestShell(t *testing.T) {\n\ttestFramework(t, sort.Shell[int])\n}\n\nfunc TestRadix(t *testing.T) {\n\ttestFramework(t, sort.RadixSort[int])\n}\n\nfunc TestSimple(t *testing.T) {\n\ttestFramework(t, sort.Simple[int])\n}\n\nfunc TestImprovedSimple(t *testing.T) {\n\ttestFramework(t, sort.ImprovedSimple[int])\n}\n\nfunc TestSelection(t *testing.T) {\n\ttestFramework(t, sort.Selection[int])\n}\n\nfunc TestComb(t *testing.T) {\n\ttestFramework(t, sort.Comb[int])\n}\n\nfunc TestPancakeSort(t *testing.T) {\n\ttestFramework(t, sort.Pancake[int])\n}\n\nfunc TestPigeonhole(t *testing.T) {\n\ttestFramework(t, sort.Pigeonhole[int])\n}\n\nfunc TestPatience(t *testing.T) {\n\ttestFramework(t, sort.Patience[int])\n}\n\nfunc TestCycle(t *testing.T) {\n\ttestFramework(t, sort.Cycle[int])\n}\n\nfunc TestTimsort(t *testing.T) {\n\ttestFramework(t, sort.Timsort[int])\n}\n\nfunc TestCircle(t *testing.T) {\n\ttestFramework(t, sort.Circle[int])\n}\n\nfunc TestOddEvenSort(t *testing.T) {\n\ttestFramework(t, sort.OddEvenSort[int])\n}\n\nfunc TestStooge(t *testing.T) {\n\ttestFramework(t, sort.Stooge[int])\n}\n\n// END TESTS\n\nfunc benchmarkFramework(b *testing.B, f func(arr []int) []int) {\n\tvar sortTests = []struct {\n\t\tinput    []int\n\t\texpected []int\n\t\tname     string\n\t}{\n\t\t//Sorted slice\n\t\t{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\t[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, \"Sorted Unsigned\"},\n\t\t//Reversed slice\n\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1},\n\t\t\t[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, \"Reversed Unsigned\"},\n\t\t//Sorted slice\n\t\t{[]int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t\t\t[]int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, \"Sorted Signed\"},\n\t\t//Reversed slice\n\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10},\n\t\t\t[]int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, \"Reversed Signed\"},\n\t\t//Reversed slice, even length\n\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10},\n\t\t\t[]int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, \"Reversed Signed #2\"},\n\t\t//Random order with repetitions\n\t\t{[]int{-5, 7, 4, -2, 6, 5, 8, 3, 2, -7, -1, 0, -3, 9, -6, -4, 10, 9, 1, -8, -9, -10},\n\t\t\t[]int{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10}, \"Random order Signed\"},\n\t\t//Empty slice\n\t\t{[]int{}, []int{}, \"Empty\"},\n\t\t//Single-entry slice\n\t\t{[]int{1}, []int{1}, \"Singleton\"},\n\t}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, test := range sortTests {\n\t\t\tf(test.input)\n\t\t}\n\t}\n}\n\n//BEGIN BENCHMARKS\n\nfunc BenchmarkBinaryInsertion(b *testing.B) {\n\tbenchmarkFramework(b, sort.BinaryInsertion[int])\n}\n\nfunc BenchmarkBubble(b *testing.B) {\n\tbenchmarkFramework(b, sort.Bubble[int])\n}\n\nfunc BenchmarkBogo(b *testing.B) {\n\tb.Skip(\"Skipping benchmark for Bogo Sort, as it uses a lot of resource.\")\n\tbenchmarkFramework(b, sort.Bogo[int])\n}\n\nfunc BenchmarkBucketSort(b *testing.B) {\n\tbenchmarkFramework(b, sort.Bucket[int])\n}\n\nfunc BenchmarkCocktailSort(b *testing.B) {\n\tbenchmarkFramework(b, sort.Cocktail[int])\n}\n\nfunc BenchmarkExchange(b *testing.B) {\n\tbenchmarkFramework(b, sort.Exchange[int])\n}\n\nfunc BenchmarkInsertion(b *testing.B) {\n\tbenchmarkFramework(b, sort.Insertion[int])\n}\n\nfunc BenchmarkMerge(b *testing.B) {\n\tbenchmarkFramework(b, sort.Merge[int])\n}\n\nfunc BenchmarkMergeIter(b *testing.B) {\n\tbenchmarkFramework(b, sort.MergeIter[int])\n}\n\nfunc BenchmarkMergeParallel(b *testing.B) {\n\tbenchmarkFramework(b, sort.ParallelMerge[int])\n}\n\nfunc BenchmarkHeap(b *testing.B) {\n\tbenchmarkFramework(b, sort.HeapSort[int])\n}\n\nfunc BenchmarkCount(b *testing.B) {\n\tbenchmarkFramework(b, sort.Count[int])\n}\n\nfunc BenchmarkQuick(b *testing.B) {\n\tbenchmarkFramework(b, sort.Quicksort[int])\n}\n\nfunc BenchmarkShell(b *testing.B) {\n\tbenchmarkFramework(b, sort.Shell[int])\n}\n\nfunc BenchmarkRadix(b *testing.B) {\n\tbenchmarkFramework(b, sort.RadixSort[int])\n}\n\nfunc BenchmarkSimple(b *testing.B) {\n\tbenchmarkFramework(b, sort.Simple[int])\n}\n\nfunc BenchmarkImprovedSimple(b *testing.B) {\n\tbenchmarkFramework(b, sort.ImprovedSimple[int])\n}\n\n// Very Slow, consider commenting\nfunc BenchmarkSelection(b *testing.B) {\n\tbenchmarkFramework(b, sort.Selection[int])\n}\n\nfunc BenchmarkComb(b *testing.B) {\n\tbenchmarkFramework(b, sort.Comb[int])\n}\n\nfunc BenchmarkPancakeSort(b *testing.B) {\n\tbenchmarkFramework(b, sort.Pancake[int])\n}\n\nfunc BenchmarkPigeonhole(b *testing.B) {\n\tbenchmarkFramework(b, sort.Pigeonhole[int])\n}\n\nfunc BenchmarkPatience(b *testing.B) {\n\tbenchmarkFramework(b, sort.Patience[int])\n}\n\nfunc BenchmarkCycle(b *testing.B) {\n\tbenchmarkFramework(b, sort.Cycle[int])\n}\n\nfunc BenchmarkTimsort(b *testing.B) {\n\tbenchmarkFramework(b, sort.Timsort[int])\n}\n\nfunc BenchmarkCircle(b *testing.B) {\n\tbenchmarkFramework(b, sort.Circle[int])\n}\n\nfunc BenchmarkStooge(b *testing.B) {\n\tbenchmarkFramework(b, sort.Stooge[int])\n}\n"
  },
  {
    "path": "sort/stooge_sort.go",
    "content": "// implementation of the Stooge sort\n// more info at https://en.wikipedia.org/wiki/Stooge_sort\n// worst-case time complexity    O(n^2.709511)\n// worst-case space complexity   O(n)\n\npackage sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\n\t// math imported for floor division\n\t\"math\"\n)\n\nfunc innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T {\n\tif arr[i] > arr[j] {\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\tif (j - i + 1) > 2 {\n\t\tt := int32(math.Floor(float64(j-i+1) / 3.0))\n\t\tarr = innerStooge(arr, i, j-t)\n\t\tarr = innerStooge(arr, i+t, j)\n\t\tarr = innerStooge(arr, i, j-t)\n\t}\n\treturn arr\n}\n\nfunc Stooge[T constraints.Ordered](arr []T) []T {\n\tif len(arr) == 0 {\n\t\treturn arr\n\t}\n\n\treturn innerStooge(arr, 0, int32(len(arr)-1))\n}\n"
  },
  {
    "path": "sort/timsort.go",
    "content": "// Implementation of Timsort algorithm\n// Reference: https://en.wikipedia.org/wiki/Timsort\n\npackage sort\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\nconst runSizeThreshold = 8\n\n// Timsort is a simple generic implementation of Timsort algorithm.\nfunc Timsort[T constraints.Ordered](data []T) []T {\n\trunSize := calculateRunSize(len(data))\n\tinsertionSortRuns(data, runSize)\n\tmergeRuns(data, runSize)\n\treturn data\n}\n\n// calculateRunSize returns a run size parameter that is further used\n// to slice the data slice.\nfunc calculateRunSize(dataLength int) int {\n\tremainder := 0\n\tfor dataLength >= runSizeThreshold {\n\t\tif dataLength%2 == 1 {\n\t\t\tremainder = 1\n\t\t}\n\n\t\tdataLength = dataLength / 2\n\t}\n\n\treturn dataLength + remainder\n}\n\n// insertionSortRuns runs insertion sort on all the data runs one by one.\nfunc insertionSortRuns[T constraints.Ordered](data []T, runSize int) {\n\tfor lower := 0; lower < len(data); lower += runSize {\n\t\tupper := lower + runSize\n\t\tif upper >= len(data) {\n\t\t\tupper = len(data)\n\t\t}\n\n\t\tInsertion(data[lower:upper])\n\t}\n}\n\n// mergeRuns merge sorts all the data runs into a single sorted data slice.\nfunc mergeRuns[T constraints.Ordered](data []T, runSize int) {\n\tfor size := runSize; size < len(data); size *= 2 {\n\t\tfor lowerBound := 0; lowerBound < len(data); lowerBound += size * 2 {\n\t\t\tmiddleBound := lowerBound + size - 1\n\t\t\tupperBound := lowerBound + 2*size - 1\n\t\t\tif len(data)-1 < upperBound {\n\t\t\t\tupperBound = len(data) - 1\n\t\t\t}\n\n\t\t\tmergeRun(data, lowerBound, middleBound, upperBound)\n\t\t}\n\t}\n}\n\n// mergeRun uses merge sort to sort adjacent data runs.\nfunc mergeRun[T constraints.Ordered](data []T, lower, mid, upper int) {\n\tleft := data[lower : mid+1]\n\tright := data[mid+1 : upper+1]\n\tmerged := merge(left, right)\n\t// rewrite original data slice values with sorted values from merged slice\n\tfor i, value := range merged {\n\t\tdata[lower+i] = value\n\t}\n}\n"
  },
  {
    "path": "sqrt/sqrtdecomposition.go",
    "content": "// Package sqrt contains algorithms and data structures that contains a √n in their complexity\npackage sqrt\n\nimport \"math\"\n\n// Sqrt (or Square Root) Decomposition is a technique used for query an array and perform updates\n// Inside this package is described its most simple data structure, you can find more at: https://cp-algorithms.com/data_structures/sqrt_decomposition.html\n//\n// Formally, You can use SqrtDecomposition only if:\n//\n// Given a function $Query:E_1,...,E_n\\rightarrow Q$\n//\n// if $\\exist unionQ:Q,Q\\rightarrow Q$\n//\n// s.t.\n//\n// - $\\forall n\\in \\N > 1, 1\\le i<n, E_1,..., E_n\\in E \\\\ query(E_1,..., E_n)=unionQ(query(E_1,..., E_i), query(E_{i+1},...,E_n))$\n//\n// - (Only if you want use $update$ function)\n// $\\forall n\\in \\N > 0, E_1,..., E_n\\in E \\\\ query(E_1,...,E_{new},..., E_n)=updateQ(query(E_1,...,E_{old},...,E_n), indexof(E_{old}), E_{new})$\ntype SqrtDecomposition[E any, Q any] struct {\n\tquerySingleElement func(element E) Q\n\tunionQ             func(q1 Q, q2 Q) Q\n\tupdateQ            func(oldQ Q, oldE E, newE E) (newQ Q)\n\n\telements  []E\n\tblocks    []Q\n\tblockSize uint64\n}\n\n// Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment\n// Assumptions:\n//   - len(elements) > 0\nfunc NewSqrtDecomposition[E any, Q any](\n\telements []E,\n\tquerySingleElement func(element E) Q,\n\tunionQ func(q1 Q, q2 Q) Q,\n\tupdateQ func(oldQ Q, oldE E, newE E) (newQ Q),\n) *SqrtDecomposition[E, Q] {\n\tsqrtDec := &SqrtDecomposition[E, Q]{\n\t\tquerySingleElement: querySingleElement,\n\t\tunionQ:             unionQ,\n\t\tupdateQ:            updateQ,\n\t\telements:           elements,\n\t}\n\tsqrt := math.Sqrt(float64(len(sqrtDec.elements)))\n\tblockSize := uint64(sqrt)\n\tnumBlocks := uint64(math.Ceil(float64(len(elements)) / float64(blockSize)))\n\tsqrtDec.blocks = make([]Q, numBlocks)\n\tfor i := uint64(0); i < uint64(len(elements)); i++ {\n\t\tif i%blockSize == 0 {\n\t\t\tsqrtDec.blocks[i/blockSize] = sqrtDec.querySingleElement(elements[i])\n\t\t} else {\n\t\t\tsqrtDec.blocks[i/blockSize] = sqrtDec.unionQ(sqrtDec.blocks[i/blockSize], sqrtDec.querySingleElement(elements[i]))\n\t\t}\n\t}\n\tsqrtDec.blockSize = blockSize\n\treturn sqrtDec\n}\n\n// Performs a query from index start to index end (non included)\n// Assumptions:\n//   - start < end\n//   - start and end are valid\nfunc (s *SqrtDecomposition[E, Q]) Query(start uint64, end uint64) Q {\n\tfirstIndexNextBlock := ((start / s.blockSize) + 1) * s.blockSize\n\tq := s.querySingleElement(s.elements[start])\n\tif firstIndexNextBlock > end { // if in same block\n\t\tstart++\n\t\tfor start < end {\n\t\t\tq = s.unionQ(q, s.querySingleElement(s.elements[start]))\n\t\t\tstart++\n\t\t}\n\t} else {\n\t\t// left side\n\t\tstart++\n\t\tfor start < firstIndexNextBlock {\n\t\t\tq = s.unionQ(q, s.querySingleElement(s.elements[start]))\n\t\t\tstart++\n\t\t}\n\n\t\t//middle part\n\t\tendBlock := end / s.blockSize\n\t\tfor i := firstIndexNextBlock / s.blockSize; i < endBlock; i++ {\n\t\t\tq = s.unionQ(q, s.blocks[i])\n\t\t}\n\n\t\t// right part\n\t\tfor i := endBlock * s.blockSize; i < end; i++ {\n\t\t\tq = s.unionQ(q, s.querySingleElement(s.elements[i]))\n\t\t}\n\t}\n\treturn q\n}\n\n// Assumptions:\n//   - index is valid\nfunc (s *SqrtDecomposition[E, Q]) Update(index uint64, newElement E) {\n\ti := index / s.blockSize\n\ts.blocks[i] = s.updateQ(s.blocks[i], s.elements[index], newElement)\n\ts.elements[index] = newElement\n}\n"
  },
  {
    "path": "sqrt/sqrtdecomposition_test.go",
    "content": "package sqrt_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/sqrt\"\n\t\"testing\"\n)\n\n// Query interval\ntype query struct {\n\tfirstIndex uint64\n\tlastIndex  uint64\n}\n\ntype update struct {\n\tindex uint64\n\tvalue int\n}\n\nfunc TestSqrtDecomposition(t *testing.T) {\n\tvar sqrtDecompositionTestData = []struct {\n\t\tdescription string\n\t\tarray       []int\n\t\tupdates     []update\n\t\tqueries     []query\n\t\texpected    []int\n\t}{\n\t\t{\n\t\t\tdescription: \"test 1-sized array\",\n\t\t\tarray:       []int{1},\n\t\t\tqueries:     []query{{0, 1}},\n\t\t\texpected:    []int{1},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tqueries:     []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected:    []int{15, 3, 7},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5 and updates\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates: []update{{index: 1, value: 3},\n\t\t\t\t{index: 2, value: 4}},\n\t\t\tqueries:  []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected: []int{17, 4, 8},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 11 and updates\",\n\t\t\tarray:       []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n\t\t\tupdates: []update{{index: 2, value: 2},\n\t\t\t\t{index: 3, value: 3},\n\t\t\t\t{index: 6, value: 6}},\n\t\t\tqueries:  []query{{3, 5}, {7, 8}, {3, 7}, {0, 10}},\n\t\t\texpected: []int{4, 1, 11, 18},\n\t\t},\n\t}\n\tfor _, test := range sqrtDecompositionTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\ts := sqrt.NewSqrtDecomposition(test.array,\n\t\t\t\tfunc(e int) int { return e },\n\t\t\t\tfunc(q1, q2 int) int { return q1 + q2 },\n\t\t\t\tfunc(q, a, b int) int { return q - a + b },\n\t\t\t)\n\n\t\t\tfor i := 0; i < len(test.updates); i++ {\n\t\t\t\ts.Update(test.updates[i].index, test.updates[i].value)\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(test.queries); i++ {\n\t\t\t\tresult := s.Query(test.queries[i].firstIndex, test.queries[i].lastIndex)\n\n\t\t\t\tif result != test.expected[i] {\n\t\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\t\tt.Fatalf(\"Expected result: %d\\nFound: %d\\n\", test.expected[i], result)\n\t\t\t\t}\n\t\t\t}\n\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/ahocorasick/advancedahocorasick.go",
    "content": "package ahocorasick\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n// Advanced Function performing the Advanced Aho-Corasick algorithm.\n// Finds and prints occurrences of each pattern.\nfunc Advanced(t string, p []string) Result {\n\tstartTime := time.Now()\n\toccurrences := make(map[int][]int)\n\tac, f := BuildExtendedAc(p)\n\tcurrent := 0\n\tfor pos := 0; pos < len(t); pos++ {\n\t\tif GetTransition(current, t[pos], ac) != -1 {\n\t\t\tcurrent = GetTransition(current, t[pos], ac)\n\t\t} else {\n\t\t\tcurrent = 0\n\t\t}\n\t\t_, ok := f[current]\n\t\tif ok {\n\t\t\tfor i := range f[current] {\n\t\t\t\tif p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match\n\t\t\t\t\tnewOccurrences := IntArrayCapUp(occurrences[f[current][i]])\n\t\t\t\t\toccurrences[f[current][i]] = newOccurrences\n\t\t\t\t\toccurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telapsed := time.Since(startTime)\n\tfmt.Printf(\"\\n\\nElapsed %f secs\\n\", elapsed.Seconds())\n\n\tvar resultOccurrences = make(map[string][]int)\n\tfor key, value := range occurrences {\n\t\tresultOccurrences[p[key]] = value\n\t}\n\n\treturn Result{\n\t\tresultOccurrences,\n\t}\n}\n\n// BuildExtendedAc Functions that builds extended Aho Corasick automaton.\nfunc BuildExtendedAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int) {\n\tacTrie, stateIsTerminal, f := ConstructTrie(p)\n\ts := make([]int, len(stateIsTerminal)) //supply function\n\ti := 0                                 //root of acTrie\n\tacToReturn = acTrie\n\ts[i] = -1\n\tfor current := 1; current < len(stateIsTerminal); current++ {\n\t\to, parent := GetParent(current, acTrie)\n\t\tdown := s[parent]\n\t\tfor StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {\n\t\t\tdown = s[down]\n\t\t}\n\t\tif StateExists(down, acToReturn) {\n\t\t\ts[current] = GetTransition(down, o, acToReturn)\n\t\t\tif stateIsTerminal[s[current]] {\n\t\t\t\tstateIsTerminal[current] = true\n\t\t\t\tf[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))\n\t\t\t}\n\t\t} else {\n\t\t\ts[current] = i //initial state?\n\t\t}\n\t}\n\ta := ComputeAlphabet(p) // concat of all patterns in p\n\tfor j := range a {\n\t\tif GetTransition(i, a[j], acToReturn) == -1 {\n\t\t\tCreateTransition(i, a[j], i, acToReturn)\n\t\t}\n\t}\n\tfor current := 1; current < len(stateIsTerminal); current++ {\n\t\tfor j := range a {\n\t\t\tif GetTransition(current, a[j], acToReturn) == -1 {\n\t\t\t\tCreateTransition(current, a[j], GetTransition(s[current], a[j], acToReturn), acToReturn)\n\t\t\t}\n\t\t}\n\t}\n\treturn acToReturn, f\n}\n"
  },
  {
    "path": "strings/ahocorasick/advancedahocorasick_test.go",
    "content": "package ahocorasick\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string\n\twords    []string\n\ttext     string\n\texpected Result\n}{\n\n\t{\n\t\t\"String comparison on all patterns found\",\n\t\t[]string{\"announce\", \"annual\", \"annually\"},\n\t\t\"CPM_annual_conferenceannounce_announce_annually_announce\",\n\t\tResult{\n\t\t\tmap[string][]int{\n\t\t\t\t\"annual\":   {4, 39},\n\t\t\t\t\"announce\": {21, 30, 48},\n\t\t\t\t\"annually\": {39},\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\t\"String comparison on not all patterns found\",\n\t\t[]string{\"announce\", \"annual\", \"annually\"},\n\t\t\"CPM_annual_conference_announce\",\n\t\tResult{\n\t\t\tmap[string][]int{\n\t\t\t\t\"annual\":   {4},\n\t\t\t\t\"announce\": {22},\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\t\"String comparison on not all patterns found\",\n\t\t[]string{\"announce\", \"annual\", \"annually\"},\n\t\t\"CPM_annual_conference_announce\",\n\t\tResult{\n\t\t\tmap[string][]int{\n\t\t\t\t\"annual\":   {4},\n\t\t\t\t\"announce\": {22},\n\t\t\t},\n\t\t},\n\t},\n}\n\nfunc TestAdvanced(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := AhoCorasick(tc.text, tc.words)\n\t\t\tif !reflect.DeepEqual(actual, tc.expected) {\n\t\t\t\tactualString := convertToString(actual)\n\t\t\t\texpectedString := convertToString(tc.expected)\n\t\t\t\tt.Errorf(\"Expected matches for patterns %s for string '%s' are: patterns and positions found %v, but actual matches are: patterns and positions found %v\",\n\t\t\t\t\ttc.words, tc.text, actualString, expectedString)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/ahocorasick/ahocorasick.go",
    "content": "package ahocorasick\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n// Result structure to hold occurrences\ntype Result struct {\n\toccurrences map[string][]int\n}\n\n// AhoCorasick Function performing the Basic Aho-Corasick algorithm.\n// Finds and prints occurrences of each pattern.\nfunc AhoCorasick(t string, p []string) Result {\n\tstartTime := time.Now()\n\toccurrences := make(map[int][]int)\n\tac, f, s := BuildAc(p)\n\tcurrent := 0\n\tfor pos := 0; pos < len(t); pos++ {\n\t\tfor GetTransition(current, t[pos], ac) == -1 && s[current] != -1 {\n\t\t\tcurrent = s[current]\n\t\t}\n\t\tif GetTransition(current, t[pos], ac) != -1 {\n\t\t\tcurrent = GetTransition(current, t[pos], ac)\n\t\t\tfmt.Printf(\" (Continue) \\n\")\n\t\t} else {\n\t\t\tcurrent = 0\n\t\t}\n\t\t_, ok := f[current]\n\t\tif ok {\n\t\t\tfor i := range f[current] {\n\t\t\t\tif p[f[current][i]] == GetWord(pos-len(p[f[current][i]])+1, pos, t) { //check for word match\n\t\t\t\t\tnewOccurrences := IntArrayCapUp(occurrences[f[current][i]])\n\t\t\t\t\toccurrences[f[current][i]] = newOccurrences\n\t\t\t\t\toccurrences[f[current][i]][len(newOccurrences)-1] = pos - len(p[f[current][i]]) + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telapsed := time.Since(startTime)\n\tfmt.Printf(\"\\n\\nElapsed %f secs\\n\", elapsed.Seconds())\n\tvar resultOccurrences = make(map[string][]int)\n\tfor key, value := range occurrences {\n\t\tresultOccurrences[p[key]] = value\n\t}\n\n\treturn Result{\n\t\tresultOccurrences,\n\t}\n}\n\n// Functions that builds Aho Corasick automaton.\nfunc BuildAc(p []string) (acToReturn map[int]map[uint8]int, f map[int][]int, s []int) {\n\tacTrie, stateIsTerminal, f := ConstructTrie(p)\n\ts = make([]int, len(stateIsTerminal)) //supply function\n\ti := 0                                //root of acTrie\n\tacToReturn = acTrie\n\ts[i] = -1\n\tfor current := 1; current < len(stateIsTerminal); current++ {\n\t\to, parent := GetParent(current, acTrie)\n\t\tdown := s[parent]\n\t\tfor StateExists(down, acToReturn) && GetTransition(down, o, acToReturn) == -1 {\n\t\t\tdown = s[down]\n\t\t}\n\t\tif StateExists(down, acToReturn) {\n\t\t\ts[current] = GetTransition(down, o, acToReturn)\n\t\t\tif stateIsTerminal[s[current]] {\n\t\t\t\tstateIsTerminal[current] = true\n\t\t\t\tf[current] = ArrayUnion(f[current], f[s[current]]) //F(Current) <- F(Current) union F(S(Current))\n\t\t\t}\n\t\t} else {\n\t\t\ts[current] = i //initial state?\n\t\t}\n\t}\n\treturn acToReturn, f, s\n}\n"
  },
  {
    "path": "strings/ahocorasick/ahocorasick_test.go",
    "content": "package ahocorasick\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestAhoCorasick(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := AhoCorasick(tc.text, tc.words)\n\t\t\tif !reflect.DeepEqual(actual, tc.expected) {\n\t\t\t\tactualString := convertToString(actual)\n\t\t\t\texpectedString := convertToString(tc.expected)\n\t\t\t\tt.Errorf(\"Expected matches for patterns %s for string '%s' are: patterns and positions found %v, but actual matches are: patterns and positions found %v\",\n\t\t\t\t\ttc.words, tc.text, actualString, expectedString)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc convertToString(res Result) string {\n\tvar r strings.Builder\n\tfor key, val := range res.occurrences {\n\t\tr.WriteString(fmt.Sprintf(\"Word: '%s' at positions: \", key))\n\t\tfor i := range val {\n\t\t\tr.WriteString(fmt.Sprintf(\"%d\", val[i]))\n\t\t\tif i != len(val)-1 {\n\t\t\t\tr.WriteString(\", \")\n\t\t\t}\n\t\t}\n\t\tr.WriteString(\". \")\n\t}\n\treturn r.String()\n}\n"
  },
  {
    "path": "strings/ahocorasick/patterns.txt",
    "content": "announce annual annually"
  },
  {
    "path": "strings/ahocorasick/shared.go",
    "content": "package ahocorasick\n\n// ConstructTrie Function that constructs Trie as an automaton for a set of reversed & trimmed strings.\nfunc ConstructTrie(p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {\n\ttrie = make(map[int]map[uint8]int)\n\tstateIsTerminal = make([]bool, 1)\n\tf = make(map[int][]int)\n\tstate := 1\n\tCreateNewState(0, trie)\n\tfor i := 0; i < len(p); i++ {\n\t\tcurrent := 0\n\t\tj := 0\n\t\tfor j < len(p[i]) && GetTransition(current, p[i][j], trie) != -1 {\n\t\t\tcurrent = GetTransition(current, p[i][j], trie)\n\t\t\tj++\n\t\t}\n\t\tfor j < len(p[i]) {\n\t\t\tstateIsTerminal = BoolArrayCapUp(stateIsTerminal)\n\t\t\tCreateNewState(state, trie)\n\t\t\tstateIsTerminal[state] = false\n\t\t\tCreateTransition(current, p[i][j], state, trie)\n\t\t\tcurrent = state\n\t\t\tj++\n\t\t\tstate++\n\t\t}\n\t\tif stateIsTerminal[current] {\n\t\t\tnewArray := IntArrayCapUp(f[current])\n\t\t\tnewArray[len(newArray)-1] = i\n\t\t\tf[current] = newArray // F(Current) <- F(Current) union {i}\n\t\t} else {\n\t\t\tstateIsTerminal[current] = true\n\t\t\tf[current] = []int{i} // F(Current) <- {i}\n\t\t}\n\t}\n\treturn trie, stateIsTerminal, f\n}\n\n// Contains Returns 'true' if array of int's 's' contains int 'e', 'false' otherwise.\nfunc Contains(s []int, e int) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// GetWord Function that returns word found in text 't' at position range 'begin' to 'end'.\nfunc GetWord(begin, end int, t string) string {\n\tfor end >= len(t) {\n\t\treturn \"\"\n\t}\n\td := make([]uint8, end-begin+1)\n\tfor j, i := 0, begin; i <= end; i, j = i+1, j+1 {\n\t\td[j] = t[i]\n\t}\n\treturn string(d)\n}\n\n// ComputeAlphabet Function that returns string of all the possible characters in given patterns.\nfunc ComputeAlphabet(p []string) (s string) {\n\ts = p[0]\n\tfor i := 1; i < len(p); i++ {\n\t\ts = s + p[i]\n\t}\n\treturn s\n}\n\n// IntArrayCapUp Dynamically increases an array size of int's by 1.\nfunc IntArrayCapUp(old []int) (new []int) {\n\tnew = make([]int, cap(old)+1)\n\tcopy(new, old) //copy(dst,src)\n\t// old = new\n\treturn new\n}\n\n// BoolArrayCapUp Dynamically increases an array size of bool's by 1.\nfunc BoolArrayCapUp(old []bool) (new []bool) {\n\tnew = make([]bool, cap(old)+1)\n\tcopy(new, old)\n\t// old = new\n\treturn new\n}\n\n// ArrayUnion Concats two arrays of int's into one.\nfunc ArrayUnion(to, from []int) (concat []int) {\n\tconcat = to\n\tfor i := range from {\n\t\tif !Contains(concat, from[i]) {\n\t\t\tconcat = IntArrayCapUp(concat)\n\t\t\tconcat[len(concat)-1] = from[i]\n\t\t}\n\t}\n\treturn concat\n}\n\n// GetParent Function that finds the first previous state of a state and returns it.\n// Used for trie where there is only one parent.\nfunc GetParent(state int, at map[int]map[uint8]int) (uint8, int) {\n\tfor beginState, transitions := range at {\n\t\tfor c, endState := range transitions {\n\t\t\tif endState == state {\n\t\t\t\treturn c, beginState\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, 0 //unreachable\n}\n\n// CreateNewState Automaton function for creating a new state 'state'.\nfunc CreateNewState(state int, at map[int]map[uint8]int) {\n\tat[state] = make(map[uint8]int)\n}\n\n// CreateTransition Creates a transition for function σ(state,letter) = end.\nfunc CreateTransition(fromState int, overChar uint8, toState int, at map[int]map[uint8]int) {\n\tat[fromState][overChar] = toState\n}\n\n// GetTransition Returns ending state for transition σ(fromState,overChar), '-1' if there is none.\nfunc GetTransition(fromState int, overChar uint8, at map[int]map[uint8]int) (toState int) {\n\tif !StateExists(fromState, at) {\n\t\treturn -1\n\t}\n\ttoState, ok := at[fromState][overChar]\n\tif !ok {\n\t\treturn -1\n\t}\n\treturn toState\n}\n\n// StateExists Checks if state 'state' exists. Returns 'true' if it does, 'false' otherwise.\nfunc StateExists(state int, at map[int]map[uint8]int) bool {\n\t_, ok := at[state]\n\tif !ok || state == -1 || at[state] == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "strings/ahocorasick/text.txt",
    "content": "CPM_annual_conference_announce"
  },
  {
    "path": "strings/bom/bom.go",
    "content": "package bom\n\n// User defined.\n// Set to true to print various extra stuff out (slows down the execution)\n// Set to false for quick and quiet execution.\n// const debugMode bool = false\n\n// User defined.\n// Set to true to read input from two command line arguments\n// Set to false to read input from two files \"pattern.txt\" and \"text.txt\"\n// const commandLineInput bool = false\n\n// Implementation of Backward Oracle Matching algorithm (Factor based approach).\n// Requires either a two command line arguments separated by a single space,\n// or two files in the same folder: \"pattern.txt\" containing the string to\n// be searched for, \"text.txt\" containing the text to be searched in.\n// func main() {\n// \tif commandLineInput == true { // case of command line input\n// \t\targs := os.Args\n// \t\tif len(args) <= 2 {\n// \t\t\tlog.Fatal(\"Not enough arguments. Two string arguments separated by spaces are required!\")\n// \t\t}\n// \t\tpattern := args[1]\n// \t\ts := args[2]\n// \t\tfor i := 3; i < len(args); i++ {\n// \t\t\ts = s + \" \" + args[i]\n// \t\t}\n// \t\tif len(args[1]) > len(s) {\n// \t\t\tlog.Fatal(\"Pattern  is longer than text!\")\n// \t\t}\n// \t\tif debugMode == true {\n// \t\t\tfmt.Printf(\"\\nRunning: Backward Oracle Matching algorithm.\\n\\n\")\n// \t\t\tfmt.Printf(\"Search word (%d chars long): %q.\\n\", len(args[1]), pattern)\n// \t\t\tfmt.Printf(\"Text        (%d chars long): %q.\\n\\n\", len(s), s)\n// \t\t} else {\n// \t\t\tfmt.Printf(\"\\nRunning: Backward Oracle Matching algorithm.\\n\\n\")\n// \t\t}\n// \t\tbom(s, pattern)\n// \t} else if commandLineInput == false { // case of file line input\n// \t\tpatFile, err := ioutil.ReadFile(\"pattern.txt\")\n// \t\tif err != nil {\n// \t\t\tlog.Fatal(err)\n// \t\t}\n// \t\ttextFile, err := ioutil.ReadFile(\"text.txt\")\n// \t\tif err != nil {\n// \t\t\tlog.Fatal(err)\n// \t\t}\n// \t\tif len(patFile) > len(textFile) {\n// \t\t\tlog.Fatal(\"Pattern  is longer than text!\")\n// \t\t}\n// \t\tif debugMode == true {\n// \t\t\tfmt.Printf(\"\\nRunning: Backward Oracle Matching algorithm.\\n\\n\")\n// \t\t\tfmt.Printf(\"Search word (%d chars long): %q.\\n\", len(patFile), patFile)\n// \t\t\tfmt.Printf(\"Text        (%d chars long): %q.\\n\\n\", len(textFile), textFile)\n// \t\t} else {\n// \t\t\tfmt.Printf(\"\\nRunning: Backward Oracle Matching algorithm.\\n\\n\")\n// \t\t}\n// \t\tbom(string(textFile), string(patFile))\n// \t}\n// }\n\n// // Function bom performing the Backward Oracle Matching algorithm.\n// // Prints whether the word/pattern was found + positions of possible multiple occurrences\n// // or that the word was not found.\n// func bom(t, p string) {\n// \tstartTime := time.Now()\n// \tn, m := len(t), len(p)\n// \tvar current, j, pos int\n// \toracle := oracleOnLine(reverse(p))\n// \toccurrences := make([]int, len(t))\n// \tcurrentOcc := 0\n// \tpos = 0\n// \tif debugMode == true {\n// \t\tfmt.Printf(\"\\n\\nWe are reading backwards in %q, searching for %q\\n\\nat position %d:\\n\", t, p, pos+m-1)\n// \t}\n// \tfor pos <= n-m {\n// \t\tcurrent = 0 //initial state of the oracle\n// \t\tj = m\n// \t\tfor j > 0 && stateExists(current, oracle) {\n// \t\t\tif debugMode == true {\n// \t\t\t\tprettyPrint(current, j, n, pos, t, oracle)\n// \t\t\t}\n// \t\t\tcurrent = getTransition(current, t[pos+j-1], oracle)\n// \t\t\tj--\n// \t\t}\n// \t\tif stateExists(current, oracle) {\n// \t\t\tif debugMode == true {\n// \t\t\t\tfmt.Printf(\" We got an occurrence!\")\n// \t\t\t}\n// \t\t\toccurrences[currentOcc] = pos\n// \t\t\tcurrentOcc++\n// \t\t}\n// \t\tpos = pos + j + 1\n// \t\tif pos+m-1 < len(t) {\n// \t\t\tif debugMode == true {\n// \t\t\t\tfmt.Printf(\"\\n\\nposition %d:\\n\", pos+m-1)\n// \t\t\t}\n// \t\t}\n// \t}\n// \telapsed := time.Since(startTime)\n// \tfmt.Printf(\"\\n\\nElapsed %f secs\\n\", elapsed.Seconds())\n// \tfmt.Printf(\"\\n\\n\")\n// \tif currentOcc > 0 {\n// \t\tfmt.Printf(\"Word %q was found %d times at positions: \", p, currentOcc)\n// \t\tfor k := 0; k < currentOcc-1; k++ {\n// \t\t\tfmt.Printf(\"%d, \", occurrences[k])\n// \t\t}\n// \t\tfmt.Printf(\"%d\", occurrences[currentOcc-1])\n// \t\tfmt.Printf(\".\\n\")\n// \t}\n// \tif currentOcc == 0 {\n// \t\tfmt.Printf(\"\\nWord was not found.\\n\")\n// \t}\n// \treturn\n// }\n\n// // Construction of the factor oracle automaton for a word p.\n// func oracleOnLine(p string) (oracle map[int]map[uint8]int) {\n// \tif debugMode == true {\n// \t\tfmt.Printf(\"Oracle construction: \\n\")\n// \t}\n// \toracle = make(map[int]map[uint8]int)\n// \tsupply := make([]int, len(p)+2) // supply function\n// \tcreateNewState(0, oracle)\n// \tsupply[0] = -1\n// \tvar orP string\n// \tfor j := 0; j < len(p); j++ {\n// \t\toracle, orP = oracleAddLetter(oracle, supply, orP, p[j])\n// \t}\n// \treturn oracle\n// }\n\n// // Adds one letter to the oracle.\n// func oracleAddLetter(oracle map[int]map[uint8]int, supply []int, orP string, o uint8) (oracleToReturn map[int]map[uint8]int, orPToReturn string) {\n// \tm := len(orP)\n// \tvar s int\n// \tcreateNewState(m+1, oracle)\n// \tcreateTransition(m, o, m+1, oracle)\n// \tk := supply[m]\n// \tfor k > -1 && getTransition(k, o, oracle) == -1 {\n// \t\tcreateTransition(k, o, m+1, oracle)\n// \t\tk = supply[k]\n// \t}\n// \tif k == -1 {\n// \t\ts = 0\n// \t} else {\n// \t\ts = getTransition(k, o, oracle)\n// \t}\n// \tsupply[m+1] = s\n// \treturn oracle, orP + string(o)\n// }\n\n// // Function that takes a single string and reverses it.\n// // @author 'Walter' http://stackoverflow.com/a/10043083\n// func reverse(s string) string {\n// \tl := len(s)\n// \tm := make([]rune, l)\n// \tfor _, c := range s {\n// \t\tl--\n// \t\tm[l] = c\n// \t}\n// \treturn string(m)\n// }\n\n// // Automaton function for creating a new state.\n// func createNewState(state int, at map[int]map[uint8]int) {\n// \tat[state] = make(map[uint8]int)\n// \tif debugMode == true {\n// \t\tfmt.Printf(\"\\ncreated state %d\", state)\n// \t}\n// }\n\n// // Creates a transition for function σ(state,letter) = end.\n// func createTransition(fromState int, overChar uint8, toState int, at map[int]map[uint8]int) {\n// \tat[fromState][overChar] = toState\n// \tif debugMode == true {\n// \t\tfmt.Printf(\"\\n    σ(%d,%c)=%d;\", fromState, overChar, toState)\n// \t}\n// }\n\n// // Returns ending state for transition σ(fromState,overChar), -1 if there is none.\n// func getTransition(fromState int, overChar uint8, at map[int]map[uint8]int) (toState int) {\n// \tif !stateExists(fromState, at) {\n// \t\treturn -1\n// \t}\n// \ttoState, ok := at[fromState][overChar]\n// \tif ok == false {\n// \t\treturn -1\n// \t}\n// \treturn toState\n// }\n\n// // Checks if state exists. Returns true if it does, false otherwise.\n// func stateExists(state int, at map[int]map[uint8]int) bool {\n// \t_, ok := at[state]\n// \tif !ok || state == -1 || at[state] == nil {\n// \t\treturn false\n// \t}\n// \treturn true\n// }\n\n// // Just some printing of extra information about what the algorithm does.\n// func prettyPrint(current int, j int, n int, pos int, t string, oracle map[int]map[uint8]int) {\n// \tif current == 0 && !(getTransition(current, t[pos+j-1], oracle) == -1) {\n// \t\tfmt.Printf(\"\\n -->(%d)---(%c)--->(%d)\", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))\n// \t} else if getTransition(current, t[pos+j-1], oracle) == -1 && current != 0 {\n// \t\tfmt.Printf(\"\\n    (%d)---(%c)       \", current, t[pos+j-1])\n// \t} else if getTransition(current, t[pos+j-1], oracle) == -1 && current == 0 {\n// \t\tfmt.Printf(\"\\n -->(%d)---(%c)       \", current, t[pos+j-1])\n// \t} else {\n// \t\tfmt.Printf(\"\\n    (%d)---(%c)--->(%d)\", current, t[pos+j-1], getTransition(current, t[pos+j-1], oracle))\n// \t}\n// \tfmt.Printf(\" \")\n// \tfor a := 0; a < pos+j-1; a++ {\n// \t\tfmt.Printf(\"%c\", t[a])\n// \t}\n// \tif getTransition(current, t[pos+j-1], oracle) == -1 {\n// \t\tfmt.Printf(\"[%c]\", t[pos+j-1])\n// \t} else {\n// \t\tfmt.Printf(\"[%c]\", t[pos+j-1])\n// \t}\n// \tfor a := pos + j; a < n; a++ {\n// \t\tfmt.Printf(\"%c\", t[a])\n// \t}\n// \tif getTransition(current, t[pos+j-1], oracle) == -1 {\n// \t\tfmt.Printf(\" FAIL on the character[%c]\", t[pos+j-1])\n// \t}\n// }\n"
  },
  {
    "path": "strings/charoccurrence.go",
    "content": "// charoccurrence.go\n// description: An algorithm which counts the number\n// of times a character occurred in a string.\n// author(s) [Moein](https://github.com/mo1ein)\n// see charoccurrence_test.go\n\npackage strings\n\n// CountChars counts the number of a times a character\n// has occurred in the provided string argument and\n// returns a map with `rune` as keys and the count as value.\nfunc CountChars(text string) map[rune]int {\n\tcharMap := make(map[rune]int, 0)\n\tfor _, c := range text {\n\t\tif _, ok := charMap[c]; !ok {\n\t\t\tcharMap[c] = 0\n\t\t}\n\t\tcharMap[c]++\n\t}\n\treturn charMap\n}\n"
  },
  {
    "path": "strings/charoccurrence_test.go",
    "content": "package strings_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/strings\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestCountChars(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname     string\n\t\tinput    string\n\t\texpected map[rune]int\n\t}{\n\t\t{\n\t\t\t\"english text\",\n\t\t\t\"hello world!\",\n\t\t\tmap[rune]int{32: 1, 33: 1, 100: 1, 101: 1, 104: 1, 108: 3, 111: 2, 114: 1, 119: 1},\n\t\t},\n\t\t{\n\t\t\t\"chinese text\",\n\t\t\t\" 世界 \",\n\t\t\tmap[rune]int{32: 2, 19990: 1, 30028: 1},\n\t\t},\n\t\t{\n\t\t\t\"persian text\",\n\t\t\t\"سلام دنیا!\",\n\t\t\tmap[rune]int{32: 1, 33: 1, 1575: 2, 1583: 1, 1587: 1, 1604: 1, 1605: 1, 1606: 1, 1740: 1},\n\t\t},\n\t}\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfuncResult := strings.CountChars(test.input)\n\t\t\tif !reflect.DeepEqual(test.expected, funcResult) {\n\t\t\t\tt.Errorf(\"expected: %v, got %v\", test.expected, funcResult)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/combination/combination.go",
    "content": "// Package combination ...\npackage combination\n\nimport \"fmt\"\n\n// Combinations structure with in and out rune\ntype Combinations struct {\n\tout []rune\n\tin  []rune\n}\n\n// Start ...\nfunc Start(input string) {\n\tc := &Combinations{\n\t\tin: []rune(input),\n\t}\n\n\tc.Combine(0)\n}\n\n// Combine ...\nfunc (c *Combinations) Combine(seed int) {\n\tinLen := len(c.in)\n\tfor i := seed; i < inLen-1; i++ {\n\t\tc.out = append(c.out, c.in[i])\n\t\tfmt.Println(string(c.out))\n\t\tc.Combine(i + 1)\n\t\tc.out = c.out[:len(c.out)-1]\n\t}\n\tc.out = append(c.out, c.in[inLen-1])\n\tfmt.Println(string(c.out))\n\tc.out = c.out[:len(c.out)-1]\n}\n"
  },
  {
    "path": "strings/doc.go",
    "content": "// Package strings is a package that contains all algorithms\n// that are used to analyse and manipulate strings.\npackage strings\n"
  },
  {
    "path": "strings/generateparentheses/generateparentheses.go",
    "content": "// generateparenthesesgo\n// description: Generate Parentheses\n// details:\n// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see generateparentheses_test.go\n\npackage generateparentheses\n\nimport \"strings\"\n\nfunc GenerateParenthesis(n int) []string {\n\tresult := make([]string, 0)\n\tmaxLen := 2 * n\n\tvar recursiveComputation func(s []string, left int, right int)\n\trecursiveComputation = func(s []string, left int, right int) {\n\t\tif len(s) == maxLen {\n\t\t\tresult = append(result, strings.Join(s, \"\"))\n\t\t\treturn\n\t\t}\n\t\tif left < n {\n\t\t\ts = append(s, \"(\")\n\t\t\trecursiveComputation(s, left+1, right)\n\t\t\ts = s[:len(s)-1]\n\t\t}\n\t\tif right < left {\n\t\t\ts = append(s, \")\")\n\t\t\trecursiveComputation(s, left, right+1)\n\t\t\t_ = s[:len(s)-1]\n\t\t}\n\t}\n\trecursiveComputation(make([]string, 0), 0, 0)\n\treturn result\n}\n"
  },
  {
    "path": "strings/generateparentheses/generateparentheses_test.go",
    "content": "// generateparentheses_test.go\n// description: Generate Parentheses\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see generateparentheses.go\n\npackage generateparentheses\n\nimport \"testing\"\n\nfunc TestGenerateParenthesis(t *testing.T) {\n\tt.Run(\"GenerateParenthesis\", func(t *testing.T) {\n\t\tresult := GenerateParenthesis(3)\n\t\tt.Log(result)\n\t\texp := []string{\"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"}\n\t\tfor i, v := range result {\n\t\t\tif v != exp[i] {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%s, returned:%s \", result[i], exp[i])\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "strings/genetic/genetic.go",
    "content": "// Package genetic provides functions to work with strings\n// using genetic algorithm. https://en.wikipedia.org/wiki/Genetic_algorithm\n//\n// Author: D4rkia\npackage genetic\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n\t\"unicode/utf8\"\n)\n\n// Population item represent a single step in the evolution process.\n// One can think of population item as a single species.\n// Key stands for the actual data entity of the species, which is a string\n// in current implementation. Key can be interpreted as species DNA.\n// Value shows how close this species to the desired target, where 1 means,\n// that species DNA equals to the targeted one, 0 for no matchings in the DNA.\n//\n// **Note** In the current implementation species DNA length is suppose to be\n// equal to the target length for algorithm to work.\ntype PopulationItem struct {\n\tKey   string\n\tValue float64\n}\n\n// Conf stands for configurations set provided to GeneticString function.\ntype Conf struct {\n\t// Maximum size of the population.\n\t// Bigger could be faster but more memory expensive.\n\tPopulationNum int\n\n\t// Number of elements selected in every generation for evolution\n\t// the selection takes. Place from the best to the worst of that\n\t// generation must be smaller than PopulationNum.\n\tSelectionNum int\n\n\t// Probability that an element of a generation can mutate changing one of\n\t// its genes this guarantees that all genes will be used during evolution.\n\tMutationProb float64\n\n\t// Enables debugging output to the console.\n\tDebug bool\n}\n\n// Result structure contains generation process statistics, as well as the\n// best resulted population item.\ntype Result struct {\n\t// Number of generations steps performed.\n\tGeneration int\n\n\t// Number of generated population items.\n\tAnalyzed int\n\n\t// Result of generation with the best Value.\n\tBest PopulationItem\n}\n\n// GeneticString generates PopulationItem based on the imputed target\n// string, and a set of possible runes to build a string with. In order\n// to optimise string generation additional configurations can be provided\n// with Conf instance. Empty instance of Conf (&Conf{}) can be provided,\n// then default values would be set.\n//\n// Link to the same algorithm implemented in python:\n// https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py\nfunc GeneticString(target string, charmap []rune, conf *Conf) (*Result, error) {\n\tpopulationNum := conf.PopulationNum\n\tif populationNum == 0 {\n\t\tpopulationNum = 200\n\t}\n\n\tselectionNum := conf.SelectionNum\n\tif selectionNum == 0 {\n\t\tselectionNum = 50\n\t}\n\n\t// Verify if 'populationNum' s bigger than 'selectionNum'\n\tif populationNum < selectionNum {\n\t\treturn nil, errors.New(\"populationNum must be bigger than selectionNum\")\n\t}\n\n\tmutationProb := conf.MutationProb\n\tif mutationProb == .0 {\n\t\tmutationProb = .4\n\t}\n\n\tdebug := conf.Debug\n\n\t// Just a seed to improve randomness required by the algorithm\n\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t// Verify that the target contains no genes besides the ones inside genes variable.\n\tfor position, r := range target {\n\t\tinvalid := true\n\t\tfor _, n := range charmap {\n\t\t\tif n == r {\n\t\t\t\tinvalid = false\n\t\t\t}\n\t\t}\n\t\tif invalid {\n\t\t\tmessage := fmt.Sprintf(\"character not available in charmap at position: %v\", position)\n\t\t\treturn nil, errors.New(message)\n\t\t}\n\t}\n\n\t// Generate random starting population\n\tpop := make([]PopulationItem, populationNum)\n\tfor i := 0; i < populationNum; i++ {\n\t\tkey := \"\"\n\t\tfor x := 0; x < utf8.RuneCountInString(target); x++ {\n\t\t\tchoice := rnd.Intn(len(charmap))\n\t\t\tkey += string(charmap[choice])\n\t\t}\n\t\tpop[i] = PopulationItem{key, 0}\n\t}\n\n\t// Just some logs to know what the algorithms is doing\n\tgen, generatedPop := 0, 0\n\n\t// This loop will end when we will find a perfect match for our target\n\tfor {\n\t\tgen++\n\t\tgeneratedPop += len(pop)\n\n\t\t// Random population created now it's time to evaluate\n\t\tfor i, item := range pop {\n\t\t\tpop[i].Value = 0\n\t\t\titemKey, targetRune := []rune(item.Key), []rune(target)\n\t\t\tfor x := 0; x < len(target); x++ {\n\t\t\t\tif itemKey[x] == targetRune[x] {\n\t\t\t\t\tpop[i].Value++\n\t\t\t\t}\n\t\t\t}\n\t\t\tpop[i].Value = pop[i].Value / float64(len(targetRune))\n\t\t}\n\t\tsort.SliceStable(pop, func(i, j int) bool { return pop[i].Value > pop[j].Value })\n\n\t\t// Check if there is a matching evolution\n\t\tif pop[0].Key == target {\n\t\t\tbreak\n\t\t}\n\n\t\t// Print the best resultPrint the Best result every 10 generations\n\t\t// just to know that the algorithm is working\n\t\tif debug && gen%10 == 0 {\n\t\t\tfmt.Println(\"Generation:\", strconv.Itoa(gen), \"Analyzed:\", generatedPop, \"Best:\", pop[0])\n\t\t}\n\n\t\t// Generate a new population vector keeping some of the best evolutions\n\t\t// Keeping this avoid regression of evolution\n\t\tvar popChildren []PopulationItem\n\t\tpopChildren = append(popChildren, pop[0:int(selectionNum/3)]...)\n\n\t\t// This is Selection\n\t\tfor i := 0; i < int(selectionNum); i++ {\n\t\t\tparent1 := pop[i]\n\t\t\t// Generate more child proportionally to the fitness score\n\t\t\tnChild := (parent1.Value * 100) + 1\n\t\t\tif nChild >= 10 {\n\t\t\t\tnChild = 10\n\t\t\t}\n\t\t\tfor x := 0.0; x < nChild; x++ {\n\t\t\t\tparent2 := pop[rnd.Intn(selectionNum)]\n\t\t\t\t// Crossover\n\t\t\t\tsplit := rnd.Intn(utf8.RuneCountInString(target))\n\t\t\t\tchild1 := append([]rune(parent1.Key)[:split], []rune(parent2.Key)[split:]...)\n\t\t\t\tchild2 := append([]rune(parent2.Key)[:split], []rune(parent1.Key)[split:]...)\n\t\t\t\t// Clean fitness value\n\t\t\t\t// Mutate\n\t\t\t\tif rnd.Float64() < mutationProb {\n\t\t\t\t\tchild1[rnd.Intn(len(child1))] = charmap[rnd.Intn(len(charmap))]\n\t\t\t\t}\n\t\t\t\tif rnd.Float64() < mutationProb {\n\t\t\t\t\tchild2[rnd.Intn(len(child2))] = charmap[rnd.Intn(len(charmap))]\n\t\t\t\t}\n\t\t\t\t// Push into 'popChildren'\n\t\t\t\tpopChildren = append(popChildren, PopulationItem{string(child1), 0})\n\t\t\t\tpopChildren = append(popChildren, PopulationItem{string(child2), 0})\n\n\t\t\t\t// Check if the population has already reached the maximum value and if so,\n\t\t\t\t// break the cycle. If this check is disabled the algorithm will take\n\t\t\t\t// forever to compute large strings but will also calculate small string in\n\t\t\t\t// a lot fewer generationsù\n\t\t\t\tif len(popChildren) >= selectionNum {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpop = popChildren\n\t}\n\treturn &Result{gen, generatedPop, pop[0]}, nil\n}\n"
  },
  {
    "path": "strings/genetic/geneticalgorithm_test.go",
    "content": "package genetic\n\nimport (\n\t\"testing\"\n)\n\nfunc TestSimple(t *testing.T) {\n\ttarget := \"This is a genetic algorithm to evaluate, combine, evolve and mutate a string!\"\n\tcharmap := []rune(\" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\\\\")\n\n\tres, err := GeneticString(target, charmap, &Conf{})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\\n\", err)\n\t}\n\n\tgot := res.Best\n\n\tif got.Value != float64(1.0) {\n\t\tt.Errorf(\"Target value not reached\\nwant: %f\\n, got: %f\\n\", float64(1.0), got.Value)\n\t}\n\n\tif got.Key != target {\n\t\tt.Errorf(\"Target string not reached\\nwant: %s\\n, got: %s\\n\", target, got.Key)\n\t}\n}\n"
  },
  {
    "path": "strings/guid/guid.go",
    "content": "// guid.go\n// description: Generate random globally unique identifiers (GUIDs).\n// details:\n// A GUID (globally unique identifier) is a 128-bit text string that\n// represents an identification (ID). Organizations generate GUIDs when\n// a unique reference number is needed to identify information on\n// a computer or network. A GUID can be used to ID hardware, software,\n// accounts, documents and other items. The term is also often used in\n// software created by Microsoft.\n// See more information on: https://en.wikipedia.org/wiki/Universally_unique_identifier\n// author(s) [cheatsnake](https://github.com/cheatsnake)\n// see guid_test.go\n\n// Package guid provides facilities for generating random globally unique identifiers.\npackage guid\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"strings\"\n)\n\nconst pattern string = \"xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx\"\nconst versionIndex int = 14\n\n// New returns a randomly generated global unique identifier.\nfunc New() (string, error) {\n\tvar guid strings.Builder\n\n\tfor i, ch := range pattern {\n\t\tif i == versionIndex {\n\t\t\tguid.WriteRune(ch)\n\t\t\tcontinue\n\t\t}\n\t\tif ch == '-' {\n\t\t\tguid.WriteRune(ch)\n\t\t\tcontinue\n\t\t}\n\t\trandom, err := rand.Int(rand.Reader, big.NewInt(16))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tguid.WriteString(fmt.Sprintf(\"%x\", random.Int64()))\n\t}\n\n\treturn guid.String(), nil\n}\n"
  },
  {
    "path": "strings/guid/guid_test.go",
    "content": "package guid\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\tt.Run(\"check for allowed characters\", func(t *testing.T) {\n\t\tallowedChars := \"0123456789abcdef-\"\n\t\tguid, err := New()\n\t\tif err != nil {\n\t\t\tt.Errorf(`the test failed, an error occurred: %s`, err.Error())\n\t\t}\n\n\t\tfor _, char := range guid {\n\t\t\tif !strings.Contains(allowedChars, string(char)) {\n\t\t\t\tt.Errorf(`allowed only \"%s\" characters, but got %v`, allowedChars, char)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"check string length\", func(t *testing.T) {\n\t\tguid, err := New()\n\t\tif err != nil {\n\t\t\tt.Errorf(`the test failed, an error occurred: %s`, err.Error())\n\t\t}\n\n\t\tif len(guid) != len(pattern) {\n\t\t\tt.Errorf(`the length of the string should be \"%d\", but got %d`, len(pattern), len(guid))\n\t\t}\n\t})\n\n\tt.Run(\"check for version index\", func(t *testing.T) {\n\t\texpected := \"4\"\n\t\tversionIndex := strings.Index(pattern, expected)\n\t\tguid, err := New()\n\t\tif err != nil {\n\t\t\tt.Errorf(`the test failed, an error occurred: %s`, err.Error())\n\t\t}\n\n\t\tresult := string(guid[versionIndex])\n\n\t\tif expected != result {\n\t\t\tt.Errorf(`at the index %d should be %s, but got %s`, versionIndex, expected, result)\n\t\t}\n\t})\n\n\tt.Run(\"check the number of dashes\", func(t *testing.T) {\n\t\texpected := strings.Count(pattern, \"-\")\n\t\tguid, err := New()\n\t\tif err != nil {\n\t\t\tt.Errorf(`the test failed, an error occurred: %s`, err.Error())\n\t\t}\n\n\t\tresult := strings.Count(guid, \"-\")\n\n\t\tif expected != result {\n\t\t\tt.Errorf(`the length of the string should be \"%d\", but got %d`, len(pattern), len(guid))\n\t\t}\n\t})\n}\n\nfunc BenchmarkNew(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = New()\n\t}\n}\n"
  },
  {
    "path": "strings/hamming/hammingdistance.go",
    "content": "/*\nThis algorithm calculates the hamming distance between two equal length strings.\nThe Hamming distance between two equal-length strings of symbols is the number of positions\nat which the corresponding symbols are different:\nhttps://en.wikipedia.org/wiki/Hamming_distance\n\nNote that we didn't consider strings as an array of bytes, therefore, we didn't use the XOR operator.\nIn this case, we used a simple loop to compare each character of the strings, and if they are different,\nwe increment the hamming distance by 1.\n\nParameters: two strings to compare\nOutput: distance between both strings */\n\npackage hamming\n\nimport \"errors\"\n\nfunc Distance(str1, str2 string) (int, error) {\n\tif len(str1) != len(str2) {\n\t\treturn -1, errors.New(\"strings must have a same length\")\n\t}\n\n\thammingDistance := 0\n\tfor i := 0; i < len(str1); i++ {\n\t\tif str1[i] != str2[i] {\n\t\t\thammingDistance++\n\t\t}\n\t}\n\n\treturn hammingDistance, nil\n}\n"
  },
  {
    "path": "strings/hamming/hammingdistance_test.go",
    "content": "package hamming\n\nimport \"testing\"\n\nvar testCases = []struct {\n\tname     string\n\tstring1  string\n\tstring2  string\n\texpected int\n}{\n\t{\n\t\t\"empty strings\",\n\t\t\"\",\n\t\t\"\",\n\t\t0,\n\t},\n\t{\n\t\t\"single character strings\",\n\t\t\"A\",\n\t\t\"A\",\n\t\t0,\n\t},\n\t{\n\t\t\"two different strings with a same length\",\n\t\t\"TestString 1\",\n\t\t\"TestString 2\",\n\t\t1,\n\t},\n\t{\n\t\t\"two different strings with a different length\",\n\t\t\"TestString1\",\n\t\t\"TestString\",\n\t\t-1,\n\t},\n\t{\n\t\t\"two same strings with a same length\",\n\t\t\"TestString\",\n\t\t\"TestString\",\n\t\t0,\n\t},\n}\n\nfunc TestHammingDistance(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual, err := Distance(tc.string1, tc.string2)\n\t\t\tif err != nil {\n\t\t\t\tif tc.expected != -1 {\n\t\t\t\t\tt.Fatalf(\"Expected no error, but got %v\", err)\n\t\t\t\t}\n\t\t\t} else if actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected Hamming distance between strings: '%s' and '%s' is %v, but got: %v\", tc.string1, tc.string2, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/horspool/horspool.go",
    "content": "// Implementation of the\n// [Boyer–Moore–Horspool algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm)\n\npackage horspool\n\nimport \"errors\"\n\nvar ErrNotFound = errors.New(\"pattern was not found in the input string\")\n\nfunc Horspool(t, p string) (int, error) {\n\t// in order to handle multy-byte character properly\n\t// the input is converted into rune arrays\n\treturn horspool([]rune(t), []rune(p))\n}\n\nfunc horspool(t, p []rune) (int, error) {\n\tshiftMap := computeShiftMap(t, p)\n\tpos := 0\n\tfor pos <= len(t)-len(p) {\n\t\tif isMatch(pos, t, p) {\n\t\t\treturn pos, nil\n\t\t}\n\t\tif pos+len(p) >= len(t) {\n\t\t\t// because the remaining length of the input string\n\t\t\t// is the same as the length of the pattern\n\t\t\t// and it does not match the pattern\n\t\t\t// it is impossible to find the pattern\n\t\t\tbreak\n\t\t}\n\n\t\t// because of the check above\n\t\t// t[pos+len(p)] is defined\n\t\tpos += shiftMap[t[pos+len(p)]]\n\t}\n\n\treturn -1, ErrNotFound\n}\n\n// Checks if the array p matches the subarray of t starting at pos.\n// Note that backward iteration.\n// There are [other](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm#Tuning_the_comparison_loop)\n// approaches possible.\nfunc isMatch(pos int, t, p []rune) bool {\n\tj := len(p)\n\tfor j > 0 && t[pos+j-1] == p[j-1] {\n\t\tj--\n\t}\n\treturn j == 0\n}\n\nfunc computeShiftMap(t, p []rune) (res map[rune]int) {\n\tres = make(map[rune]int)\n\tfor _, tCode := range t {\n\t\tres[tCode] = len(p)\n\t}\n\tfor i, pCode := range p {\n\t\tres[pCode] = len(p) - i\n\t}\n\treturn res\n}\n"
  },
  {
    "path": "strings/horspool/horspool_test.go",
    "content": "// horspool_test.go\n// description: Tests for horspool\n// see horspool.go\n\npackage horspool\n\nimport \"testing\"\nimport \"fmt\"\n\nfunc TestLHorspool(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput    string\n\t\tpattern  string\n\t\texpected int\n\t}{\n\t\t{\"aaaaXaaa\", \"X\", 4},\n\t\t{\"aaaaXXaa\", \"XX\", 4},\n\t\t{\"Xaaab\", \"X\", 0},\n\t\t{\"XYaab\", \"XY\", 0},\n\t\t{\"abcefghXYZ\", \"XYZ\", 7},\n\t\t{\"abcefgh€YZ⌘\", \"€YZ\", 7},\n\t\t{\"⌘bcefgh€YZ⌘\", \"€YZ\", 7},\n\t\t{\"abc\", \"abc\", 0},\n\t\t{\"\", \"\", 0},\n\t\t{\"a\", \"\", 0},\n\t\t{\"a\", \"a\", 0},\n\t\t{\"aa\", \"a\", 0},\n\t\t{\"aa\", \"aa\", 0},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(fmt.Sprint(\"test with \", tc.input, \" \", tc.pattern), func(t *testing.T) {\n\t\t\tresult, curError := Horspool(tc.input, tc.pattern)\n\t\t\tif curError != nil {\n\t\t\t\tt.Fatalf(\"Got unexpected error\")\n\t\t\t}\n\t\t\tif tc.expected != result {\n\t\t\t\tt.Fatalf(\"expected %d, got %d\", tc.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLHorspoolNotExisintPattern(t *testing.T) {\n\ttestCases := []struct {\n\t\tinput   string\n\t\tpattern string\n\t}{\n\t\t{\"\", \"X\"},\n\t\t{\"X\", \"Y\"},\n\t\t{\"X\", \"XX\"},\n\t\t{\"aaaaaaaXaXaaaa\", \"XXX\"},\n\t\t{\"aaaaaaaXaX\", \"XXX\"},\n\t\t{\"XaX\", \"XXX\"},\n\t\t{\"XaX\", \"XXX\"},\n\t\t{\"\\xe2\\x8c\\x98\", \"\\x98\"},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(fmt.Sprint(\"test with \", tc.input, \" \", tc.pattern), func(t *testing.T) {\n\t\t\tresult, curError := Horspool(tc.input, tc.pattern)\n\t\t\tif curError != ErrNotFound {\n\t\t\t\tt.Fatalf(\"Got unexpected error\")\n\t\t\t}\n\t\t\tif result != -1 {\n\t\t\t\tt.Fatalf(\"expected -1, got %d\", result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/isisogram.go",
    "content": "// Checks if a given string is an isogram.\n// A first-order isogram is a word in which no letter of the alphabet occurs more than once.\n// A second-order isogram is a word in which each letter appears twice.\n// A third-order isogram is a word in which each letter appears three times.\n// wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms\n// Author: M3talM0nk3y\n\npackage strings\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype IsogramOrder int\n\nconst (\n\tFirst IsogramOrder = iota + 1\n\tSecond\n\tThird\n)\n\nfunc hasDigit(text string) bool {\n\tre := regexp.MustCompile(`\\d`)\n\treturn re.MatchString(text)\n}\n\nfunc hasSymbol(text string) bool {\n\tre := regexp.MustCompile(`[-!@#$%^&*()+]`)\n\treturn re.MatchString(text)\n}\n\nfunc IsIsogram(text string, order IsogramOrder) (bool, error) {\n\tif order < First || order > Third {\n\t\treturn false, errors.New(\"Invalid isogram order provided\")\n\t}\n\n\ttext = strings.ToLower(text)\n\ttext = strings.Join(strings.Fields(text), \"\")\n\n\tif hasDigit(text) || hasSymbol(text) {\n\t\treturn false, errors.New(\"Cannot contain numbers or symbols\")\n\t}\n\n\tletters := make(map[string]int)\n\tfor _, c := range text {\n\t\tl := string(c)\n\t\tif _, ok := letters[l]; ok {\n\t\t\tletters[l] += 1\n\n\t\t\tif letters[l] > 3 {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\t\tletters[l] = 1\n\t}\n\n\tmapVals := make(map[int]bool)\n\tfor _, v := range letters {\n\t\tmapVals[v] = true\n\t}\n\n\tif _, ok := mapVals[int(order)]; ok && len(mapVals) == 1 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n"
  },
  {
    "path": "strings/isisogram_test.go",
    "content": "package strings_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/strings\"\n)\n\nvar testCases = []struct {\n\tname        string\n\tinput       string\n\torder       strings.IsogramOrder\n\texpectedVal bool\n\texpectedErr error\n}{\n\t{\n\t\t\"Alphanumeric string 1\",\n\t\t\"copy1\",\n\t\t1,\n\t\tfalse,\n\t\terrors.New(\"Cannot contain numbers or symbols\"),\n\t},\n\t{\n\t\t\"Alphanumeric string 2\",\n\t\t\"copy1sentence\",\n\t\t1,\n\t\tfalse,\n\t\terrors.New(\"Cannot contain numbers or symbols\"),\n\t},\n\t{\n\t\t\"Alphanumeric string 3\",\n\t\t\"copy1 sentence with space\",\n\t\t1,\n\t\tfalse,\n\t\terrors.New(\"Cannot contain numbers or symbols\"),\n\t},\n\t{\n\t\t\"Alphabetic string 1\",\n\t\t\"allowance\",\n\t\t1,\n\t\tfalse,\n\t\tnil,\n\t},\n\t{\n\t\t\"Alphabetic string 2\",\n\t\t\"My Doodle\",\n\t\t1,\n\t\tfalse,\n\t\tnil,\n\t},\n\t{\n\t\t\"Alphabetic string with symbol\",\n\t\t\"Isogram!\",\n\t\t1,\n\t\tfalse,\n\t\terrors.New(\"Cannot contain numbers or symbols\"),\n\t},\n\t{\n\t\t\"Isogram string 1\",\n\t\t\"Uncopyrightable\",\n\t\t1,\n\t\ttrue,\n\t\tnil,\n\t},\n\t{\n\t\t\"Second order isogram 1\",\n\t\t\"Caucasus\",\n\t\t2,\n\t\ttrue,\n\t\tnil,\n\t},\n\t{\n\t\t\"Second order isogram 2\",\n\t\t\"Couscous\",\n\t\t2,\n\t\ttrue,\n\t\tnil,\n\t},\n\t{\n\t\t\"Third order isogram 1\",\n\t\t\"Deeded\",\n\t\t3,\n\t\ttrue,\n\t\tnil,\n\t},\n\t{\n\t\t\"Third order isogram 2\",\n\t\t\"Sestettes\",\n\t\t3,\n\t\ttrue,\n\t\tnil,\n\t},\n\t{\n\t\t\"Not an isogram\",\n\t\t\"Pneumonoultramicroscopicsilicovolcanoconiosis\",\n\t\t1,\n\t\tfalse,\n\t\tnil,\n\t},\n\t{\n\t\t\"Not an isogram\",\n\t\t\"Randomstring\",\n\t\t4,\n\t\tfalse,\n\t\terrors.New(\"Invalid isogram order provided\"),\n\t},\n\t{\n\t\t\"Third order isogram checked as first order\",\n\t\t\"Deeded\",\n\t\t1,\n\t\tfalse,\n\t\tnil,\n\t},\n}\n\nfunc TestIsIsogram(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tactualVal, actualErr := strings.IsIsogram(test.input, test.order)\n\n\t\t\tif actualErr != nil && test.expectedErr.Error() != actualErr.Error() {\n\t\t\t\tt.Errorf(\"Expected to be '%v' for string %s but was '%v'.\", test.expectedErr, test.input, actualErr)\n\t\t\t}\n\n\t\t\tif test.expectedVal != actualVal {\n\t\t\t\tt.Errorf(\"Expected to be '%v' for string %s but was '%v'.\", test.expectedVal, test.input, actualVal)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/issubsequence.go",
    "content": "// Checks if a given string is a subsequence of another string.\n// A subsequence of a given string is a string that can be derived from the given\n// string by deleting some or no characters without changing the order of the\n// remaining characters. (i.e., \"dpr\" is a subsequence of \"depqr\" while \"drp\" is not).\n// Author: sanjibgirics\n\npackage strings\n\n// Returns true if s is subsequence of t, otherwise return false.\nfunc IsSubsequence(s string, t string) bool {\n\tif len(s) > len(t) {\n\t\treturn false\n\t}\n\n\tif s == t {\n\t\treturn true\n\t}\n\n\tif len(s) == 0 {\n\t\treturn true\n\t}\n\n\tsIndex := 0\n\tfor tIndex := 0; tIndex < len(t); tIndex++ {\n\t\tif s[sIndex] == t[tIndex] {\n\t\t\tsIndex++\n\t\t}\n\n\t\tif sIndex == len(s) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n"
  },
  {
    "path": "strings/issubsequence_test.go",
    "content": "package strings_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/strings\"\n)\n\nfunc TestIsSubsequence(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname     string\n\t\ts        string\n\t\tt        string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\t\"Valid case 1 \",\n\t\t\t\"ace\",\n\t\t\t\"abcde\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Invalid case 1\",\n\t\t\t\"aec\",\n\t\t\t\"abcde\",\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"Empty strings\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"s is more then t\",\n\t\t\t\"aeccccc\",\n\t\t\t\"abcde\",\n\t\t\tfalse,\n\t\t},\n\t\t{\n\t\t\t\"s is empty\",\n\t\t\t\"\",\n\t\t\t\"abcde\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Equal strings\",\n\t\t\t\"aec\",\n\t\t\t\"aec\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Valid case 2\",\n\t\t\t\"pyr\",\n\t\t\t\"wpxqyrz\",\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"Invalid case 2\",\n\t\t\t\"prx\",\n\t\t\t\"wpxqyrz\",\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfuncResult := strings.IsSubsequence(test.s, test.t)\n\t\t\tif !reflect.DeepEqual(test.expected, funcResult) {\n\t\t\t\tt.Errorf(\"expected: %v, got %v\", test.expected, funcResult)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/kmp/kmp.go",
    "content": "package kmp\n\n// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.\nfunc Kmp(word, text string, patternTable []int) []int {\n\tif len(word) > len(text) {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\ti, j    int\n\t\tmatches []int\n\t)\n\tfor i+j < len(text) {\n\n\t\tif word[j] == text[i+j] {\n\t\t\tj++\n\t\t\tif j == len(word) {\n\t\t\t\tmatches = append(matches, i)\n\n\t\t\t\ti = i + j\n\t\t\t\tj = 0\n\t\t\t}\n\t\t} else {\n\t\t\ti = i + j - patternTable[j]\n\t\t\tif patternTable[j] > -1 {\n\t\t\t\tj = patternTable[j]\n\t\t\t} else {\n\t\t\t\tj = 0\n\t\t\t}\n\t\t}\n\t}\n\treturn matches\n}\n\n// table building for kmp algorithm.\nfunc table(w string) []int {\n\tvar (\n\t\tt []int = []int{-1}\n\t\tk int\n\t)\n\tfor j := 1; j < len(w); j++ {\n\t\tk = j - 1\n\t\tfor w[0:k] != w[j-k:j] && k > 0 {\n\t\t\tk--\n\t\t}\n\t\tt = append(t, k)\n\t}\n\treturn t\n}\n"
  },
  {
    "path": "strings/kmp/kmp_test.go",
    "content": "package kmp\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestKmp(t *testing.T) {\n\ttype args struct {\n\t\tword         string\n\t\ttext         string\n\t\tpatternTable []int\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []int\n\t}{\n\t\t{\n\t\t\tname: \"test1\",\n\t\t\targs: args{\n\t\t\t\tword:         \"ab\",\n\t\t\t\ttext:         \"ababacaab\",\n\t\t\t\tpatternTable: table(\"ababacaab\"),\n\t\t\t},\n\t\t\twant: []int{0, 2, 7},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := Kmp(tt.args.word, tt.args.text, tt.args.patternTable); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"Kmp() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTable(t *testing.T) {\n\ttype args struct {\n\t\tw string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant []int\n\t}{\n\t\t{\n\t\t\tname: \"test1\",\n\t\t\targs: args{\n\t\t\t\tw: \"ababacaab\",\n\t\t\t},\n\t\t\twant: []int{-1, 0, 0, 1, 2, 3, 0, 1, 1},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := table(tt.args.w); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"Table() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/levenshtein/levenshteindistance.go",
    "content": "/*\nThis algorithm calculates the distance between two strings.\nParameters: two strings to compare and weights of insertion, substitution and deletion.\nOutput: distance between both strings\n*/\n\npackage levenshtein\n\n// Distance Function that gives Levenshtein Distance\nfunc Distance(str1, str2 string, icost, scost, dcost int) int {\n\trow1 := make([]int, len(str2)+1)\n\trow2 := make([]int, len(str2)+1)\n\n\tfor i := 1; i <= len(str2); i++ {\n\t\trow1[i] = i * icost\n\t}\n\n\tfor i := 1; i <= len(str1); i++ {\n\t\trow2[0] = i * dcost\n\n\t\tfor j := 1; j <= len(str2); j++ {\n\t\t\tif str1[i-1] == str2[j-1] {\n\t\t\t\trow2[j] = row1[j-1]\n\t\t\t} else {\n\t\t\t\tins := row2[j-1] + icost\n\t\t\t\tdel := row1[j] + dcost\n\t\t\t\tsub := row1[j-1] + scost\n\n\t\t\t\tif ins < del && ins < sub {\n\t\t\t\t\trow2[j] = ins\n\t\t\t\t} else if del < sub {\n\t\t\t\t\trow2[j] = del\n\t\t\t\t} else {\n\t\t\t\t\trow2[j] = sub\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trow1, row2 = row2, row1\n\t}\n\n\treturn row1[len(row1)-1]\n}\n"
  },
  {
    "path": "strings/levenshtein/levenshteindistance_test.go",
    "content": "package levenshtein\n\nimport \"testing\"\n\nvar testCases = []struct {\n\tname             string\n\tstring1          string\n\tstring2          string\n\tinsertionCost    int\n\tsubstitutionCost int\n\tdeletionCost     int\n\texpected         int\n}{\n\t{\n\t\t\"strings with equal operation weights.\",\n\t\t\"stingy\",\n\t\t\"ring\",\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t3,\n\t},\n\t{\n\t\t\"strings with different operation weights.\",\n\t\t\"stingy\",\n\t\t\"ring\",\n\t\t1,\n\t\t1,\n\t\t3,\n\t\t7,\n\t},\n\t{\n\t\t\"strings with different operation weights.\",\n\t\t\"kitten\",\n\t\t\"sitting\",\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t3,\n\t},\n}\n\nfunc TestLevenshteinDistance(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Distance(tc.string1, tc.string2, tc.insertionCost, tc.substitutionCost, tc.deletionCost)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected Levenshtein distance between strings: '%s' and '%s' is %v, but got: %v\", tc.string1, tc.string2, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/manacher/longestpalindrome.go",
    "content": "// longestpalindrome.go\n// description: Manacher's algorithm (Longest palindromic substring)\n// details:\n// An algorithm with linear running time that allows you to get compressed information about all palindromic substrings of a given string. - [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_substring)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see longestpalindrome_test.go\n\npackage manacher\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/min\"\n\t\"strings\"\n)\n\nfunc makeBoundaries(s string) string {\n\tvar result strings.Builder\n\tresult.WriteRune('#')\n\tfor _, ch := range s {\n\t\tif ch != ' ' { //ignore space as palindrome character\n\t\t\tresult.WriteRune(ch)\n\t\t}\n\t\tresult.WriteRune('#')\n\t}\n\treturn result.String()\n}\n\nfunc nextBoundary(s string) string {\n\tvar result strings.Builder\n\tfor _, ch := range s {\n\t\tif ch != '#' {\n\t\t\tresult.WriteRune(ch)\n\t\t}\n\t}\n\treturn result.String()\n}\n\nfunc LongestPalindrome(s string) string {\n\tboundaries := makeBoundaries(s)\n\tb := make([]int, len(boundaries))\n\tk := 0\n\tindex := 0\n\tmaxLen := 0\n\tmaxCenterSize := 0\n\tfor i := range b {\n\t\tif i < k {\n\t\t\tb[i] = min.Int(b[2*index-i], k-i)\n\t\t} else {\n\t\t\tb[i] = 1\n\t\t}\n\t\tfor i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {\n\t\t\tb[i] += 1\n\t\t}\n\t\tif maxLen < b[i]-1 {\n\t\t\tmaxLen = b[i] - 1\n\t\t\tmaxCenterSize = i\n\t\t}\n\t\tif b[i]+i-1 > k {\n\t\t\tk = b[i] + i - 1\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen])\n}\n"
  },
  {
    "path": "strings/manacher/longestpalindrome_test.go",
    "content": "// longestpalindrome_test.go\n// description: Manacher's algorithm (Longest palindromic substring)\n// author(s) [red_byte](https://github.com/i-redbyte)\n// see longestpalindrome.go\n\npackage manacher\n\nimport \"testing\"\n\nfunc getTests() []struct {\n\ts      string\n\tresult string\n} {\n\tvar tests = []struct {\n\t\ts      string\n\t\tresult string\n\t}{\n\t\t{\"olokazakabba\", \"kazak\"},\n\t\t{\"abaacakkkkk\", \"kkkkk\"},\n\t\t{\"qqqq C++ groovy mom pooop\", \"pooop\"},\n\t\t{\"CCCPCCC @@@ hello\", \"CCCPCCC\"},\n\t\t{\"goog gogogogogog -go- gogogogo \", \"gogogogogog\"},\n\t}\n\treturn tests\n}\n\nfunc TestLongestPalindrome(t *testing.T) {\n\ttests := getTests()\n\tfor _, tv := range tests {\n\t\tt.Run(tv.s, func(t *testing.T) {\n\t\t\tresult := LongestPalindrome(tv.s)\n\t\t\tt.Log(tv.s, \" \", result)\n\t\t\tif result != tv.result {\n\t\t\t\tt.Errorf(\"Wrong result! Expected:%s, returned:%s \", tv.result, result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/palindrome/ispalindrome.go",
    "content": "// ispalindrome.go\n// description: Checks if a given string is palindrome or not\n// details:\n// Palindromes are expressions that read the same way forwards and backwards.\n// They can be words/phrases (like \"racecar\" and \"Do geese see God?\"), or even\n// numbers (like \"02/02/2020\"). Usually punctuation signs, capitalization\n// and spaces are ignored. A regular expression was used to achieve that.\n// See more information on: https://en.wikipedia.org/wiki/Palindrome\n// author(s) [Fernanda Kawasaki](https://github.com/fernandakawasaki)\n// see ispalindrome_test.go\n\npackage palindrome\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc cleanString(text string) string {\n\tclean_text := strings.ToLower(text)\n\tclean_text = strings.Join(strings.Fields(clean_text), \"\") // Remove spaces\n\tregex, _ := regexp.Compile(`[^\\p{L}\\p{N} ]+`)             // Regular expression for alphanumeric only characters\n\treturn regex.ReplaceAllString(clean_text, \"\")\n}\n\nfunc IsPalindrome(text string) bool {\n\tclean_text := cleanString(text)\n\tvar i, j int\n\trune := []rune(clean_text)\n\tfor i = 0; i < len(rune)/2; i++ {\n\t\tj = len(rune) - 1 - i\n\t\tif string(rune[i]) != string(rune[j]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc IsPalindromeRecursive(text string) bool {\n\tclean_text := cleanString(text)\n\trunes := []rune(clean_text)\n\treturn isPalindromeRecursiveHelper(runes, 0, int64(len(runes)))\n}\n\nfunc isPalindromeRecursiveHelper(runes []rune, start int64, end int64) bool {\n\tif start >= end {\n\t\treturn true\n\t}\n\tif runes[start] != runes[end-1] {\n\t\treturn false\n\t}\n\tstart = start + 1\n\tend = end - 1\n\treturn isPalindromeRecursiveHelper(runes, start, end)\n}\n"
  },
  {
    "path": "strings/palindrome/ispalindrome_test.go",
    "content": "package palindrome\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string // test description\n\tinput    string // user input\n\texpected bool   // expected return\n}{\n\t{\n\t\t\"non palindrome string\",\n\t\t\"According to the laws of aviation bees can't flyã\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"non palindrome string\",\n\t\t\"Alô?\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"palindrome string 1\",\n\t\t\"Do geese see God?\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"palindrome string 2\",\n\t\t\"ΝΙΨΟΝ ΑΝΟΜΗΜΑΤΑ ΜΗ ΜΟΝΑΝ ΟΨΙΝ\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"palindrome string 3\",\n\t\t\"Was it a car or a cat I saw?\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"empty string\",\n\t\t\"\",\n\t\ttrue,\n\t},\n}\n\nfunc TestIsPalindrome(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfunc_result := IsPalindrome(test.input)\n\t\t\tif test.expected != func_result {\n\t\t\t\tt.Errorf(\"Expected answer '%t' for string '%s' but answer given was %t\", test.expected, test.input, func_result)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsPalindromeRecursive(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfunc_result := IsPalindromeRecursive(test.input)\n\t\t\tif test.expected != func_result {\n\t\t\t\tt.Errorf(\"Expected answer '%t' for string '%s' but answer given was %t\", test.expected, test.input, func_result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/pangram/ispangram.go",
    "content": "// ispangram.go\n// description: Checks if a given string is pangram or not\n// details: A pangram is a sentence or expression that uses all the letters of the alphabet.\n// Reference: https://www.geeksforgeeks.org/pangram-checking/\n// Author : Kavitha J\n\npackage pangram\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc cleanString(text string) string {\n\tcleanText := strings.ToLower(text)                      // Convert to lowercase\n\tcleanText = strings.Join(strings.Fields(cleanText), \"\") // Remove spaces\n\tregex, _ := regexp.Compile(`[^\\p{L}\\p{N} ]+`)           // Regular expression for alphanumeric only characters\n\treturn regex.ReplaceAllString(cleanText, \"\")\n}\n\nfunc IsPangram(text string) bool {\n\tcleanText := cleanString(text)\n\tif len(cleanText) < 26 {\n\t\treturn false\n\t}\n\tvar data = make(map[rune]bool)\n\tfor _, i := range cleanText {\n\t\tdata[i] = true\n\t}\n\treturn len(data) == 26\n}\n"
  },
  {
    "path": "strings/pangram/ispangram_test.go",
    "content": "package pangram\n\nimport (\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string // test description\n\tinput    string // user input\n\texpected bool   // expected return\n}{\n\t{\n\t\t\"empty string\",\n\t\t\"\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"non pangram string without spaces\",\n\t\t\"abc\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"non pangram string with spaces\",\n\t\t\"Hello World\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"Pangram string 1\",\n\t\t\" Abcdefghijklmnopqrstuvwxyz\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"pangram string 2\",\n\t\t\"cdefghijklmnopqrstuvwxABC zyb\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"pangram string 3\",\n\t\t\"The Quick Brown Fox Jumps Over the Lazy Dog\",\n\t\ttrue,\n\t},\n}\n\nfunc TestIsPangram(t *testing.T) {\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tfunc_result := IsPangram(test.input)\n\t\t\tif test.expected != func_result {\n\t\t\t\tt.Errorf(\"Expected answer '%t' for string '%s' but answer given was %t\", test.expected, test.input, func_result)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/parenthesis/parenthesis.go",
    "content": "package parenthesis\n\n// Parenthesis algorithm checks if every opened parenthesis\n// is closed correctly. When parcounter is less than 0 when a closing\n// parenthesis is detected without an opening parenthesis\n// that surrounds it and parcounter will be 0 if all open\n// parenthesis are closed correctly.\nfunc Parenthesis(text string) bool {\n\tparcounter := 0\n\n\tfor _, r := range text {\n\t\tswitch r {\n\t\tcase '(':\n\t\t\tparcounter++\n\t\tcase ')':\n\t\t\tparcounter--\n\t\t}\n\t\tif parcounter < 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn parcounter == 0\n}\n"
  },
  {
    "path": "strings/parenthesis/parenthesis_test.go",
    "content": "package parenthesis\n\nimport (\n\t\"testing\"\n)\n\nvar parenthesisTestCases = []struct {\n\tname     string\n\ttext     string\n\texpected bool\n}{\n\t{\n\t\t\"simple test with one level deep\",\n\t\t\"(3*9-2)+(3/7^3)\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"three nested parenthesis with three deep level\",\n\t\t\"(-1*(5+2^(3-4)*(7.44-12)+6.66/(3.43-(1+2)))*(sqrt(3-4)))\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"one opened parenthesis without be closed\",\n\t\t\"(2*9-17)*((7+3/3)*2*(-1+4)\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"one open parenthesis for each close one but not in pairs\",\n\t\t\"(4*(39.22-7.4)/6.77))(\",\n\t\tfalse,\n\t},\n\t{\n\t\t\"6 deep level\",\n\t\t\"(5+33.2)*((8.04-6.5)*(1 - (1^(2-1.22*5.44+(4.33*7.2^(0.34*(-1.23+2)))))))\",\n\t\ttrue,\n\t},\n\t{\n\t\t\"inverted parenthesis\",\n\t\t\")()()()()(\",\n\t\tfalse,\n\t},\n}\n\nfunc TestParenthesis(t *testing.T) {\n\tfor _, tc := range parenthesisTestCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Parenthesis(tc.text)\n\t\t\tif actual != tc.expected {\n\t\t\t\tt.Errorf(\"Expected %t value from test %s with input %s\\n\", tc.expected, tc.name, tc.text)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/search/boyermoore.go",
    "content": "package search\n\n// Implementation of boyer moore string search\n// O(l) where l=len(text)\nfunc BoyerMoore(text string, pattern string) []int {\n\tvar positions []int\n\n\tl := len(text)\n\tn := len(pattern)\n\n\t// using booyer moore horspool modification\n\t// O(n) space instead of O(n**2)\n\tbcr := make(map[byte]int)\n\tfor i := 0; i < n-1; i++ {\n\t\tbcr[pattern[i]] = n - i - 1\n\t}\n\n\t// Apostolico–Giancarlo modification\n\t// allow to skip patterns that we know matches\n\t// let us do O(l) instead of O(ln)\n\tskips := make(map[int]int)\n\tfor _, s := range bcr {\n\t\ti := 0\n\t\tfor ; i < n-s; i++ {\n\t\t\tif pattern[n-1-i] != pattern[n-1-s-i] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tskips[s] = i\n\t}\n\n\tskip := 0\n\tjump := n\n\tfor i := 0; i < l-n+1; {\n\t\tskip = skips[jump]\n\t\tfor k := n - 1; k > -1; k-- {\n\t\t\tif text[i+k] != pattern[k] {\n\t\t\t\tjump, ok := bcr[text[i+k]]\n\t\t\t\tif !ok {\n\t\t\t\t\tjump = n\n\t\t\t\t}\n\t\t\t\ti += jump\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif k == n-jump {\n\t\t\t\tk -= skip\n\t\t\t}\n\t\t\tif k == 0 {\n\t\t\t\tpositions = append(positions, i)\n\t\t\t\tjump = 1\n\t\t\t\ti += jump\n\t\t\t}\n\t\t}\n\t}\n\n\treturn positions\n}\n"
  },
  {
    "path": "strings/search/naive.go",
    "content": "package search\n\n// Implementation of naive string search\n// O(n*m) where n=len(txt) and m=len(pattern)\nfunc Naive(text string, pattern string) []int {\n\tvar positions []int\n\tfor i := 0; i <= len(text)-len(pattern); i++ {\n\t\tvar match bool = true\n\t\tfor j := 0; j < len(pattern); j++ {\n\t\t\tif text[i+j] != pattern[j] {\n\t\t\t\tmatch = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t\tif match {\n\t\t\tpositions = append(positions, i)\n\t\t}\n\t}\n\treturn positions\n}\n"
  },
  {
    "path": "strings/search/patternsearch_test.go",
    "content": "package search\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar testCases = []struct {\n\tname     string\n\tinput    string\n\tpattern  string\n\texpected []int\n}{\n\t{\n\t\t\"string with multiple pattern matches\",\n\t\t\"ABAAABCDBBABCDDEBCABC\",\n\t\t\"ABC\",\n\t\t[]int{4, 10, 18},\n\t},\n\t{\n\t\t\"string with single pattern match\",\n\t\t\"ABCDEFGHIJKLMN\",\n\t\t\"CDE\",\n\t\t[]int{2},\n\t},\n\t{\n\t\t\"string with no pattern match\",\n\t\t\"ABCDEFGHIJKLMN\",\n\t\t\"XYZ\",\n\t\t[]int(nil),\n\t},\n\t{\n\t\t\"empty string\",\n\t\t\"\",\n\t\t\"XYZ\",\n\t\t[]int(nil),\n\t},\n\t{\n\t\t\"worse case 1\",\n\t\t\"AAAAAAAAAA\",\n\t\t\"AAA\",\n\t\t[]int{0, 1, 2, 3, 4, 5, 6, 7},\n\t},\n\t{\n\t\t\"worse case 2\",\n\t\t\"NANANANANANANANANA\",\n\t\t\"NANANA\",\n\t\t[]int{0, 2, 4, 6, 8, 10, 12},\n\t},\n}\n\nfunc TestNaive(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := Naive(tc.input, tc.pattern)\n\t\t\tif !reflect.DeepEqual(actual, tc.expected) {\n\t\t\t\tt.Errorf(\"Expected matches for pattern '%s' for string '%s' are: %v, but actual matches are: %v\", tc.pattern, tc.input, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestBooyerMoore(t *testing.T) {\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tactual := BoyerMoore(tc.input, tc.pattern)\n\t\t\tif !reflect.DeepEqual(actual, tc.expected) {\n\t\t\t\tt.Errorf(\"Expected matches for pattern '%s' for string '%s' are: %v, but actual matches are: %v\", tc.pattern, tc.input, tc.expected, actual)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "strings/strings_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage strings\n"
  },
  {
    "path": "structure/circularqueue/circularqueue_test.go",
    "content": "package circularqueue\n\nimport \"testing\"\n\nfunc TestCircularQueue(t *testing.T) {\n\tt.Run(\"Size Check\", func(t *testing.T) {\n\t\t_, err := NewCircularQueue[int](-3)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected error, got nil\")\n\t\t}\n\n\t\tqueue, _ := NewCircularQueue[int](5)\n\t\texpectedSize := 5\n\t\tgotSize := queue.Size()\n\t\tif gotSize != expectedSize {\n\t\t\tt.Errorf(\"Expected size: %v, got: %v\\n\", expectedSize, gotSize)\n\t\t}\n\n\t\tif err := queue.Enqueue(1); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(2); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(3); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(4); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(5); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\terr = queue.Enqueue(6)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected error, got nil\")\n\t\t}\n\n\t\texpectedSize = 5\n\t\tgotSize = queue.Size()\n\t\tif gotSize != expectedSize {\n\t\t\tt.Errorf(\"Expected size: %v, got: %v\\n\", expectedSize, gotSize)\n\t\t}\n\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\terr = queue.Enqueue(6)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected nil, got error: %v\\n\", err.Error())\n\t\t}\n\n\t\texpectedSize = 5\n\t\tgotSize = queue.Size()\n\t\tif gotSize != expectedSize {\n\t\t\tt.Errorf(\"Expected size: %v, got: %v\\n\", expectedSize, gotSize)\n\t\t}\n\t})\n\tt.Run(\"Enqueue\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[int](10)\n\n\t\tif err := queue.Enqueue(1); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(2); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(3); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected := 1\n\t\tgot, err := queue.Peek()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\t})\n\tt.Run(\"Dequeue\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[string](10)\n\n\t\tif err := queue.Enqueue(\"one\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(\"two\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(\"three\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected := \"one\"\n\t\tgot, err := queue.Dequeue()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\n\t\texpected = \"two\"\n\t\tgot, err = queue.Peek()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\t})\n\tt.Run(\"Circularity\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[int](10)\n\n\t\tif err := queue.Enqueue(1); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(2); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(3); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(4); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(5); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected := 4\n\t\tgot, err := queue.Peek()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\t})\n\tt.Run(\"IsFull\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[bool](2)\n\t\tif err := queue.Enqueue(false); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue(true); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected := true\n\t\tgot := queue.IsFull()\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected = false\n\t\tgot = queue.IsFull()\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\t})\n\tt.Run(\"IsEmpty\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[float64](2)\n\n\t\texpected := true\n\t\tgot := queue.IsEmpty()\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\n\t\tif err := queue.Enqueue(1.0); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected = false\n\t\tgot = queue.IsEmpty()\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\n\t})\n\tt.Run(\"Peak\", func(t *testing.T) {\n\t\tqueue, _ := NewCircularQueue[rune](10)\n\n\t\tif err := queue.Enqueue('a'); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue('b'); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif err := queue.Enqueue('c'); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\texpected := 'a'\n\t\tgot, err := queue.Peek()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\n\t\tif got != expected {\n\t\t\tt.Errorf(\"Expected: %v got: %v\\n\", expected, got)\n\t\t}\n\t})\n}\n\n// BenchmarkCircularQueue benchmarks the CircularQueue implementation.\nfunc BenchmarkCircularQueue(b *testing.B) {\n\tb.Run(\"Enqueue\", func(b *testing.B) {\n\t\tqueue, _ := NewCircularQueue[int](1000)\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tif err := queue.Enqueue(i); err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t}\n\t\t}\n\t})\n\n\tb.Run(\"Dequeue\", func(b *testing.B) {\n\t\tqueue, _ := NewCircularQueue[int](1000)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tif err := queue.Enqueue(i); err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t}\n\t\t}\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tif _, err := queue.Dequeue(); err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t}\n\t\t}\n\t})\n\n\tb.Run(\"Peek\", func(b *testing.B) {\n\t\tqueue, _ := NewCircularQueue[int](1000)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tif err := queue.Enqueue(i); err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t}\n\t\t}\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tif _, err := queue.Peek(); err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/circularqueue/circularqueuearray.go",
    "content": "// circularqueuearray.go\n// description: Implementation of a circular queue data structure\n// details:\n// This file contains the implementation of a circular queue data structure\n// using generics in Go. The circular queue supports basic operations such as\n// enqueue, dequeue, peek, and checks for full and empty states.\n// author(s): [Aram Ceballos](https://github.com/aramceballos)\n// ref: https://www.programiz.com/dsa/circular-queue\n// ref: https://en.wikipedia.org/wiki/Circular_buffer\n\n// Package queue provides an implementation of a circular queue data structure.\npackage circularqueue\n\n// errors package: Provides functions to create and manipulate error values\nimport (\n\t\"errors\"\n)\n\n// CircularQueue represents a circular queue data structure.\ntype CircularQueue[T any] struct {\n\titems []T\n\tfront int\n\trear  int\n\tsize  int\n}\n\n// NewCircularQueue creates a new CircularQueue with the given size.\n// Returns an error if the size is less than or equal to 0.\nfunc NewCircularQueue[T any](size int) (*CircularQueue[T], error) {\n\tif size <= 0 {\n\t\treturn nil, errors.New(\"size must be greater than 0\")\n\t}\n\treturn &CircularQueue[T]{\n\t\titems: make([]T, size),\n\t\tfront: -1,\n\t\trear:  -1,\n\t\tsize:  size,\n\t}, nil\n}\n\n// Enqueue adds an item to the rear of the queue.\n// Returns an error if the queue is full.\nfunc (cq *CircularQueue[T]) Enqueue(item T) error {\n\tif cq.IsFull() {\n\t\treturn errors.New(\"queue is full\")\n\t}\n\tif cq.IsEmpty() {\n\t\tcq.front = 0\n\t}\n\tcq.rear = (cq.rear + 1) % cq.size\n\tcq.items[cq.rear] = item\n\treturn nil\n}\n\n// Dequeue removes and returns the item from the front of the queue.\n// Returns an error if the queue is empty.\nfunc (cq *CircularQueue[T]) Dequeue() (T, error) {\n\tif cq.IsEmpty() {\n\t\tvar zeroValue T\n\t\treturn zeroValue, errors.New(\"queue is empty\")\n\t}\n\tretVal := cq.items[cq.front]\n\tif cq.front == cq.rear {\n\t\tcq.front = -1\n\t\tcq.rear = -1\n\t} else {\n\t\tcq.front = (cq.front + 1) % cq.size\n\t}\n\treturn retVal, nil\n}\n\n// IsFull checks if the queue is full.\nfunc (cq *CircularQueue[T]) IsFull() bool {\n\treturn (cq.front == 0 && cq.rear == cq.size-1) || cq.front == cq.rear+1\n}\n\n// IsEmpty checks if the queue is empty.\nfunc (cq *CircularQueue[T]) IsEmpty() bool {\n\treturn cq.front == -1 && cq.rear == -1\n}\n\n// Peek returns the item at the front of the queue without removing it.\n// Returns an error if the queue is empty.\nfunc (cq *CircularQueue[T]) Peek() (T, error) {\n\tif cq.IsEmpty() {\n\t\tvar zeroValue T\n\t\treturn zeroValue, errors.New(\"queue is empty\")\n\t}\n\n\treturn cq.items[cq.front], nil\n}\n\n// Size returns the size of the queue.\nfunc (cq *CircularQueue[T]) Size() int {\n\treturn cq.size\n}\n"
  },
  {
    "path": "structure/deque/deque.go",
    "content": "// description: Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends.\n// References:\n//\tWikipedia : https://en.wikipedia.org/wiki/Double-ended_queue\n//\tGithub: https://www.geeksforgeeks.org/deque-set-1-introduction-applications/\n// author [Sayan](https://github.com/bose-sayan)\n\n// Package deque implements a Double Ended Queue data structure.\npackage deque\n\nimport (\n\t\"errors\"\n)\n\n// ErrEmptyDequeue is a custom error for handling cases when some dequeuing operation is performed on an empty deque.\nvar ErrEmptyDequeue = errors.New(\"DoublyEnded queue is empty, so can't perform this operation\")\n\ntype DoublyEndedQueue[T any] struct {\n\tdeque []T\n}\n\n// New returns a new DoublyEndedQueue.\nfunc New[T any]() *DoublyEndedQueue[T] {\n\treturn &DoublyEndedQueue[T]{deque: make([]T, 0)}\n}\n\n// EnqueueFront adds an item at the front of Deque.\nfunc (dq *DoublyEndedQueue[T]) EnqueueFront(item T) {\n\tdq.deque = append([]T{item}, dq.deque...)\n}\n\n// EnqueueRear adds an item at the rear of Deque.\nfunc (dq *DoublyEndedQueue[T]) EnqueueRear(item T) {\n\tdq.deque = append(dq.deque, item)\n}\n\n// DequeueFront deletes an item from front of Deque and returns it.\nfunc (dq *DoublyEndedQueue[T]) DequeueFront() (T, error) {\n\tif len(dq.deque) == 0 {\n\t\tvar zeroVal T\n\t\treturn zeroVal, ErrEmptyDequeue\n\t}\n\tfrontElement := dq.deque[0]\n\tdq.deque = dq.deque[1:]\n\treturn frontElement, nil\n}\n\n// DequeueRear deletes an item from rear of Deque and returns it.\nfunc (dq *DoublyEndedQueue[T]) DequeueRear() (T, error) {\n\tif len(dq.deque) == 0 {\n\t\tvar zeroVal T\n\t\treturn zeroVal, ErrEmptyDequeue\n\t}\n\trearElement := dq.deque[len(dq.deque)-1]\n\tdq.deque = dq.deque[:len(dq.deque)-1]\n\treturn rearElement, nil\n}\n\n// Front gets the front item from queue.\nfunc (dq *DoublyEndedQueue[T]) Front() (T, error) {\n\tif (len(dq.deque)) == 0 {\n\t\tvar zeroVal T\n\t\treturn zeroVal, ErrEmptyDequeue\n\t}\n\treturn dq.deque[0], nil\n}\n\n// Rear gets the last item from queue.\nfunc (dq *DoublyEndedQueue[T]) Rear() (T, error) {\n\tif (len(dq.deque)) == 0 {\n\t\tvar zeroVal T\n\t\treturn zeroVal, ErrEmptyDequeue\n\t}\n\treturn dq.deque[len(dq.deque)-1], nil\n}\n\n// IsEmpty checks whether Deque is empty or not.\nfunc (dq *DoublyEndedQueue[T]) IsEmpty() bool {\n\treturn len(dq.deque) == 0\n}\n\n// Length gets the length of Deque.\nfunc (dq *DoublyEndedQueue[T]) Length() int {\n\treturn len(dq.deque)\n}\n"
  },
  {
    "path": "structure/deque/deque_test.go",
    "content": "//\n// This file contains unit tests for the deque package.\n// The tests cover the following scenarios:\n// - Empty deque\n// - Deque with one element\n// - Deque with multiple elements\n// The tests are parameterized with int and string types.\n// Each test case is defined with a description and a list of queries to be executed on the deque.\n// The expected results and errors are also defined for each query.\n//\n\npackage deque_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/structure/deque\"\n)\n\ntype QueryStructure[T any] struct {\n\tqueryType      string\n\tparameter      T\n\texpectedResult interface{}\n\texpectedError  error\n}\n\ntype TestCaseData[T any] struct {\n\tdescription string\n\tqueries     []QueryStructure[T]\n}\n\nfunc TestDeque(t *testing.T) {\n\n\t// Test cases with ints as params\n\ttestCasesInt := []TestCaseData[int]{\n\t\t{\n\t\t\tdescription: \"Test empty deque\",\n\t\t\tqueries: []QueryStructure[int]{\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: true,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"Front\",\n\t\t\t\t\texpectedError: deque.ErrEmptyDequeue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"Rear\",\n\t\t\t\t\texpectedError: deque.ErrEmptyDequeue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"DeQueueFront\",\n\t\t\t\t\texpectedError: deque.ErrEmptyDequeue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"DeQueueRear\",\n\t\t\t\t\texpectedError: deque.ErrEmptyDequeue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 0,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"Test deque with one element\",\n\t\t\tqueries: []QueryStructure[int]{\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     1,\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Front\",\n\t\t\t\t\texpectedResult: 1,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Rear\",\n\t\t\t\t\texpectedResult: 1,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 1,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueFront\",\n\t\t\t\t\texpectedResult: 1,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: true,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 0,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"Test deque with multiple elements\",\n\t\t\tqueries: []QueryStructure[int]{\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     1,\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     2,\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueRear\",\n\t\t\t\t\tparameter:     3,\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueRear\",\n\t\t\t\t\tparameter:     4,\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Front\",\n\t\t\t\t\texpectedResult: 2,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Rear\",\n\t\t\t\t\texpectedResult: 4,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 4,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueFront\",\n\t\t\t\t\texpectedResult: 2,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueRear\",\n\t\t\t\t\texpectedResult: 4,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 2,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Test cases with strings as params\n\ttestCasesString := []TestCaseData[string]{\n\t\t{\n\t\t\tdescription: \"Test one element deque\",\n\t\t\tqueries: []QueryStructure[string]{\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     \"a\",\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Front\",\n\t\t\t\t\texpectedResult: \"a\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Rear\",\n\t\t\t\t\texpectedResult: \"a\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 1,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueFront\",\n\t\t\t\t\texpectedResult: \"a\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: true,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 0,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"Test multiple elements deque\",\n\t\t\tqueries: []QueryStructure[string]{\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     \"a\",\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueFront\",\n\t\t\t\t\tparameter:     \"b\",\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueRear\",\n\t\t\t\t\tparameter:     \"c\",\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:     \"EnQueueRear\",\n\t\t\t\t\tparameter:     \"d\",\n\t\t\t\t\texpectedError: nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Front\",\n\t\t\t\t\texpectedResult: \"b\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Rear\",\n\t\t\t\t\texpectedResult: \"d\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 4,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueFront\",\n\t\t\t\t\texpectedResult: \"b\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"DeQueueRear\",\n\t\t\t\t\texpectedResult: \"d\",\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"IsEmpty\",\n\t\t\t\t\texpectedResult: false,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tqueryType:      \"Length\",\n\t\t\t\t\texpectedResult: 2,\n\t\t\t\t\texpectedError:  nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Run tests with ints\n\tfor _, testCase := range testCasesInt {\n\t\tt.Run(testCase.description, func(t *testing.T) {\n\t\t\tdq := deque.New[int]()\n\t\t\tfor _, query := range testCase.queries {\n\t\t\t\tswitch query.queryType {\n\t\t\t\tcase \"EnQueueFront\":\n\t\t\t\t\tdq.EnqueueFront(query.parameter)\n\t\t\t\tcase \"EnQueueRear\":\n\t\t\t\t\tdq.EnqueueRear(query.parameter)\n\t\t\t\tcase \"DeQueueFront\":\n\t\t\t\t\tresult, err := dq.DequeueFront()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"DeQueueRear\":\n\t\t\t\t\tresult, err := dq.DequeueRear()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"Front\":\n\t\t\t\t\tresult, err := dq.Front()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v, %v\", query.expectedResult, result, testCase.description)\n\t\t\t\t\t}\n\t\t\t\tcase \"Rear\":\n\t\t\t\t\tresult, err := dq.Rear()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"IsEmpty\":\n\t\t\t\t\tresult := dq.IsEmpty()\n\t\t\t\t\tif result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"Length\":\n\t\t\t\t\tresult := dq.Length()\n\t\t\t\t\tif result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\t// Run tests with strings\n\tfor _, testCase := range testCasesString {\n\t\tt.Run(testCase.description, func(t *testing.T) {\n\t\t\tdq := deque.New[string]()\n\t\t\tfor _, query := range testCase.queries {\n\t\t\t\tswitch query.queryType {\n\t\t\t\tcase \"EnQueueFront\":\n\t\t\t\t\tdq.EnqueueFront(query.parameter)\n\t\t\t\tcase \"EnQueueRear\":\n\t\t\t\t\tdq.EnqueueRear(query.parameter)\n\t\t\t\tcase \"DeQueueFront\":\n\t\t\t\t\tresult, err := dq.DequeueFront()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"DeQueueRear\":\n\t\t\t\t\tresult, err := dq.DequeueRear()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"Front\":\n\t\t\t\t\tresult, err := dq.Front()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v, %v\", query.expectedResult, result, testCase.description)\n\t\t\t\t\t}\n\t\t\t\tcase \"Rear\":\n\t\t\t\t\tresult, err := dq.Rear()\n\t\t\t\t\tif err != query.expectedError {\n\t\t\t\t\t\tt.Errorf(\"Expected error: %v, got : %v\", query.expectedError, err)\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil && result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"IsEmpty\":\n\t\t\t\t\tresult := dq.IsEmpty()\n\t\t\t\t\tif result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v, got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\tcase \"Length\":\n\t\t\t\t\tresult := dq.Length()\n\t\t\t\t\tif result != query.expectedResult {\n\t\t\t\t\t\tt.Errorf(\"Expected %v got %v\", query.expectedResult, result)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "structure/doc.go",
    "content": "// Package structure is a subpackage that is dedicated to\n// different implementations of data structures in the\n// domain of computer science.\npackage structure\n"
  },
  {
    "path": "structure/dynamicarray/dynamicarray.go",
    "content": "// Package dynamicarray\n// A dynamic array is quite similar to a regular array, but its Size is modifiable during program runtime,\n// very similar to how a slice in Go works. The implementation is for educational purposes and explains\n// how one might go about implementing their own version of slices.\n//\n// For more details check out those links below here:\n// GeeksForGeeks article : https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/\n// Go blog: https://blog.golang.org/slices-intro\n// Go blog: https://blog.golang.org/slices\n// authors [Wesllhey Holanda](https://github.com/wesllhey), [Milad](https://github.com/miraddo)\n// see dynamicarray.go, dynamicarray_test.go\npackage dynamicarray\n\nimport (\n\t\"errors\"\n)\n\nvar defaultCapacity = 10\n\n// DynamicArray structure\ntype DynamicArray struct {\n\tSize        int\n\tCapacity    int\n\tElementData []any\n}\n\n// Put function is change/update the value in array with the index and new value\nfunc (da *DynamicArray) Put(index int, element any) error {\n\terr := da.CheckRangeFromIndex(index)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tda.ElementData[index] = element\n\n\treturn nil\n}\n\n// Add function is add new element to our array\nfunc (da *DynamicArray) Add(element any) {\n\tif da.Size == da.Capacity {\n\t\tda.NewCapacity()\n\t}\n\n\tda.ElementData[da.Size] = element\n\tda.Size++\n}\n\n// Remove function is remove an element with the index\nfunc (da *DynamicArray) Remove(index int) error {\n\terr := da.CheckRangeFromIndex(index)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcopy(da.ElementData[index:], da.ElementData[index+1:da.Size])\n\tda.ElementData[da.Size-1] = nil\n\n\tda.Size--\n\n\treturn nil\n}\n\n// Get function is return one element with the index of array\nfunc (da *DynamicArray) Get(index int) (any, error) {\n\terr := da.CheckRangeFromIndex(index)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn da.ElementData[index], nil\n}\n\n// IsEmpty function is check that the array has value or not\nfunc (da *DynamicArray) IsEmpty() bool {\n\treturn da.Size == 0\n}\n\n// GetData function return all value of array\nfunc (da *DynamicArray) GetData() []any {\n\treturn da.ElementData[:da.Size]\n}\n\n// CheckRangeFromIndex function it will check the range from the index\nfunc (da *DynamicArray) CheckRangeFromIndex(index int) error {\n\tif index >= da.Size || index < 0 {\n\t\treturn errors.New(\"index out of range\")\n\t}\n\treturn nil\n}\n\n// NewCapacity function increase the Capacity\nfunc (da *DynamicArray) NewCapacity() {\n\tif da.Capacity == 0 {\n\t\tda.Capacity = defaultCapacity\n\t} else {\n\t\tda.Capacity = da.Capacity << 1\n\t}\n\n\tnewDataElement := make([]any, da.Capacity)\n\n\tcopy(newDataElement, da.ElementData)\n\n\tda.ElementData = newDataElement\n}\n"
  },
  {
    "path": "structure/dynamicarray/dynamicarray_test.go",
    "content": "package dynamicarray\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDynamicArray(t *testing.T) {\n\tnumbers := DynamicArray{}\n\n\t// check numbers is empty or nut\n\tt.Run(\"Check Empty Dynamic Array\", func(t *testing.T) {\n\t\tif numbers.IsEmpty() != true {\n\t\t\tt.Errorf(\"Expected be true but got %v\", numbers.IsEmpty())\n\t\t}\n\t})\n\n\tnumbers.Add(10)\n\tnumbers.Add(20)\n\tnumbers.Add(30)\n\tnumbers.Add(40)\n\tnumbers.Add(50)\n\n\t// check numbers added to our dynamic array\n\tt.Run(\"Add Element into Dynamic Array\", func(t *testing.T) {\n\t\tif numbers.IsEmpty() != false {\n\t\t\tt.Errorf(\"Expected be false but got %v\", numbers.IsEmpty())\n\t\t}\n\t\tvar res []any\n\t\tres = append(res, 10)\n\t\tres = append(res, 20)\n\t\tres = append(res, 30)\n\t\tres = append(res, 40)\n\t\tres = append(res, 50)\n\n\t\tif !reflect.DeepEqual(numbers.GetData(), res) {\n\t\t\tt.Errorf(\"Expected be [10, 20, 30, 40, 50] but got %v\", numbers.GetData())\n\t\t}\n\t})\n\n\t// Remove an Element inside the dynamic array with the index of array\n\tt.Run(\"Remove in Dynamic Array\", func(t *testing.T) {\n\t\tif numbers.IsEmpty() != false {\n\t\t\tt.Errorf(\"Expected be false but got %v\", numbers.IsEmpty())\n\t\t}\n\t\tvar res []any\n\t\tres = append(res, 10)\n\t\tres = append(res, 30)\n\t\tres = append(res, 40)\n\t\tres = append(res, 50)\n\n\t\t// remove the element by the index\n\t\terr := numbers.Remove(1)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected be [10, 30, 40, 50] but got an Error %v\", err)\n\t\t}\n\n\t\tif !reflect.DeepEqual(numbers.GetData(), res) {\n\t\t\tt.Errorf(\"Expected be [10, 30, 40, 50] but got %v\", numbers.GetData())\n\t\t}\n\t})\n\n\t// get one element by the index of the dynamic array\n\tt.Run(\"Get in Dynamic Array\", func(t *testing.T) {\n\t\tif numbers.IsEmpty() != false {\n\t\t\tt.Errorf(\"Expected be false but got %v\", numbers.IsEmpty())\n\t\t}\n\n\t\t// return one element with the index\n\t\tgetOne, _ := numbers.Get(2)\n\n\t\tif getOne != 40 {\n\t\t\tt.Errorf(\"Expected be 40 but got %v\", getOne)\n\t\t}\n\n\t})\n\n\t// Put to add a value to specific index of Dynamic Array\n\tt.Run(\"Put to Dynamic Array\", func(t *testing.T) {\n\t\tif numbers.IsEmpty() != false {\n\t\t\tt.Errorf(\"Expected be false but got %v\", numbers.IsEmpty())\n\t\t}\n\n\t\t// change value of specific index\n\t\terr := numbers.Put(0, 100)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected be [10, 30, 40, 50] but got an Error %v\", err)\n\t\t}\n\n\t\tgetOne, _ := numbers.Get(0)\n\t\tif getOne != 100 {\n\t\t\tt.Errorf(\"Expected be 100 but got %v\", getOne)\n\t\t}\n\t})\n\n}\n"
  },
  {
    "path": "structure/fenwicktree/fenwicktree.go",
    "content": "// Fenwick Tree Data Structure for efficient range queries on an array of integers.\n// Also known as Binary Indexed Tree. It can query the sum of any range of the array and\n// can update the array at a specific position by adding a value to it (point update).\n// Build: O(N)\n// Query: O(log(N))\n// Update: O(log(N))\n// reference: https://brilliant.org/wiki/fenwick-tree/\npackage fenwicktree\n\n// FenwickTree represents the data structure of the Fenwick Tree\ntype FenwickTree struct {\n\tn     int   // n: Size of the input array.\n\tarray []int // array: the input array on which queries are made.\n\tbit   []int // bit: store the sum of ranges.\n}\n\n// NewFenwickTree creates a new Fenwick tree, initializes bit with\n// the values of the array. Note that the queries and updates should have\n// one based indexing.\nfunc NewFenwickTree(array []int) *FenwickTree {\n\tnewArray := []int{0} // Appending a 0 to the beginning as this implementation uses 1 based indexing\n\tfenwickTree := &FenwickTree{\n\t\tn:     len(array),\n\t\tarray: append(newArray, array...),\n\t\tbit:   append(newArray, array...),\n\t}\n\tfor i := 1; i < fenwickTree.n; i++ {\n\t\tnextPos := i + (i & -i)\n\t\tif nextPos <= fenwickTree.n {\n\t\t\tfenwickTree.bit[nextPos] += fenwickTree.bit[i]\n\t\t}\n\t}\n\treturn fenwickTree\n}\n\n// PrefixSum returns the sum of the prefix ending at position pos.\nfunc (f *FenwickTree) PrefixSum(pos int) int {\n\tif pos > f.n {\n\t\treturn 0\n\t}\n\tprefixSum := 0\n\tfor i := pos; i > 0; i -= (i & -i) {\n\t\tprefixSum += f.bit[i]\n\t}\n\treturn prefixSum\n}\n\n// RangeSum returns the sum of the elements in the range l to r\n// both inclusive.\nfunc (f *FenwickTree) RangeSum(l int, r int) int {\n\treturn f.PrefixSum(r) - f.PrefixSum(l-1)\n}\n\n// Add Adds value to the element at position pos of the array\n// and recomputes the range sums.\nfunc (f *FenwickTree) Add(pos int, value int) {\n\tfor i := pos; i <= f.n; i += (i & -i) {\n\t\tf.bit[i] += value\n\t}\n}\n"
  },
  {
    "path": "structure/fenwicktree/fenwicktree_test.go",
    "content": "package fenwicktree_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/structure/fenwicktree\"\n\t\"testing\"\n)\n\ntype query struct {\n\tqueryType  string\n\tfirstIndex int // firstIndex and lastIndex are same for point queries\n\tlastIndex  int\n}\n\ntype update struct {\n\tpos   int\n\tvalue int\n}\n\nfunc TestFenwickTree(t *testing.T) {\n\tvar fenwickTreeTestData = []struct {\n\t\tdescription string\n\t\tarray       []int\n\t\tupdates     []update\n\t\tqueries     []query\n\t\texpected    []int\n\t}{\n\t\t{\n\t\t\tdescription: \"test empty array\",\n\t\t\tarray:       []int{},\n\t\t\tqueries:     []query{{\"point\", 1, 1}},\n\t\t\texpected:    []int{0},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tqueries:     []query{{\"range\", 1, 5}, {\"range\", 1, 3}, {\"range\", 3, 5}},\n\t\t\texpected:    []int{15, 6, 12},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5, single index updates and range queries\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates:     []update{{pos: 2, value: 2}, {pos: 3, value: 3}},\n\t\t\tqueries:     []query{{\"range\", 1, 5}, {\"range\", 1, 3}, {\"range\", 3, 5}},\n\t\t\texpected:    []int{20, 11, 15},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5, single index updates and point queries\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates:     []update{{pos: 2, value: 2}, {pos: 3, value: 3}},\n\t\t\tqueries:     []query{{\"point\", 3, 3}, {\"point\", 1, 1}, {\"point\", 5, 5}},\n\t\t\texpected:    []int{11, 1, 20},\n\t\t},\n\t}\n\n\tfor _, test := range fenwickTreeTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tfenwickTree := fenwicktree.NewFenwickTree(test.array)\n\n\t\t\tfor i := 0; i < len(test.updates); i++ {\n\t\t\t\tfenwickTree.Add(test.updates[i].pos, test.updates[i].value)\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(test.queries); i++ {\n\n\t\t\t\tvar result int\n\n\t\t\t\tif test.queries[i].queryType == \"point\" {\n\t\t\t\t\tresult = fenwickTree.PrefixSum(test.queries[i].firstIndex)\n\t\t\t\t} else {\n\t\t\t\t\tresult = fenwickTree.RangeSum(test.queries[i].firstIndex, test.queries[i].lastIndex)\n\t\t\t\t}\n\n\t\t\t\tif result != test.expected[i] {\n\t\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\t\tt.Fatalf(\"Expected result: %d\\nFound: %d\\n\", test.expected[i], result)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n}\n"
  },
  {
    "path": "structure/hashmap/hashmap.go",
    "content": "package hashmap\n\nimport (\n\t\"fmt\"\n\t\"hash/fnv\"\n)\n\nvar defaultCapacity uint64 = 1 << 10\n\ntype node struct {\n\tkey   any\n\tvalue any\n\tnext  *node\n}\n\n// HashMap is a Golang implementation of a hashmap\ntype HashMap struct {\n\tcapacity uint64\n\tsize     uint64\n\ttable    []*node\n}\n\n// DefaultNew returns a new HashMap instance with default values\nfunc DefaultNew() *HashMap {\n\treturn &HashMap{\n\t\tcapacity: defaultCapacity,\n\t\ttable:    make([]*node, defaultCapacity),\n\t}\n}\n\n// New creates a new HashMap instance with the specified size and capacity\nfunc New(size, capacity uint64) *HashMap {\n\treturn &HashMap{\n\t\tsize:     size,\n\t\tcapacity: capacity,\n\t\ttable:    make([]*node, capacity),\n\t}\n}\n\n// Get returns the value associated with the given key\nfunc (hm *HashMap) Get(key any) any {\n\tnode := hm.getNodeByKey(key)\n\tif node != nil {\n\t\treturn node.value\n\t}\n\treturn nil\n}\n\n// Put inserts a new key-value pair into the hashmap\nfunc (hm *HashMap) Put(key, value any) {\n\tindex := hm.hash(key)\n\tif hm.table[index] == nil {\n\t\thm.table[index] = &node{key: key, value: value}\n\t} else {\n\t\tcurrent := hm.table[index]\n\t\tfor {\n\t\t\tif current.key == key {\n\t\t\t\tcurrent.value = value\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif current.next == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrent = current.next\n\t\t}\n\t\tcurrent.next = &node{key: key, value: value}\n\t}\n\thm.size++\n\tif float64(hm.size)/float64(hm.capacity) > 0.75 {\n\t\thm.resize()\n\t}\n}\n\n// Contains checks if the given key is stored in the hashmap\nfunc (hm *HashMap) Contains(key any) bool {\n\treturn hm.getNodeByKey(key) != nil\n}\n\n// getNodeByKey finds the node associated with the given key\nfunc (hm *HashMap) getNodeByKey(key any) *node {\n\tindex := hm.hash(key)\n\tcurrent := hm.table[index]\n\tfor current != nil {\n\t\tif current.key == key {\n\t\t\treturn current\n\t\t}\n\t\tcurrent = current.next\n\t}\n\treturn nil\n}\n\n// resize doubles the capacity of the hashmap and rehashes all existing entries\nfunc (hm *HashMap) resize() {\n\toldTable := hm.table\n\thm.capacity <<= 1\n\thm.table = make([]*node, hm.capacity)\n\thm.size = 0\n\n\tfor _, head := range oldTable {\n\t\tfor current := head; current != nil; current = current.next {\n\t\t\thm.Put(current.key, current.value)\n\t\t}\n\t}\n}\n\n// hash generates a hash value for the given key\nfunc (hm *HashMap) hash(key any) uint64 {\n\th := fnv.New64a()\n\t_, _ = h.Write([]byte(fmt.Sprintf(\"%v\", key)))\n\thashValue := h.Sum64()\n\treturn (hm.capacity - 1) & (hashValue ^ (hashValue >> 16))\n}\n"
  },
  {
    "path": "structure/hashmap/hashmap_test.go",
    "content": "package hashmap_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TheAlgorithms/Go/structure/hashmap\"\n)\n\nfunc TestHashMap(t *testing.T) {\n\tmp := hashmap.DefaultNew()\n\n\tt.Run(\"Test 1: Put(10) and checking if Get() is correct\", func(t *testing.T) {\n\t\tmp.Put(\"test\", 10)\n\t\tgot := mp.Get(\"test\")\n\t\tif got != 10 {\n\t\t\tt.Errorf(\"Put: %v, Got: %v\", 10, got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 2: Reassiging the value and checking if its correct\", func(t *testing.T) {\n\t\tmp.Put(\"test\", 20)\n\t\tgot := mp.Get(\"test\")\n\t\tif got != 20 {\n\t\t\tt.Errorf(\"Put (reassign): %v, Got: %v\", 20, got)\n\t\t}\n\t})\n\n\tt.Run(\"Test 3: Adding new key when there is already some data\", func(t *testing.T) {\n\t\tmp.Put(\"test2\", 30)\n\t\tgot := mp.Get(\"test2\")\n\t\tif got != 30 {\n\t\t\tt.Errorf(\"Put: %v, Got: %v\", got, 30)\n\t\t}\n\t})\n\n\tt.Run(\"Test 4: Adding numeric key\", func(t *testing.T) {\n\t\tmp.Put(1, 40)\n\t\tgot := mp.Get(1)\n\t\tif got != 40 {\n\t\t\tt.Errorf(\"Put: %v, Got: %v\", got, 40)\n\t\t}\n\t})\n\n\tt.Run(\"Test 5: Checking the Contains function\", func(t *testing.T) {\n\t\twant := true\n\t\tgot := mp.Contains(1)\n\t\tif want != got {\n\t\t\tt.Errorf(\"Key '1' exists but couldn't be retrieved\")\n\t\t}\n\t})\n\n\tt.Run(\"Test 6: Checking if the key that does not exist returns false\", func(t *testing.T) {\n\t\twant := false\n\t\tgot := mp.Contains(2)\n\t\tif got != want {\n\t\t\tt.Errorf(\"Key '2' does not exist in the map but it says otherwise\")\n\t\t}\n\t})\n\n\tt.Run(\"Test 7: Checking if the key does not exist Get func returns nil\", func(t *testing.T) {\n\t\twant := any(nil)\n\t\tgot := mp.Get(2)\n\t\tif got != want {\n\t\t\tt.Errorf(\"Key '2' does not exists in the map but it says otherwise\")\n\t\t}\n\t})\n\n\tt.Run(\"Test 8: Resizing a map\", func(t *testing.T) {\n\t\tmp := hashmap.New(4, 4)\n\n\t\tfor i := 0; i < 20; i++ {\n\t\t\tmp.Put(i, 40)\n\t\t}\n\n\t\tgot := mp.Get(5)\n\t\tif got != 40 {\n\t\t\tt.Errorf(\"Put: %v, Got: %v\", got, 40)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/heap/heap.go",
    "content": "package heap\n\nimport (\n\t\"errors\"\n\t\"github.com/TheAlgorithms/Go/constraints\"\n)\n\n// Heap heap implementation using generic.\ntype Heap[T any] struct {\n\theaps    []T\n\tlessFunc func(a, b T) bool\n}\n\n// New gives a new heap object.\nfunc New[T constraints.Ordered]() *Heap[T] {\n\tless := func(a, b T) bool {\n\t\treturn a < b\n\t}\n\th, _ := NewAny[T](less)\n\treturn h\n}\n\n// NewAny gives a new heap object. element can be anything, but must provide less function.\nfunc NewAny[T any](less func(a, b T) bool) (*Heap[T], error) {\n\tif less == nil {\n\t\treturn nil, errors.New(\"less func is necessary\")\n\t}\n\treturn &Heap[T]{\n\t\tlessFunc: less,\n\t}, nil\n}\n\n// Push pushes the element t onto the heap.\n// The complexity is O(log n) where n = h.Len().\nfunc (h *Heap[T]) Push(t T) {\n\th.heaps = append(h.heaps, t)\n\th.up(len(h.heaps) - 1)\n}\n\n// Top returns the minimum element (according to Less) from the heap.\n// Top panics if the heap is empty.\nfunc (h *Heap[T]) Top() T {\n\treturn h.heaps[0]\n}\n\n// Pop removes the minimum element (according to Less) from the heap.\n// The complexity is O(log n) where n = h.Len().\nfunc (h *Heap[T]) Pop() {\n\tif len(h.heaps) <= 1 {\n\t\th.heaps = nil\n\t\treturn\n\t}\n\th.swap(0, len(h.heaps)-1)\n\th.heaps = h.heaps[:len(h.heaps)-1]\n\th.down(0)\n}\n\n// Empty returns the heap is empty or not.\nfunc (h *Heap[T]) Empty() bool {\n\treturn len(h.heaps) == 0\n}\n\n// Size returns the size of the heap\nfunc (h *Heap[T]) Size() int {\n\treturn len(h.heaps)\n}\n\nfunc (h *Heap[T]) swap(i, j int) {\n\th.heaps[i], h.heaps[j] = h.heaps[j], h.heaps[i]\n}\n\nfunc (h *Heap[T]) up(child int) {\n\tif child <= 0 {\n\t\treturn\n\t}\n\tparent := (child - 1) >> 1\n\tif !h.lessFunc(h.heaps[child], h.heaps[parent]) {\n\t\treturn\n\t}\n\th.swap(child, parent)\n\th.up(parent)\n}\n\nfunc (h *Heap[T]) down(parent int) {\n\tlessIdx := parent\n\tlChild, rChild := (parent<<1)+1, (parent<<1)+2\n\tif lChild < len(h.heaps) && h.lessFunc(h.heaps[lChild], h.heaps[lessIdx]) {\n\t\tlessIdx = lChild\n\t}\n\tif rChild < len(h.heaps) && h.lessFunc(h.heaps[rChild], h.heaps[lessIdx]) {\n\t\tlessIdx = rChild\n\t}\n\tif lessIdx == parent {\n\t\treturn\n\t}\n\th.swap(lessIdx, parent)\n\th.down(lessIdx)\n}\n"
  },
  {
    "path": "structure/heap/heap_test.go",
    "content": "package heap_test\n\nimport (\n\t\"github.com/TheAlgorithms/Go/structure/heap\"\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype testInt int\n\nfunc (u testInt) Less(o testInt) bool {\n\treturn u < o\n}\n\ntype testStudent struct {\n\tName  string\n\tScore int64\n}\n\nfunc (u testStudent) Less(o testStudent) bool {\n\tif u.Score == o.Score {\n\t\treturn u.Name < o.Name\n\t}\n\treturn u.Score > o.Score\n}\n\nfunc TestHeap_Empty(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant bool\n\t}{\n\t\t{name: \"empty\", want: true},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\th := heap.New[testInt]()\n\t\t\tif got := h.Empty(); got != tt.want {\n\t\t\t\tt.Errorf(\"Empty() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype testOpType int\n\nconst (\n\ttestPush  = 1\n\ttestPop   = 2\n\ttestTop   = 3\n\ttestEmpty = 4\n)\n\ntype testOp[T any] struct {\n\ttyp     testOpType\n\tx       T\n\tisEmpty bool\n}\n\ntype testStruct[T any] struct {\n\tname string\n\tops  []testOp[T]\n}\n\nfunc TestHeapExample1(t *testing.T) {\n\ttests1 := []testStruct[testInt]{\n\t\t{\n\t\t\tname: \"example 1\",\n\t\t\tops: []testOp[testInt]{\n\t\t\t\t{typ: testEmpty, isEmpty: true},\n\t\t\t\t{typ: testPush, x: 10},\n\t\t\t\t{typ: testEmpty, isEmpty: false},\n\t\t\t\t{typ: testTop, x: 10},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testEmpty, isEmpty: true},\n\t\t\t\t{typ: testPush, x: 9},\n\t\t\t\t{typ: testPush, x: 8},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testPush, x: 3},\n\t\t\t\t{typ: testTop, x: 3},\n\t\t\t\t{typ: testPush, x: 2},\n\t\t\t\t{typ: testTop, x: 2},\n\t\t\t\t{typ: testPush, x: 4},\n\t\t\t\t{typ: testPush, x: 6},\n\t\t\t\t{typ: testPush, x: 5},\n\t\t\t\t{typ: testTop, x: 2},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testTop, x: 3},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testTop, x: 5},\n\t\t\t\t{typ: testEmpty, isEmpty: false},\n\t\t\t},\n\t\t},\n\t}\n\ttestFunc(t, tests1, testInt.Less)\n}\n\nfunc TestHeapExample2(t *testing.T) {\n\ttests1 := []testStruct[testStudent]{\n\t\t{\n\t\t\tname: \"example 2\",\n\t\t\tops: []testOp[testStudent]{\n\t\t\t\t{typ: testPush, x: testStudent{Name: \"Alan\", Score: 87}},\n\t\t\t\t{typ: testPush, x: testStudent{Name: \"Bob\", Score: 98}},\n\t\t\t\t{typ: testTop, x: testStudent{Name: \"Bob\", Score: 98}},\n\t\t\t\t{typ: testPop},\n\t\t\t\t{typ: testPush, x: testStudent{Name: \"Carl\", Score: 70}},\n\t\t\t\t{typ: testTop, x: testStudent{Name: \"Alan\", Score: 87}},\n\t\t\t},\n\t\t},\n\t}\n\ttestFunc(t, tests1, testStudent.Less)\n}\n\nfunc testFunc[T any](t *testing.T, tests []testStruct[T], less func(a, b T) bool) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\th, err := heap.NewAny[T](less)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"New Heap err %v\", err)\n\t\t\t}\n\t\t\tfor i, op := range tt.ops {\n\t\t\t\tswitch op.typ {\n\t\t\t\tcase testPush:\n\t\t\t\t\toldSize := h.Size()\n\t\t\t\t\th.Push(op.x)\n\t\t\t\t\tnewSize := h.Size()\n\t\t\t\t\tif oldSize+1 != newSize {\n\t\t\t\t\t\tt.Errorf(\"op %d testPush %v failed\", i, op.x)\n\t\t\t\t\t}\n\t\t\t\tcase testPop:\n\t\t\t\t\toldSize := h.Size()\n\t\t\t\t\th.Pop()\n\t\t\t\t\tnewSize := h.Size()\n\t\t\t\t\tif oldSize-1 != newSize {\n\t\t\t\t\t\tt.Errorf(\"op %d testPop %v failed\", i, op.x)\n\t\t\t\t\t}\n\t\t\t\tcase testTop:\n\t\t\t\t\tif got := h.Top(); !reflect.DeepEqual(got, op.x) {\n\t\t\t\t\t\tt.Errorf(\"op %d testTop %v, want %v\", i, got, op.x)\n\t\t\t\t\t}\n\t\t\t\tcase testEmpty:\n\t\t\t\t\tif got := h.Empty(); got != op.isEmpty {\n\t\t\t\t\t\tt.Errorf(\"op %d Empty() = %v, want %v\", i, got, op.isEmpty)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "structure/linkedlist/Readme.md",
    "content": "# Linked List\n***\n## What is it?\n***\n[Linked list](https://www.scaler.com/topics/linked-list/) is a data structure that is a linear chain of data elements whose order is not given by their phyisical placement in memory. This structure is built up of nodes which point to the element ahead or behind this particular node (depending on the type of Linked List).\n\n# Types of Linked List implemented within this repository\n\n## Singly Linked List\nSingly Linked List is a linked list in which a node only points to the next element.\nSome of the main applications of Singly Linked List are in the construction\nof fundamental data structures such as Stacks and Queues.\n\n## Doubly Linked List\nDoubly Linked List is a linked list in which a node points to both the element ahead and behind the node.\nAny application which requires us to keep track of forward and backward information uses doubly linked list.\nFor example, the feature of undo and redo are implemented using these doubly linked lists.\n\n## Cyclic Linked List AKA Looped Linked List\nLooped Linked Lists are singly or doubly-linked that chase their own tail:\nA points to B, B points to C, C points to D, and D points to A. \nThey are better suited for cyclic data such as train schedules.\nThese lists are missing the first and last items.\nTherefore, it is necessary to introduce the concept of the current position.\n\nThis picture shows similar lists:\n![Alt text](./Linked_Cyclic_List.jpg?raw=true)\n"
  },
  {
    "path": "structure/linkedlist/cyclic.go",
    "content": "package linkedlist\n\nimport \"fmt\"\n\n// Cyclic Struct which cycles the linked list in this implementation.\ntype Cyclic[T any] struct {\n\tSize int\n\tHead *Node[T]\n}\n\n// Create new list.\nfunc NewCyclic[T any]() *Cyclic[T] {\n\treturn &Cyclic[T]{}\n}\n\n// Inserting the first node is a special case. It will\n// point to itself. For other cases, the node will be added\n// to the end of the list. End of the list is Prev field of\n// current item. Complexity O(1).\nfunc (cl *Cyclic[T]) Add(val T) {\n\tn := NewNode(val)\n\tcl.Size++\n\tif cl.Head == nil {\n\t\tn.Prev = n\n\t\tn.Next = n\n\t\tcl.Head = n\n\t} else {\n\t\tn.Prev = cl.Head.Prev\n\t\tn.Next = cl.Head\n\t\tcl.Head.Prev.Next = n\n\t\tcl.Head.Prev = n\n\t}\n}\n\n// Rotate list by P places.\n// This method is interesting for optimization.\n// For first optimization we must decrease\n// P value so that it ranges from 0 to N-1.\n// For this we need to use the operation of\n// division modulo. But be careful if P is less than 0.\n// if it is - make it positive. This can be done without\n// violating the meaning of the number by adding to it\n// a multiple of N. Now you can decrease P modulo N to\n// rotate the list by the minimum number of places.\n// We use the fact that moving forward in a circle by P\n// places is the same as moving N - P places back.\n// Therefore, if P > N / 2, you can turn the list by N-P places back.\n// Complexity O(n).\nfunc (cl *Cyclic[T]) Rotate(places int) {\n\tif cl.Size > 0 {\n\t\tif places < 0 {\n\t\t\tmultiple := cl.Size - 1 - places/cl.Size\n\t\t\tplaces += multiple * cl.Size\n\t\t}\n\t\tplaces %= cl.Size\n\n\t\tif places > cl.Size/2 {\n\t\t\tplaces = cl.Size - places\n\t\t\tfor i := 0; i < places; i++ {\n\t\t\t\tcl.Head = cl.Head.Prev\n\t\t\t}\n\t\t} else if places == 0 {\n\t\t\treturn\n\t\t} else {\n\t\t\tfor i := 0; i < places; i++ {\n\t\t\t\tcl.Head = cl.Head.Next\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n// Delete the current item.\nfunc (cl *Cyclic[T]) Delete() bool {\n\tvar deleted bool\n\tvar prevItem, thisItem, nextItem *Node[T]\n\n\tif cl.Size == 0 {\n\t\treturn deleted\n\t}\n\n\tdeleted = true\n\tthisItem = cl.Head\n\tnextItem = thisItem.Next\n\tprevItem = thisItem.Prev\n\n\tif cl.Size == 1 {\n\t\tcl.Head = nil\n\t} else {\n\t\tcl.Head = nextItem\n\t\tnextItem.Prev = prevItem\n\t\tprevItem.Next = nextItem\n\t}\n\tcl.Size--\n\n\treturn deleted\n}\n\n// Destroy all items in the list.\nfunc (cl *Cyclic[T]) Destroy() {\n\tfor cl.Delete() {\n\t\tcontinue\n\t}\n}\n\n// Show list body.\nfunc (cl *Cyclic[T]) Walk() *Node[T] {\n\tvar start *Node[T]\n\tstart = cl.Head\n\n\tfor i := 0; i < cl.Size; i++ {\n\t\tfmt.Printf(\"%v \\n\", start.Val)\n\t\tstart = start.Next\n\t}\n\treturn start\n}\n\n// https://en.wikipedia.org/wiki/Josephus_problem\n// This is a struct-based solution for Josephus problem.\nfunc JosephusProblem(cl *Cyclic[int], k int) int {\n\tfor cl.Size > 1 {\n\t\tcl.Rotate(k)\n\t\tcl.Delete()\n\t\tcl.Rotate(-1)\n\t}\n\tretval := cl.Head.Val\n\tcl.Destroy()\n\treturn retval\n}\n"
  },
  {
    "path": "structure/linkedlist/cyclic_test.go",
    "content": "package linkedlist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc fillList(list *Cyclic[int], n int) {\n\tfor i := 1; i <= n; i++ {\n\t\tlist.Add(i)\n\t}\n}\n\nfunc TestAdd(t *testing.T) {\n\tlist := NewCyclic[int]()\n\tfillList(list, 3)\n\n\twant := []any{1, 2, 3}\n\tvar got []any\n\tvar start *Node[int]\n\tstart = list.Head\n\n\tfor i := 0; i < list.Size; i++ {\n\t\tgot = append(got, start.Val)\n\t\tstart = start.Next\n\t}\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t}\n}\n\nfunc TestWalk(t *testing.T) {\n\tlist := NewCyclic[int]()\n\tfillList(list, 3)\n\n\twant := 1\n\tgot := list.Walk()\n\n\tif got.Val != want {\n\t\tt.Errorf(\"got: %v, want: nil\", got)\n\t}\n}\n\nfunc TestRotate(t *testing.T) {\n\ttype testCase struct {\n\t\tparam        int\n\t\twantToReturn int\n\t}\n\tlist := NewCyclic[int]()\n\tfillList(list, 3)\n\n\ttestCases := []testCase{\n\t\t{1, 2},\n\t\t{3, 2},\n\t\t{6, 2},\n\t\t{7, 3},\n\t\t{-2, 1},\n\t\t{5, 3},\n\t\t{8, 2},\n\t\t{-8, 3},\n\t}\n\tfor idx, tCase := range testCases {\n\t\tlist.Rotate(tCase.param)\n\t\tgot := list.Head.Val\n\t\tif got != tCase.wantToReturn {\n\t\t\tt.Errorf(\"got: %v, want: %v for test id %v\", got, tCase.wantToReturn, idx)\n\t\t}\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tlist := NewCyclic[int]()\n\tfillList(list, 3)\n\n\twant := 2\n\twantSize := 2\n\tlist.Delete()\n\tgot := list.Head.Val\n\tif want != got {\n\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t}\n\tif wantSize != list.Size {\n\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t}\n}\n\nfunc TestDestroy(t *testing.T) {\n\tlist := NewCyclic[int]()\n\tfillList(list, 3)\n\twantSize := 0\n\tlist.Destroy()\n\n\tgot := list.Head\n\n\tif got != nil {\n\t\tt.Errorf(\"got: %v, want: nil\", got)\n\t}\n\n\tif wantSize != list.Size {\n\t\tt.Errorf(\"got: %v, want: %v\", got, wantSize)\n\t}\n}\n\nfunc TestJosephusProblem(t *testing.T) {\n\ttype testCase struct {\n\t\tparam        int\n\t\twantToReturn int\n\t\tlistCount    int\n\t}\n\n\ttestCases := []testCase{\n\t\t{5, 4, 8},\n\t\t{3, 8, 8},\n\t\t{8, 5, 8},\n\t\t{8, 5, 8},\n\t\t{2, 14, 14},\n\t\t{13, 56, 58},\n\t\t{7, 5, 5},\n\t}\n\n\tfor _, tCase := range testCases {\n\t\tlist := NewCyclic[int]()\n\t\tfillList(list, tCase.listCount)\n\t\tgot := JosephusProblem(list, tCase.param)\n\t\tif got != tCase.wantToReturn {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, tCase.wantToReturn)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "structure/linkedlist/doc.go",
    "content": "// Package linkedlist demonstrates different implementations on linkedlists.\npackage linkedlist\n"
  },
  {
    "path": "structure/linkedlist/doubly.go",
    "content": "package linkedlist\n\nimport \"fmt\"\n\n// Doubly structure with just the Head Node\n// We call it `Doubly` to make it easier to\n// understand when calling this in peoples\n// own local code to understand and experiment\n// with this easily.\n// For example, we can use gotools `go get` command to get\n// this repository cloned inside the\n// $GOPATH/src/github.com/TheAlgorithms/Go (you can do this\n// manually as well) and use the import statement as follows:\n//\n// `import \"github.com/TheAlgorithms/Go/structure/linkedlist\"`\n//\n// and call linkedlist.Doubly to create a new doubly linked list.\ntype Doubly[T any] struct {\n\tHead *Node[T]\n}\n\n// Init initializes double linked list\nfunc (ll *Doubly[T]) Init() *Doubly[T] {\n\tll.Head = &Node[T]{}\n\tll.Head.Next = ll.Head\n\tll.Head.Prev = ll.Head\n\n\treturn ll\n}\n\nfunc NewDoubly[T any]() *Doubly[T] {\n\treturn new(Doubly[T]).Init()\n}\n\n// lazyInit lazily initializes a zero List value.\nfunc (ll *Doubly[T]) lazyInit() {\n\tif ll.Head.Next == nil {\n\t\tll.Init()\n\t}\n}\n\nfunc (ll *Doubly[T]) insert(n, at *Node[T]) *Node[T] {\n\tn.Prev = at\n\tn.Next = at.Next\n\tn.Prev.Next = n\n\tn.Next.Prev = n\n\n\treturn n\n}\n\nfunc (ll *Doubly[T]) insertValue(val T, at *Node[T]) *Node[T] {\n\treturn ll.insert(NewNode(val), at)\n}\n\n// AddAtBeg Add a node to the beginning of the linkedlist\nfunc (ll *Doubly[T]) AddAtBeg(val T) {\n\tll.lazyInit()\n\tll.insertValue(val, ll.Head)\n}\n\n// AddAtEnd Add a node at the end of the linkedlist\nfunc (ll *Doubly[T]) AddAtEnd(val T) {\n\tll.lazyInit()\n\tll.insertValue(val, ll.Head.Prev)\n}\n\nfunc (ll *Doubly[T]) Remove(n *Node[T]) T {\n\tn.Prev.Next = n.Next\n\tn.Next.Prev = n.Prev\n\tn.Next = nil\n\tn.Prev = nil\n\n\treturn n.Val\n}\n\n// DelAtBeg Delete the node at the beginning of the linkedlist\nfunc (ll *Doubly[T]) DelAtBeg() (T, bool) {\n\t// no item\n\tif ll.Head.Next == nil {\n\t\tvar r T\n\t\treturn r, false\n\t}\n\n\tn := ll.Head.Next\n\tval := n.Val\n\tll.Remove(n)\n\treturn val, true\n}\n\n// DetAtEnd Delete a node at the end of the linkedlist\nfunc (ll *Doubly[T]) DelAtEnd() (T, bool) {\n\t// no item\n\tif ll.Head.Prev == nil {\n\t\tvar r T\n\t\treturn r, false\n\t}\n\n\tn := ll.Head.Prev\n\tval := n.Val\n\tll.Remove(n)\n\treturn val, true\n}\n\n// DelByPos deletes node at middle based on position in list\n// and returns value. If empty or position of node is less than linked list length, returns false\nfunc (ll *Doubly[T]) DelByPos(pos int) (T, bool) {\n\n\tswitch {\n\tcase ll.Head == nil:\n\t\tvar r T\n\t\treturn r, false\n\tcase pos-1 == 0:\n\t\treturn ll.DelAtBeg()\n\tcase pos-1 == ll.Count():\n\t\treturn ll.DelAtEnd()\n\tcase pos-1 > ll.Count():\n\t\tvar r T\n\t\treturn r, false\n\t}\n\tvar prev *Node[T]\n\tvar val T\n\tcur := ll.Head\n\tcount := 0\n\n\tfor count < pos-1 {\n\t\tprev = cur\n\t\tcur = cur.Next\n\t\tcount++\n\t}\n\n\tcur.Next.Prev = prev\n\tval = cur.Val\n\tprev.Next = cur.Next\n\treturn val, true\n}\n\n// Count Number of nodes in the linkedlist\nfunc (ll *Doubly[T]) Count() int {\n\tvar ctr int = 0\n\n\tif ll.Head.Next == nil {\n\t\treturn 0\n\t}\n\n\tfor cur := ll.Head.Next; cur != ll.Head; cur = cur.Next {\n\t\tctr += 1\n\t}\n\n\treturn ctr\n}\n\n// Reverse Reverse the order of the linkedlist\nfunc (ll *Doubly[T]) Reverse() {\n\tvar Prev, Next *Node[T]\n\tcur := ll.Head\n\n\tfor cur != nil {\n\t\tNext = cur.Next\n\t\tcur.Next = Prev\n\t\tcur.Prev = Next\n\t\tPrev = cur\n\t\tcur = Next\n\t}\n\n\tll.Head = Prev\n}\n\n// Display display the linked list\nfunc (ll *Doubly[T]) Display() {\n\tfor cur := ll.Head.Next; cur != ll.Head; cur = cur.Next {\n\t\tfmt.Print(cur.Val, \" \")\n\t}\n\n\tfmt.Print(\"\\n\")\n}\n\n// DisplayReverse Display the linkedlist in reverse order\nfunc (ll *Doubly[T]) DisplayReverse() {\n\tif ll.Head == nil {\n\t\treturn\n\t}\n\tvar cur *Node[T]\n\tfor cur = ll.Head.Prev; cur != ll.Head; cur = cur.Prev {\n\t\tfmt.Print(cur.Val, \" \")\n\t}\n\n\tfmt.Print(\"\\n\")\n}\n\nfunc (ll *Doubly[T]) Front() *Node[T] {\n\tif ll.Count() == 0 {\n\t\treturn nil\n\t}\n\n\treturn ll.Head.Next\n}\n\nfunc (ll *Doubly[T]) Back() *Node[T] {\n\tif ll.Count() == 0 {\n\t\treturn nil\n\t}\n\n\treturn ll.Head.Prev\n}\n\nfunc (ll *Doubly[T]) MoveToBack(n *Node[T]) {\n\tif ll.Head.Prev == n {\n\t\treturn\n\t}\n\n\tll.move(n, ll.Head.Prev)\n}\n\nfunc (ll *Doubly[T]) move(n, at *Node[T]) {\n\tif n == at {\n\t\treturn\n\t}\n\n\tn.Prev.Next = n.Next\n\tn.Next.Prev = n.Prev\n\n\tn.Prev = at\n\tn.Next = at.Next\n\tn.Prev.Next = n\n\tn.Next.Prev = n\n}\n"
  },
  {
    "path": "structure/linkedlist/doubly_test.go",
    "content": "package linkedlist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDoubly(t *testing.T) {\n\tnewList := NewDoubly[int]()\n\n\tnewList.AddAtBeg(1)\n\tnewList.AddAtBeg(2)\n\tnewList.AddAtBeg(3)\n\n\tt.Run(\"Test AddAtBeg\", func(t *testing.T) {\n\t\twantNext := []int{3, 2, 1}\n\t\twantPrev := []int{1, 2, 3}\n\t\tgot := []int{}\n\n\t\t// check from Next address\n\t\tcurrent := newList.Head.Next\n\n\t\tgot = append(got, current.Val)\n\n\t\tfor current.Next != newList.Head {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\n\t\tif !reflect.DeepEqual(got, wantNext) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, wantNext)\n\t\t}\n\n\t\t// check from Prev address\n\t\tgot = []int{}\n\t\tgot = append(got, current.Val)\n\n\t\tfor current.Prev != newList.Head {\n\t\t\tcurrent = current.Prev\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\n\t\tif !reflect.DeepEqual(got, wantPrev) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, wantPrev)\n\t\t}\n\t})\n\n\tnewList.AddAtEnd(4)\n\n\tt.Run(\"Test AddAtEnd\", func(t *testing.T) {\n\t\twant := []int{3, 2, 1, 4}\n\t\tgot := []int{}\n\t\tcurrent := newList.Head.Next\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != newList.Head {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test DelAtBeg\", func(t *testing.T) {\n\t\twant := 3\n\t\tgot, ok := newList.DelAtBeg()\n\t\tif !ok {\n\t\t\tt.Error(\"unexpected not-ok\")\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test DelAtEnd\", func(t *testing.T) {\n\t\twant := 4\n\t\tgot, ok := newList.DelAtEnd()\n\t\tif !ok {\n\t\t\tt.Error(\"unexpected not-ok\")\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test Count\", func(t *testing.T) {\n\t\twant := 2\n\t\tgot := newList.Count()\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tnewList2 := NewDoubly[int]()\n\tnewList2.AddAtBeg(1)\n\tnewList2.AddAtBeg(2)\n\tnewList2.AddAtBeg(3)\n\tt.Run(\"Test Reverse\", func(t *testing.T) {\n\t\twant := []int{1, 2, 3}\n\t\tgot := []int{}\n\t\tnewList2.Reverse()\n\t\tcurrent := newList2.Head.Next\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != newList2.Head {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/linkedlist/shared.go",
    "content": "package linkedlist\n\n// Node Structure representing the linkedlist node.\n// This node is shared across different implementations.\ntype Node[T any] struct {\n\tVal  T\n\tPrev *Node[T]\n\tNext *Node[T]\n}\n\n// Create new node.\nfunc NewNode[T any](val T) *Node[T] {\n\treturn &Node[T]{val, nil, nil}\n}\n"
  },
  {
    "path": "structure/linkedlist/singlylinkedlist.go",
    "content": "package linkedlist\n\n// demonstration of singly linked list in golang\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// Singly structure with length of the list and its head\ntype Singly[T any] struct {\n\tlength int\n\n\t// Note that Node here holds both Next and Prev Node\n\t// however only the Next node is used in Singly methods.\n\tHead *Node[T]\n}\n\n// NewSingly returns a new instance of a linked list\nfunc NewSingly[T any]() *Singly[T] {\n\treturn &Singly[T]{}\n}\n\n// AddAtBeg adds a new snode with given value at the beginning of the list.\nfunc (ll *Singly[T]) AddAtBeg(val T) {\n\tn := NewNode(val)\n\tn.Next = ll.Head\n\tll.Head = n\n\tll.length++\n}\n\n// AddAtEnd adds a new snode with given value at the end of the list.\nfunc (ll *Singly[T]) AddAtEnd(val T) {\n\tn := NewNode(val)\n\n\tif ll.Head == nil {\n\t\tll.Head = n\n\t\tll.length++\n\t\treturn\n\t}\n\n\tcur := ll.Head\n\tfor ; cur.Next != nil; cur = cur.Next {\n\t}\n\tcur.Next = n\n\tll.length++\n}\n\n// DelAtBeg deletes the snode at the head(beginning) of the list\n// and returns its value. Returns false if the list is empty.\nfunc (ll *Singly[T]) DelAtBeg() (T, bool) {\n\tif ll.Head == nil {\n\t\tvar r T\n\t\treturn r, false\n\t}\n\n\tcur := ll.Head\n\tll.Head = cur.Next\n\tll.length--\n\n\treturn cur.Val, true\n}\n\n// DelAtEnd deletes the snode at the tail(end) of the list\n// and returns its value. Returns false if the list is empty.\nfunc (ll *Singly[T]) DelAtEnd() (T, bool) {\n\tif ll.Head == nil {\n\t\tvar r T\n\t\treturn r, false\n\t}\n\n\tif ll.Head.Next == nil {\n\t\treturn ll.DelAtBeg()\n\t}\n\n\tcur := ll.Head\n\n\tfor ; cur.Next.Next != nil; cur = cur.Next {\n\t}\n\n\tretval := cur.Next.Val\n\tcur.Next = nil\n\tll.length--\n\treturn retval, true\n\n}\n\n// DelByPos deletes the node at the middle based on position in the list\n// and returns its value. Returns false if the list is empty or length is not more than given position\nfunc (ll *Singly[T]) DelByPos(pos int) (T, bool) {\n\tswitch {\n\tcase ll.Head == nil:\n\t\tvar r T\n\t\treturn r, false\n\tcase pos-1 > ll.length:\n\t\tvar r T\n\t\treturn r, false\n\tcase pos-1 == 0:\n\t\treturn ll.DelAtBeg()\n\tcase pos-1 == ll.Count():\n\t\treturn ll.DelAtEnd()\n\t}\n\n\tvar prev *Node[T]\n\tvar val T\n\tcur := ll.Head\n\tcount := 0\n\n\tfor count < pos-1 {\n\t\tprev = cur\n\t\tcur = cur.Next\n\t\tcount++\n\t}\n\n\tval = cur.Val\n\tprev.Next = cur.Next\n\tll.length--\n\n\treturn val, true\n}\n\n// Count returns the current size of the list.\nfunc (ll *Singly[T]) Count() int {\n\treturn ll.length\n}\n\n// Reverse reverses the list.\nfunc (ll *Singly[T]) Reverse() {\n\tvar prev, next *Node[T]\n\tcur := ll.Head\n\n\tfor cur != nil {\n\t\tnext = cur.Next\n\t\tcur.Next = prev\n\t\tprev = cur\n\t\tcur = next\n\t}\n\n\tll.Head = prev\n}\n\n// ReversePartition Reverse the linked list from the ath to the bth node\nfunc (ll *Singly[T]) ReversePartition(left, right int) error {\n\terr := ll.CheckRangeFromIndex(left, right)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttmpNode := &Node[T]{}\n\ttmpNode.Next = ll.Head\n\tpre := tmpNode\n\tfor i := 0; i < left-1; i++ {\n\t\tpre = pre.Next\n\t}\n\tcur := pre.Next\n\tfor i := 0; i < right-left; i++ {\n\t\tnext := cur.Next\n\t\tcur.Next = next.Next\n\t\tnext.Next = pre.Next\n\t\tpre.Next = next\n\t}\n\tll.Head = tmpNode.Next\n\treturn nil\n}\nfunc (ll *Singly[T]) CheckRangeFromIndex(left, right int) error {\n\tif left > right {\n\t\treturn errors.New(\"left boundary must smaller than right\")\n\t} else if left < 1 {\n\t\treturn errors.New(\"left boundary starts from the first node\")\n\t} else if right > ll.length {\n\t\treturn errors.New(\"right boundary cannot be greater than the length of the linked list\")\n\t}\n\treturn nil\n}\n\n// Display prints out the elements of the list.\nfunc (ll *Singly[T]) Display() {\n\tfor cur := ll.Head; cur != nil; cur = cur.Next {\n\t\tfmt.Print(cur.Val, \" \")\n\t}\n\n\tfmt.Print(\"\\n\")\n}\n"
  },
  {
    "path": "structure/linkedlist/singlylinkedlist_test.go",
    "content": "package linkedlist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSingly(t *testing.T) {\n\tlist := NewSingly[int]()\n\tlist.AddAtBeg(1)\n\tlist.AddAtBeg(2)\n\tlist.AddAtBeg(3)\n\n\tt.Run(\"Test AddAtBeg()\", func(t *testing.T) {\n\t\twant := []any{3, 2, 1}\n\t\tgot := []any{}\n\t\tcurrent := list.Head\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != nil {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tlist.AddAtEnd(4)\n\n\tt.Run(\"Test AddAtEnd()\", func(t *testing.T) {\n\t\twant := []any{3, 2, 1, 4}\n\t\tgot := []any{}\n\t\tcurrent := list.Head\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != nil {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test DelAtBeg()\", func(t *testing.T) {\n\t\twant := any(3)\n\t\tgot, ok := list.DelAtBeg()\n\t\tif !ok {\n\t\t\tt.Error(\"unexpected not-ok\")\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test DelAtEnd()\", func(t *testing.T) {\n\t\twant := any(4)\n\t\tgot, ok := list.DelAtEnd()\n\t\tif !ok {\n\t\t\tt.Error(\"unexpected not-ok\")\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test Count()\", func(t *testing.T) {\n\t\twant := 2\n\t\tgot := list.Count()\n\t\tif got != want {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tlist2 := Singly[int]{}\n\tlist2.AddAtBeg(1)\n\tlist2.AddAtBeg(2)\n\tlist2.AddAtBeg(3)\n\tlist2.AddAtBeg(4)\n\tlist2.AddAtBeg(5)\n\tlist2.AddAtBeg(6)\n\n\tt.Run(\"Test Reverse()\", func(t *testing.T) {\n\t\twant := []any{1, 2, 3, 4, 5, 6}\n\t\tgot := []any{}\n\t\tlist2.Reverse()\n\t\tcurrent := list2.Head\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != nil {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n\n\tt.Run(\"Test ReversePartition()\", func(t *testing.T) {\n\t\twant := []any{1, 5, 4, 3, 2, 6}\n\t\tgot := []any{}\n\t\terr := list2.ReversePartition(2, 5)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Incorrect boundary conditions entered%v\", err)\n\t\t}\n\t\tcurrent := list2.Head\n\t\tgot = append(got, current.Val)\n\t\tfor current.Next != nil {\n\t\t\tcurrent = current.Next\n\t\t\tgot = append(got, current.Val)\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Errorf(\"got: %v, want: %v\", got, want)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/queue/queue_test.go",
    "content": "// Queue Test\n// description: based on `geeksforgeeks` description A Queue is a linear structure which follows a particular order in which the operations are performed.\n// \tThe order is First In First Out (FIFO).\n// details:\n// \tQueue Data Structure : https://www.geeksforgeeks.org/queue-data-structure/\n//  Queue (abstract data type) : https://en.wikipedia.org/wiki/Queue_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see queuearray.go, queuelinkedlist.go, queuelinkedlistwithlist.go\n\npackage queue\n\nimport (\n\t\"container/list\"\n\t\"testing\"\n)\n\nfunc TestQueue(t *testing.T) {\n\n\t// Handle Queue Linked List\n\tt.Run(\"Test Queue Linked List\", func(t *testing.T) {\n\n\t\tt.Run(\"Test EnQueue\", func(t *testing.T) {\n\t\t\tvar newQueue Queue\n\t\t\tnewQueue.enqueue(2)\n\t\t\tnewQueue.enqueue(3)\n\t\t\tnewQueue.enqueue(4)\n\t\t\tnewQueue.enqueue(45)\n\n\t\t\tif newQueue.frontQueue() != 2 && newQueue.backQueue() != 45 {\n\t\t\t\tt.Errorf(\"Test EnQueue is wrong the result must be %v and %v but got %v and %v\", 2, 45, newQueue.frontQueue(), newQueue.backQueue())\n\t\t\t}\n\n\t\t})\n\n\t\tt.Run(\"Test DeQueue\", func(t *testing.T) {\n\t\t\tvar newQueue Queue\n\t\t\tnewQueue.enqueue(2)\n\t\t\tnewQueue.enqueue(3)\n\t\t\tnewQueue.enqueue(4)\n\n\t\t\tnewQueue.dequeue()\n\t\t\tif newQueue.dequeue() != 3 {\n\t\t\t\tt.Errorf(\"Test DeQueue is wrong the result must be %v but got %v\", 3, newQueue.dequeue())\n\t\t\t}\n\n\t\t\t//fmt.Println(newQueue.show())\n\t\t})\n\n\t\tt.Run(\"Test Queue isEmpty\", func(t *testing.T) {\n\t\t\tvar newQueue Queue\n\t\t\tif newQueue.isEmpty() != true {\n\t\t\t\tt.Errorf(\"Test Queue isEmpty is wrong the result must be %v but got %v\", true, newQueue.isEmpty())\n\t\t\t}\n\n\t\t\tnewQueue.enqueue(3)\n\t\t\tnewQueue.enqueue(4)\n\n\t\t\tif newQueue.isEmpty() != false {\n\t\t\t\tt.Errorf(\"Test Queue isEmpty is wrong the result must be %v but got %v\", false, newQueue.isEmpty())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Test Queue Length\", func(t *testing.T) {\n\t\t\tvar newQueue Queue\n\t\t\tif newQueue.len() != 0 {\n\t\t\t\tt.Errorf(\"Test Queue Length is wrong the result must be %v but got %v\", 0, newQueue.len())\n\t\t\t}\n\n\t\t\tnewQueue.enqueue(3)\n\t\t\tnewQueue.enqueue(4)\n\t\t\tnewQueue.dequeue()\n\t\t\tnewQueue.enqueue(22)\n\t\t\tnewQueue.enqueue(99)\n\t\t\tnewQueue.dequeue()\n\t\t\tnewQueue.dequeue()\n\n\t\t\tif newQueue.len() != 1 {\n\t\t\t\tt.Errorf(\"Test Queue Length is wrong the result must be %v but got %v\", 1, newQueue.len())\n\t\t\t}\n\n\t\t})\n\t})\n\n\t// Handle Queue Array\n\tt.Run(\"Test Queue Array\", func(t *testing.T) {\n\t\tt.Run(\"Test EnQueue\", func(t *testing.T) {\n\t\t\tEnQueue(2)\n\t\t\tEnQueue(23)\n\t\t\tEnQueue(45)\n\t\t\tEnQueue(66)\n\n\t\t\tif FrontQueue() != 2 && BackQueue() != 66 {\n\t\t\t\tt.Errorf(\"Test EnQueue is wrong the result must be %v and %v but got %v and %v\", 2, 66, FrontQueue(), BackQueue())\n\t\t\t}\n\n\t\t})\n\n\t\tt.Run(\"Test DeQueue\", func(t *testing.T) {\n\t\t\tEnQueue(2)\n\t\t\tEnQueue(23)\n\t\t\tEnQueue(45)\n\t\t\tEnQueue(66)\n\n\t\t\tDeQueue()\n\t\t\tDeQueue()\n\n\t\t\tif DeQueue() != 45 {\n\t\t\t\tt.Errorf(\"Test DeQueue is wrong the result must be %v but got %v\", 45, DeQueue())\n\t\t\t}\n\t\t})\n\n\t\tListQueue = []any{}\n\n\t\tt.Run(\"Test Queue isEmpty\", func(t *testing.T) {\n\n\t\t\tif IsEmptyQueue() != true {\n\t\t\t\tt.Errorf(\"Test Queue isEmpty is wrong the result must be %v but got %v\", true, IsEmptyQueue())\n\t\t\t}\n\n\t\t\tEnQueue(3)\n\t\t\tEnQueue(4)\n\n\t\t\tif IsEmptyQueue() != false {\n\t\t\t\tt.Errorf(\"Test Queue isEmpty is wrong the result must be %v but got %v\", false, IsEmptyQueue())\n\t\t\t}\n\t\t})\n\n\t\tListQueue = []any{}\n\t\tt.Run(\"Test Queue Length\", func(t *testing.T) {\n\t\t\tif LenQueue() != 0 {\n\t\t\t\tt.Errorf(\"Test Queue Length is wrong the result must be %v but got %v\", 0, LenQueue())\n\t\t\t}\n\n\t\t\tEnQueue(3)\n\t\t\tEnQueue(4)\n\t\t\tDeQueue()\n\t\t\tEnQueue(22)\n\t\t\tEnQueue(99)\n\t\t\tDeQueue()\n\t\t\tDeQueue()\n\n\t\t\tif LenQueue() != 1 {\n\t\t\t\tt.Errorf(\"Test Queue Length is wrong the result must be %v but got %v\", 1, LenQueue())\n\t\t\t}\n\n\t\t})\n\n\t})\n\n\t// Handle Queue Linked-List With Container/List (STL)\n\tt.Run(\"Test Container/List For Queue\", func(t *testing.T) {\n\t\tlistQueue := &LQueue{\n\t\t\tqueue: list.New(),\n\t\t}\n\n\t\tt.Run(\"List Enqueue\", func(t *testing.T) {\n\t\t\tlistQueue.Enqueue(\"Snap\")\n\t\t\tlistQueue.Enqueue(123)\n\t\t\tlistQueue.Enqueue(true)\n\t\t\tlistQueue.Enqueue(212.545454)\n\n\t\t\tif listQueue.Len() != 4 {\n\t\t\t\tt.Errorf(\"List Enqueue is not correct expected %d but got %d\", 4, listQueue.Len())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"List Dequeue\", func(t *testing.T) {\n\n\t\t\terr := listQueue.Dequeue()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\t\t\tif listQueue.Len() != 3 {\n\t\t\t\tt.Errorf(\"List Dequeue is not correct expected %d but got %d\", 3, listQueue.Len())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"List Front\", func(t *testing.T) {\n\n\t\t\terr := listQueue.Dequeue()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tresult, err := listQueue.Front()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tif result != true {\n\t\t\t\tt.Errorf(\"List Front is not correct expected %v but got %v\", true, result)\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"List Back\", func(t *testing.T) {\n\n\t\t\terr := listQueue.Dequeue()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tresult, err := listQueue.Back()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tif result != 212.545454 {\n\t\t\t\tt.Errorf(\"List Back is not correct expected %v but got %v\", 212.545454, result)\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"List Length\", func(t *testing.T) {\n\n\t\t\tlistQueue.Enqueue(\"Snap\")\n\n\t\t\terr := listQueue.Dequeue()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tif listQueue.Len() != 1 {\n\t\t\t\tt.Errorf(\"List Length is not correct expected %v but got %v\", 1, listQueue.Len())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"List Empty\", func(t *testing.T) {\n\n\t\t\terr := listQueue.Dequeue()\n\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"got an unexpected error \", err)\n\t\t\t}\n\n\t\t\tif !listQueue.Empty() {\n\t\t\t\tt.Errorf(\"List Empty is not correct expected %v but got %v\", true, listQueue.Empty())\n\t\t\t}\n\t\t})\n\n\t})\n\n}\n"
  },
  {
    "path": "structure/queue/queuearray.go",
    "content": "// Queue Array\n// description: based on `geeksforgeeks` description A Queue is a linear structure which follows a particular order in which the operations are performed.\n// \tThe order is First In First Out (FIFO).\n// details:\n// \tQueue Data Structure : https://www.geeksforgeeks.org/queue-data-structure/\n//  Queue (abstract data type) : https://en.wikipedia.org/wiki/Queue_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see queuelinkedlist.go, queuelinkedlistwithlist.go, queue_test.go\n\npackage queue\n\nvar ListQueue []any\n\n// EnQueue it will be added new value into our list\nfunc EnQueue(n any) {\n\tListQueue = append(ListQueue, n)\n}\n\n// DeQueue it will be removed the first value that added into the list\nfunc DeQueue() any {\n\tdata := ListQueue[0]\n\tListQueue = ListQueue[1:]\n\treturn data\n}\n\n// FrontQueue return the Front value\nfunc FrontQueue() any {\n\treturn ListQueue[0]\n}\n\n// BackQueue return the Back value\nfunc BackQueue() any {\n\treturn ListQueue[len(ListQueue)-1]\n}\n\n// LenQueue will return the length of the queue list\nfunc LenQueue() int {\n\treturn len(ListQueue)\n}\n\n// IsEmptyQueue check our list is empty or not\nfunc IsEmptyQueue() bool {\n\treturn len(ListQueue) == 0\n}\n"
  },
  {
    "path": "structure/queue/queuelinkedlist.go",
    "content": "// Queue Linked-List\n// description: based on `geeksforgeeks` description A Queue is a linear structure which follows a particular order in which the operations are performed.\n// \tThe order is First In First Out (FIFO).\n// details:\n// \tQueue Data Structure : https://www.geeksforgeeks.org/queue-data-structure/\n//  Queue (abstract data type) : https://en.wikipedia.org/wiki/Queue_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see queuearray.go, queuelinkedlistwithlist.go, queue_test.go\n\npackage queue\n\n// Node will be store the value and the next node as well\ntype Node struct {\n\tData any\n\tNext *Node\n}\n\n// Queue structure is tell us what our head is and what tail should be with length of the list\ntype Queue struct {\n\thead   *Node\n\ttail   *Node\n\tlength int\n}\n\n// enqueue it will be added new value into queue\nfunc (ll *Queue) enqueue(n any) {\n\tvar newNode Node // create new Node\n\tnewNode.Data = n // set the data\n\n\tif ll.tail != nil {\n\t\tll.tail.Next = &newNode\n\t}\n\n\tll.tail = &newNode\n\n\tif ll.head == nil {\n\t\tll.head = &newNode\n\t}\n\tll.length++\n}\n\n// dequeue it will be removed the first value into queue (First In First Out)\nfunc (ll *Queue) dequeue() any {\n\tif ll.isEmpty() {\n\t\treturn -1 // if is empty return -1\n\t}\n\tdata := ll.head.Data\n\n\tll.head = ll.head.Next\n\n\tif ll.head == nil {\n\t\tll.tail = nil\n\t}\n\n\tll.length--\n\treturn data\n}\n\n// isEmpty it will check our list is empty or not\nfunc (ll *Queue) isEmpty() bool {\n\treturn ll.length == 0\n}\n\n// len is return the length of queue\nfunc (ll *Queue) len() int {\n\treturn ll.length\n}\n\n// frontQueue it will return the front data\nfunc (ll *Queue) frontQueue() any {\n\treturn ll.head.Data\n}\n\n// backQueue it will return the back data\nfunc (ll *Queue) backQueue() any {\n\treturn ll.tail.Data\n}\n"
  },
  {
    "path": "structure/queue/queuelinklistwithlist.go",
    "content": "// Queue Linked-List with standard library (Container/List)\n// description: based on `geeksforgeeks` description A Queue is a linear structure which follows a particular order in which the operations are performed.\n// \tThe order is First In First Out (FIFO).\n// details:\n// \tQueue Data Structure : https://www.geeksforgeeks.org/queue-data-structure/\n//  Queue (abstract data type) : https://en.wikipedia.org/wiki/Queue_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see queuearray.go, queuelinkedlist.go, queue_test.go\n\npackage queue\n\n// container/list: is used as linked-list\n// fmt: used to return fmt.Errorf for the error part\nimport (\n\t\"container/list\"\n\t\"fmt\"\n)\n\n// LQueue will be store the value into the list\ntype LQueue struct {\n\tqueue *list.List\n}\n\n// Enqueue will be added new value\nfunc (lq *LQueue) Enqueue(value any) {\n\tlq.queue.PushBack(value)\n}\n\n// Dequeue will be removed the first value that input (First In First Out - FIFO)\nfunc (lq *LQueue) Dequeue() error {\n\n\tif !lq.Empty() {\n\t\telement := lq.queue.Front()\n\t\tlq.queue.Remove(element)\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"dequeue is empty we got an error\")\n}\n\n// Front it will return the front value\nfunc (lq *LQueue) Front() (any, error) {\n\tif !lq.Empty() {\n\t\tval := lq.queue.Front().Value\n\t\treturn val, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"error queue is empty\")\n}\n\n// Back it will return the back value\nfunc (lq *LQueue) Back() (any, error) {\n\tif !lq.Empty() {\n\t\tval := lq.queue.Back().Value\n\t\treturn val, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"error queue is empty\")\n}\n\n// Len it will return the length of list\nfunc (lq *LQueue) Len() int {\n\treturn lq.queue.Len()\n}\n\n// Empty is check our list is empty or not\nfunc (lq *LQueue) Empty() bool {\n\treturn lq.queue.Len() == 0\n}\n"
  },
  {
    "path": "structure/segmenttree/segmenttree.go",
    "content": "// Segment Tree Data Structure for efficient range queries on an array of integers.\n// It can query the sum and update the elements to a new value of any range of the array.\n// Build: O(n*log(n))\n// Query: O(log(n))\n// Update: O(log(n))\n// reference: https://cp-algorithms.com/data_structures/segment_tree.html\npackage segmenttree\n\nimport (\n\t\"github.com/TheAlgorithms/Go/math/max\"\n\t\"github.com/TheAlgorithms/Go/math/min\"\n)\n\nconst emptyLazyNode = 0\n\n// SegmentTree represents the data structure of a segment tree with lazy propagation\ntype SegmentTree struct {\n\tArray       []int // The original array\n\tSegmentTree []int // Stores the sum of different ranges\n\tLazyTree    []int // Stores the values of lazy propagation\n}\n\n// Propagate propagates the lazy updates to the child nodes\nfunc (s *SegmentTree) Propagate(node int, leftNode int, rightNode int) {\n\tif s.LazyTree[node] != emptyLazyNode {\n\t\t//add lazy node value multiplied by (right-left+1), which represents all interval\n\t\t//this is the same of adding a value on each node\n\t\ts.SegmentTree[node] += (rightNode - leftNode + 1) * s.LazyTree[node]\n\n\t\tif leftNode == rightNode {\n\t\t\t//leaf node\n\t\t\ts.Array[leftNode] += s.LazyTree[node]\n\t\t} else {\n\t\t\t//propagate lazy node value for children nodes\n\t\t\t//may propagate multiple times, children nodes should accumulate lazy node value\n\t\t\ts.LazyTree[2*node] += s.LazyTree[node]\n\t\t\ts.LazyTree[2*node+1] += s.LazyTree[node]\n\t\t}\n\n\t\t//clear lazy node\n\t\ts.LazyTree[node] = emptyLazyNode\n\t}\n}\n\n// Query returns the sum of elements of the array in the interval [firstIndex, leftIndex].\n// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively.\nfunc (s *SegmentTree) Query(node int, leftNode int, rightNode int, firstIndex int, lastIndex int) int {\n\tif (firstIndex > lastIndex) || (leftNode > rightNode) {\n\t\t//outside the interval\n\t\treturn 0\n\t}\n\n\t//propagate lazy tree\n\ts.Propagate(node, leftNode, rightNode)\n\n\tif (leftNode >= firstIndex) && (rightNode <= lastIndex) {\n\t\t//inside the interval\n\t\treturn s.SegmentTree[node]\n\t}\n\n\t//get sum of left and right nodes\n\tmid := (leftNode + rightNode) / 2\n\n\tleftNodeSum := s.Query(2*node, leftNode, mid, firstIndex, min.Int(mid, lastIndex))\n\trightNodeSum := s.Query(2*node+1, mid+1, rightNode, max.Int(firstIndex, mid+1), lastIndex)\n\n\treturn leftNodeSum + rightNodeSum\n}\n\n// Update updates the elements of the array in the range [firstIndex, lastIndex]\n// with the new value provided and recomputes the sum of different ranges.\n// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively.\nfunc (s *SegmentTree) Update(node int, leftNode int, rightNode int, firstIndex int, lastIndex int, value int) {\n\t//propagate lazy tree\n\ts.Propagate(node, leftNode, rightNode)\n\n\tif (firstIndex > lastIndex) || (leftNode > rightNode) {\n\t\t//outside the interval\n\t\treturn\n\t}\n\n\tif (leftNode >= firstIndex) && (rightNode <= lastIndex) {\n\t\t//inside the interval\n\t\t//accumulate the lazy node value\n\t\ts.LazyTree[node] += value\n\t\ts.Propagate(node, leftNode, rightNode)\n\t} else {\n\t\t//update left and right nodes\n\t\tmid := (leftNode + rightNode) / 2\n\n\t\ts.Update(2*node, leftNode, mid, firstIndex, min.Int(mid, lastIndex), value)\n\t\ts.Update(2*node+1, mid+1, rightNode, max.Int(firstIndex, mid+1), lastIndex, value)\n\n\t\ts.SegmentTree[node] = s.SegmentTree[2*node] + s.SegmentTree[2*node+1]\n\t}\n}\n\n// Build builds the SegmentTree by computing the sum of different ranges.\n// node, leftNode and rightNode should always start with 1, 0 and len(Array)-1, respectively.\nfunc (s *SegmentTree) Build(node int, left int, right int) {\n\tif left == right {\n\t\t//leaf node\n\t\ts.SegmentTree[node] = s.Array[left]\n\t} else {\n\t\t//get sum of left and right nodes\n\t\tmid := (left + right) / 2\n\n\t\ts.Build(2*node, left, mid)\n\t\ts.Build(2*node+1, mid+1, right)\n\n\t\ts.SegmentTree[node] = s.SegmentTree[2*node] + s.SegmentTree[2*node+1]\n\t}\n}\n\n// NewSegmentTree returns a new instance of a SegmentTree. It takes an input\n// array of integers representing Array, initializes and builds the SegmentTree.\nfunc NewSegmentTree(Array []int) *SegmentTree {\n\tif len(Array) == 0 {\n\t\treturn nil\n\t}\n\n\tsegTree := SegmentTree{\n\t\tArray:       Array,\n\t\tSegmentTree: make([]int, 4*len(Array)),\n\t\tLazyTree:    make([]int, 4*len(Array)),\n\t}\n\n\tfor i := range segTree.LazyTree {\n\t\t//fill LazyTree with empty lazy nodes\n\t\tsegTree.LazyTree[i] = emptyLazyNode\n\t}\n\n\t//starts with node 1 and interval [0, len(arr)-1] inclusive\n\tsegTree.Build(1, 0, len(Array)-1)\n\n\treturn &segTree\n}\n"
  },
  {
    "path": "structure/segmenttree/segmenttree_test.go",
    "content": "package segmenttree\n\nimport (\n\t\"testing\"\n)\n\n// Query interval\ntype query struct {\n\tfirstIndex int\n\tlastIndex  int\n}\n\ntype update struct {\n\tfirstIndex int\n\tlastIndex  int\n\tvalue      int\n}\n\nfunc TestSegmentTree(t *testing.T) {\n\tvar segmentTreeTestData = []struct {\n\t\tdescription string\n\t\tarray       []int\n\t\tupdates     []update\n\t\tqueries     []query\n\t\texpected    []int\n\t}{\n\t\t{\n\t\t\tdescription: \"test empty array\",\n\t\t\tarray:       []int{},\n\t\t\tqueries:     []query{{0, 0}},\n\t\t\texpected:    []int{0},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tqueries:     []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected:    []int{15, 6, 12},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5 and updates\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates: []update{{firstIndex: 1, lastIndex: 1, value: 2},\n\t\t\t\t{firstIndex: 2, lastIndex: 2, value: 3}},\n\t\t\tqueries:  []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected: []int{20, 11, 15},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5 and single index updates\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates: []update{{firstIndex: 1, lastIndex: 1, value: 2},\n\t\t\t\t{firstIndex: 2, lastIndex: 2, value: 3}},\n\t\t\tqueries:  []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected: []int{20, 11, 15},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 5 and range updates\",\n\t\t\tarray:       []int{1, 2, 3, 4, 5},\n\t\t\tupdates: []update{{firstIndex: 0, lastIndex: 4, value: 2},\n\t\t\t\t{firstIndex: 2, lastIndex: 4, value: 2}},\n\t\t\tqueries:  []query{{0, 5}, {0, 2}, {2, 4}},\n\t\t\texpected: []int{31, 14, 24},\n\t\t},\n\t\t{\n\t\t\tdescription: \"test array with size 11 and range updates\",\n\t\t\tarray:       []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n\t\t\tupdates: []update{{firstIndex: 2, lastIndex: 8, value: 2},\n\t\t\t\t{firstIndex: 2, lastIndex: 8, value: 2}},\n\t\t\tqueries:  []query{{3, 5}, {7, 8}, {4, 5}, {8, 8}},\n\t\t\texpected: []int{15, 10, 10, 5},\n\t\t},\n\t}\n\tfor _, test := range segmentTreeTestData {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tsegmentTree := NewSegmentTree(test.array)\n\n\t\t\tfor i := 0; i < len(test.updates); i++ {\n\t\t\t\tsegmentTree.Update(1, 0, len(test.array)-1, test.updates[i].firstIndex, test.updates[i].lastIndex, test.updates[i].value)\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(test.queries); i++ {\n\t\t\t\tresult := segmentTree.Query(1, 0, len(test.array)-1, test.queries[i].firstIndex, test.queries[i].lastIndex)\n\n\t\t\t\tif result != test.expected[i] {\n\t\t\t\t\tt.Logf(\"FAIL: %s\", test.description)\n\t\t\t\t\tt.Fatalf(\"Expected result: %d\\nFound: %d\\n\", test.expected[i], result)\n\t\t\t\t}\n\t\t\t}\n\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "structure/set/set.go",
    "content": "// package set implements a Set using a golang map.\n// This implies that only the types that are accepted as valid map keys can be used as set elements.\n// For instance, do not try to Add a slice, or the program will panic.\npackage set\n\n// New gives new set.\nfunc New[T comparable](items ...T) Set[T] {\n\tst := set[T]{\n\t\telements: make(map[T]bool),\n\t}\n\tfor _, item := range items {\n\t\tst.Add(item)\n\t}\n\treturn &st\n}\n\n// Set is an interface of possible methods on 'set'.\ntype Set[T comparable] interface {\n\t// Add: adds new element to the set\n\tAdd(item T)\n\t// Delete: deletes the passed element from the set if present\n\tDelete(item T)\n\t// Len: gives the length of the set (total no. of elements in set)\n\tLen() int\n\t// GetItems: gives the array( []T ) of elements of the set.\n\tGetItems() []T\n\t// In: checks whether item is present in set or not.\n\tIn(item T) bool\n\t// IsSubsetOf: checks whether set is subset of set2 or not.\n\tIsSubsetOf(set2 Set[T]) bool\n\t// IsProperSubsetOf: checks whether set is proper subset of set2 or not.\n\t// ex: [1,2,3] proper subset of [1,2,3,4] -> true\n\tIsProperSubsetOf(set2 Set[T]) bool\n\t// IsSupersetOf: checks whether set is superset of set2 or not.\n\tIsSupersetOf(set2 Set[T]) bool\n\t// IsProperSupersetOf: checks whether set is proper superset of set2 or not.\n\t// ex: [1,2,3,4] proper superset of [1,2,3] -> true\n\tIsProperSupersetOf(set2 Set[T]) bool\n\t// Union: gives new union set of both sets.\n\t// ex: [1,2,3] union [3,4,5] -> [1,2,3,4,5]\n\tUnion(set2 Set[T]) Set[T]\n\t// Intersection: gives new intersection set of both sets.\n\t// ex: [1,2,3] Intersection [3,4,5] -> [3]\n\tIntersection(set2 Set[T]) Set[T]\n\t// Difference: gives new difference set of both sets.\n\t// ex: [1,2,3] Difference [3,4,5] -> [1,2]\n\tDifference(set2 Set[T]) Set[T]\n\t// SymmetricDifference: gives new symmetric difference set of both sets.\n\t// ex: [1,2,3] SymmetricDifference [3,4,5] -> [1,2,4,5]\n\tSymmetricDifference(set2 Set[T]) Set[T]\n}\n\ntype set[T comparable] struct {\n\telements map[T]bool\n}\n\nfunc (st *set[T]) Add(value T) {\n\tst.elements[value] = true\n}\n\nfunc (st *set[T]) Delete(value T) {\n\tdelete(st.elements, value)\n}\n\nfunc (st *set[T]) GetItems() []T {\n\tkeys := make([]T, 0, len(st.elements))\n\tfor k := range st.elements {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\nfunc (st *set[T]) Len() int {\n\treturn len(st.elements)\n}\n\nfunc (st *set[T]) In(value T) bool {\n\tif _, in := st.elements[value]; in {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (st *set[T]) IsSubsetOf(superSet Set[T]) bool {\n\tif st.Len() > superSet.Len() {\n\t\treturn false\n\t}\n\n\tfor _, item := range st.GetItems() {\n\t\tif !superSet.In(item) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (st *set[T]) IsProperSubsetOf(superSet Set[T]) bool {\n\tif st.Len() == superSet.Len() {\n\t\treturn false\n\t}\n\treturn st.IsSubsetOf(superSet)\n}\n\nfunc (st *set[T]) IsSupersetOf(subSet Set[T]) bool {\n\treturn subSet.IsSubsetOf(st)\n}\n\nfunc (st *set[T]) IsProperSupersetOf(subSet Set[T]) bool {\n\tif st.Len() == subSet.Len() {\n\t\treturn false\n\t}\n\treturn st.IsSupersetOf(subSet)\n}\n\nfunc (st *set[T]) Union(st2 Set[T]) Set[T] {\n\tunionSet := New[T]()\n\tfor _, item := range st.GetItems() {\n\t\tunionSet.Add(item)\n\t}\n\tfor _, item := range st2.GetItems() {\n\t\tunionSet.Add(item)\n\t}\n\treturn unionSet\n}\n\nfunc (st *set[T]) Intersection(st2 Set[T]) Set[T] {\n\tintersectionSet := New[T]()\n\tvar minSet, maxSet Set[T]\n\tif st.Len() > st2.Len() {\n\t\tminSet = st2\n\t\tmaxSet = st\n\t} else {\n\t\tminSet = st\n\t\tmaxSet = st2\n\t}\n\tfor _, item := range minSet.GetItems() {\n\t\tif maxSet.In(item) {\n\t\t\tintersectionSet.Add(item)\n\t\t}\n\t}\n\treturn intersectionSet\n}\n\nfunc (st *set[T]) Difference(st2 Set[T]) Set[T] {\n\tdifferenceSet := New[T]()\n\tfor _, item := range st.GetItems() {\n\t\tif !st2.In(item) {\n\t\t\tdifferenceSet.Add(item)\n\t\t}\n\t}\n\treturn differenceSet\n}\n\nfunc (st *set[T]) SymmetricDifference(st2 Set[T]) Set[T] {\n\tsymmetricDifferenceSet := New[T]()\n\tdropSet := New[T]()\n\tfor _, item := range st.GetItems() {\n\t\tif st2.In(item) {\n\t\t\tdropSet.Add(item)\n\t\t} else {\n\t\t\tsymmetricDifferenceSet.Add(item)\n\t\t}\n\t}\n\tfor _, item := range st2.GetItems() {\n\t\tif !dropSet.In(item) {\n\t\t\tsymmetricDifferenceSet.Add(item)\n\t\t}\n\t}\n\treturn symmetricDifferenceSet\n}\n"
  },
  {
    "path": "structure/set/set_test.go",
    "content": "package set\n\nimport (\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\tset := New(1, 2, 3)\n\tif set.Len() != 3 {\n\t\tt.Errorf(\"expecting 3 elements in the set but got %v: %v\", set.Len(), set.GetItems())\n\t}\n\tfor _, n := range []int{1, 2, 3} {\n\t\tif !set.In(n) {\n\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, set.GetItems())\n\t\t}\n\t}\n\tif set.In(5) {\n\t\tt.Errorf(\"expecting 5 not to be present in the set but it was; set is %v\", set.GetItems())\n\t}\n}\n\nfunc TestAdd(t *testing.T) {\n\ttd := []struct {\n\t\tname     string\n\t\tinput    int\n\t\texpElems []int\n\t}{\n\t\t{\"add new element\", 5, []int{1, 2, 3, 5}},\n\t\t{\"add exiting element\", 3, []int{1, 2, 3}},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := New(1, 2, 3)\n\t\t\ts.Add(tc.input)\n\t\t\tif s.Len() != len(tc.expElems) {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", len(tc.expElems), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expElems {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\ttd := []struct {\n\t\tname     string\n\t\tinput    int\n\t\texpElems []int\n\t}{\n\t\t{\"delete exiting element\", 3, []int{1, 2}},\n\t\t{\"delete not existing element\", 5, []int{1, 2, 3}},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := New(1, 2, 3)\n\t\t\ts.Delete(tc.input)\n\t\t\tif s.Len() != len(tc.expElems) {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", len(tc.expElems), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expElems {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsSubsetOf(t *testing.T) {\n\ts1, s2 := New(1, 2, 3), New(1, 2, 3, 4)\n\tif !s1.IsSubsetOf(s2) {\n\t\tt.Errorf(\"expecting %v to be a subset of %v\", s1, s2)\n\t}\n\tif s2.IsSubsetOf(s1) {\n\t\tt.Errorf(\"expecting %v not to be a subset of %v\", s2, s1)\n\t}\n\tif s3 := New(1, 2, 5, 6); s1.IsSubsetOf(s3) {\n\t\tt.Errorf(\"expecting %v not to be a subset of %v\", s1, s3)\n\t}\n}\n\nfunc TestIsProperSubsetOf(t *testing.T) {\n\ts1, s2 := New(1, 2, 3), New(1, 2, 3, 4)\n\tif !s1.IsProperSubsetOf(s2) {\n\t\tt.Errorf(\"expecting %v to be a proper subset of %v\", s1, s2)\n\t}\n\tif s3 := New(3, 2, 1); s1.IsProperSubsetOf(s3) {\n\t\tt.Errorf(\"expecting %v not to be a proper subset of %v\", s1, s3)\n\t}\n}\n\nfunc TestIsSupersetOf(t *testing.T) {\n\ts1, s2 := New(1, 2, 3), New(1, 2, 3, 4)\n\tif !s2.IsSupersetOf(s1) {\n\t\tt.Errorf(\"expecting %v to be a superset of %v\", s2, s1)\n\t}\n\tif s1.IsSupersetOf(s2) {\n\t\tt.Errorf(\"expecting %v not to be a superset of %v\", s1, s2)\n\t}\n\tif s3 := New(1, 2, 5); s2.IsSupersetOf(s3) {\n\t\tt.Errorf(\"expecting %v not to be a superset of %v\", s2, s3)\n\t}\n}\n\nfunc TestIsProperSupersetOf(t *testing.T) {\n\ts1, s2 := New(1, 2, 3), New(1, 2, 3, 4)\n\tif !s2.IsProperSupersetOf(s1) {\n\t\tt.Errorf(\"expecting %v to be a proper superset of %v\", s2, s1)\n\t}\n\tif s3 := New(3, 2, 1); s1.IsProperSupersetOf(s3) {\n\t\tt.Errorf(\"expecting %v not to be a proper superset of %v\", s1, s3)\n\t}\n}\n\nfunc TestUnion(t *testing.T) {\n\ttd := []struct {\n\t\tname   string\n\t\ts1     Set[int]\n\t\ts2     Set[int]\n\t\texpSet Set[int]\n\t}{\n\t\t{\"union of different sets\", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3, 4, 5, 6)},\n\t\t{\"union of sets with elements in common\", New(1, 2, 3), New(1, 2, 4), New(1, 2, 3, 4)},\n\t\t{\"union of same sets\", New(1, 2, 3), New(1, 2, 3), New(1, 2, 3)},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := tc.s1.Union(tc.s2)\n\t\t\tif s.Len() != tc.expSet.Len() {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", tc.expSet.Len(), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expSet.GetItems() {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIntersection(t *testing.T) {\n\ttd := []struct {\n\t\tname   string\n\t\ts1     Set[int]\n\t\ts2     Set[int]\n\t\texpSet Set[int]\n\t}{\n\t\t{\"intersection of different sets\", New(0, 1, 2, 3), New(4, 5, 6), New[int]()},\n\t\t{\"intersection of sets with elements in common\", New(1, 2, 3), New(1, 2, 4), New(1, 2)},\n\t\t{\"intersection of same sets\", New(1, 2, 3), New(1, 2, 3), New(1, 2, 3)},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := tc.s1.Intersection(tc.s2)\n\t\t\tif s.Len() != tc.expSet.Len() {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", tc.expSet.Len(), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expSet.GetItems() {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDifference(t *testing.T) {\n\ttd := []struct {\n\t\tname   string\n\t\ts1     Set[int]\n\t\ts2     Set[int]\n\t\texpSet Set[int]\n\t}{\n\t\t{\"difference of different sets\", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3)},\n\t\t{\"difference of sets with elements in common\", New(1, 2, 3), New(1, 2, 4), New(3)},\n\t\t{\"difference of same sets\", New(1, 2, 3), New(1, 2, 3), New[int]()},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := tc.s1.Difference(tc.s2)\n\t\t\tif s.Len() != tc.expSet.Len() {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", tc.expSet.Len(), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expSet.GetItems() {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSymmetricDifference(t *testing.T) {\n\ttd := []struct {\n\t\tname   string\n\t\ts1     Set[int]\n\t\ts2     Set[int]\n\t\texpSet Set[int]\n\t}{\n\t\t{\"symmetric difference of different sets\", New(1, 2, 3), New(4, 5, 6), New(1, 2, 3, 4, 5, 6)},\n\t\t{\"symmetric difference of sets with elements in common\", New(1, 2, 3), New(1, 2, 4), New(3, 4)},\n\t\t{\"symmetric difference of same sets\", New(1, 2, 3), New(1, 2, 3), New[int]()},\n\t}\n\tfor _, tc := range td {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ts := tc.s1.SymmetricDifference(tc.s2)\n\t\t\tif s.Len() != tc.expSet.Len() {\n\t\t\t\tt.Errorf(\"expecting %d elements in the set but got %d: set is %v\", tc.expSet.Len(), s.Len(), s.GetItems())\n\t\t\t}\n\t\t\tfor _, n := range tc.expSet.GetItems() {\n\t\t\t\tif !s.In(n) {\n\t\t\t\t\tt.Errorf(\"expecting %d to be present in the set but was not; set is %v\", n, s.GetItems())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "structure/set/setexample_test.go",
    "content": "package set\n\nimport (\n\t\"fmt\"\n)\n\nfunc ExampleSet() {\n\n\tset := New(1, 2, 3)\n\tfmt.Println(set.Len()) // 3\n\tset.Add(3)\n\tfmt.Println(set.Len()) // 3\n\tset.Add(4)\n\tfmt.Println(set.Len()) // 4\n\n\t// output:\n\t// 3\n\t// 3\n\t// 4\n}\n"
  },
  {
    "path": "structure/stack/stack_test.go",
    "content": "// Stack Test\n// description: based on `geeksforgeeks` description Stack is a linear data structure which follows a particular order in which the operations are performed.\n//\tThe order may be LIFO(Last In First Out) or FILO(First In Last Out).\n// details:\n// \tStack Data Structure : https://www.geeksforgeeks.org/stack-data-structure-introduction-program/\n// \tStack (abstract data type) : https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see stackarray.go, stacklinkedlist.go, stacklinkedlistwithlist.go\n\npackage stack_test\n\nimport (\n\t\"container/list\"\n\t\"github.com/TheAlgorithms/Go/structure/stack\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n// TestStackLinkedList for testing Stack with LinkedList\nfunc TestStackLinkedList(t *testing.T) {\n\tvar newStack stack.Stack\n\n\tnewStack.Push(1)\n\tnewStack.Push(2)\n\n\tt.Run(\"Stack Push\", func(t *testing.T) {\n\t\tresult := newStack.Show()\n\t\texpected := []any{2, 1}\n\t\tfor x := range result {\n\t\t\tif result[x] != expected[x] {\n\t\t\t\tt.Errorf(\"Stack Push is not work, got %v but expected %v\", result, expected)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Stack isEmpty\", func(t *testing.T) {\n\t\tif newStack.IsEmpty() {\n\t\t\tt.Error(\"Stack isEmpty is returned true but expected false\", newStack.IsEmpty())\n\t\t}\n\n\t})\n\n\tt.Run(\"Stack Length\", func(t *testing.T) {\n\t\tif newStack.Length() != 2 {\n\t\t\tt.Error(\"Stack Length should be 2 but got\", newStack.Length())\n\t\t}\n\t})\n\n\tnewStack.Pop()\n\tpop := newStack.Pop()\n\n\tt.Run(\"Stack Pop\", func(t *testing.T) {\n\t\tif pop != 1 {\n\t\t\tt.Error(\"Stack Pop should return 1 but is returned\", pop)\n\t\t}\n\n\t})\n\n\tnewStack.Push(52)\n\tnewStack.Push(23)\n\tnewStack.Push(99)\n\tt.Run(\"Stack Peek\", func(t *testing.T) {\n\t\tif newStack.Peek() != 99 {\n\t\t\tt.Error(\"Stack Peak should return 99 but got \", newStack.Peek())\n\t\t}\n\t})\n}\n\n// TestStackArray for testing Stack with Array\nfunc TestStackArray(t *testing.T) {\n\tnewStack := stack.NewStack[int]()\n\tt.Run(\"Stack With Array\", func(t *testing.T) {\n\n\t\tnewStack.Push(2)\n\t\tnewStack.Push(3)\n\n\t\tt.Run(\"Stack Push\", func(t *testing.T) {\n\t\t\tvar stackElements []any\n\t\t\tfor i := 0; i < 2; i++ {\n\t\t\t\tpoppedElement := newStack.Pop()\n\t\t\t\tstackElements = append(stackElements, poppedElement)\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual([]any{3, 2}, stackElements) {\n\t\t\t\tt.Errorf(\"Stack Push is not work we expected %v but got %v\", []any{3, 2}, newStack)\n\t\t\t}\n\n\t\t\tnewStack.Push(2)\n\t\t\tnewStack.Push(3)\n\t\t})\n\n\t\tpop := newStack.Pop()\n\n\t\tt.Run(\"Stack Pop\", func(t *testing.T) {\n\t\t\tif newStack.Length() == 2 && pop != 3 {\n\t\t\t\tt.Errorf(\"Stack Pop is not work we expected %v but got %v\", 3, pop)\n\t\t\t}\n\t\t})\n\n\t\tnewStack.Push(2)\n\t\tnewStack.Push(83)\n\n\t\tt.Run(\"Stack Peak\", func(t *testing.T) {\n\t\t\tif newStack.Peek() != 83 {\n\t\t\t\tt.Errorf(\"Stack Peek is not work we expected %v but got %v\", 83, newStack.Peek())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Stack Length\", func(t *testing.T) {\n\t\t\tif newStack.Length() != 3 {\n\t\t\t\tt.Errorf(\"Stack Length is not work we expected %v but got %v\", 3, newStack.Length())\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Stack Empty\", func(t *testing.T) {\n\t\t\tif newStack.IsEmpty() == true {\n\t\t\t\tt.Errorf(\"Stack Empty is not work we expected %v but got %v\", false, newStack.IsEmpty())\n\t\t\t}\n\n\t\t\tnewStack.Pop()\n\t\t\tnewStack.Pop()\n\t\t\tnewStack.Pop()\n\n\t\t\tif newStack.IsEmpty() == false {\n\t\t\t\tt.Errorf(\"Stack Empty is not work we expected %v but got %v\", true, newStack.IsEmpty())\n\t\t\t}\n\t\t})\n\t})\n}\n\n// TestStackLinkedListWithList for testing Stack with Container/List Library (STL)\nfunc TestStackLinkedListWithList(t *testing.T) {\n\tstackList := &stack.SList{\n\t\tStack: list.New(),\n\t}\n\n\tt.Run(\"Stack Push\", func(t *testing.T) {\n\n\t\tstackList.Push(2)\n\t\tstackList.Push(3)\n\n\t\tif stackList.Length() != 2 {\n\t\t\tt.Errorf(\"Stack Push is not work we expected %v but got %v\", 2, stackList.Length())\n\t\t}\n\t})\n\n\tt.Run(\"Stack Pop\", func(t *testing.T) {\n\t\tpop, _ := stackList.Pop()\n\n\t\tif stackList.Length() == 1 && pop != 3 {\n\t\t\tt.Errorf(\"Stack Pop is not work we expected %v but got %v\", 3, pop)\n\t\t}\n\t})\n\n\tt.Run(\"Stack Peak\", func(t *testing.T) {\n\n\t\tstackList.Push(2)\n\t\tstackList.Push(83)\n\t\tpeak, _ := stackList.Peek()\n\t\tif peak != 83 {\n\t\t\tt.Errorf(\"Stack Peak is not work we expected %v but got %v\", 83, peak)\n\t\t}\n\t})\n\n\tt.Run(\"Stack Length\", func(t *testing.T) {\n\t\tif stackList.Length() != 3 {\n\t\t\tt.Errorf(\"Stack Length is not work we expected %v but got %v\", 3, stackList.Length())\n\t\t}\n\t})\n\n\tt.Run(\"Stack Empty\", func(t *testing.T) {\n\t\tif stackList.IsEmpty() == true {\n\t\t\tt.Errorf(\"Stack Empty is not work we expected %v but got %v\", false, stackList.IsEmpty())\n\t\t}\n\n\t\td1, err := stackList.Pop()\n\t\td2, _ := stackList.Pop()\n\t\td3, _ := stackList.Pop()\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"got an unexpected error %v, pop1: %v, pop2: %v, pop3: %v\", err, d1, d2, d3)\n\t\t}\n\n\t\tif stackList.IsEmpty() == false {\n\t\t\tt.Errorf(\"Stack Empty is not work we expected %v but got %v\", true, stackList.IsEmpty())\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/stack/stackarray.go",
    "content": "// Stack Array\n// description: based on `geeksforgeeks` description Stack is a linear data structure which follows a particular order in which the operations are performed.\n//\tThe order may be LIFO(Last In First Out) or FILO(First In Last Out).\n// details:\n// \tStack Data Structure : https://www.geeksforgeeks.org/stack-data-structure-introduction-program/\n// \tStack (abstract data type) : https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see stacklinkedlist.go, stacklinkedlistwithlist.go, stack_test.go\n\npackage stack\n\ntype Array[T any] struct {\n\telements []T\n}\n\n// NewStack creates and returns a new stack.\nfunc NewStack[T any]() *Array[T] {\n\treturn &Array[T]{}\n}\n\n// Push adds an element to the top of the stack.\nfunc (s *Array[T]) Push(value T) {\n\ts.elements = append(s.elements, value)\n}\n\n// Size returns the number of elements in the stack.\nfunc (s *Array[T]) Length() int {\n\treturn len(s.elements)\n}\n\n// Peek returns the top element of the stack without removing it.\nfunc (s *Array[T]) Peek() T {\n\tif s.IsEmpty() {\n\t\tvar zeroValue T\n\t\treturn zeroValue // Stack is empty\n\t}\n\treturn s.elements[len(s.elements)-1]\n}\n\n// IsEmpty returns true if the stack is empty, false otherwise.\nfunc (s *Array[T]) IsEmpty() bool {\n\treturn len(s.elements) == 0\n}\n\n// Pop removes and returns the top element from the stack.\nfunc (s *Array[T]) Pop() T {\n\tif s.IsEmpty() {\n\t\tvar zeroValue T\n\t\treturn zeroValue // Stack is empty\n\t}\n\tindex := len(s.elements) - 1\n\tpopped := s.elements[index]\n\ts.elements = s.elements[:index]\n\treturn popped\n}\n"
  },
  {
    "path": "structure/stack/stacklinkedlist.go",
    "content": "// Stack Linked-List\n// description: based on `geeksforgeeks` description Stack is a linear data structure which follows a particular order in which the operations are performed.\n//\tThe order may be LIFO(Last In First Out) or FILO(First In Last Out).\n// details:\n// \tStack Data Structure : https://www.geeksforgeeks.org/stack-data-structure-introduction-program/\n// \tStack (abstract data type) : https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see stacklinkedlistwithlist.go, stackarray.go, stack_test.go\n\npackage stack\n\n// Node structure\ntype Node struct {\n\tVal  any\n\tNext *Node\n}\n\n// Stack has jost top of node and with length\ntype Stack struct {\n\ttop    *Node\n\tlength int\n}\n\n// push add value to last index\nfunc (ll *Stack) Push(n any) {\n\tnewStack := &Node{} // new node\n\n\tnewStack.Val = n\n\tnewStack.Next = ll.top\n\n\tll.top = newStack\n\tll.length++\n}\n\n// pop remove last item as first output\nfunc (ll *Stack) Pop() any {\n\tresult := ll.top.Val\n\tif ll.top.Next == nil {\n\t\tll.top = nil\n\t} else {\n\t\tll.top.Val, ll.top.Next = ll.top.Next.Val, ll.top.Next.Next\n\t}\n\n\tll.length--\n\treturn result\n}\n\n// isEmpty to check our array is empty or not\nfunc (ll *Stack) IsEmpty() bool {\n\treturn ll.length == 0\n}\n\n// len use to return length of our stack\nfunc (ll *Stack) Length() int {\n\treturn ll.length\n}\n\n// peak return last input value\nfunc (ll *Stack) Peek() any {\n\treturn ll.top.Val\n}\n\n// show all value as an interface array\nfunc (ll *Stack) Show() (in []any) {\n\tcurrent := ll.top\n\n\tfor current != nil {\n\t\tin = append(in, current.Val)\n\t\tcurrent = current.Next\n\t}\n\treturn\n}\n"
  },
  {
    "path": "structure/stack/stacklinkedlistwithlist.go",
    "content": "// Stack Linked-List with standard library (Container/List)\n// description: based on `geeksforgeeks` description Stack is a linear data structure which follows a particular order in which the operations are performed.\n//\tThe order may be LIFO(Last In First Out) or FILO(First In Last Out).\n// details:\n// \tStack Data Structure : https://www.geeksforgeeks.org/stack-data-structure-introduction-program/\n// \tStack (abstract data type) : https://en.wikipedia.org/wiki/Stack_(abstract_data_type)\n// author [Milad](https://github.com/miraddo)\n// see stacklinkedlist.go, stackarray.go, stack_test.go\n\npackage stack\n\nimport (\n\t\"container/list\"\n\t\"fmt\"\n)\n\n// SList is our struct that point to stack with container/list.List library\ntype SList struct {\n\tStack *list.List\n}\n\n// Push add a value into our stack\nfunc (sl *SList) Push(val any) {\n\tsl.Stack.PushFront(val)\n}\n\n// Peak is return last value that insert into our stack\nfunc (sl *SList) Peek() (any, error) {\n\tif !sl.IsEmpty() {\n\t\telement := sl.Stack.Front()\n\t\treturn element.Value, nil\n\t}\n\treturn \"\", fmt.Errorf(\"stack list is empty\")\n}\n\n// Pop is return last value that insert into our stack\n// also it will remove it in our stack\nfunc (sl *SList) Pop() (any, error) {\n\tif !sl.IsEmpty() {\n\t\t// get last element that insert into stack\n\t\telement := sl.Stack.Front()\n\t\t// remove element in stack\n\t\tsl.Stack.Remove(element)\n\t\t// return element value\n\t\treturn element.Value, nil\n\t}\n\treturn \"\", fmt.Errorf(\"stack list is empty\")\n}\n\n// Length return length of our stack\nfunc (sl *SList) Length() int {\n\treturn sl.Stack.Len()\n}\n\n// Empty check our stack has value or not\nfunc (sl *SList) IsEmpty() bool {\n\t// check our stack is empty or not\n\t// if is 0 it means our stack is empty otherwise is not empty\n\treturn sl.Stack.Len() == 0\n}\n"
  },
  {
    "path": "structure/structure_test.go",
    "content": "// Empty test file to keep track of all the tests for the algorithms.\n\npackage structure\n"
  },
  {
    "path": "structure/tree/avl.go",
    "content": "// AVL tree is a self-balancing binary search tree.\n//\n// For more details check out those link below here:\n// Wikipedia article: https://en.wikipedia.org/wiki/AVL_tree\n// see avl.go\n\npackage tree\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/max\"\n)\n\n// Verify Interface Compliance\nvar _ Node[int] = &AVLNode[int]{}\n\n// AVLNode represents a single node in the AVL.\ntype AVLNode[T constraints.Ordered] struct {\n\tkey    T\n\tparent *AVLNode[T]\n\tleft   *AVLNode[T]\n\tright  *AVLNode[T]\n\theight int\n}\n\nfunc (n *AVLNode[T]) Key() T {\n\treturn n.key\n}\n\nfunc (n *AVLNode[T]) Parent() Node[T] {\n\treturn n.parent\n}\n\nfunc (n *AVLNode[T]) Left() Node[T] {\n\treturn n.left\n}\n\nfunc (n *AVLNode[T]) Right() Node[T] {\n\treturn n.right\n}\n\nfunc (n *AVLNode[T]) Height() int {\n\treturn n.height\n}\n\n// AVL represents a AVL tree.\n// By default, _NIL = nil.\ntype AVL[T constraints.Ordered] struct {\n\tRoot *AVLNode[T]\n\t_NIL *AVLNode[T] // a sentinel value for nil\n}\n\n// NewAVL creates a novel AVL tree\nfunc NewAVL[T constraints.Ordered]() *AVL[T] {\n\treturn &AVL[T]{\n\t\tRoot: nil,\n\t\t_NIL: nil,\n\t}\n}\n\n// Empty determines the AVL tree is empty\nfunc (avl *AVL[T]) Empty() bool {\n\treturn avl.Root == avl._NIL\n}\n\n// Push a chain of Node's into the AVL Tree\nfunc (avl *AVL[T]) Push(keys ...T) {\n\tfor _, k := range keys {\n\t\tavl.Root = avl.pushHelper(avl.Root, k)\n\t}\n}\n\n// Delete a Node from the AVL Tree\nfunc (avl *AVL[T]) Delete(key T) bool {\n\tif !avl.Has(key) {\n\t\treturn false\n\t}\n\n\tavl.Root = avl.deleteHelper(avl.Root, key)\n\treturn true\n}\n\n// Get a Node from the AVL Tree\nfunc (avl *AVL[T]) Get(key T) (Node[T], bool) {\n\treturn searchTreeHelper[T](avl.Root, avl._NIL, key)\n}\n\n// Has Determines the tree has the node of Key\nfunc (avl *AVL[T]) Has(key T) bool {\n\t_, ok := searchTreeHelper[T](avl.Root, avl._NIL, key)\n\treturn ok\n}\n\n// PreOrder Traverses the tree in the following order Root --> Left --> Right\nfunc (avl *AVL[T]) PreOrder() []T {\n\ttraversal := make([]T, 0)\n\tpreOrderRecursive[T](avl.Root, avl._NIL, &traversal)\n\treturn traversal\n}\n\n// InOrder Traverses the tree in the following order Left --> Root --> Right\nfunc (avl *AVL[T]) InOrder() []T {\n\treturn inOrderHelper[T](avl.Root, avl._NIL)\n}\n\n// PostOrder traverses the tree in the following order Left --> Right --> Root\nfunc (avl *AVL[T]) PostOrder() []T {\n\ttraversal := make([]T, 0)\n\tpostOrderRecursive[T](avl.Root, avl._NIL, &traversal)\n\treturn traversal\n}\n\n// LevelOrder returns the level order traversal of the tree\nfunc (avl *AVL[T]) LevelOrder() []T {\n\ttraversal := make([]T, 0)\n\tlevelOrderHelper[T](avl.Root, avl._NIL, &traversal)\n\treturn traversal\n}\n\n// AccessNodesByLayer accesses nodes layer by layer (2-D array),  instead of printing the results as 1-D array.\nfunc (avl *AVL[T]) AccessNodesByLayer() [][]T {\n\treturn accessNodeByLayerHelper[T](avl.Root, avl._NIL)\n}\n\n// Depth returns the calculated depth of the AVL tree\nfunc (avl *AVL[T]) Depth() int {\n\treturn calculateDepth[T](avl.Root, avl._NIL, 0)\n}\n\n// Max returns the Max value of the tree\nfunc (avl *AVL[T]) Max() (T, bool) {\n\tret := maximum[T](avl.Root, avl._NIL)\n\tif ret == avl._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Min returns the Min value of the tree\nfunc (avl *AVL[T]) Min() (T, bool) {\n\tret := minimum[T](avl.Root, avl._NIL)\n\tif ret == avl._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Predecessor returns the Predecessor of the node of Key\n// if there is no predecessor, return default value of type T and false\n// otherwise return the Key of predecessor and true\nfunc (avl *AVL[T]) Predecessor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](avl.Root, avl._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn predecessorHelper[T](node, avl._NIL)\n}\n\n// Successor returns the Successor of the node of Key\n// if there is no successor, return default value of type T and false\n// otherwise return the Key of successor and true\nfunc (avl *AVL[T]) Successor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](avl.Root, avl._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn successorHelper[T](node, avl._NIL)\n}\n\nfunc (avl *AVL[T]) pushHelper(root *AVLNode[T], key T) *AVLNode[T] {\n\tif root == avl._NIL {\n\t\treturn &AVLNode[T]{\n\t\t\tkey:    key,\n\t\t\tleft:   avl._NIL,\n\t\t\tright:  avl._NIL,\n\t\t\tparent: avl._NIL,\n\t\t\theight: 1,\n\t\t}\n\t}\n\n\tswitch {\n\tcase key < root.key:\n\t\ttmp := avl.pushHelper(root.left, key)\n\t\ttmp.parent = root\n\t\troot.left = tmp\n\tcase key > root.key:\n\t\ttmp := avl.pushHelper(root.right, key)\n\t\ttmp.parent = root\n\t\troot.right = tmp\n\tdefault:\n\t\treturn root\n\t}\n\n\t// balance the tree\n\troot.height = avl.height(root)\n\tbFactor := avl.balanceFactor(root)\n\tif bFactor > 1 {\n\t\tswitch {\n\t\tcase key < root.left.key:\n\t\t\treturn avl.rightRotate(root)\n\t\tcase key > root.left.key:\n\t\t\troot.left = avl.leftRotate(root.left)\n\t\t\treturn avl.rightRotate(root)\n\t\t}\n\t}\n\n\tif bFactor < -1 {\n\t\tswitch {\n\t\tcase key > root.right.key:\n\t\t\treturn avl.leftRotate(root)\n\t\tcase key < root.right.key:\n\t\t\troot.right = avl.rightRotate(root.right)\n\t\t\treturn avl.leftRotate(root)\n\t\t}\n\t}\n\n\treturn root\n}\n\nfunc (avl *AVL[T]) deleteHelper(root *AVLNode[T], key T) *AVLNode[T] {\n\tif root == avl._NIL {\n\t\treturn root\n\t}\n\n\tswitch {\n\tcase key < root.key:\n\t\ttmp := avl.deleteHelper(root.left, key)\n\t\troot.left = tmp\n\t\tif tmp != avl._NIL {\n\t\t\ttmp.parent = root\n\t\t}\n\tcase key > root.key:\n\t\ttmp := avl.deleteHelper(root.right, key)\n\t\troot.right = tmp\n\t\tif tmp != avl._NIL {\n\t\t\ttmp.parent = root\n\t\t}\n\tdefault:\n\t\tif root.left == avl._NIL || root.right == avl._NIL {\n\t\t\ttmp := root.left\n\t\t\tif root.right != avl._NIL {\n\t\t\t\ttmp = root.right\n\t\t\t}\n\n\t\t\tif tmp == avl._NIL {\n\t\t\t\troot = avl._NIL\n\t\t\t} else {\n\t\t\t\ttmp.parent = root.parent\n\t\t\t\troot = tmp\n\t\t\t}\n\t\t} else {\n\t\t\ttmp := minimum[T](root.right, avl._NIL).(*AVLNode[T])\n\t\t\troot.key = tmp.key\n\t\t\tdel := avl.deleteHelper(root.right, tmp.key)\n\t\t\troot.right = del\n\t\t\tif del != avl._NIL {\n\t\t\t\tdel.parent = root\n\t\t\t}\n\t\t}\n\t}\n\n\tif root == avl._NIL {\n\t\treturn root\n\t}\n\n\t// balance the tree\n\troot.height = avl.height(root)\n\tbFactor := avl.balanceFactor(root)\n\tswitch {\n\tcase bFactor > 1:\n\t\tswitch {\n\t\tcase avl.balanceFactor(root.left) >= 0:\n\t\t\treturn avl.rightRotate(root)\n\t\tdefault:\n\t\t\troot.left = avl.leftRotate(root.left)\n\t\t\treturn avl.rightRotate(root)\n\t\t}\n\tcase bFactor < -1:\n\t\tswitch {\n\t\tcase avl.balanceFactor(root.right) <= 0:\n\t\t\treturn avl.leftRotate(root)\n\t\tdefault:\n\t\t\troot.right = avl.rightRotate(root.right)\n\t\t\treturn avl.leftRotate(root)\n\t\t}\n\t}\n\n\treturn root\n}\n\nfunc (avl *AVL[T]) height(root *AVLNode[T]) int {\n\tif root == avl._NIL {\n\t\treturn 1\n\t}\n\n\tvar leftHeight, rightHeight int\n\tif root.left != avl._NIL {\n\t\tleftHeight = root.left.height\n\t}\n\tif root.right != avl._NIL {\n\t\trightHeight = root.right.height\n\t}\n\treturn 1 + max.Int(leftHeight, rightHeight)\n}\n\n// balanceFactor : negative balance factor means subtree Root is heavy toward Left\n// and positive balance factor means subtree Root is heavy toward Right side\nfunc (avl *AVL[T]) balanceFactor(root *AVLNode[T]) int {\n\tvar leftHeight, rightHeight int\n\tif root.left != avl._NIL {\n\t\tleftHeight = root.left.height\n\t}\n\tif root.right != avl._NIL {\n\t\trightHeight = root.right.height\n\t}\n\treturn leftHeight - rightHeight\n}\n\nfunc (avl *AVL[T]) leftRotate(x *AVLNode[T]) *AVLNode[T] {\n\ty := x.right\n\tyl := y.left\n\ty.left = x\n\tx.right = yl\n\n\tif yl != avl._NIL {\n\t\tyl.parent = x\n\t}\n\n\ty.parent = x.parent\n\tx.parent = y\n\n\tx.height = avl.height(x)\n\ty.height = avl.height(y)\n\treturn y\n}\n\nfunc (avl *AVL[T]) rightRotate(x *AVLNode[T]) *AVLNode[T] {\n\ty := x.left\n\tyr := y.right\n\ty.right = x\n\tx.left = yr\n\n\tif yr != avl._NIL {\n\t\tyr.parent = x\n\t}\n\n\ty.parent = x.parent\n\tx.parent = y\n\n\tx.height = avl.height(x)\n\ty.height = avl.height(y)\n\treturn y\n}\n"
  },
  {
    "path": "structure/tree/avl_test.go",
    "content": "package tree_test\n\nimport (\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n\t\"math/rand\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestAVLPush(t *testing.T) {\n\tt.Run(\"LLRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\ttree.Push(5, 4, 3)\n\n\t\troot := tree.Root\n\t\tif root.Key() != 4 {\n\t\t\tt.Errorf(\"Root should have value = 4, not %v\", root.Key())\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2, not %d\", root.Height())\n\t\t}\n\n\t\tif root.Left().Key() != 3 {\n\t\t\tt.Errorf(\"Left child should have value = 3\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 5 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\t})\n\n\tt.Run(\"LRRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\ttree.Push(5, 3, 4)\n\n\t\troot := tree.Root\n\t\tif root.Key() != 4 {\n\t\t\tt.Errorf(\"Root should have value = 4, not %v\", root.Key())\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2, not %d\", root.Height())\n\t\t}\n\n\t\tif root.Left().Key() != 3 {\n\t\t\tt.Errorf(\"Left child should have value = 3\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 5 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\t})\n\n\tt.Run(\"RRRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\ttree.Push(3)\n\t\ttree.Push(4)\n\t\ttree.Push(5)\n\n\t\troot := tree.Root\n\t\tif root.Key() != 4 {\n\t\t\tt.Errorf(\"Root should have value = 4, not %v\", root.Key())\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2, not %d\", root.Height())\n\t\t}\n\n\t\tif root.Left().Key() != 3 {\n\t\t\tt.Errorf(\"Left child should have value = 3\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 5 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\t})\n\tt.Run(\"RLRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\ttree.Push(3)\n\t\ttree.Push(5)\n\t\ttree.Push(4)\n\n\t\troot := tree.Root\n\t\tif root.Key() != 4 {\n\t\t\tt.Errorf(\"Root should have value = 4\")\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2\")\n\t\t}\n\n\t\tif root.Left().Key() != 3 {\n\t\t\tt.Errorf(\"Left child should have value = 3\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 5 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\t})\n}\n\nfunc TestAVLDelete(t *testing.T) {\n\tt.Run(\"LLRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\tif tree.Delete(5) {\n\t\t\tt.Errorf(\"There is no node, whose value is 5\")\n\t\t}\n\n\t\ttree.Push(5)\n\t\ttree.Push(4)\n\t\ttree.Push(3)\n\t\ttree.Push(2)\n\n\t\tif !tree.Delete(5) {\n\t\t\tt.Errorf(\"There is a node, whose value is 5\")\n\t\t}\n\n\t\tif tree.Delete(50) {\n\t\t\tt.Errorf(\"There is no node, whose value is 50\")\n\t\t}\n\n\t\troot := tree.Root\n\t\tif root.Key() != 3 {\n\t\t\tt.Errorf(\"Root should have value = 3\")\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2\")\n\t\t}\n\n\t\tif root.Left().Key() != 2 {\n\t\t\tt.Errorf(\"Left child should have value = 2\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 4 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\t})\n\n\tt.Run(\"LRRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\n\t\ttree.Push(10)\n\t\ttree.Push(8)\n\t\ttree.Push(8)\n\t\ttree.Push(6)\n\t\ttree.Push(7)\n\n\t\tif !tree.Delete(10) {\n\t\t\tt.Errorf(\"There is a node, whose value is 10\")\n\t\t}\n\n\t\tif tree.Delete(5) {\n\t\t\tt.Errorf(\"There is no node, whose value is 5\")\n\t\t}\n\n\t\troot := tree.Root\n\t\tif root.Key() != 7 {\n\t\t\tt.Errorf(\"Root should have value = 7\")\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2\")\n\t\t}\n\n\t\tif root.Left().Key() != 6 {\n\t\t\tt.Errorf(\"Left child should have value = 6\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 8 {\n\t\t\tt.Errorf(\"Right child should have value = 8\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\n\t})\n\n\tt.Run(\"RRRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\n\t\ttree.Push(2)\n\t\ttree.Push(3)\n\t\ttree.Push(3)\n\t\ttree.Push(4)\n\t\ttree.Push(5)\n\n\t\tif !tree.Delete(2) {\n\t\t\tt.Errorf(\"There is a node, whose value is 2\")\n\t\t}\n\n\t\tif tree.Delete(15) {\n\t\t\tt.Errorf(\"There is no node, whose value is 15\")\n\t\t}\n\n\t\troot := tree.Root\n\t\tif root.Key() != 4 {\n\t\t\tt.Errorf(\"Root should have value = 4\")\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2\")\n\t\t}\n\n\t\tif root.Left().Key() != 3 {\n\t\t\tt.Errorf(\"Left child should have value = 3\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 5 {\n\t\t\tt.Errorf(\"Right child should have value = 5\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\n\t})\n\n\tt.Run(\"RLRotation-Test\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\n\t\ttree.Push(7)\n\t\ttree.Push(6)\n\t\ttree.Push(6)\n\t\ttree.Push(9)\n\t\ttree.Push(8)\n\n\t\ttree.Delete(6)\n\n\t\troot := tree.Root\n\t\tif root.Key() != 8 {\n\t\t\tt.Errorf(\"Root should have value = 8\")\n\t\t}\n\t\tif root.Height() != 2 {\n\t\t\tt.Errorf(\"Height of Root should be = 2\")\n\t\t}\n\n\t\tif root.Left().Key() != 7 {\n\t\t\tt.Errorf(\"Left child should have value = 7\")\n\t\t}\n\t\tif root.Left().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Left child should be 1\")\n\t\t}\n\n\t\tif root.Right().Key() != 9 {\n\t\t\tt.Errorf(\"Right child should have value = 9\")\n\t\t}\n\t\tif root.Right().(*bt.AVLNode[int]).Height() != 1 {\n\t\t\tt.Errorf(\"Height of Right should be 1\")\n\t\t}\n\n\t})\n\n\tt.Run(\"Random Test\", func(t *testing.T) {\n\t\tnums := []int{100, 500, 1000, 10_000}\n\t\tfor _, n := range nums {\n\t\t\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\tnums := rnd.Perm(n)\n\t\t\ttree.Push(nums...)\n\n\t\t\trets := tree.InOrder()\n\t\t\tif !sort.IntsAreSorted(rets) {\n\t\t\t\tt.Error(\"Error with Push\")\n\t\t\t}\n\n\t\t\tif res, ok := tree.Min(); !ok || res != rets[0] {\n\t\t\t\tt.Errorf(\"Error with Min, get %d, want: %d\", res, rets[0])\n\t\t\t}\n\n\t\t\tif res, ok := tree.Max(); !ok || res != rets[n-1] {\n\t\t\t\tt.Errorf(\"Error with Max, get %d, want: %d\", res, rets[n-1])\n\t\t\t}\n\n\t\t\tfor i := 0; i < n-1; i++ {\n\t\t\t\tif ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok {\n\t\t\t\t\tt.Error(\"Error with Successor\")\n\t\t\t\t}\n\t\t\t\tif ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok {\n\t\t\t\t\tt.Error(\"Error with Predecessor\")\n\t\t\t\t}\n\n\t\t\t\tok := tree.Delete(nums[i])\n\t\t\t\trets = tree.InOrder()\n\t\t\t\tif !ok || !sort.IntsAreSorted(rets) {\n\t\t\t\t\tt.Errorf(\"Error With Delete\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/tree/bstree.go",
    "content": "// Binary search tree.\n//\n// For more details check out those links below here:\n// Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree\n// see bstree.go\n\npackage tree\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\n// Verify Interface Compliance\nvar _ Node[int] = &BSNode[int]{}\n\n// BSNode represents a single node in the BinarySearch.\ntype BSNode[T constraints.Ordered] struct {\n\tkey    T\n\tparent *BSNode[T]\n\tleft   *BSNode[T]\n\tright  *BSNode[T]\n}\n\nfunc (n *BSNode[T]) Key() T {\n\treturn n.key\n}\n\nfunc (n *BSNode[T]) Parent() Node[T] {\n\treturn n.parent\n}\n\nfunc (n *BSNode[T]) Left() Node[T] {\n\treturn n.left\n}\n\nfunc (n *BSNode[T]) Right() Node[T] {\n\treturn n.right\n}\n\n// BinarySearch represents a Binary-Search tree.\n// By default, _NIL = nil.\ntype BinarySearch[T constraints.Ordered] struct {\n\tRoot *BSNode[T]\n\t_NIL *BSNode[T] // a sentinel value for nil\n}\n\n// NewBinarySearch creates a novel Binary-Search tree\nfunc NewBinarySearch[T constraints.Ordered]() *BinarySearch[T] {\n\treturn &BinarySearch[T]{\n\t\tRoot: nil,\n\t\t_NIL: nil,\n\t}\n}\n\n// Empty determines the Binary-Search tree is empty\nfunc (t *BinarySearch[T]) Empty() bool {\n\treturn t.Root == t._NIL\n}\n\n// Push a chain of Node's into the BinarySearch\nfunc (t *BinarySearch[T]) Push(keys ...T) {\n\tfor _, key := range keys {\n\t\tt.pushHelper(t.Root, key)\n\t}\n}\n\n// Delete removes the node of val\nfunc (t *BinarySearch[T]) Delete(val T) bool {\n\tnode, ok := t.Get(val)\n\tif !ok {\n\t\treturn false\n\t}\n\tt.deleteHelper(node.(*BSNode[T]))\n\treturn true\n}\n\n// Get a Node from the Binary-Search Tree\nfunc (t *BinarySearch[T]) Get(key T) (Node[T], bool) {\n\treturn searchTreeHelper[T](t.Root, t._NIL, key)\n}\n\n// Has Determines the tree has the node of Key\nfunc (t *BinarySearch[T]) Has(key T) bool {\n\t_, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\treturn ok\n}\n\n// PreOrder Traverses the tree in the following order Root --> Left --> Right\nfunc (t *BinarySearch[T]) PreOrder() []T {\n\ttraversal := make([]T, 0)\n\tpreOrderRecursive[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// InOrder Traverses the tree in the following order Left --> Root --> Right\nfunc (t *BinarySearch[T]) InOrder() []T {\n\treturn inOrderHelper[T](t.Root, t._NIL)\n}\n\n// PostOrder traverses the tree in the following order Left --> Right --> Root\nfunc (t *BinarySearch[T]) PostOrder() []T {\n\ttraversal := make([]T, 0)\n\tpostOrderRecursive[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// LevelOrder returns the level order traversal of the tree\nfunc (t *BinarySearch[T]) LevelOrder() []T {\n\ttraversal := make([]T, 0)\n\tlevelOrderHelper[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// AccessNodesByLayer accesses nodes layer by layer (2-D array),  instead of printing the results as 1-D array.\nfunc (t *BinarySearch[T]) AccessNodesByLayer() [][]T {\n\treturn accessNodeByLayerHelper[T](t.Root, t._NIL)\n}\n\n// Depth returns the calculated depth of a binary search tree\nfunc (t *BinarySearch[T]) Depth() int {\n\treturn calculateDepth[T](t.Root, t._NIL, 0)\n}\n\n// Max returns the Max value of the tree\nfunc (t *BinarySearch[T]) Max() (T, bool) {\n\tret := maximum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Min returns the Min value of the tree\nfunc (t *BinarySearch[T]) Min() (T, bool) {\n\tret := minimum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Predecessor returns the Predecessor of the node of Key\n// if there is no predecessor, return default value of type T and false\n// otherwise return the Key of predecessor and true\nfunc (t *BinarySearch[T]) Predecessor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn predecessorHelper[T](node, t._NIL)\n}\n\n// Successor returns the Successor of the node of Key\n// if there is no successor, return default value of type T and false\n// otherwise return the Key of successor and true\nfunc (t *BinarySearch[T]) Successor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn successorHelper[T](node, t._NIL)\n}\n\nfunc (t *BinarySearch[T]) pushHelper(x *BSNode[T], val T) {\n\ty := t._NIL\n\tfor x != t._NIL {\n\t\ty = x\n\t\tswitch {\n\t\tcase val < x.Key():\n\t\t\tx = x.left\n\t\tcase val > x.Key():\n\t\t\tx = x.right\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n\n\tz := &BSNode[T]{\n\t\tkey:    val,\n\t\tleft:   t._NIL,\n\t\tright:  t._NIL,\n\t\tparent: y,\n\t}\n\tif y == t._NIL {\n\t\tt.Root = z\n\t} else if val < y.key {\n\t\ty.left = z\n\t} else {\n\t\ty.right = z\n\t}\n}\n\nfunc (t *BinarySearch[T]) deleteHelper(z *BSNode[T]) {\n\tswitch {\n\tcase z.left == t._NIL:\n\t\tt.transplant(z, z.right)\n\tcase z.right == t._NIL:\n\t\tt.transplant(z, z.left)\n\tdefault:\n\t\ty := minimum[T](z.right, t._NIL).(*BSNode[T])\n\t\tif y.parent != z {\n\t\t\tt.transplant(y, y.right)\n\t\t\ty.right = z.right\n\t\t\ty.right.parent = y\n\t\t}\n\n\t\tt.transplant(z, y)\n\t\ty.left = z.left\n\t\ty.left.parent = y\n\t}\n}\n\nfunc (t *BinarySearch[T]) transplant(u, v *BSNode[T]) {\n\tswitch {\n\tcase u.parent == t._NIL:\n\t\tt.Root = v\n\tcase u == u.parent.left:\n\t\tu.parent.left = v\n\tdefault:\n\t\tu.parent.right = v\n\t}\n\n\tif v != t._NIL {\n\t\tv.parent = u.parent\n\t}\n}\n"
  },
  {
    "path": "structure/tree/bstree_test.go",
    "content": "package tree_test\n\nimport (\n\t\"math/rand\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n)\n\nfunc TestPush(t *testing.T) {\n\tbst := bt.NewBinarySearch[int]()\n\n\tbst.Push(90)\n\tbst.Push(80)\n\tbst.Push(100)\n\n\tif bst.Root.Key() != 90 {\n\t\tt.Errorf(\"Root should have value = 90\")\n\t}\n\n\tif bst.Root.Left().Key() != 80 {\n\t\tt.Errorf(\"Left child should have value = 80\")\n\t}\n\n\tif bst.Root.Right().Key() != 100 {\n\t\tt.Errorf(\"Right child should have value = 100\")\n\t}\n\n\tif bst.Depth() != 2 {\n\t\tt.Errorf(\"tree should have depth = 1\")\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tt.Run(\"Delete a node with no child\", func(t *testing.T) {\n\t\tbst := bt.NewBinarySearch[int]()\n\n\t\tbst.Push(90)\n\t\tbst.Push(80)\n\t\tbst.Push(80)\n\t\tbst.Push(100)\n\n\t\tif !bst.Delete(100) {\n\t\t\tt.Errorf(\"There is a node, whose value is 100\")\n\t\t}\n\n\t\tif bst.Delete(105) {\n\t\t\tt.Errorf(\"There is no node, whose value is 105\")\n\t\t}\n\n\t\troot := bst.Root\n\t\tif root.Key() != 90 {\n\t\t\tt.Errorf(\"Root should have value = 90\")\n\t\t}\n\n\t\tif root.Left().Key() != 80 {\n\t\t\tt.Errorf(\"Left child should have value = 80\")\n\t\t}\n\n\t\tif root.Right().(*bt.BSNode[int]) != nil {\n\t\t\tt.Errorf(\"Right child should have value = nil\")\n\t\t}\n\n\t\tif bst.Depth() != 2 {\n\t\t\tt.Errorf(\"Depth should have value = 2\")\n\t\t}\n\n\t\tbst.Delete(80)\n\n\t\tif root.Key() != 90 {\n\t\t\tt.Errorf(\"Root should have value = 90\")\n\t\t}\n\n\t\tif root.Left().(*bt.BSNode[int]) != nil {\n\t\t\tt.Errorf(\"Left child should have value = nil\")\n\t\t}\n\n\t\tif bst.Depth() != 1 {\n\t\t\tt.Errorf(\"Depth should have value = 1\")\n\t\t}\n\t})\n\n\tt.Run(\"Delete a node with one child\", func(t *testing.T) {\n\t\tbst := bt.NewBinarySearch[int]()\n\n\t\tbst.Push(90)\n\t\tbst.Push(80)\n\t\tbst.Push(100)\n\t\tbst.Push(70)\n\n\t\tif bst.Delete(102) {\n\t\t\tt.Errorf(\"There is no node, whose value is 102\")\n\t\t}\n\n\t\tif !bst.Delete(80) {\n\t\t\tt.Errorf(\"There is a node, whose value is 80\")\n\t\t}\n\n\t\troot := bst.Root\n\t\tif root.Key() != 90 {\n\t\t\tt.Errorf(\"Root should have value = 90\")\n\t\t}\n\n\t\tif root.Right().Key() != 100 {\n\t\t\tt.Errorf(\"Right child should have value = 100\")\n\t\t}\n\n\t\tif root.Left().Key() != 70 {\n\t\t\tt.Errorf(\"Left child should have value = 70\")\n\t\t}\n\n\t\tif bst.Depth() != 2 {\n\t\t\tt.Errorf(\"Depth should have value = 2\")\n\t\t}\n\t})\n\n\tt.Run(\"Delete a node with two children\", func(t *testing.T) {\n\t\tbst := bt.NewBinarySearch[int]()\n\n\t\tbst.Push(90)\n\t\tbst.Push(80)\n\t\tbst.Push(100)\n\t\tbst.Push(70)\n\t\tbst.Push(85)\n\n\t\tif !bst.Delete(80) {\n\t\t\tt.Errorf(\"There is a node, whose value is 80\")\n\t\t}\n\n\t\tif bst.Delete(102) {\n\t\t\tt.Errorf(\"There is no node, whose value is 102\")\n\t\t}\n\n\t\troot := bst.Root\n\t\tif root.Key() != 90 {\n\t\t\tt.Errorf(\"Root should have value = 90\")\n\t\t}\n\n\t\tif root.Left().Key() != 85 {\n\t\t\tt.Errorf(\"Left child should have value = 85\")\n\t\t}\n\n\t\tif root.Right().Key() != 100 {\n\t\t\tt.Errorf(\"Right child should have value = 100\")\n\t\t}\n\n\t\tif bst.Depth() != 3 {\n\t\t\tt.Errorf(\"Depth should have value = 3\")\n\t\t}\n\t})\n\n\tt.Run(\"Random Test\", func(t *testing.T) {\n\t\ttests := []int{100, 500, 1000, 10_000}\n\t\tfor _, n := range tests {\n\t\t\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\tnums := rnd.Perm(n)\n\t\t\ttree.Push(nums...)\n\n\t\t\trets := tree.InOrder()\n\t\t\tif !sort.IntsAreSorted(rets) {\n\t\t\t\tt.Error(\"Error with Push\")\n\t\t\t}\n\n\t\t\tif res, ok := tree.Min(); !ok || res != rets[0] {\n\t\t\t\tt.Errorf(\"Error with Min, get %d, want: %d\", res, rets[0])\n\t\t\t}\n\n\t\t\tif res, ok := tree.Max(); !ok || res != rets[n-1] {\n\t\t\t\tt.Errorf(\"Error with Max, get %d, want: %d\", res, rets[n-1])\n\t\t\t}\n\n\t\t\tfor i := 0; i < n-1; i++ {\n\t\t\t\tif ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok {\n\t\t\t\t\tt.Error(\"Error with Successor\")\n\t\t\t\t}\n\n\t\t\t\tif ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok {\n\t\t\t\t\tt.Error(\"Error with Predecessor\")\n\t\t\t\t}\n\n\t\t\t\tok := tree.Delete(nums[i])\n\t\t\t\trets = tree.InOrder()\n\t\t\t\tif !ok || !sort.IntsAreSorted(rets) {\n\t\t\t\t\tt.Errorf(\"Error With Delete\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "structure/tree/btree.go",
    "content": "// B-tree is a self balancing tree that promotes data locality.\n// For more details, see https://en.wikipedia.org/wiki/B-tree\n\npackage tree\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\ntype BTreeNode[T constraints.Ordered] struct {\n\tkeys     []T\n\tchildren []*BTreeNode[T]\n\tnumKeys  int\n\tisLeaf   bool\n}\n\ntype BTree[T constraints.Ordered] struct {\n\troot    *BTreeNode[T]\n\tmaxKeys int\n}\n\nfunc minKeys(maxKeys int) int {\n\treturn (maxKeys - 1) / 2\n}\n\nfunc NewBTreeNode[T constraints.Ordered](maxKeys int, isLeaf bool) *BTreeNode[T] {\n\tif maxKeys <= 0 {\n\t\tpanic(\"BTree maxKeys cannot be zero\")\n\t}\n\treturn &BTreeNode[T]{\n\t\tkeys:     make([]T, maxKeys),\n\t\tchildren: make([]*BTreeNode[T], maxKeys+1),\n\t\tisLeaf:   isLeaf,\n\t}\n}\n\nfunc NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] {\n\tif maxKeys <= 2 {\n\t\tpanic(\"Must be >= 3 keys\")\n\t}\n\treturn &BTree[T]{\n\t\troot:    nil,\n\t\tmaxKeys: maxKeys,\n\t}\n}\n\nfunc (node *BTreeNode[T]) Verify(tree *BTree[T]) {\n\tminKeys := minKeys(tree.maxKeys)\n\tif node != tree.root && node.numKeys < minKeys {\n\t\tpanic(\"node has too few keys\")\n\t} else if node.numKeys > tree.maxKeys {\n\t\tpanic(\"node has too many keys\")\n\t}\n}\n\nfunc (node *BTreeNode[T]) IsFull(maxKeys int) bool {\n\treturn node.numKeys == maxKeys\n}\n\nfunc (node *BTreeNode[T]) Search(key T) bool {\n\ti := 0\n\tfor ; i < node.numKeys; i++ {\n\t\tif key == node.keys[i] {\n\t\t\treturn true\n\t\t}\n\t\tif key < node.keys[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\tif node.isLeaf {\n\t\treturn false\n\t}\n\treturn node.children[i].Search(key)\n}\n\nfunc (tree *BTree[T]) Search(key T) bool {\n\tif tree.root == nil {\n\t\treturn false\n\t}\n\treturn tree.root.Search(key)\n}\n\nfunc (node *BTreeNode[T]) InsertKeyChild(key T, child *BTreeNode[T]) {\n\ti := node.numKeys\n\tnode.children[i+1] = node.children[i]\n\tfor ; i > 0; i-- {\n\t\tif key > node.keys[i-1] {\n\t\t\tnode.keys[i] = key\n\t\t\tnode.children[i] = child\n\t\t\tbreak\n\t\t}\n\t\tnode.keys[i] = node.keys[i-1]\n\t\tnode.children[i] = node.children[i-1]\n\t}\n\tif i == 0 {\n\t\tnode.keys[0] = key\n\t\tnode.children[0] = child\n\t}\n\tnode.numKeys++\n}\n\nfunc (node *BTreeNode[T]) Append(key T, child *BTreeNode[T]) {\n\tnode.keys[node.numKeys] = key\n\tnode.children[node.numKeys+1] = child\n\tnode.numKeys++\n}\n\n// Add all of other's keys starting from idx and children starting from idx + 1\nfunc (node *BTreeNode[T]) Concat(other *BTreeNode[T], idx int) {\n\tfor i := 0; i < other.numKeys-idx; i++ {\n\t\tnode.keys[node.numKeys+i] = other.keys[i+idx]\n\t\tnode.children[node.numKeys+i+1] = other.children[i+idx+1]\n\t}\n\tnode.numKeys += other.numKeys - idx\n}\n\n// Transform:\n//\n//\tA B\n//\t |\n//\n// a b c d\n//\n// Into:\n//\n//\tA c B\n//\t / \\\n//\n// a b  d\nfunc (parent *BTreeNode[T]) Split(idx int, maxKeys int) {\n\tchild := parent.children[idx]\n\tmidKeyIndex := maxKeys / 2\n\trightChild := NewBTreeNode[T](maxKeys, child.isLeaf)\n\trightChild.Concat(child, midKeyIndex+1)\n\trightChild.children[0] = child.children[midKeyIndex+1]\n\n\t// Reuse child as the left node\n\tchild.numKeys = midKeyIndex\n\n\t// Insert the child's mid index to the parent\n\tfor i := parent.numKeys; i > idx; i-- {\n\t\tparent.keys[i] = parent.keys[i-1]\n\t\tparent.children[i+1] = parent.children[i]\n\t}\n\tparent.keys[idx] = child.keys[midKeyIndex]\n\tparent.children[idx] = child\n\tparent.children[idx+1] = rightChild\n\tparent.numKeys += 1\n}\n\nfunc (node *BTreeNode[T]) InsertNonFull(tree *BTree[T], key T) {\n\tnode.Verify(tree)\n\tif node.IsFull(tree.maxKeys) {\n\t\tpanic(\"Called InsertNonFull() with a full node\")\n\t}\n\n\tif node.isLeaf {\n\t\t// Node is a leaf. Directly insert the key.\n\t\tnode.InsertKeyChild(key, nil)\n\t\treturn\n\t}\n\n\t// Find the child node to insert into\n\ti := 0\n\tfor ; i < node.numKeys; i++ {\n\t\tif key < node.keys[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif node.children[i].IsFull(tree.maxKeys) {\n\t\tnode.Split(i, tree.maxKeys)\n\t\tif key > node.keys[i] {\n\t\t\ti++\n\t\t}\n\t}\n\tnode.children[i].InsertNonFull(tree, key)\n}\n\nfunc (tree *BTree[T]) Insert(key T) {\n\tif tree.root == nil {\n\t\ttree.root = NewBTreeNode[T](tree.maxKeys, true)\n\t\ttree.root.keys[0] = key\n\t\ttree.root.numKeys = 1\n\t\treturn\n\t}\n\n\tif tree.root.IsFull(tree.maxKeys) {\n\t\tnewRoot := NewBTreeNode[T](tree.maxKeys, false)\n\t\tnewRoot.numKeys = 0\n\t\tnewRoot.children[0] = tree.root\n\t\tnewRoot.Split(0, tree.maxKeys)\n\t\ttree.root = newRoot\n\t}\n\ttree.root.InsertNonFull(tree, key)\n}\n\nfunc (node *BTreeNode[T]) DeleteIthKey(i int) {\n\tif i >= node.numKeys {\n\t\tpanic(\"deleting out of bounds key\")\n\t}\n\tfor j := i; j < node.numKeys-1; j++ {\n\t\tnode.keys[j] = node.keys[j+1]\n\t\tnode.children[j+1] = node.children[j+2]\n\t}\n\tnode.numKeys--\n}\n\n// Transform:\n//\n//\tA B C\n//\t / \\\n//\ta   b\n//\n// Into:\n//\n//\tA C\n//\t |\n//\n// a B c\nfunc (node *BTreeNode[T]) Merge(idx int) {\n\tif node.isLeaf {\n\t\tpanic(\"cannot merge when leaf node is parent\")\n\t}\n\tleft := node.children[idx]\n\tright := node.children[idx+1]\n\tleft.Append(node.keys[idx], right.children[0])\n\tleft.Concat(right, 0)\n\tnode.DeleteIthKey(idx)\n}\n\nfunc (node *BTreeNode[T]) Min() T {\n\tif node.isLeaf {\n\t\treturn node.keys[0]\n\t}\n\treturn node.children[0].Min()\n}\n\nfunc (node *BTreeNode[T]) Max() T {\n\tif node.isLeaf {\n\t\treturn node.keys[node.numKeys-1]\n\t}\n\treturn node.children[node.numKeys].Max()\n}\n\nfunc (node *BTreeNode[T]) Delete(tree *BTree[T], key T) {\n\tnode.Verify(tree)\n\tif node.isLeaf {\n\t\t// Case 1: Node is a leaf. Directly delete the key.\n\t\tfor i := 0; i < node.numKeys; i++ {\n\t\t\tif key == node.keys[i] {\n\t\t\t\tnode.DeleteIthKey(i)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tminKeys := minKeys(tree.maxKeys)\n\ti := 0\n\tfor ; i < node.numKeys; i++ {\n\t\tif key == node.keys[i] {\n\t\t\t// Case 2: key exists in a non-leaf node\n\t\t\tleft := node.children[i]\n\t\t\tright := node.children[i+1]\n\t\t\tif left.numKeys > minKeys {\n\t\t\t\t// Replace the key we want to delete with the max key from the left\n\t\t\t\t// subtree. Then delete that key from the left subtree.\n\t\t\t\t//  A B C\n\t\t\t\t//   /\n\t\t\t\t// a b c\n\t\t\t\t//\n\t\t\t\t// If we want to delete `B`, then replace `B` with `c`, and delete `c` in the subtree.\n\t\t\t\t//  A c C\n\t\t\t\t//   /\n\t\t\t\t// a b\n\t\t\t\treplacementKey := left.Max()\n\t\t\t\tnode.keys[i] = replacementKey\n\t\t\t\tleft.Delete(tree, replacementKey)\n\t\t\t} else if right.numKeys > minKeys {\n\t\t\t\t// Replace the key we want to delete with the min key from the right\n\t\t\t\t// subtree. Then delete that key in the right subtree. Mirrors the\n\t\t\t\t// transformation above for replacing from the left subtree.\n\t\t\t\treplacementKey := right.Min()\n\t\t\t\tnode.keys[i] = replacementKey\n\t\t\t\tright.Delete(tree, replacementKey)\n\t\t\t} else {\n\t\t\t\t// Both left and right subtrees have the minimum number of keys. Merge\n\t\t\t\t// the left tree, the deleted key, and the right tree together into the\n\t\t\t\t// left tree. Then recursively delete the key in the left tree.\n\t\t\t\tif left.numKeys != minKeys || right.numKeys != minKeys {\n\t\t\t\t\tpanic(\"nodes should not have less than the minimum number of keys\")\n\t\t\t\t}\n\t\t\t\tnode.Merge(i)\n\t\t\t\tleft.Delete(tree, key)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif key < node.keys[i] {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Case 3: key may exist in a child node.\n\tchild := node.children[i]\n\tif child.numKeys == minKeys {\n\t\t// Before we recurse into the child node, make sure it has more than\n\t\t// the minimum number of keys.\n\t\tif i > 0 && node.children[i-1].numKeys > minKeys {\n\t\t\t// Take a key from the left sibling\n\t\t\t// Transform:\n\t\t\t//  A  B  C\n\t\t\t//   /   \\\n\t\t\t// a b    c\n\t\t\t//\n\t\t\t// Into:\n\t\t\t//  A  b  C\n\t\t\t//   /   \\\n\t\t\t//  a    B c\n\t\t\tleft := node.children[i-1]\n\t\t\tchild.InsertKeyChild(node.keys[i-1], left.children[left.numKeys])\n\t\t\tnode.keys[i-1] = left.keys[left.numKeys-1]\n\t\t\tleft.numKeys--\n\t\t} else if i < node.numKeys && node.children[i+1].numKeys > minKeys {\n\t\t\t// Take a key from the right sibling. Mirrors the transformation above for taking a key from the left sibling.\n\t\t\tright := node.children[i+1]\n\t\t\tchild.Append(node.keys[i], right.children[0])\n\t\t\tnode.keys[i] = right.keys[0]\n\t\t\tright.children[0] = right.children[1]\n\t\t\tright.DeleteIthKey(0)\n\t\t} else {\n\t\t\tif i == 0 {\n\t\t\t\t// Merge with right sibling\n\t\t\t\tnode.Merge(i)\n\t\t\t} else {\n\t\t\t\t// Merge with left sibling\n\t\t\t\tnode.Merge(i - 1)\n\t\t\t\tchild = node.children[i-1]\n\t\t\t}\n\t\t}\n\t}\n\tif child.numKeys == minKeys {\n\t\tpanic(\"cannot delete key from node with minimum number of keys\")\n\t}\n\tchild.Delete(tree, key)\n}\n\nfunc (tree *BTree[T]) Delete(key T) {\n\tif tree.root == nil {\n\t\treturn\n\t}\n\ttree.root.Delete(tree, key)\n\tif tree.root.numKeys == 0 {\n\t\ttree.root = tree.root.children[0]\n\t}\n}\n"
  },
  {
    "path": "structure/tree/btree_test.go",
    "content": "package tree_test\n\nimport (\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n\t\"math/rand\"\n\t\"testing\"\n)\n\nfunc TestBTreeIncreasing(t *testing.T) {\n\tmaxKeysCases := []int{4, 16}\n\tsizes := []int{100, 0xBA5, 0xF00}\n\tfor _, maxKeys := range maxKeysCases {\n\t\tfor _, size := range sizes {\n\t\t\ttree := bt.NewBTree[int](maxKeys)\n\t\t\tif tree.Search(0) {\n\t\t\t\tt.Errorf(\"Tree expected to contain 0\")\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\ttree.Insert(i)\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tif !tree.Search(i) {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tree.Search(size + 1) {\n\t\t\t\tt.Errorf(\"Tree not expected to contain %d\", size+1)\n\t\t\t}\n\n\t\t\tfor i := 0; i < size; i += 5 {\n\t\t\t\ttree.Delete(i)\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\thasKey := tree.Search(i)\n\t\t\t\tif i%5 == 0 && hasKey {\n\t\t\t\t\tt.Errorf(\"Tree not expected to contain %d\", i)\n\t\t\t\t} else if i%5 != 0 && !hasKey {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestBTreeDecreasing(t *testing.T) {\n\tmaxKeysCases := []int{4, 16}\n\tsizes := []int{100, 1000}\n\tfor _, maxKeys := range maxKeysCases {\n\t\tfor _, size := range sizes {\n\t\t\ttree := bt.NewBTree[int](maxKeys)\n\t\t\tif tree.Search(0) {\n\t\t\t\tt.Errorf(\"Tree expected to contain 0\")\n\t\t\t}\n\t\t\tfor i := size - 1; i >= 0; i-- {\n\t\t\t\ttree.Insert(i)\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tif !tree.Search(i) {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tree.Search(size + 1) {\n\t\t\t\tt.Errorf(\"Tree not expected to contain %d\", size+1)\n\t\t\t}\n\n\t\t\tfor i := 0; i < size; i += 5 {\n\t\t\t\ttree.Delete(i)\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\thasKey := tree.Search(i)\n\t\t\t\tif i%5 == 0 && hasKey {\n\t\t\t\t\tt.Errorf(\"Tree not expected to contain %d\", i)\n\t\t\t\t} else if i%5 != 0 && !hasKey {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestBTreeRandom(t *testing.T) {\n\tmaxKeysCases := []int{4, 16}\n\tsizes := []int{100, 0xBA5, 0xF00}\n\tfor _, maxKeys := range maxKeysCases {\n\t\tfor _, size := range sizes {\n\t\t\trnd := rand.New(rand.NewSource(0))\n\t\t\ttree := bt.NewBTree[int](maxKeys)\n\t\t\tnums := rnd.Perm(size)\n\t\t\tif tree.Search(0) {\n\t\t\t\tt.Errorf(\"Tree expected to contain 0\")\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\ttree.Insert(nums[i])\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tif !tree.Search(nums[i]) {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", nums[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor i := 0; i < size; i += 5 {\n\t\t\t\ttree.Delete(nums[i])\n\t\t\t}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\thasKey := tree.Search(nums[i])\n\t\t\t\tif i%5 == 0 && hasKey {\n\t\t\t\t\tt.Errorf(\"Tree not expected to contain %d\", i)\n\t\t\t\t} else if i%5 != 0 && !hasKey {\n\t\t\t\t\tt.Errorf(\"Tree expected to contain %d\", i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestBTreeDeleteEverything(t *testing.T) {\n\ttree := bt.NewBTree[int](4)\n\tsize := 128\n\tfor i := 0; i < size; i++ {\n\t\ttree.Insert(i)\n\t}\n\tfor i := 0; i < size; i++ {\n\t\ttree.Delete(i)\n\t}\n\ttree.Delete(-1)\n\ttree.Delete(1000)\n\n\tfor i := 0; i < size; i++ {\n\t\tif tree.Search(i) {\n\t\t\tt.Errorf(\"Tree not expected to contain %d\", i)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "structure/tree/example_test.go",
    "content": "package tree_test\n\nimport (\n\t\"fmt\"\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"testing\"\n\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n)\n\ntype TestTree[T constraints.Ordered] interface {\n\tPush(...T)\n\tDelete(T) bool\n\tGet(T) (bt.Node[T], bool)\n\tEmpty() bool\n\tHas(T) bool\n\tDepth() int\n\tMax() (T, bool)\n\tMin() (T, bool)\n\tPredecessor(T) (T, bool)\n\tSuccessor(T) (T, bool)\n\tPreOrder() []T\n\tInOrder() []T\n\tPostOrder() []T\n\tLevelOrder() []T\n\tAccessNodesByLayer() [][]T\n}\n\n// BinarySearch, AVL and RB have completed the `TestTree` interface.\nvar (\n\t_ TestTree[int] = (*bt.BinarySearch[int])(nil)\n\t_ TestTree[int] = (*bt.AVL[int])(nil)\n\t_ TestTree[int] = (*bt.RB[int])(nil)\n)\n\nvar tree TestTree[int]\n\nfunc TestBinarySearch(t *testing.T) {\n\ttree = bt.NewBinarySearch[int]()\n\n\tif tree.Empty() {\n\t\tt.Log(\"Binary Search Tree is empty now.\")\n\t}\n\n\ttree.Push(1, 4, 10)\n\ttree.Push(-8)\n\tnums := []int{87, 18, 10, -34}\n\ttree.Push(nums...)\n\ttree.Push(4) // duplicate key, dismiss it\n\n\tif tree.Has(4) {\n\t\tt.Logf(\"There is a node of 4\")\n\t}\n\n\tif n, ok := tree.Get(10); ok {\n\t\tt.Logf(\"node of 10: %T\", n)\n\t}\n\n\tif ret, ok := tree.Min(); ok {\n\t\tt.Logf(\"tree.Min() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Max(); ok {\n\t\tt.Logf(\"tree.Max() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Predecessor(1); ok {\n\t\tt.Logf(\"tree.Preducessor(1) = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Successor(18); ok {\n\t\tt.Logf(\"tree.Successor(18) = %v\", ret)\n\t}\n\n\tfmt.Println(tree.InOrder())\n\tfmt.Println(tree.AccessNodesByLayer())\n\n\ttree.Delete(18)\n\tfmt.Println(\"Delete 18\")\n\tfmt.Println(tree.InOrder())\n}\n\nfunc TestAVL(t *testing.T) {\n\ttree = bt.NewAVL[int]()\n\n\tif tree.Empty() {\n\t\tt.Log(\"AVL Tree is empty now.\")\n\t}\n\n\ttree.Push(1, 4, 10)\n\ttree.Push(-8)\n\tnums := []int{87, 18, 10, -34}\n\ttree.Push(nums...)\n\ttree.Push(4) // duplicate key, dismiss it\n\n\tif tree.Has(4) {\n\t\tt.Logf(\"There is a node of 4\")\n\t}\n\n\tif n, ok := tree.Get(10); ok {\n\t\tt.Logf(\"node of 10: %T\", n)\n\t}\n\n\tif ret, ok := tree.Min(); ok {\n\t\tt.Logf(\"tree.Min() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Max(); ok {\n\t\tt.Logf(\"tree.Max() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Predecessor(1); ok {\n\t\tt.Logf(\"tree.Preducessor(1) = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Successor(18); ok {\n\t\tt.Logf(\"tree.Successor(18) = %v\", ret)\n\t}\n\n\tfmt.Println(tree.InOrder())\n\tfmt.Println(tree.AccessNodesByLayer())\n\n\ttree.Delete(18)\n\tfmt.Println(\"Delete 18\")\n\tfmt.Println(tree.InOrder())\n}\n\nfunc TestRB(t *testing.T) {\n\ttree = bt.NewRB[int]()\n\n\tif tree.Empty() {\n\t\tt.Log(\"RB Tree is empty now.\")\n\t}\n\n\ttree.Push(1, 4, 10)\n\ttree.Push(-8)\n\tnums := []int{87, 18, 10, -34}\n\ttree.Push(nums...)\n\ttree.Push(4) // duplicate key, dismiss it\n\n\tif tree.Has(4) {\n\t\tt.Logf(\"There is a node of 4\")\n\t}\n\n\tif n, ok := tree.Get(10); ok {\n\t\tt.Logf(\"node of 10: %T\", n)\n\t}\n\n\tif ret, ok := tree.Min(); ok {\n\t\tt.Logf(\"tree.Min() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Max(); ok {\n\t\tt.Logf(\"tree.Max() = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Predecessor(1); ok {\n\t\tt.Logf(\"tree.Preducessor(1) = %v\", ret)\n\t}\n\n\tif ret, ok := tree.Successor(18); ok {\n\t\tt.Logf(\"tree.Successor(18) = %v\", ret)\n\t}\n\n\tfmt.Println(tree.InOrder())\n\tfmt.Println(tree.AccessNodesByLayer())\n}\n"
  },
  {
    "path": "structure/tree/rbtree.go",
    "content": "// Red-Black Tree is a kind of self-balancing binary search tree.\n// Each node stores \"color\" (\"red\" or \"black\"), used to ensure that the tree remains balanced during insertions and deletions.\n//\n// For more details check out those links below here:\n// Programiz article : https://www.programiz.com/dsa/red-black-tree\n// Wikipedia article: https://en.wikipedia.org/wiki/Red_black_tree\n// authors [guuzaa](https://github.com/guuzaa)\n// see rbtree.go\n\npackage tree\n\nimport \"github.com/TheAlgorithms/Go/constraints\"\n\ntype Color byte\n\nconst (\n\tRed Color = iota\n\tBlack\n)\n\n// Verify Interface Compliance\nvar _ Node[int] = &RBNode[int]{}\n\n// RBNode represents a single node in the RB.\ntype RBNode[T constraints.Ordered] struct {\n\tkey    T\n\tparent *RBNode[T]\n\tleft   *RBNode[T]\n\tright  *RBNode[T]\n\tcolor  Color\n}\n\nfunc (n *RBNode[T]) Key() T {\n\treturn n.key\n}\n\nfunc (n *RBNode[T]) Parent() Node[T] {\n\treturn n.parent\n}\n\nfunc (n *RBNode[T]) Left() Node[T] {\n\treturn n.left\n}\n\nfunc (n *RBNode[T]) Right() Node[T] {\n\treturn n.right\n}\n\n// RB represents a Red-Black tree.\n// By default, _NIL = leaf, a dummy variable.\ntype RB[T constraints.Ordered] struct {\n\tRoot *RBNode[T]\n\t_NIL *RBNode[T] // a sentinel value for nil\n}\n\n// NewRB creates a new Red-Black Tree\nfunc NewRB[T constraints.Ordered]() *RB[T] {\n\tleaf := &RBNode[T]{color: Black, left: nil, right: nil}\n\tleaf.parent = leaf\n\treturn &RB[T]{\n\t\tRoot: leaf,\n\t\t_NIL: leaf,\n\t}\n}\n\n// Empty determines the Red-Black tree is empty\nfunc (t *RB[T]) Empty() bool {\n\treturn t.Root == t._NIL\n}\n\n// Push a chain of Node's into the Red-Black Tree\nfunc (t *RB[T]) Push(keys ...T) {\n\tfor _, key := range keys {\n\t\tt.pushHelper(t.Root, key)\n\t}\n}\n\n// Delete a node of Red-Black Tree\n// Returns false if the node does not exist, otherwise returns true.\nfunc (t *RB[T]) Delete(data T) bool {\n\treturn t.deleteHelper(t.Root, data)\n}\n\n// Get a Node from the Red-Black Tree\nfunc (t *RB[T]) Get(key T) (Node[T], bool) {\n\treturn searchTreeHelper[T](t.Root, t._NIL, key)\n}\n\n// Has Determines the tree has the node of Key\nfunc (t *RB[T]) Has(key T) bool {\n\t_, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\treturn ok\n}\n\n// PreOrder Traverses the tree in the following order Root --> Left --> Right\nfunc (t *RB[T]) PreOrder() []T {\n\ttraversal := make([]T, 0)\n\tpreOrderRecursive[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// InOrder Traverses the tree in the following order Left --> Root --> Right\nfunc (t *RB[T]) InOrder() []T {\n\treturn inOrderHelper[T](t.Root, t._NIL)\n}\n\n// PostOrder traverses the tree in the following order Left --> Right --> Root\nfunc (t *RB[T]) PostOrder() []T {\n\ttraversal := make([]T, 0)\n\tpostOrderRecursive[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// LevelOrder returns the level order traversal of the tree\nfunc (t *RB[T]) LevelOrder() []T {\n\ttraversal := make([]T, 0)\n\tlevelOrderHelper[T](t.Root, t._NIL, &traversal)\n\treturn traversal\n}\n\n// AccessNodesByLayer accesses nodes layer by layer (2-D array),  instead of printing the results as 1-D array.\nfunc (t *RB[T]) AccessNodesByLayer() [][]T {\n\treturn accessNodeByLayerHelper[T](t.Root, t._NIL)\n}\n\n// Depth returns the calculated depth of a Red-Black tree\nfunc (t *RB[T]) Depth() int {\n\treturn calculateDepth[T](t.Root, t._NIL, 0)\n}\n\n// Max returns the Max value of the tree\nfunc (t *RB[T]) Max() (T, bool) {\n\tret := maximum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Min returns the Min value of the tree\nfunc (t *RB[T]) Min() (T, bool) {\n\tret := minimum[T](t.Root, t._NIL)\n\tif ret == t._NIL {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn ret.Key(), true\n}\n\n// Predecessor returns the Predecessor of the node of Key\n// if there is no predecessor, return default value of type T and false\n// otherwise return the Key of predecessor and true\nfunc (t *RB[T]) Predecessor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn predecessorHelper[T](node, t._NIL)\n}\n\n// Successor returns the Successor of the node of Key\n// if there is no successor, return default value of type T and false\n// otherwise return the Key of successor and true\nfunc (t *RB[T]) Successor(key T) (T, bool) {\n\tnode, ok := searchTreeHelper[T](t.Root, t._NIL, key)\n\tif !ok {\n\t\tvar dft T\n\t\treturn dft, ok\n\t}\n\treturn successorHelper[T](node, t._NIL)\n}\n\nfunc (t *RB[T]) pushHelper(x *RBNode[T], key T) {\n\ty := t._NIL\n\tfor x != t._NIL {\n\t\ty = x\n\t\tswitch {\n\t\tcase key < x.Key():\n\t\t\tx = x.left\n\t\tcase key > x.Key():\n\t\t\tx = x.right\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n\n\tnode := &RBNode[T]{\n\t\tkey:    key,\n\t\tleft:   t._NIL,\n\t\tright:  t._NIL,\n\t\tparent: y,\n\t\tcolor:  Red,\n\t}\n\tif y == t._NIL {\n\t\tt.Root = node\n\t} else if node.key < y.key {\n\t\ty.left = node\n\t} else {\n\t\ty.right = node\n\t}\n\n\tif node.parent == t._NIL {\n\t\tnode.color = Black\n\t\treturn\n\t}\n\n\tif node.parent.parent == t._NIL {\n\t\treturn\n\t}\n\n\tt.pushFix(node)\n}\n\nfunc (t *RB[T]) leftRotate(x *RBNode[T]) {\n\ty := x.right\n\tx.right = y.left\n\n\tif y.left != t._NIL {\n\t\ty.left.parent = x\n\t}\n\n\ty.parent = x.parent\n\tif x.parent == t._NIL {\n\t\tt.Root = y\n\t} else if x == x.parent.left {\n\t\tx.parent.left = y\n\t} else {\n\t\tx.parent.right = y\n\t}\n\n\ty.left = x\n\tx.parent = y\n}\n\nfunc (t *RB[T]) rightRotate(x *RBNode[T]) {\n\ty := x.left\n\tx.left = y.right\n\tif y.right != t._NIL {\n\t\ty.right.parent = x\n\t}\n\n\ty.parent = x.parent\n\tif x.parent == t._NIL {\n\t\tt.Root = y\n\t} else if x == y.parent.right {\n\t\ty.parent.right = y\n\t} else {\n\t\ty.parent.left = y\n\t}\n\n\ty.right = x\n\tx.parent = y\n}\n\nfunc (t *RB[T]) pushFix(k *RBNode[T]) {\n\tfor k.parent.color == Red {\n\t\tif k.parent == k.parent.parent.right {\n\t\t\tu := k.parent.parent.left\n\t\t\tif u.color == Red {\n\t\t\t\tu.color = Black\n\t\t\t\tk.parent.color = Black\n\t\t\t\tk.parent.parent.color = Red\n\t\t\t\tk = k.parent.parent\n\t\t\t} else {\n\t\t\t\tif k == k.parent.left {\n\t\t\t\t\tk = k.parent\n\t\t\t\t\tt.rightRotate(k)\n\t\t\t\t}\n\t\t\t\tk.parent.color = Black\n\t\t\t\tk.parent.parent.color = Red\n\t\t\t\tt.leftRotate(k.parent.parent)\n\t\t\t}\n\t\t} else {\n\t\t\tu := k.parent.parent.right\n\t\t\tif u.color == Red {\n\t\t\t\tu.color = Black\n\t\t\t\tk.parent.color = Black\n\t\t\t\tk.parent.parent.color = Red\n\t\t\t\tk = k.parent.parent\n\t\t\t} else {\n\t\t\t\tif k == k.parent.right {\n\t\t\t\t\tk = k.parent\n\t\t\t\t\tt.leftRotate(k)\n\t\t\t\t}\n\t\t\t\tk.parent.color = Black\n\t\t\t\tk.parent.parent.color = Red\n\t\t\t\tt.rightRotate(k.parent.parent)\n\t\t\t}\n\t\t}\n\t\tif k == t.Root {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tt.Root.color = Black\n}\n\nfunc (t *RB[T]) deleteHelper(node *RBNode[T], key T) bool {\n\tz := t._NIL\n\tfor node != t._NIL {\n\t\tswitch {\n\t\tcase node.key == key:\n\t\t\tz = node\n\t\t\tfallthrough\n\t\tcase node.key <= key:\n\t\t\tnode = node.right\n\t\tcase node.key > key:\n\t\t\tnode = node.left\n\t\t}\n\t}\n\n\tif z == t._NIL {\n\t\treturn false\n\t}\n\n\tvar x *RBNode[T]\n\ty := z\n\tyOriginColor := y.color\n\tif z.left == t._NIL {\n\t\tx = z.right\n\t\tt.transplant(z, z.right)\n\t} else if z.right == t._NIL {\n\t\tx = z.left\n\t\tt.transplant(z, z.left)\n\t} else {\n\t\ty = minimum[T](z.right, t._NIL).(*RBNode[T])\n\t\tyOriginColor = y.color\n\t\tx = y.right\n\t\tif y.parent == z {\n\t\t\tx.parent = y\n\t\t} else {\n\t\t\tt.transplant(y, y.right)\n\t\t\ty.right = z.right\n\t\t\ty.right.parent = y\n\t\t}\n\n\t\tt.transplant(z, y)\n\t\ty.left = z.left\n\t\ty.left.parent = y\n\t\ty.color = z.color\n\t}\n\n\tif yOriginColor == Black {\n\t\tt.deleteFix(x)\n\t}\n\n\treturn true\n}\n\nfunc (t *RB[T]) deleteFix(x *RBNode[T]) {\n\tvar s *RBNode[T]\n\tfor x != t.Root && x.color == Black {\n\t\tif x == x.parent.left {\n\t\t\ts = x.parent.right\n\t\t\tif s.color == Red {\n\t\t\t\ts.color = Black\n\t\t\t\tx.parent.color = Red\n\t\t\t\tt.leftRotate(x.parent)\n\t\t\t\ts = x.parent.right\n\t\t\t}\n\n\t\t\tif s.left.color == Black && s.right.color == Black {\n\t\t\t\ts.color = Red\n\t\t\t\tx = x.parent\n\t\t\t} else {\n\t\t\t\tif s.right.color == Black {\n\t\t\t\t\ts.left.color = Black\n\t\t\t\t\ts.color = Red\n\t\t\t\t\tt.rightRotate(s)\n\t\t\t\t\ts = x.parent.right\n\t\t\t\t}\n\n\t\t\t\ts.color = x.parent.color\n\t\t\t\tx.parent.color = Black\n\t\t\t\ts.right.color = Black\n\t\t\t\tt.leftRotate(x.parent)\n\t\t\t\tx = t.Root\n\t\t\t}\n\t\t} else {\n\t\t\ts = x.parent.left\n\t\t\tif s.color == Red {\n\t\t\t\ts.color = Black\n\t\t\t\tx.parent.color = Red\n\t\t\t\tt.rightRotate(x.parent)\n\t\t\t\ts = x.parent.left\n\t\t\t}\n\n\t\t\tif s.right.color == Black && s.left.color == Black {\n\t\t\t\ts.color = Red\n\t\t\t\tx = x.parent\n\t\t\t} else {\n\t\t\t\tif s.left.color == Black {\n\t\t\t\t\ts.right.color = Black\n\t\t\t\t\ts.color = Red\n\t\t\t\t\tt.leftRotate(s)\n\t\t\t\t\ts = x.parent.left\n\t\t\t\t}\n\n\t\t\t\ts.color = x.parent.color\n\t\t\t\tx.parent.color = Black\n\t\t\t\ts.left.color = Black\n\t\t\t\tt.rightRotate(x.parent)\n\t\t\t\tx = t.Root\n\t\t\t}\n\t\t}\n\t}\n\n\tx.color = Black\n}\n\nfunc (t *RB[T]) transplant(u, v *RBNode[T]) {\n\tswitch {\n\tcase u.parent == t._NIL:\n\t\tt.Root = v\n\tcase u == u.parent.left:\n\t\tu.parent.left = v\n\tdefault:\n\t\tu.parent.right = v\n\t}\n\n\tv.parent = u.parent\n}\n"
  },
  {
    "path": "structure/tree/rbtree_test.go",
    "content": "package tree_test\n\nimport (\n\t\"math/rand\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n)\n\nfunc TestRBTreePush(t *testing.T) {\n\ttree := bt.NewRB[int]()\n\n\tret := tree.InOrder()\n\n\tif !sort.IntsAreSorted(ret) || len(ret) != 0 {\n\t\tt.Errorf(\"Error with Push: %v\", ret)\n\t}\n\n\tif r, ok := tree.Min(); ok {\n\t\tt.Errorf(\"Error with Min: %v\", r)\n\t}\n\n\tif r, ok := tree.Max(); ok {\n\t\tt.Errorf(\"Error with Max: %v\", r)\n\t}\n\n\tnums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 1 << 32}\n\n\ttree.Push(nums...)\n\n\tret = tree.InOrder()\n\n\tif !sort.IntsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Push: %v\", ret)\n\t}\n\n\tif r, ok := tree.Min(); !ok || ret[0] != r {\n\t\tt.Errorf(\"Error with Min: %v\", r)\n\t}\n\n\tif r, ok := tree.Max(); !ok || ret[len(ret)-1] != r {\n\t\tt.Errorf(\"Error with Max: %v\", r)\n\t}\n}\n\nfunc TestRBTreeDelete(t *testing.T) {\n\ttree := bt.NewRB[int]()\n\tvar ok bool\n\n\tnums := []int{10, 8, 88, 888, 4, 1<<63 - 1, -(1 << 62), 188, -188, 4, 88, 1 << 32}\n\ttree.Push(nums...)\n\n\tok = tree.Delete(188)\n\n\tif ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Delete: %v\", ret)\n\t}\n\n\tok = tree.Delete(188)\n\tif ret := tree.InOrder(); ok || !sort.IntsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Delete: %v\", ret)\n\t}\n\n\tok = tree.Delete(1<<63 - 1)\n\tif ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Delete: %v\", ret)\n\t}\n\n\tok = tree.Delete(4)\n\tif ret := tree.InOrder(); !ok || !sort.IntsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Delete: %v\", ret)\n\t}\n\n\tif ret, ok := tree.Max(); !ok || ret != (1<<32) {\n\t\tt.Errorf(\"Error with Delete, max: %v, want: %v\", ret, (1 << 32))\n\t}\n\n\tif ret, ok := tree.Min(); !ok || ret != -(1<<62) {\n\t\tt.Errorf(\"Error with Delete, min: %v, want: %v\", ret, (1 << 32))\n\t}\n}\n\nfunc TestRBTree(t *testing.T) {\n\ttestcases := []int{100, 200, 1000, 10000}\n\tfor _, n := range testcases {\n\t\trnd := rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\ttree := bt.NewRB[int]()\n\t\tnums := rnd.Perm(n)\n\t\ttree.Push(nums...)\n\n\t\trets := tree.InOrder()\n\t\tif !sort.IntsAreSorted(rets) {\n\t\t\tt.Error(\"Error with Push\")\n\t\t}\n\n\t\tif res, ok := tree.Min(); !ok || res != rets[0] {\n\t\t\tt.Errorf(\"Error with Min, get %d, want: %d\", res, rets[0])\n\t\t}\n\n\t\tif res, ok := tree.Max(); !ok || res != rets[n-1] {\n\t\t\tt.Errorf(\"Error with Max, get %d, want: %d\", res, rets[n-1])\n\t\t}\n\n\t\tfor i := 0; i < n-1; i++ {\n\t\t\tif ret, ok := tree.Successor(rets[0]); ret != rets[1] || !ok {\n\t\t\t\tt.Error(\"Error with Successor\")\n\t\t\t}\n\t\t\tif ret, ok := tree.Predecessor(rets[1]); ret != rets[0] || !ok {\n\t\t\t\tt.Error(\"Error with Predecessor\")\n\t\t\t}\n\n\t\t\tok := tree.Delete(nums[i])\n\t\t\trets = tree.InOrder()\n\t\t\tif !ok || !sort.IntsAreSorted(rets) {\n\t\t\t\tt.Errorf(\"Error With Delete\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestRBTreeString(t *testing.T) {\n\ttree := bt.NewRB[string]()\n\n\tif tree.Has(\"Golang\") {\n\t\tt.Errorf(\"Error with Has when T is string.\")\n\t}\n\n\tstrs := []string{\"Hello\", \"World\", \"Golang\", \"Python\", \"Rust\", \"C\", \"JavaScript\", \"Haskell\", \"Pascal\", \"ZZ\"}\n\tfor _, str := range strs {\n\t\ttree.Push(str)\n\t}\n\n\tif !tree.Has(\"Golang\") {\n\t\tt.Errorf(\"Error with Has when T is string.\")\n\t}\n\n\tif tree.Has(\"Pasc\") {\n\t\tt.Errorf(\"Error with Has when T is string.\")\n\t}\n\n\tif ok := tree.Delete(\"Hello\"); !ok {\n\t\tt.Errorf(\"Error with Delete when T is string.\")\n\t}\n\n\tif ok := tree.Delete(\"Pasc\"); ok {\n\t\tt.Errorf(\"Error with Delete when T is string.\")\n\t}\n\n\tif tree.Has(\"Hello\") {\n\t\tt.Errorf(\"Error with Has when T is string.\")\n\t}\n\n\tret := tree.InOrder()\n\tif !sort.StringsAreSorted(ret) {\n\t\tt.Errorf(\"Error with Push when T is string\")\n\t}\n\n\tif ret, ok := tree.Min(); !ok || ret != \"C\" {\n\t\tt.Errorf(\"Error with Min when T is string\")\n\t}\n\n\tif ret, ok := tree.Max(); !ok || ret != \"ZZ\" {\n\t\tt.Errorf(\"Error with Max when T is string\")\n\t}\n}\n"
  },
  {
    "path": "structure/tree/tree.go",
    "content": "// Binary-Search tree is the tree, with the key of each internal node\n// being greater than keys in the respective node's left subtree\n// and less than the ones in its right subtree.\n\n// For more details check out those links below here:\n// Wikipedia article: https://en.wikipedia.org/wiki/Binary_search_tree\n// authors [guuzaa](https://github.com/guuzaa)\npackage tree\n\nimport (\n\t\"github.com/TheAlgorithms/Go/constraints\"\n\t\"github.com/TheAlgorithms/Go/math/max\"\n)\n\ntype Node[T constraints.Ordered] interface {\n\tKey() T\n\tParent() Node[T]\n\tLeft() Node[T]\n\tRight() Node[T]\n}\n\n// The following is a collection of helper functions for BinarySearch, AVL and RB.\n\nfunc accessNodeByLayerHelper[T constraints.Ordered](root, nilNode Node[T]) [][]T {\n\tif root == nilNode {\n\t\treturn [][]T{}\n\t}\n\tvar q []Node[T]\n\tvar n Node[T]\n\tvar idx = 0\n\tq = append(q, root)\n\tvar res [][]T\n\n\tfor len(q) != 0 {\n\t\tres = append(res, []T{})\n\t\tqLen := len(q)\n\t\tfor i := 0; i < qLen; i++ {\n\t\t\tn, q = q[0], q[1:]\n\t\t\tres[idx] = append(res[idx], n.Key())\n\t\t\tif n.Left() != nilNode {\n\t\t\t\tq = append(q, n.Left())\n\t\t\t}\n\t\t\tif n.Right() != nilNode {\n\t\t\t\tq = append(q, n.Right())\n\t\t\t}\n\t\t}\n\t\tidx++\n\t}\n\treturn res\n}\n\nfunc searchTreeHelper[T constraints.Ordered](node, nilNode Node[T], key T) (Node[T], bool) {\n\tif node == nilNode {\n\t\treturn node, false\n\t}\n\n\tif key == node.Key() {\n\t\treturn node, true\n\t}\n\tif key < node.Key() {\n\t\treturn searchTreeHelper(node.Left(), nilNode, key)\n\t}\n\treturn searchTreeHelper(node.Right(), nilNode, key)\n}\n\nfunc inOrderHelper[T constraints.Ordered](node, nilNode Node[T]) []T {\n\tvar stack []Node[T]\n\tvar ret []T\n\n\tfor node != nilNode || len(stack) > 0 {\n\t\tfor node != nilNode {\n\t\t\tstack = append(stack, node)\n\t\t\tnode = node.Left()\n\t\t}\n\n\t\tnode = stack[len(stack)-1]\n\t\tstack = stack[:len(stack)-1]\n\t\tret = append(ret, node.Key())\n\t\tnode = node.Right()\n\t}\n\n\treturn ret\n}\n\nfunc preOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) {\n\tif n == nilNode {\n\t\treturn\n\t}\n\n\t*traversal = append(*traversal, n.Key())\n\tpreOrderRecursive(n.Left(), nilNode, traversal)\n\tpreOrderRecursive(n.Right(), nilNode, traversal)\n\n}\n\nfunc postOrderRecursive[T constraints.Ordered](n, nilNode Node[T], traversal *[]T) {\n\tif n == nilNode {\n\t\treturn\n\t}\n\n\tpostOrderRecursive(n.Left(), nilNode, traversal)\n\tpostOrderRecursive(n.Right(), nilNode, traversal)\n\t*traversal = append(*traversal, n.Key())\n}\n\nfunc calculateDepth[T constraints.Ordered](n, nilNode Node[T], depth int) int {\n\tif n == nilNode {\n\t\treturn depth\n\t}\n\n\treturn max.Int(calculateDepth(n.Left(), nilNode, depth+1), calculateDepth(n.Right(), nilNode, depth+1))\n}\n\nfunc minimum[T constraints.Ordered](node, nilNode Node[T]) Node[T] {\n\tif node == nilNode {\n\t\treturn node\n\t}\n\n\tfor node.Left() != nilNode {\n\t\tnode = node.Left()\n\t}\n\treturn node\n}\n\nfunc maximum[T constraints.Ordered](node, nilNode Node[T]) Node[T] {\n\tif node == nilNode {\n\t\treturn node\n\t}\n\n\tfor node.Right() != nilNode {\n\t\tnode = node.Right()\n\t}\n\treturn node\n}\n\nfunc levelOrderHelper[T constraints.Ordered](root, nilNode Node[T], traversal *[]T) {\n\tvar q []Node[T] // queue\n\tvar tmp Node[T]\n\n\tq = append(q, root)\n\n\tfor len(q) != 0 {\n\t\ttmp, q = q[0], q[1:]\n\t\t*traversal = append(*traversal, tmp.Key())\n\t\tif tmp.Left() != nilNode {\n\t\t\tq = append(q, tmp.Left())\n\t\t}\n\n\t\tif tmp.Right() != nilNode {\n\t\t\tq = append(q, tmp.Right())\n\t\t}\n\t}\n}\n\nfunc predecessorHelper[T constraints.Ordered](node, nilNode Node[T]) (T, bool) {\n\tif node.Left() != nilNode {\n\t\treturn maximum(node.Left(), nilNode).Key(), true\n\t}\n\n\tp := node.Parent()\n\tfor p != nilNode && node == p.Left() {\n\t\tnode = p\n\t\tp = p.Parent()\n\t}\n\n\tif p == nilNode {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn p.Key(), true\n}\n\nfunc successorHelper[T constraints.Ordered](node, nilNode Node[T]) (T, bool) {\n\tif node.Right() != nilNode {\n\t\treturn minimum(node.Right(), nilNode).Key(), true\n\t}\n\n\tp := node.Parent()\n\tfor p != nilNode && node == p.Right() {\n\t\tnode = p\n\t\tp = p.Parent()\n\t}\n\n\tif p == nilNode {\n\t\tvar dft T\n\t\treturn dft, false\n\t}\n\treturn p.Key(), true\n}\n"
  },
  {
    "path": "structure/tree/tree_test.go",
    "content": "package tree_test\n\nimport (\n\t\"math/rand\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\n\tbt \"github.com/TheAlgorithms/Go/structure/tree\"\n)\n\nfunc TestTreeGetOrHas(t *testing.T) {\n\thelper := func(tree TestTree[int], nums []int) {\n\t\ttree.Push(nums...)\n\t\tfor _, num := range nums {\n\t\t\tif !tree.Has(num) {\n\t\t\t\tt.Errorf(\"Error with Has or Push method\")\n\t\t\t}\n\t\t}\n\n\t\tmin, _ := tree.Min()\n\t\tmax, _ := tree.Max()\n\n\t\tif _, ok := tree.Get(min - 1); ok {\n\t\t\tt.Errorf(\"Error with Get method\")\n\t\t}\n\n\t\tif _, ok := tree.Get(max + 1); ok {\n\t\t\tt.Errorf(\"Error with Get method\")\n\t\t}\n\t}\n\n\tlens := []int{100, 1_000, 10_000, 100_000}\n\tfor _, ll := range lens {\n\t\tnums := rand.Perm(ll)\n\t\tt.Run(\"Test Binary Search Tree\", func(t *testing.T) {\n\t\t\tbsTree := bt.NewBinarySearch[int]()\n\t\t\thelper(bsTree, nums)\n\t\t})\n\n\t\tt.Run(\"Test Red-Black Tree\", func(t *testing.T) {\n\t\t\trbTree := bt.NewRB[int]()\n\t\t\thelper(rbTree, nums)\n\t\t})\n\n\t\tt.Run(\"Test AVL Tree\", func(t *testing.T) {\n\t\t\tavlTree := bt.NewAVL[int]()\n\t\t\thelper(avlTree, nums)\n\t\t})\n\t}\n}\n\nfunc TestTreePreOrder(t *testing.T) {\n\tt.Run(\"Test for Binary-Search Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{90, 80, 70, 1, 21, 31, 41, 51, 61, 71, 85, 100, 95, 105}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"Error with PreOrder\")\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{70, 41, 21, 1, 31, 51, 61, 90, 80, 71, 85, 100, 95, 105}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 3, 2, 1, 5, 4, 6, 9, 8, 10}},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"Error with PreOrder\")\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 70, 85, 100, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, []int{80, 41, 21, 1, 31, 61, 51, 70, 71, 90, 85, 100, 95, 105}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 5, 3, 2, 1, 4, 6, 9, 8, 10}},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttree := bt.NewRB[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PreOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"Error with PreOrder\")\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTreeInOrder(t *testing.T) {\n\tlens := []int{100, 1_000, 10_000, 100_000}\n\tfor _, ll := range lens {\n\t\tnums := rand.Perm(ll)\n\n\t\tt.Run(\"Test Binary Search Tree\", func(t *testing.T) {\n\t\t\tbsTree := bt.NewBinarySearch[int]()\n\t\t\tbsTree.Push(nums...)\n\t\t\tif ret := bsTree.InOrder(); !sort.IntsAreSorted(ret) {\n\t\t\t\tt.Errorf(\"Error with InOrder\")\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Test Red-Black Tree\", func(t *testing.T) {\n\t\t\trbTree := bt.NewRB[int]()\n\t\t\trbTree.Push(nums...)\n\t\t\tif ret := rbTree.InOrder(); !sort.IntsAreSorted(ret) {\n\t\t\t\tt.Errorf(\"Error with InOrder\")\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Test AVL Tree\", func(t *testing.T) {\n\t\t\tavlTree := bt.NewAVL[int]()\n\t\t\tavlTree.Push(nums...)\n\t\t\tif ret := avlTree.InOrder(); !sort.IntsAreSorted(ret) {\n\t\t\t\tt.Errorf(\"Error with InOrder\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTreePostOrder(t *testing.T) {\n\tt.Run(\"Test for Binary-Search Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{61, 51, 41, 31, 21, 1, 71, 70, 85, 80, 95, 105, 100, 90}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with Post\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{1, 31, 21, 61, 51, 41, 71, 85, 80, 95, 105, 100, 90, 70}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 6, 5, 3, 8, 10, 9, 7}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with PostOrder\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{70, 85, 80, 95, 105, 100, 90}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{1, 31, 21, 51, 71, 70, 61, 41, 85, 95, 105, 100, 90, 80}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{1, 2, 4, 3, 6, 5, 8, 10, 9, 7}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewRB[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.PostOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with PostOrder\", i)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTreeLevelOrder(t *testing.T) {\n\tt.Run(\"Test for Binary-Search Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{90, 80, 100, 70, 85, 95, 105, 1, 71, 21, 31, 41, 51, 61}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with LevelOrder\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{70, 41, 90, 21, 51, 80, 100, 1, 31, 61, 71, 85, 95, 105}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 3, 9, 2, 5, 8, 10, 1, 4, 6}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with LevelOrder\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  []int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, []int{90, 80, 100, 70, 85, 95, 105}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[]int{80, 41, 90, 21, 61, 85, 100, 1, 31, 51, 70, 95, 105, 71}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, []int{7, 5, 9, 3, 6, 8, 10, 2, 4, 1}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewRB[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.LevelOrder(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with LevelOrder %v\", i, ret)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTreeMinAndMax(t *testing.T) {\n\thelper := func(tree TestTree[int], nums []int) {\n\t\tll := len(nums)\n\t\tif _, ok := tree.Min(); ok {\n\t\t\tt.Errorf(\"Error with Min method.\")\n\t\t}\n\t\tif _, ok := tree.Max(); ok {\n\t\t\tt.Errorf(\"Error with Max method.\")\n\t\t}\n\t\ttree.Push(nums...)\n\t\tif min, ok := tree.Min(); !ok || min != nums[0] {\n\t\t\tt.Errorf(\"Error with Min method.\")\n\t\t}\n\t\tif max, ok := tree.Max(); !ok || max != nums[ll-1] {\n\t\t\tt.Errorf(\"Error with Max method.\")\n\t\t}\n\t}\n\n\tlens := []int{500, 1_000, 10_000}\n\tfor _, ll := range lens {\n\t\tnums := rand.Perm(ll)\n\t\tsort.Ints(nums)\n\n\t\tt.Run(\"Test Binary Search Tree\", func(t *testing.T) {\n\t\t\thelper(bt.NewBinarySearch[int](), nums)\n\t\t})\n\n\t\tt.Run(\"Test Red-Black Tree\", func(t *testing.T) {\n\t\t\thelper(bt.NewRB[int](), nums)\n\t\t})\n\n\t\tt.Run(\"Test AVL Tree\", func(t *testing.T) {\n\t\t\thelper(bt.NewAVL[int](), nums)\n\t\t})\n\t}\n}\n\nfunc TestTreeDepth(t *testing.T) {\n\tt.Run(\"Test for Binary-Search Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  int\n\t\t}{\n\t\t\t{[]int{}, 0},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, 3},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 9},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 10},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.Depth(); ret != tt.want {\n\t\t\t\tt.Errorf(\"Error with Depth\")\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  int\n\t\t}{\n\t\t\t{[]int{}, 0},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, 3},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 4},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 4},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.Depth(); ret != tt.want {\n\t\t\t\tt.Errorf(\"#%d Error with Depth\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  int\n\t\t}{\n\t\t\t{[]int{}, 0},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, 3},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71}, 5},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 5},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewRB[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.Depth(); ret != tt.want {\n\t\t\t\tt.Errorf(\"#%d Error with Depth\", i)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTreeAccessNodesByLayer(t *testing.T) {\n\tt.Run(\"Test for Binary-Search Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  [][]int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[][]int{{90}, {80, 100}, {70, 85, 95, 105}, {1, 71}, {21}, {31}, {41}, {51}, {61}}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{10}, {9}, {8}, {7}, {6}, {5}, {4}, {3}, {2}, {1}}},\n\t\t\t{[]int{}, [][]int{}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewBinarySearch[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with AccessNoedsByLayer\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  [][]int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[][]int{{70}, {41, 90}, {21, 51, 80, 100}, {1, 31, 61, 71, 85, 95, 105}}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{7}, {3, 9}, {2, 5, 8, 10}, {1, 4, 6}}},\n\t\t\t{[]int{}, [][]int{}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewAVL[int]()\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with AccessNoedsByLayer\", i)\n\t\t\t}\n\t\t}\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tinput []int\n\t\t\twant  [][]int\n\t\t}{\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105}, [][]int{{90}, {80, 100}, {70, 85, 95, 105}}},\n\t\t\t{[]int{90, 80, 100, 70, 85, 95, 105, 1, 21, 31, 41, 51, 61, 71},\n\t\t\t\t[][]int{{80}, {41, 90}, {21, 61, 85, 100}, {1, 31, 51, 70, 95, 105}, {71}}},\n\t\t\t{[]int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, [][]int{{7}, {5, 9}, {3, 6, 8, 10}, {2, 4}, {1}}},\n\t\t\t{[]int{}, [][]int{}},\n\t\t}\n\t\tfor i, tt := range tests {\n\t\t\ttree := bt.NewRB[int]()\n\t\t\tt.Log(reflect.TypeOf(tree).String() == \"*tree.RB[int]\")\n\t\t\ttree.Push(tt.input...)\n\t\t\tif ret := tree.AccessNodesByLayer(); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"#%d Error with AccessNoedsByLayer, %v\", i, ret)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestTreePredecessorAndSuccessor(t *testing.T) {\n\thelper := func(tree TestTree[int]) {\n\t\tnums := []int{10, 8, 88, 888, 4, -1, 100}\n\t\ttree.Push(nums...)\n\t\tif ret, ok := tree.Predecessor(100); !ok || ret != 88 {\n\t\t\tt.Error(\"Error with Predecessor\")\n\t\t}\n\n\t\tif _, ok := tree.Predecessor(-1); ok {\n\t\t\tt.Error(\"Error with Predecessor\")\n\t\t}\n\n\t\ttree.Push(-100)\n\t\tif ret, ok := tree.Predecessor(-1); !ok || ret != -100 {\n\t\t\tt.Error(\"Error with Predecessor\")\n\t\t}\n\n\t\tif _, ok := tree.Predecessor(-12); ok {\n\t\t\tt.Error(\"Error with Predecessor\")\n\t\t}\n\n\t\tif ret, ok := tree.Predecessor(4); !ok || ret != -1 {\n\t\t\tt.Error(\"Error with Predecessor\")\n\t\t}\n\n\t\tif ret, ok := tree.Successor(4); !ok || ret != 8 {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif ret, ok := tree.Successor(8); !ok || ret != 10 {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif ret, ok := tree.Successor(88); !ok || ret != 100 {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif ret, ok := tree.Successor(100); !ok || ret != 888 {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\ttree.Delete(888)\n\t\tif _, ok := tree.Successor(100); ok {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif ret, ok := tree.Successor(-1); !ok || ret != 4 {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif _, ok := tree.Successor(888); ok {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\n\t\tif _, ok := tree.Successor(188); ok {\n\t\t\tt.Error(\"Error with Successor\")\n\t\t}\n\t}\n\n\tt.Run(\"Test for Binary Search Tree\", func(t *testing.T) {\n\t\ttree := bt.NewBinarySearch[int]()\n\t\thelper(tree)\n\t})\n\n\tt.Run(\"Test for Red-Black Tree\", func(t *testing.T) {\n\t\ttree := bt.NewRB[int]()\n\t\thelper(tree)\n\t})\n\n\tt.Run(\"Test for AVL Tree\", func(t *testing.T) {\n\t\ttree := bt.NewAVL[int]()\n\t\thelper(tree)\n\t})\n}\n\n// Benchmark the comparisons between BST, AVL and RB Tree\nconst testNum = 10_000\n\nfunc BenchmarkBSTree_Insert(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewBinarySearch[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkBSTree_Has(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewBinarySearch[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Has(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkBSTree_Delete(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewBinarySearch[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Delete(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkRBTree_Insert(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewRB[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkRBTree_Has(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewRB[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Has(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkRBTree_Delete(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewRB[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Delete(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkAVLTree_Insert(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewAVL[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n\n}\n\nfunc BenchmarkAVLTree_Has(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewAVL[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Has(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n\nfunc BenchmarkAVLTree_Delete(b *testing.B) {\n\thelper := func() {\n\t\ttree := bt.NewAVL[int]()\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Push(i)\n\t\t}\n\n\t\tfor i := 1; i <= testNum; i++ {\n\t\t\ttree.Delete(i)\n\t\t}\n\t}\n\n\tfor i := 0; i < b.N; i++ {\n\t\thelper()\n\t}\n}\n"
  },
  {
    "path": "structure/trie/trie.go",
    "content": "// Package trie provides Trie data structures in golang.\n//\n// Wikipedia: https://en.wikipedia.org/wiki/Trie\npackage trie\n\n// Node represents each node in Trie.\ntype Node struct {\n\tchildren map[rune]*Node // map children nodes\n\tisLeaf   bool           // current node value\n}\n\n// NewNode creates a new Trie node with initialized\n// children map.\nfunc NewNode() *Node {\n\tn := &Node{}\n\tn.children = make(map[rune]*Node)\n\tn.isLeaf = false\n\treturn n\n}\n\n// insert a single word at a Trie node.\nfunc (n *Node) insert(s string) {\n\tcurr := n\n\tfor _, c := range s {\n\t\tnext, ok := curr.children[c]\n\t\tif !ok {\n\t\t\tnext = NewNode()\n\t\t\tcurr.children[c] = next\n\t\t}\n\t\tcurr = next\n\t}\n\tcurr.isLeaf = true\n}\n\n// Insert zero, one or more words at a Trie node.\nfunc (n *Node) Insert(s ...string) {\n\tfor _, ss := range s {\n\t\tn.insert(ss)\n\t}\n}\n\n// Find  words at a Trie node.\nfunc (n *Node) Find(s string) bool {\n\tnext, ok := n, false\n\tfor _, c := range s {\n\t\tnext, ok = next.children[c]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn next.isLeaf\n}\n\n// Capacity returns the number of nodes in the Trie\nfunc (n *Node) Capacity() int {\n\tr := 0\n\tfor _, c := range n.children {\n\t\tr += c.Capacity()\n\t}\n\treturn 1 + r\n}\n\n// Size returns the number of words in the Trie\nfunc (n *Node) Size() int {\n\tr := 0\n\tfor _, c := range n.children {\n\t\tr += c.Size()\n\t}\n\tif n.isLeaf {\n\t\tr++\n\t}\n\treturn r\n}\n\n// remove lazily a word from the Trie node, no node is actually removed.\nfunc (n *Node) remove(s string) {\n\tif len(s) == 0 {\n\t\treturn\n\t}\n\tnext, ok := n, false\n\tfor _, c := range s {\n\t\tnext, ok = next.children[c]\n\t\tif !ok {\n\t\t\t// word cannot be found - we're done !\n\t\t\treturn\n\t\t}\n\t}\n\tnext.isLeaf = false\n}\n\n// Remove zero, one or more words lazily from the Trie, no node is actually removed.\nfunc (n *Node) Remove(s ...string) {\n\tfor _, ss := range s {\n\t\tn.remove(ss)\n\t}\n}\n\n// Compact will remove unecessay nodes, reducing the capacity, returning true if node n itself should be removed.\nfunc (n *Node) Compact() (remove bool) {\n\n\tfor r, c := range n.children {\n\t\tif c.Compact() {\n\t\t\tdelete(n.children, r)\n\t\t}\n\t}\n\treturn !n.isLeaf && len(n.children) == 0\n}\n"
  },
  {
    "path": "structure/trie/trie_bench_test.go",
    "content": "package trie\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"testing\"\n)\n\n// CAUTION : make sure to limit the benchmarks to 3000 iterations,\n// or removal will mostly process an empty Trie, giving absurd results.\n\nfunc BenchmarkTrie_Insert(b *testing.B) {\n\tinsert := make([]string, 3000)\n\tfor i := 0; i < len(insert); i++ {\n\t\tinsert[i] = fmt.Sprintf(\"%f\", rand.Float64())\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tn := NewNode()\n\t\tn.Insert(insert...)\n\t}\n}\n\nfunc BenchmarkTrie_Find_non_existent(b *testing.B) {\n\n\tinsert := make([]string, 3000)\n\tfor i := 0; i < len(insert); i++ {\n\t\tinsert[i] = fmt.Sprintf(\"%f\", rand.Float64())\n\t}\n\tn := NewNode()\n\tn.Insert(insert...)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tn.Find(\"0.3213213244346546546546565465465\") // does not exists\n\t}\n}\n\nfunc BenchmarkTrie_Find_existent(b *testing.B) {\n\tinsert := make([]string, 3000)\n\tfor i := 0; i < len(insert); i++ {\n\t\tinsert[i] = fmt.Sprintf(\"%f\", rand.Float64())\n\t}\n\tn := NewNode()\n\tn.Insert(insert...)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tn.Find(insert[i%3000]) // always exists !\n\t}\n}\n\nfunc BenchmarkTrie_Remove_lazy(b *testing.B) {\n\tinsert := make([]string, 3000)\n\tfor i := 0; i < len(insert); i++ {\n\t\tinsert[i] = fmt.Sprintf(\"%f\", rand.Float64())\n\t}\n\tn := NewNode()\n\tn.Insert(insert...)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tn.Remove(insert[i%3000]) //  exists, at least until removed ...\n\t}\n}\n\nfunc BenchmarkTrie_Remove_and_Compact(b *testing.B) {\n\tinsert := make([]string, 3000)\n\tfor i := 0; i < len(insert); i++ {\n\t\tinsert[i] = fmt.Sprintf(\"%f\", rand.Float64())\n\t}\n\tn := NewNode()\n\tn.Insert(insert...)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tn.Remove(insert[i%3000])\n\t\tn.Compact()\n\t}\n}\n"
  },
  {
    "path": "structure/trie/trie_test.go",
    "content": "package trie\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrieInsert(t *testing.T) {\n\tn := NewNode()\n\n\tinsertWords := []string{\n\t\t\"nikola\",\n\t\t\"tesla\",\n\t}\n\n\tcheckWords := map[string]bool{\n\t\t\"thomas\": false,\n\t\t\"edison\": false,\n\t\t\"nikola\": true,\n\t}\n\n\tn.Insert(insertWords...)\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, 2, 12)\n\n}\n\nfunc TestTrieInsert_substrings(t *testing.T) {\n\tn := NewNode()\n\n\tinsertWords := []string{\n\t\t\"aa\",\n\t\t\"aaaa\",\n\t\t\"aaaaa\",\n\t}\n\n\tcheckWords := map[string]bool{\n\t\t\"a\":       false,\n\t\t\"aa\":      true,\n\t\t\"aaa\":     false,\n\t\t\"aaaa\":    true,\n\t\t\"aaaaa\":   true,\n\t\t\"aaaaaa\":  false,\n\t\t\"aaaaaaa\": false,\n\t}\n\n\tn.Insert(insertWords...)\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, 3, 5+1)\n\n\tn.Remove(\"aaaa\")\n\tcheckWords[\"aaaa\"] = false\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, 2, 5+1)\n\n\tif n.Compact() {\n\t\tt.Fatalf(\"it should not be possible to remove the node\")\n\t}\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, 2, 5+1)\n}\n\nfunc TestTrieRemove(t *testing.T) {\n\tn := NewNode()\n\n\tinsertWords := []string{\n\t\t\"nikola\",\n\t\t\"tesla\",\n\t\t\"albert\",\n\t\t\"einstein\",\n\t}\n\n\tcheckWords := map[string]bool{\n\t\t\"thomas\":   false,\n\t\t\"edison\":   false,\n\t\t\"nikola\":   true,\n\t\t\"albert\":   true,\n\t\t\"einstein\": true,\n\t}\n\n\tn.Insert(insertWords...)\n\tn.verify(t, checkWords)\n\tsize, capa := n.Size(), n.Capacity() // 4 words ...\n\n\tn.Remove(\"albert\")\n\tcheckWords[\"albert\"] = false\n\tsize-- // 3 words in size, but no change in capacity\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa)\n\n\tn.Remove(\"albert\") // no effect since already removed\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa)\n\n\tn.Remove(\"marcel\") // no effect since ,o, existent\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa)\n\n\tn.Remove(\"nikola\", \"tesla\") // 1 word\n\tcheckWords[\"nikola\"] = false\n\tcheckWords[\"tesla\"] = false\n\tsize -= 2 // t1 word left,  but still no change in capacity\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa)\n\n\t// compact the Tree\n\tif n.Compact() {\n\t\tt.Fatal(\"the Trie should not be completely removable after compaction\")\n\t}\n\tif capa <= n.Capacity() {\n\t\tt.Fatal(\"capacity should have reduced following compaction\")\n\t}\n\tcapa = n.Capacity()\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa) // still 1 word, reduced capacity\n\n\tn.Remove(\"einstein\")\n\tcheckWords[\"einstein\"] = false\n\tsize-- // No more words\n\tn.verify(t, checkWords)\n\tn.verifySizeCapa(t, size, capa) // no words, but still have some nodes left capacity\n\n\tif !n.Compact() {\n\t\tt.Fatal(\"the root node of an empty Trie should be marked as removable after compaction\")\n\t}\n\tn.verifySizeCapa(t, 0, 1) // no words, only the root node left\n}\n\n// --------------- helper functions ---------------------------\n\n// verify if provided words are present\nfunc (n *Node) verify(t *testing.T, checkWords map[string]bool) {\n\tfor k, v := range checkWords {\n\t\tok := n.Find(k)\n\t\tif ok != v {\n\t\t\tt.Fatalf(\n\t\t\t\t\"%q is %s supposed to be in the Trie.\",\n\t\t\t\tk,\n\t\t\t\tmap[bool]string{true: \"\", false: \"NOT \"}[v],\n\t\t\t)\n\t\t}\n\t\t// t.Logf(\n\t\t// \t\"\\\"%s\\\" is %sin the Trie.\",\n\t\t// \tk,\n\t\t// \tmap[bool]string{true: \"\", false: \"NOT \"}[ok],\n\t\t// )\n\t}\n}\n\n// verify expected size and capacity\nfunc (n *Node) verifySizeCapa(t *testing.T, expectedSize, expectedCapacity int) {\n\tif got := n.Size(); got != expectedSize {\n\t\tt.Fatalf(\"Expected Size was %d but got %d\", expectedSize, got)\n\t}\n\tif got := n.Capacity(); got != expectedCapacity {\n\t\tt.Fatalf(\"Expected Capacity was %d but got %d\", expectedCapacity, got)\n\t}\n}\n"
  },
  {
    "path": "structure/trie/trieexample_test.go",
    "content": "package trie\n\nimport \"fmt\"\n\nfunc ExampleNode() {\n\t// creates a new node\n\tnode := NewNode()\n\n\t// adds words\n\tnode.Insert(\"nikola\")\n\tnode.Insert(\"tesla\")\n\n\t// check size and capacity\n\tfmt.Println(node.Size())     // 2 words\n\tfmt.Println(node.Capacity()) // 12 nodes\n\n\t// finds words\n\tfmt.Println(node.Find(\"thomas\")) // false\n\tfmt.Println(node.Find(\"edison\")) // false\n\tfmt.Println(node.Find(\"nikola\")) // true\n\n\t// remove a word, and check it is gone\n\tnode.Remove(\"tesla\")\n\tfmt.Println(node.Find(\"tesla\")) // false\n\n\t// size and capacity have changed\n\tfmt.Println(node.Size())     // 1 word left\n\tfmt.Println(node.Capacity()) // 12 nodes remaining\n\n\t// output:\n\t// 2\n\t// 12\n\t// false\n\t// false\n\t// true\n\t// false\n\t// 1\n\t// 12\n}\n"
  }
]