diff --git a/.github/linters/.golangci.yml b/.github/linters/.golangci.yml new file mode 100644 index 00000000..a8eddf87 --- /dev/null +++ b/.github/linters/.golangci.yml @@ -0,0 +1,4 @@ +linters: + enable: + - gofmt + - goimports diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml new file mode 100644 index 00000000..efb36386 --- /dev/null +++ b/.github/linters/.markdown-lint.yml @@ -0,0 +1,3 @@ +MD013: false +MD045: false +MD033: false diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 02472043..6f222a44 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,10 +1,14 @@ +# Instructions + Before opening a Pull Request, please read the following items: + 1. Make sure you have read the [CONTRIBUTING](../CONTRIBUTING.md) guidelines 2. Make sure no other PR is implementing the same change 3. Make sure the Continuous Integration workflows (Github Actions) are all passing -4. If in doubt about how to approach another contributor, read our [CODE OF CONDUCT](../CODE-OF-CONDUCT.md) guidelines +4. If in doubt about how to approach another contributor, read our [CODE OF CONDUCT](../CODE_OF_CONDUCT.md) guidelines -# Description +## Description + diff --git a/.github/workflows/link-checker.yml b/.github/workflows/link-checker.yml index 12b2e093..624386be 100644 --- a/.github/workflows/link-checker.yml +++ b/.github/workflows/link-checker.yml @@ -6,9 +6,9 @@ jobs: link-checker: runs-on: ubuntu-latest steps: - - name: Checkout Code - uses: actions/checkout@main - - name: Check Links - uses: lycheeverse/lychee-action@v1.7.0 - with: - fail: true + - name: Checkout Code + uses: actions/checkout@main + - name: Check Links + uses: lycheeverse/lychee-action@v1.7.0 + with: + fail: true diff --git a/.github/workflows/lint-checker.yml b/.github/workflows/lint-checker.yml index 817c08f3..5a30fe47 100644 --- a/.github/workflows/lint-checker.yml +++ b/.github/workflows/lint-checker.yml @@ -7,20 +7,28 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Check Code - uses: github/super-linter@v5 + uses: super-linter/super-linter@v7.1.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - VALIDATE_SCALAFMT: true VALIDATE_GO: true + VALIDATE_RUBY: true + VALIDATE_JSON: true + VALIDATE_YAML: true + VALIDATE_KOTLIN: true + VALIDATE_MARKDOWN: true + VALIDATE_SCALAFMT: true VALIDATE_RUST_2021: true VALIDATE_RUST_CLIPPY: true - VALIDATE_KOTLIN: true - VALIDATE_RUBY: true - VALIDATE_JAVASCRIPT_ES: true - VALIDATE_GOOGLE_JAVA_FORMAT: true + VALIDATE_PYTHON_RUFF: true VALIDATE_PYTHON_BLACK: true VALIDATE_PYTHON_ISORT: true + VALIDATE_CLANG_FORMAT: true + VALIDATE_JAVASCRIPT_ES: true + VALIDATE_JSON_PRETTIER: true + VALIDATE_YAML_PRETTIER: true + VALIDATE_MARKDOWN_PRETTIER: true + VALIDATE_GOOGLE_JAVA_FORMAT: true diff --git a/.ruby-lint.yml b/.ruby-lint.yml deleted file mode 100644 index 97a36c94..00000000 --- a/.ruby-lint.yml +++ /dev/null @@ -1,14 +0,0 @@ -Metrics/AbcSize: - Enabled: false - -Style/MixinUsage: - Enabled: false - -Metrics/MethodLength: - Enabled: false - -Style/CombinableLoops: - Enabled: false - -Metrics/CyclomaticComplexity: - Enabled: false diff --git a/CODE-OF-CONDUCT.md b/CODE_OF_CONDUCT.md similarity index 76% rename from CODE-OF-CONDUCT.md rename to CODE_OF_CONDUCT.md index da32d376..224c0402 100644 --- a/CODE-OF-CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,4 +1,3 @@ - # Code of Conduct ## Our Pledge @@ -18,23 +17,23 @@ diverse, inclusive, and healthy community. Examples of behavior that contributes to a positive environment for our community include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or advances of +- The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities @@ -74,6 +73,3 @@ version 2.1, available at [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8f78fce9..30c794b2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Before you start contributing, please take a moment to review this document to u ## Code of Conduct -We have adopted a [Code of Conduct](./CODE-OF-CONDUCT.md) that we expect all community members to follow. Please make sure to review and adhere to it in all interactions within our community. +We have adopted a [Code of Conduct](./CODE_OF_CONDUCT.md) that we expect all community members to follow. Please make sure to review and adhere to it in all interactions within our community. ## How Can I Contribute? @@ -28,7 +28,7 @@ If you encounter an issue or have a feature request, please follow these steps: Before you start working on a contribution, please keep in mind the following guidelines: -- Adhere to our [Code of Conduct](./CODE-OF-CONDUCT.md). +- Adhere to our [Code of Conduct](./CODE_OF_CONDUCT.md). - Respect and follow existing project coding standards. - Write clear and concise commit messages. - Test your changes thoroughly. diff --git a/README.md b/README.md index 8a387279..48882c8c 100644 --- a/README.md +++ b/README.md @@ -65,10 +65,10 @@ In order to achieve greater coverage and encourage more people to contribute to - Dijkstra's Algorithm + A* Algorithm - - + + @@ -77,28 +77,28 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + - - + + - - + + - - + + @@ -112,8 +112,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -123,32 +123,148 @@ In order to achieve greater coverage and encourage more people to contribute to - Floyd–Warshall Algorithm + Bellman-Ford Algorithm - - + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Binary Search + + + + + + + + + + + + + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Connected Components + + + + + + + + + + + + + + + + + + + + + + + + + @@ -181,67 +297,473 @@ In order to achieve greater coverage and encourage more people to contribute to - Binary Search + Dijkstra's Algorithm + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Exponentiation (Iterative) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Exponentiation (Recursive) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Factorial (Iterative) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Factorial (Recursive) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fibonacci (Iterative) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fibonacci (Memoization) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fibonacci (Recursive) - + - + - + - + - + - + - + - + - + - - + + - - + + - Graph Search + Floyd–Warshall Algorithm - + @@ -251,18 +773,18 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - + - - + + @@ -271,8 +793,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -297,55 +819,55 @@ In order to achieve greater coverage and encourage more people to contribute to - Linear Search (Iterative) + Ford-Fulkerson Algorithm - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + @@ -355,15 +877,15 @@ In order to achieve greater coverage and encourage more people to contribute to - Linear Search (Recursive) + Gale-Shapley Algorithm - - + + - - + + @@ -372,8 +894,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -382,13 +904,13 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + @@ -397,13 +919,13 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + @@ -413,10 +935,10 @@ In order to achieve greater coverage and encourage more people to contribute to - Linear Search (Sentinel) + Genetic Algorithm - - + + @@ -430,7 +952,7 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -440,13 +962,13 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + @@ -471,15 +993,15 @@ In order to achieve greater coverage and encourage more people to contribute to - Interpolation Search + Graph Search - - + + - - + + @@ -488,7 +1010,7 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -498,12 +1020,12 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - + @@ -529,9 +1051,9 @@ In order to achieve greater coverage and encourage more people to contribute to - Travelling Salesman + Hamiltonian Cycle - + @@ -551,8 +1073,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -587,10 +1109,10 @@ In order to achieve greater coverage and encourage more people to contribute to - Hamiltonian Cycle + Huffman's Algorithm - - + + @@ -604,8 +1126,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -645,15 +1167,15 @@ In order to achieve greater coverage and encourage more people to contribute to - Connected Components + Hungarian Algorithm - - + + - - + + @@ -703,45 +1225,45 @@ In order to achieve greater coverage and encourage more people to contribute to - Exponentiation (Iterative) + Interpolation Search - - + + - + - - + + - + - - + + - + - + - - + + @@ -761,24 +1283,24 @@ In order to achieve greater coverage and encourage more people to contribute to - Exponentiation (Recursive) + Knight's Tour - - + + - - + + - - + + - + @@ -788,23 +1310,23 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + - - + + - - + + @@ -813,118 +1335,118 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - Factorial (Iterative) + Kruskal's Algorithm - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - Factorial (Recursive) + Linear Search (Iterative) - + - + - + - + - - + + - + - + - + - + - + @@ -935,151 +1457,151 @@ In order to achieve greater coverage and encourage more people to contribute to - Fibonacci (Iterative) + Linear Search (Recursive) - + - + - - + + - + - - + + - + - + - - + + - + - + - - + + - - Fibonacci (Recursive) + + Linear Search (Sentinel) - + - - + + - - + + - + - - + + - + - + - - + + - - + + - - + + - - + + - - Fibonacci (Memoization) + + LZ77 Algorithm - - + + - - + + - - + + - + - - + + - - + + @@ -1088,45 +1610,45 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + - - + + - - + + Max (Recursive) - + - + - + - + @@ -1136,7 +1658,7 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -1167,24 +1689,24 @@ In order to achieve greater coverage and encourage more people to contribute to - Min and Max (Iterative) + Min and Max (D&C) - + - + - - + + - + @@ -1194,13 +1716,13 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + @@ -1209,13 +1731,13 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + @@ -1225,39 +1747,39 @@ In order to achieve greater coverage and encourage more people to contribute to - Min and Max (Recursive) + Min and Max (Iterative) - + - - + + - + - + - - + + - + - + @@ -1267,12 +1789,12 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + @@ -1283,40 +1805,40 @@ In order to achieve greater coverage and encourage more people to contribute to - Min and Max (D&C) + Min and Max (Recursive) - + - - + + - - + + - + - - + + - + - - + + @@ -1325,13 +1847,13 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + - - + + @@ -1341,7 +1863,7 @@ In order to achieve greater coverage and encourage more people to contribute to - Knight's Tour + Prim's Algorithm @@ -1358,8 +1880,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -1401,7 +1923,7 @@ In order to achieve greater coverage and encourage more people to contribute to Tower of Hanoi - + @@ -1416,17 +1938,17 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + - + @@ -1436,12 +1958,12 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + @@ -1457,10 +1979,10 @@ In order to achieve greater coverage and encourage more people to contribute to - Genetic Algorithm + Travelling Salesman - - + + @@ -1474,13 +1996,13 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + @@ -1514,66 +2036,68 @@ In order to achieve greater coverage and encourage more people to contribute to + + - - + - - - - - - - - - - - + -
Huffman's Algorithm - - + Data Structures + + - - + + + - - + + + - + + - - + + + - - + + + - - + + + - - + + + - - + + + - - + + + - - + + +
LZ77 AlgorithmAVL Tree @@ -1590,8 +2114,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -1630,76 +2154,74 @@ In order to achieve greater coverage and encourage more people to contribute to
- - - + - - - - - - - - - - - + @@ -1761,12 +2283,12 @@ In order to achieve greater coverage and encourage more people to contribute to @@ -1781,8 +2303,8 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -1892,28 +2414,28 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -1940,7 +2462,7 @@ In order to achieve greater coverage and encourage more people to contribute to @@ -1981,40 +2503,40 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -2039,9 +2561,9 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -2056,8 +2578,8 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + - + - + - + - + @@ -2445,10 +2967,10 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + + + + + + + + + + + + + + + @@ -3029,8 +3609,8 @@ In order to achieve greater coverage and encourage more people to contribute to @@ -3213,7 +3793,7 @@ In order to achieve greater coverage and encourage more people to contribute to @@ -3276,8 +3856,8 @@ In order to achieve greater coverage and encourage more people to contribute to @@ -3490,6 +4070,64 @@ In order to achieve greater coverage and encourage more people to contribute to + + + + + + + + + + + + + +
Data Structures - + Binary Search Tree + - + + - + + - + + - - + + + - + + - + + - - + + + - - + + + - - + + + - - + + +
Binary Tree - + - - + + @@ -1718,8 +2240,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -1749,9 +2271,9 @@ In order to achieve greater coverage and encourage more people to contribute to
Binary Search TreeCircular Linked List - + - - + + - + - - + + @@ -1865,24 +2387,24 @@ In order to achieve greater coverage and encourage more people to contribute to
QueueDynamic Queue - + - - + + - - + + - + - - + + - - + + - - + + - - + + - - + + @@ -1923,14 +2445,14 @@ In order to achieve greater coverage and encourage more people to contribute to
Dynamic QueueDynamic Stack - + - + - +
GraphDoubly Linked List - + - - + + - - + + - - + + - - + + - - + + - - + + @@ -2023,7 +2545,7 @@ In order to achieve greater coverage and encourage more people to contribute to - +
Circular Linked ListGraph - + - - + + @@ -2081,8 +2603,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -2097,15 +2619,15 @@ In order to achieve greater coverage and encourage more people to contribute to
Singly Linked ListHash Table - - + + - - + + @@ -2114,33 +2636,33 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + - + - - + + - - + + - - + + @@ -2155,55 +2677,55 @@ In order to achieve greater coverage and encourage more people to contribute to
Doubly Linked ListQueue - + - - + + - + - + - - + + - + - + - - + + - + - - + + @@ -2213,10 +2735,10 @@ In order to achieve greater coverage and encourage more people to contribute to
Unordered Linked ListRed-Black Tree - - + + @@ -2235,8 +2757,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -2271,10 +2793,10 @@ In order to achieve greater coverage and encourage more people to contribute to
Sorted Linked ListRing Buffer - - + + @@ -2288,13 +2810,13 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + @@ -2329,55 +2851,55 @@ In order to achieve greater coverage and encourage more people to contribute to
StackSingly Linked List - + - + - - + + - + - + - + - + - + - + - - + + @@ -2387,15 +2909,15 @@ In order to achieve greater coverage and encourage more people to contribute to
Dynamic StackSkip List - - + + - - + + @@ -2404,7 +2926,7 @@ In order to achieve greater coverage and encourage more people to contribute to - +
Ring BufferSorted Linked List - - + + @@ -2462,13 +2984,13 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + @@ -2503,12 +3025,70 @@ In order to achieve greater coverage and encourage more people to contribute to
Hash TableStack + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Unordered Linked List + + + + @@ -2520,18 +3100,18 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + - - + + @@ -2638,8 +3218,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -2668,8 +3248,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -2923,8 +3503,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -2938,13 +3518,13 @@ In order to achieve greater coverage and encourage more people to contribute to - + - - + + @@ -3011,7 +3591,7 @@ In order to achieve greater coverage and encourage more people to contribute to - +
Heapsort - - + + @@ -3155,7 +3735,7 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + - - + + @@ -3450,7 +4030,7 @@ In order to achieve greater coverage and encourage more people to contribute to - +
Topological Sort + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
@@ -3551,15 +4189,15 @@ In order to achieve greater coverage and encourage more people to contribute to - + - + - + + + + + + + + + + + + + + + - + @@ -3783,7 +4479,7 @@ In order to achieve greater coverage and encourage more people to contribute to - + @@ -3841,15 +4537,15 @@ In order to achieve greater coverage and encourage more people to contribute to - + + + + + + + + + + + + + + +
Queue using StacksFind Distinct Subsets - - + + @@ -3568,8 +4206,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -3609,30 +4247,30 @@ In order to achieve greater coverage and encourage more people to contribute to
Two-Sum ProblemIsogram - - + + - - + + - - + + - - + + - - + + @@ -3651,8 +4289,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -3667,52 +4305,110 @@ In order to achieve greater coverage and encourage more people to contribute to
PalindromeLeibniz Formula for Pi - + - + - + - + - - + + - + - + - + - + + + + + + + + +
Maze-Solving Algorithm + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -3725,54 +4421,54 @@ In order to achieve greater coverage and encourage more people to contribute to
Leibniz Formula for PiPalindrome - + - + - + - + - - + + - + - + - + - + - +
Maze-Solving AlgorithmQueue using Stacks @@ -3800,7 +4496,7 @@ In order to achieve greater coverage and encourage more people to contribute to - +
IsogramRotten Oranges - - + + @@ -3863,8 +4559,8 @@ In order to achieve greater coverage and encourage more people to contribute to - - + + @@ -3898,6 +4594,64 @@ In order to achieve greater coverage and encourage more people to contribute to
Two-Sum Problem + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/c/AlgoritmoDijkstra.c b/src/c/AlgoritmoDijkstra.c deleted file mode 100644 index f22d63c1..00000000 --- a/src/c/AlgoritmoDijkstra.c +++ /dev/null @@ -1,99 +0,0 @@ -/* -* Graphs - Dijkstra Algorithm in C -* Kelvin Salton do Prado - 2015 -* Complexity: Theta(n^2) -* -* 1 for all - Edges with non-negative weights - Greedy algorithm -* Finds the shortest path from one vertex (start) to another (destination) -* -* Graph with 5 vertices and 6 edges -* -* 6 -* (0)-----------------(1) -* | | -* 10 | | 2 -* | 1 | -* (2)-----------------(3) -* \ / -* 3 \ / 8 -* \ / -* -----(4)----- -* -* Distance Matrix -* 0 1 2 3 4 -* 0 0 6 10 - - -* 1 6 0 - 2 - -* 2 10 - 0 1 3 -* 3 - 2 1 0 8 -* 4 - - 3 8 0 -* -* For infinite values, the value will be considered: 4294967295 -* The objective is to leave the starting point (0) and reach the destination (4) by the shortest route -* Response: (0)->(1)->(3)->(2)->(4) = 12 -* -*/ - -#include -#include - -#define noVertices 5 // Defines a constant 5 which is the number of vertices in the graph - -// Dijkstra's algorithm takes as parameters the distance matrix and the number of vertices -void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n){ - -bool visited[n]; // Variable that holds true for visited vertices - - // The value 'i' from the for below is not used, as the for is only used to traverse the entire number of columns in the matrix - for(int i = 1; i < n; i++){ // Starts at 1 because you don't need to compare the vertex with itself - -int min = -1; // Variable that stores the position of the smallest value, starts at -1 as it is an invalid position - unsigned long int MinValue = 4294967295; // Variable that stores the smallest value found, starts with 'infinity', so always on the first pass the value will be smaller than this variable - // For that loops through all rows in column [0] - for(int j = 1; j < n; j++){ - // If the vertex has not yet been visited and the value is less than the 'MinValor' - if( !visited[j] && matrix[j][0] < MinValue ){ - min = j; // Saves the position of the smallest - MinValue = matrix[j][0]; // Save the smallest value - } - } - - visited[min] = true; // Mark the value of the minimum position as visited - - // Goes from 1 to n - for(int j = 1; j < n; j++){ - // If the value of column [0] + the value of the passing column is less than the value of the passing row and column [0] - // Update the first column of the matrix, which will be used for the next iterations - if( (matrix[min][0] + matrix[min][j]) < matrix[j][0] ){ - matrix[j][0] = matrix[min][0] + matrix[min][j]; - } - } - } -} - -int main(){ - - unsigned long int Matrix[noVertices][noVertices] = {{ 0, 6, 10, 4294967295, 4294967295 }, - { 6, 0, 4294967295, 2, 4294967295 }, - { 10, 4294967295, 0, 1, 3 }, - { 4294967295, 2, 1, 0, 8 }, - { 4294967295, 4294967295, 3, 8, 0 }}; - - Dijkstra(Matrix, noVertices); - - printf("Total shortest path from vertex 0 to 4: %lu\n", Matrix[4][0]); // Shortest total path - - // Print the matrix with the updated values - printf("Matrix:\n"); - for (int i = 0; i < noVertices; ++i){ - for (int e = 0; e < noVertices; ++e){ - if( Matrix[i][e] < 10 ) - printf(" %lu ", Matrix[i][e]); - else - printf("%lu ", Matrix[i][e]); - } - printf("\n"); - } - printf("\n"); - - return 0; -} diff --git a/src/c/AlgoritmoFloydWarshall.c b/src/c/AlgoritmoFloydWarshall.c deleted file mode 100644 index 765a10be..00000000 --- a/src/c/AlgoritmoFloydWarshall.c +++ /dev/null @@ -1,86 +0,0 @@ -/* -* Grafos - Algoritmo de Floyd-Warshall em C -* Kelvin Salton do Prado - 2015 -* Complexidade: Teta de vértices ao cubo = Teta(n^3) -* -* Encontra o caminho de todos para todos os vértices -* -* Grafo com 5 vértices e 6 arestas -* -* 6 -* (0)-----------------(1) -* | | -* 10 | | 2 -* | 1 | -* (2)-----------------(3) -* \ / -* 3 \ / 8 -* \ / -* -----(4)----- -* -* Matriz de Distância -* 0 1 2 3 4 -* 0 0 6 10 - - -* 1 6 0 - 2 - -* 2 10 - 0 1 3 -* 3 - 2 1 0 8 -* 4 - - 3 8 0 -* -* Para valores infinitos será considerado o valor: 4294967295 -* -*/ - -#include - -#define nroVertices 5 // Define uma constante 5 que é a quantidade de vértices do grafo - -// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o número de vértices -void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n){ - for(int x = 0; x < n; x++){ - for(int y = 0; y < n; y++){ - for(int z = 0; z < n; z++){ - if( matriz[y][z] > (matriz[y][x] + matriz[x][z]) ) - matriz[y][z] = matriz[y][x] + matriz[x][z]; - } - } - } -} - -int main(){ - - unsigned long int Matriz[nroVertices][nroVertices] = {{ 0, 6, 10, 4294967295, 4294967295 }, - { 6, 0, 4294967295, 2, 4294967295 }, - { 10, 4294967295, 0, 1, 3 }, - { 4294967295, 2, 1, 0, 8 }, - { 4294967295, 4294967295, 3, 8, 0 }}; - - FloydWarshall(Matriz, nroVertices); - - // Mostra a matriz com os valores atualizados - printf("Matriz:\n"); - for (int i = 0; i < nroVertices; ++i){ - for (int e = 0; e < nroVertices; ++e){ - if( Matriz[i][e] < 10 ) - printf(" %lu ", Matriz[i][e]); - else - printf("%lu ", Matriz[i][e]); - } - printf("\n"); - } - printf("\n"); - - //printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]); // [destino] [origem] - //printf("Total caminho mais curto do vertice 2 ao 0: %lu\n", Matriz[0][2]); - //printf("Total caminho mais curto do vertice 4 ao 3: %lu\n\n", Matriz[3][4]); - - // Mostra todos os caminhos - printf("\n"); - for (int i = 0; i < nroVertices; ++i){ - for (int x = 0; x < nroVertices; ++x){ - printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x, Matriz[x][i]); - } - } - printf("\n\n"); - - return 0; -} \ No newline at end of file diff --git a/src/c/ArvoreBinaria.c b/src/c/ArvoreBinaria.c deleted file mode 100644 index 1d7e5a51..00000000 --- a/src/c/ArvoreBinaria.c +++ /dev/null @@ -1,202 +0,0 @@ -#include -#include - -// Essa é uma árvore binária não balanceada. - -struct No { - - int valor; - struct No* esquerda; - struct No* direita; - int altura; -}; - -int altura(struct No *n){ - - if(n == NULL) - return 0; - return n->altura; -} - -int max(int a, int b){ - return (a > b)? a : b; -} - -struct No* novoNo(int valor){ - - struct No* novoNo = (struct No*)malloc(sizeof(struct No)); - - novoNo->valor = valor; - novoNo->esquerda = NULL; - novoNo->direita = NULL; - novoNo->altura = 1; - - return novoNo; -} - -struct No* inserir(struct No* raiz, int valor){ - - if(raiz == NULL){ - return novoNo(valor); - } - if(valor <= raiz->valor) { - raiz->esquerda = inserir(raiz->esquerda, valor); - } - else { - raiz->direita = inserir(raiz->direita, valor); - } - - raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita)); - - return raiz; -} - -int busca(struct No* raiz, int valor){ - - if(raiz == NULL){ - printf(" Valor [%d] não encontrado.\n", valor); - } - else if(raiz->valor == valor){ - printf(" Valor [%d] encontrado.\n", valor); - } - else if(valor <= raiz->valor){ - return busca(raiz->esquerda, valor); - } - else if(valor >= raiz->valor){ - return busca(raiz->direita, valor); - } -} - -void preorder(struct No* raiz){ - - if(raiz == NULL) return; - printf("[%d]", raiz->valor); - preorder(raiz->esquerda); - preorder(raiz->direita); -} - -void inorder(struct No* raiz){ - - if(raiz == NULL) return; - inorder(raiz->esquerda); - printf("[%d]", raiz->valor); - inorder(raiz->direita); -} - -void postorder(struct No* raiz){ - - if(raiz == NULL) return; - postorder(raiz->esquerda); - postorder(raiz->direita); - printf("[%d]", raiz->valor); -} - -void levelOrder(struct No* raiz, int level){ - - if(raiz == NULL){ - return; - } - if(level == 0){ - printf("[%d]", raiz->valor); - } - else{ - levelOrder(raiz->esquerda, level-1); - levelOrder(raiz->direita, level-1); - } -} - -void printLevelOrder(struct No* raiz){ - int h = altura(raiz); - for(int i = 0; i < h; i++){ - levelOrder(raiz, i); - } -} - -struct No* encontraMenor(struct No* raiz){ - struct No* atual = raiz; - while(atual->esquerda != NULL){ - atual = atual->esquerda; - } - return atual; -} - - -struct No* deleta(struct No* raiz, int valor){ - - if(raiz == NULL){ - return raiz; - } - if(valor < raiz->valor) { - raiz->esquerda = deleta(raiz->esquerda, valor); - } - else if(valor > raiz->valor){ - raiz->direita = deleta(raiz->direita, valor); - } - else{ - if( (raiz->esquerda == NULL) || (raiz->direita == NULL) ){ - struct No* temp = raiz->esquerda ? raiz->esquerda : raiz->direita; - - if(temp == NULL){ - temp = raiz; - raiz = NULL; - } else{ - *raiz = *temp; - free(temp); - } - } - else{ - struct No* temp = encontraMenor(raiz->direita); - raiz->valor = temp->valor; - raiz->direita = deleta(raiz->direita, temp->valor); - } - } - - if(raiz == NULL){ - return raiz; - } - - raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita)); - - return raiz; -} - - -int main(void){ - - struct No* raiz; - raiz = inserir(raiz, 10); - raiz = inserir(raiz, 2); - raiz = inserir(raiz, 33); - raiz = inserir(raiz, 4); - raiz = inserir(raiz, 57); - raiz = inserir(raiz, 6); - raiz = inserir(raiz, 12); - - busca(raiz, 33); - busca(raiz, 23); - - printf("\n Preorder: "); - preorder(raiz); - - printf("\n Inorder: "); - inorder(raiz); - - printf("\n Postorder: "); - postorder(raiz); - - printf("\n Levelorder: "); - printLevelOrder(raiz); - - raiz = deleta(raiz, 7); - - printf("\n Levelorder: "); - printLevelOrder(raiz); - - raiz = deleta(raiz, 6); - - printf("\n Levelorder: "); - printLevelOrder(raiz); - - return 0; - -} \ No newline at end of file diff --git a/src/c/ArvoreBinariaDeBusca.c b/src/c/ArvoreBinariaDeBusca.c deleted file mode 100644 index 0d857516..00000000 --- a/src/c/ArvoreBinariaDeBusca.c +++ /dev/null @@ -1,208 +0,0 @@ -/* -* Árvore Binária de Busca em C -* Kelvin Salton do Prado - 2015 -* -* ( 6 ) -* / \ -* ( 2 ) ( 7 ) -* / \ \ -*( 1 ) ( 4 ) ( 8 ) -* / \ -* ( 3 ) ( 5 ) -*/ - -#include -#include - -typedef int TIPOCHAVE; - -typedef struct AUX{ - TIPOCHAVE chave; - struct AUX *esq, *dir; -}NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO - -int max(int a, int b){ - if( a > b ) - return a; - return b; -} - -int altura(PONT no){ - if( no == NULL ) // Mesma coisa que usar if(!no) - return 0; - return 1 + max( altura(no->esq), altura(no->dir) ); // Percorre a arvore pela esquerda e pela direita para ver qual tem altura maior -} - -PONT buscaBinaria(TIPOCHAVE ch, PONT raiz){ - if( !raiz ) - return NULL; - if( raiz->chave == ch ) - return raiz; - if( raiz->chave < ch ) - buscaBinaria(ch, raiz->dir); - else - buscaBinaria(ch, raiz->esq); -} - -PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual){ - while( atual != NULL ){ - if( atual->chave == ch ) - return atual; - if( atual->chave < ch ) - atual = atual->dir; - else - atual = atual->esq; - } - return NULL; -} - -PONT criaNo(TIPOCHAVE ch){ - PONT no = (PONT) malloc( sizeof(NO) ); - no->esq = NULL; - no->dir = NULL; - no->chave = ch; - return no; -} - -bool inserir(TIPOCHAVE ch, PONT atual){ - PONT ant; - // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL (vazia) - while(atual != NULL){ - ant = atual; - if( atual->chave < ch ) - atual = atual->dir; - else - atual = atual->esq; - } - atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando' - if( ant->chave < ch ) - ant->dir = atual; - else - ant->esq = atual; - return true; -} - -PONT buscaNoPai(TIPOCHAVE ch, PONT atual){ - PONT noPai = atual; - while( atual != NULL ){ - if( atual->chave == ch ) - return noPai; - noPai = atual; - if( atual->chave < ch ) - atual = atual->dir; - else - atual = atual->esq; - } - return noPai; -} - -PONT maiorAesquerda(PONT atual){ - atual = atual->esq; - while( atual->dir != NULL ) - atual = atual->dir; - return atual; -} - -bool excluir(TIPOCHAVE ch, PONT raiz){ - PONT atual, noPai, substituto, paiSubstituto; - substituto = NULL; - atual = buscaBinaria(ch, raiz); - if( atual == NULL ) return false; // Não encontrou a chave - noPai = buscaNoPai(ch, raiz); - if( atual->esq == NULL || atual->dir == NULL ){ // Se tem 0 ou 1 filho - if( atual->esq == NULL ) - substituto = atual->dir; - else - substituto = atual->esq; - if( noPai == NULL ){ // Único que não tem pai é a raiz - raiz = substituto; - }else{ - if( ch < noPai->chave) - noPai->esq = substituto; - else - noPai->dir = substituto; - } - free(atual); - }else{ - substituto = maiorAesquerda(atual); - atual->chave = substituto->chave; - if( substituto->esq != NULL ) - atual->esq = substituto->esq; - else - atual->esq = NULL; - free(substituto); - } - return true; -} - -void preordem(PONT no){ // R - E - D - if( !no ) return; - printf("%d, ", no->chave); - preordem(no->esq); - preordem(no->dir); -} - -void posordem(PONT no){ // E - D - R - if( !no ) return; - posordem(no->esq); - posordem(no->dir); - printf("%d, ", no->chave); -} - -void emordem(PONT no){ // E - R - D - if( !no ) return; - emordem(no->esq); - printf("%d, ", no->chave); - emordem(no->dir); -} - -// Esta função não está funcionando -bool insereRecursivo(TIPOCHAVE ch, PONT no){ - PONT ant; - if( !no ){ - no = criaNo(ch); - }else{ - ant = no; - if( ch < no->chave ) - insereRecursivo(ch, no->esq); - else - insereRecursivo(ch, no->dir); - } - if( ant->chave < ch ) - ant->dir = no; - else - ant->esq = no; - return true; -} - -int main(){ - PONT noArvore = criaNo(6); - - inserir(2, noArvore); - inserir(1, noArvore); - inserir(4, noArvore); - inserir(7, noArvore); - inserir(8, noArvore); - inserir(3, noArvore); - inserir(5, noArvore); - - int valorBuscado = 7; - if( buscaBinaria(valorBuscado, noArvore) ) - printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave ); - else - printf("Não encontrou\n"); - - excluir(4, noArvore); - - printf("Pre-ordem: "); - preordem(noArvore); - printf("\n"); - printf("Em-ordem: "); - emordem(noArvore); - printf("\n"); - printf("Pos-ordem: "); - posordem(noArvore); - - printf("\nAltura: %d\n", altura(noArvore) ); - return 0; -} \ No newline at end of file diff --git a/src/c/BinarySearch.c b/src/c/BinarySearch.c index ae9e5cf5..4ab19f5d 100644 --- a/src/c/BinarySearch.c +++ b/src/c/BinarySearch.c @@ -1,43 +1,43 @@ -#include +#include int BinarySearch(int array[], int size, int value) { - int start = 0; - int end = size - 1; - int middle = end / 2; + int start = 0; + int end = size - 1; + int middle = end / 2; - while (start < end && array[middle] != value) { - // new start - if (value > array[middle]) - start = middle + 1; + while (start < end && array[middle] != value) { + // new start + if (value > array[middle]) + start = middle + 1; - // new end - if (value < array[middle]) - end = middle - 1; + // new end + if (value < array[middle]) + end = middle - 1; - // new middle - middle = (start + end) / 2; - } + // new middle + middle = (start + end) / 2; + } - if (array[middle] == value) - return middle; + if (array[middle] == value) + return middle; - return -1; + return -1; } int main() { - int value; - int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129}; - size_t size = sizeof(array) / sizeof(array[0]); + int value; + int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129}; + size_t size = sizeof(array) / sizeof(array[0]); - printf("Please provide the number you want to value for: "); - scanf("%d", &value); + printf("Please provide the number you want to value for: "); + scanf("%d", &value); - int pos = BinarySearch(array, size, value); + int pos = BinarySearch(array, size, value); - if (pos != -1) - printf("Found in position = %d.\nValue = %d\n", pos, array[pos]); - else - printf("Not found\n"); + if (pos != -1) + printf("Found in position = %d.\nValue = %d\n", pos, array[pos]); + else + printf("Not found\n"); - return 0; + return 0; } diff --git a/src/c/BinarySearchTree.c b/src/c/BinarySearchTree.c new file mode 100644 index 00000000..bce19184 --- /dev/null +++ b/src/c/BinarySearchTree.c @@ -0,0 +1,214 @@ +/* + * Árvore Binária de Busca em C + * + * ( 6 ) + * / \ + * ( 2 ) ( 7 ) + * / \ \ + *( 1 ) ( 4 ) ( 8 ) + * / \ + * ( 3 ) ( 5 ) + */ + +#include +#include + +typedef int TIPOCHAVE; + +typedef struct AUX { + TIPOCHAVE chave; + struct AUX *esq, *dir; +} NO, *PONT; // NO é a estrutura e PONT é um ponteiro de NO + +int max(int a, int b) { + if (a > b) + return a; + return b; +} + +int altura(PONT no) { + if (no == NULL) // Mesma coisa que usar if(!no) + return 0; + return 1 + max(altura(no->esq), + altura(no->dir)); // Percorre a arvore pela esquerda e pela + // direita para ver qual tem altura maior +} + +PONT buscaBinaria(TIPOCHAVE ch, PONT raiz) { + if (!raiz) + return NULL; + if (raiz->chave == ch) + return raiz; + if (raiz->chave < ch) + buscaBinaria(ch, raiz->dir); + else + buscaBinaria(ch, raiz->esq); +} + +PONT buscaBinariaLinear(TIPOCHAVE ch, PONT atual) { + while (atual != NULL) { + if (atual->chave == ch) + return atual; + if (atual->chave < ch) + atual = atual->dir; + else + atual = atual->esq; + } + return NULL; +} + +PONT criaNo(TIPOCHAVE ch) { + PONT no = (PONT)malloc(sizeof(NO)); + no->esq = NULL; + no->dir = NULL; + no->chave = ch; + return no; +} + +bool inserir(TIPOCHAVE ch, PONT atual) { + PONT ant; + // Percorre a arvore para a direita ou esquerda até encontrar uma posição NULL + // (vazia) + while (atual != NULL) { + ant = atual; + if (atual->chave < ch) + atual = atual->dir; + else + atual = atual->esq; + } + atual = criaNo(ch); // Utiliza a váriavel atual, pois estava 'sobrando' + if (ant->chave < ch) + ant->dir = atual; + else + ant->esq = atual; + return true; +} + +PONT buscaNoPai(TIPOCHAVE ch, PONT atual) { + PONT noPai = atual; + while (atual != NULL) { + if (atual->chave == ch) + return noPai; + noPai = atual; + if (atual->chave < ch) + atual = atual->dir; + else + atual = atual->esq; + } + return noPai; +} + +PONT maiorAesquerda(PONT atual) { + atual = atual->esq; + while (atual->dir != NULL) + atual = atual->dir; + return atual; +} + +bool excluir(TIPOCHAVE ch, PONT raiz) { + PONT atual, noPai, substituto, paiSubstituto; + substituto = NULL; + atual = buscaBinaria(ch, raiz); + if (atual == NULL) + return false; // Não encontrou a chave + noPai = buscaNoPai(ch, raiz); + if (atual->esq == NULL || atual->dir == NULL) { // Se tem 0 ou 1 filho + if (atual->esq == NULL) + substituto = atual->dir; + else + substituto = atual->esq; + if (noPai == NULL) { // Único que não tem pai é a raiz + raiz = substituto; + } else { + if (ch < noPai->chave) + noPai->esq = substituto; + else + noPai->dir = substituto; + } + free(atual); + } else { + substituto = maiorAesquerda(atual); + atual->chave = substituto->chave; + if (substituto->esq != NULL) + atual->esq = substituto->esq; + else + atual->esq = NULL; + free(substituto); + } + return true; +} + +void preordem(PONT no) { // R - E - D + if (!no) + return; + printf("%d, ", no->chave); + preordem(no->esq); + preordem(no->dir); +} + +void posordem(PONT no) { // E - D - R + if (!no) + return; + posordem(no->esq); + posordem(no->dir); + printf("%d, ", no->chave); +} + +void emordem(PONT no) { // E - R - D + if (!no) + return; + emordem(no->esq); + printf("%d, ", no->chave); + emordem(no->dir); +} + +// Esta função não está funcionando +bool insereRecursivo(TIPOCHAVE ch, PONT no) { + PONT ant; + if (!no) { + no = criaNo(ch); + } else { + ant = no; + if (ch < no->chave) + insereRecursivo(ch, no->esq); + else + insereRecursivo(ch, no->dir); + } + if (ant->chave < ch) + ant->dir = no; + else + ant->esq = no; + return true; +} + +int main() { + PONT noArvore = criaNo(6); + + inserir(2, noArvore); + inserir(1, noArvore); + inserir(4, noArvore); + inserir(7, noArvore); + inserir(8, noArvore); + inserir(3, noArvore); + inserir(5, noArvore); + + int valorBuscado = 7; + if (buscaBinaria(valorBuscado, noArvore)) + printf("Busca : %d\n", buscaBinaria(valorBuscado, noArvore)->chave); + else + printf("Não encontrou\n"); + + excluir(4, noArvore); + + printf("Pre-ordem: "); + preordem(noArvore); + printf("\n"); + printf("Em-ordem: "); + emordem(noArvore); + printf("\n"); + printf("Pos-ordem: "); + posordem(noArvore); + + printf("\nAltura: %d\n", altura(noArvore)); + return 0; +} \ No newline at end of file diff --git a/src/c/BinaryTree.c b/src/c/BinaryTree.c new file mode 100644 index 00000000..b1b6a162 --- /dev/null +++ b/src/c/BinaryTree.c @@ -0,0 +1,192 @@ +#include +#include + +// Essa é uma árvore binária não balanceada. + +struct No { + + int valor; + struct No *esquerda; + struct No *direita; + int altura; +}; + +int altura(struct No *n) { + + if (n == NULL) + return 0; + return n->altura; +} + +int max(int a, int b) { return (a > b) ? a : b; } + +struct No *novoNo(int valor) { + + struct No *novoNo = (struct No *)malloc(sizeof(struct No)); + + novoNo->valor = valor; + novoNo->esquerda = NULL; + novoNo->direita = NULL; + novoNo->altura = 1; + + return novoNo; +} + +struct No *inserir(struct No *raiz, int valor) { + + if (raiz == NULL) { + return novoNo(valor); + } + if (valor <= raiz->valor) { + raiz->esquerda = inserir(raiz->esquerda, valor); + } else { + raiz->direita = inserir(raiz->direita, valor); + } + + raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita)); + + return raiz; +} + +int busca(struct No *raiz, int valor) { + + if (raiz == NULL) { + printf(" Valor [%d] não encontrado.\n", valor); + } else if (raiz->valor == valor) { + printf(" Valor [%d] encontrado.\n", valor); + } else if (valor <= raiz->valor) { + return busca(raiz->esquerda, valor); + } else if (valor >= raiz->valor) { + return busca(raiz->direita, valor); + } +} + +void preorder(struct No *raiz) { + + if (raiz == NULL) + return; + printf("[%d]", raiz->valor); + preorder(raiz->esquerda); + preorder(raiz->direita); +} + +void inorder(struct No *raiz) { + + if (raiz == NULL) + return; + inorder(raiz->esquerda); + printf("[%d]", raiz->valor); + inorder(raiz->direita); +} + +void postorder(struct No *raiz) { + + if (raiz == NULL) + return; + postorder(raiz->esquerda); + postorder(raiz->direita); + printf("[%d]", raiz->valor); +} + +void levelOrder(struct No *raiz, int level) { + + if (raiz == NULL) { + return; + } + if (level == 0) { + printf("[%d]", raiz->valor); + } else { + levelOrder(raiz->esquerda, level - 1); + levelOrder(raiz->direita, level - 1); + } +} + +void printLevelOrder(struct No *raiz) { + int h = altura(raiz); + for (int i = 0; i < h; i++) { + levelOrder(raiz, i); + } +} + +struct No *encontraMenor(struct No *raiz) { + struct No *atual = raiz; + while (atual->esquerda != NULL) { + atual = atual->esquerda; + } + return atual; +} + +struct No *deleta(struct No *raiz, int valor) { + + if (raiz == NULL) { + return raiz; + } + if (valor < raiz->valor) { + raiz->esquerda = deleta(raiz->esquerda, valor); + } else if (valor > raiz->valor) { + raiz->direita = deleta(raiz->direita, valor); + } else { + if ((raiz->esquerda == NULL) || (raiz->direita == NULL)) { + struct No *temp = raiz->esquerda ? raiz->esquerda : raiz->direita; + + if (temp == NULL) { + temp = raiz; + raiz = NULL; + } else { + *raiz = *temp; + free(temp); + } + } else { + struct No *temp = encontraMenor(raiz->direita); + raiz->valor = temp->valor; + raiz->direita = deleta(raiz->direita, temp->valor); + } + } + + if (raiz == NULL) { + return raiz; + } + + raiz->altura = 1 + max(altura(raiz->esquerda), altura(raiz->direita)); + + return raiz; +} + +int main(void) { + + struct No *raiz; + raiz = inserir(raiz, 10); + raiz = inserir(raiz, 2); + raiz = inserir(raiz, 33); + raiz = inserir(raiz, 4); + raiz = inserir(raiz, 57); + raiz = inserir(raiz, 6); + raiz = inserir(raiz, 12); + + busca(raiz, 33); + busca(raiz, 23); + + printf("\n Preorder: "); + preorder(raiz); + + printf("\n Inorder: "); + inorder(raiz); + + printf("\n Postorder: "); + postorder(raiz); + + printf("\n Levelorder: "); + printLevelOrder(raiz); + + raiz = deleta(raiz, 7); + + printf("\n Levelorder: "); + printLevelOrder(raiz); + + raiz = deleta(raiz, 6); + + printf("\n Levelorder: "); + printLevelOrder(raiz); + + return 0; +} \ No newline at end of file diff --git a/src/c/BubbleSort.c b/src/c/BubbleSort.c index 2b083c47..54e8dc44 100644 --- a/src/c/BubbleSort.c +++ b/src/c/BubbleSort.c @@ -1,38 +1,32 @@ #include -void swap(int array[], int j) -{ - int t = array[j]; - array[j] = array[j + 1]; - array[j + 1] = t; +void swap(int array[], int j) { + int t = array[j]; + array[j] = array[j + 1]; + array[j + 1] = t; } -void bubble_sort(int array[], int n) -{ - for (int i = 0; i < n - 1; i++) - { - for (int j = 0; j < n - i - 1; j++) - { - if (array[j] > array[j + 1]) - { - swap(array, j); - } - } +void bubble_sort(int array[], int n) { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (array[j] > array[j + 1]) { + swap(array, j); + } } + } } -int main() -{ - int array_size = 9; - int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27}; +int main() { + int array_size = 9; + int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27}; - bubble_sort(array, array_size); + bubble_sort(array, array_size); - printf("Lista ordenada:\n"); - for (int i = 0; i < array_size - 1; i++) - printf("%d, ", array[i]); + printf("Lista ordenada:\n"); + for (int i = 0; i < array_size - 1; i++) + printf("%d, ", array[i]); - printf("%d\n", array[array_size - 1]); + printf("%d\n", array[array_size - 1]); - return 0; + return 0; } \ No newline at end of file diff --git a/src/c/BuscaEmGrafo.c b/src/c/BuscaEmGrafo.c deleted file mode 100644 index a6529756..00000000 --- a/src/c/BuscaEmGrafo.c +++ /dev/null @@ -1,204 +0,0 @@ -/* -* -* Grafos - Implementação de uma estrutura de Grafo não dirigido em C -* Métodos de Busca: Busca em Profundidade e Busca em Largura -* Kelvin Salton do Prado - 2015 -* -* -* (A)---------------(B)-------------(E)---------------(F) -* | | | | -* | | | | -* | | | | -* (C)---------------(D)--------------- | -* | | -* ----------------------------------- -* -* 6 Vértices -* 8 Arestas -*/ - -#include -#include - -#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM -#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER - -// Estrutura que define cada Vértice do Grafo -typedef struct NO{ - char id; - int nroVizinhos; - struct NO* vizinhos[MAX_ARESTAS]; - bool visitado; -}*VERTICE; - -// Cria Vértice e retorna -VERTICE criaVertice(char id){ - VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice - novoVertice->id = id; - novoVertice->nroVizinhos = 0; - novoVertice->visitado = false; - for (int i = 0; i < MAX_ARESTAS; i++){ - novoVertice->vizinhos[i] = NULL; - } - return novoVertice; -} - -// Liga os vértices passados como parâmetro -bool ligaVertices(VERTICE v1, VERTICE v2){ - int aux = 0; - while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos - aux++; - } - v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos - aux = 0; - while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos - aux++; - } - v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos - v1->nroVizinhos++; // Incrementa o número de vizinhos - v2->nroVizinhos++; // Incrementa o número de vizinhos -} - -/* -* Busca em Profundidade - DFS - Depht First Search -* Percorre primeiro todos os vizinhos que foram ligados primeiro ao vértice -* -*/ -int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados){ - inicio->visitado = true; // Marca o Vértice que está passando inicio como já visitado - if( inicio == destino ) return visitados; // Se for o buscado (destino) retorna ele - - int aux = 0; - while( inicio->vizinhos[aux] != NULL ){ // Enquanto existe vizinhos a serem visitados - if( inicio->vizinhos[aux]->visitado == false ){ // Se o vizinho ainda não foi visitado - // Chama recursivamente passando novo vizinho como iniício, ou seja, irá percorrer todos os vizinhos dele, e assim, sucessivamente - int resposta = buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados+1); - // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já retorna a resposta - if( resposta != -1 ) return resposta; - } - aux++; // Incrementa 1 na lista de vizinhos - } - - return -1; // Não encontrou o vértice -} - -/* -* Busca em Largura - BFS - Breadth First Search -* Implementada com o conceito de fila, porém utilizando um array simples -* Assim ela não excluí o 'vértice' do array, apenas pula uma posição para a frente -* Percorre todos os vértices por nível -*/ -int buscaEmLargura(VERTICE inicio, VERTICE destino){ - int iniFila = 0; // Variável que controla a posição do inicio da fila, é utilizada para controlar o WHILE - int tamFila = 1; // Variável que controla o tamanho da fila - - VERTICE FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados - for (int i = 0; i < MAX_VERTICES; i++){ // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro - FILA[i] = NULL; - } - FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início - - // Enquanto não terminar a fila faça - while( iniFila < tamFila ){ - // Se o elemento que está para 'sair' da fila for o buscado (destino) então retorna iniFila, que foi a distância percorrida para encontrar - if( FILA[iniFila] == destino ) return iniFila; - - /* - * Para todos os vizinhos do vértice que está para 'sair' da fila: - * Marca todos como visitado, para não coloca-los na fila novamente, - * e então os coloca na fila, e aumenta o tamanho da fila - */ - for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++){ - if( FILA[iniFila]->vizinhos[i]->visitado == false ){ - FILA[iniFila]->vizinhos[i]->visitado = true; - FILA[tamFila] = FILA[iniFila]->vizinhos[i]; - tamFila++; - } - } - iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o primeiro que entrou na fila (FIFO - First In First Out) - } - return -1; -} - -int main(){ - - // Grafo conjunto de vértices independentes - VERTICE A = criaVertice('A'); - VERTICE B = criaVertice('B'); - VERTICE C = criaVertice('C'); - VERTICE D = criaVertice('D'); - VERTICE E = criaVertice('E'); - VERTICE F = criaVertice('F'); - - // Liga todos os vértices de acordo com o GRAFO apresentado na introdução - ligaVertices(A, B); - ligaVertices(A, C); - ligaVertices(B, D); - ligaVertices(C, D); - ligaVertices(B, E); - ligaVertices(D, E); - ligaVertices(E, F); - ligaVertices(D, F); - - // Realiza a busca em profundidade - int res = buscaEmProfundidade(A, F, 0); - if( res != -1 ) - printf("DFS - Encontrou. Distancia: %d.\n", res); - else - printf("DFS - Não encontrou.\n"); - - // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false' - A->visitado = false; - B->visitado = false; - C->visitado = false; - D->visitado = false; - E->visitado = false; - F->visitado = false; - - // Realiza a busca em largura - res = buscaEmLargura(A, F); - if( res != -1 ) - printf("BFS - Encontrou. Distancia: %d.\n", res); - else - printf("BFS - Não encontrou.\n"); - - // Grafo conjunto de vértices em um array - VERTICE GRAFO[MAX_VERTICES]; - GRAFO[0] = criaVertice('A'); - GRAFO[1] = criaVertice('B'); - GRAFO[2] = criaVertice('C'); - GRAFO[3] = criaVertice('D'); - GRAFO[4] = criaVertice('E'); - GRAFO[5] = criaVertice('F'); - - // Liga todos os vértices de acordo com o GRAFO apresentado na introdução - ligaVertices(GRAFO[0], GRAFO[1]); - ligaVertices(GRAFO[0], GRAFO[2]); - ligaVertices(GRAFO[1], GRAFO[3]); - ligaVertices(GRAFO[2], GRAFO[3]); - ligaVertices(GRAFO[1], GRAFO[4]); - ligaVertices(GRAFO[3], GRAFO[4]); - ligaVertices(GRAFO[4], GRAFO[5]); - ligaVertices(GRAFO[3], GRAFO[5]); - - // Realiza a busca em profundidade - res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0); - if( res != -1 ) - printf("DFS - Encontrou. Distancia: %d.\n", res); - else - printf("DFS - Não encontrou.\n"); - - // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false' - for (int i = 0; i < MAX_VERTICES; i++){ - GRAFO[i]->visitado = false; - } - - // Realiza a busca em largura - res = buscaEmLargura(GRAFO[0], GRAFO[5]); - if( res != -1 ) - printf("BFS - Encontrou. Distancia: %d.\n", res); - else - printf("BFS - Não encontrou.\n"); - - return 0; -} \ No newline at end of file diff --git a/src/c/BuscaSentinela.c b/src/c/BuscaSentinela.c deleted file mode 100644 index 35b5f6f3..00000000 --- a/src/c/BuscaSentinela.c +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Exemplo de Busca Sentinela em C -* Objetivo: Encontrar um valor em um vetor sem precisar testar todos os valores dentro do laço -* Kelvin Salton do Prado - 2015 -*/ - -#include -#include -#include - -#define TAM_VETOR 10 - -// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a cada passo do laço de busca -int buscaSentinela(int vetor[], int chave){ - vetor[TAM_VETOR] = chave; // Coloca o valor buscado (chave) na última posição do vetor - int aux = 0; // Variável de controle do laço - while( vetor[aux] != chave ) // Enquanto não encontrar o valor (chave) incrementa 1 em aux - aux++; - if( aux == TAM_VETOR ) // Caso o valor de aux seja igual ao tamanho do vetor, significa que foi até o final e não encontrou o valor - return -1; // Não encontrou - else // Caso aux seja diferente, significa que encontrou o valor e quebrou o laço, o aux é a posição do valor buscado - return aux; // Encontrou -} - -int main(){ - - int vetor[TAM_VETOR+1]; // Declara o vetor com +1 pois é a posição que será utilizada pela sentinela - - // Preenche o vetor com valores aleatórios 0-1000 - srand(time(NULL)); - for(int i = 0; i < TAM_VETOR; i++){ - vetor[i] = rand()%1000; - printf("%d, ", vetor[i]); - } - - // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar - int res = buscaSentinela(vetor, vetor[TAM_VETOR-2]); - if( res != -1 ) - printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res); - else - printf("\n\nValor não encontrado no vetor\n\n"); - - return 0; -} \ No newline at end of file diff --git a/src/c/BuscaSequencial.c b/src/c/BuscaSequencial.c deleted file mode 100644 index bf28b592..00000000 --- a/src/c/BuscaSequencial.c +++ /dev/null @@ -1,21 +0,0 @@ -#include - -int buscaSequencial(int vetor[], int size, int buscado) { - for (int i = 0; i < size; i++) - { - if (vetor[i] == buscado) - { - return i; - } - } - return -1; -} - -int main(){ - - int a[] = {1, 2, 3, 4, 5, 6, 7, 8}; - int n = sizeof(a) / sizeof(a[0]); - printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3)); - printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9)); -} - diff --git a/src/c/BuscaSequencialRecursiva.c b/src/c/BuscaSequencialRecursiva.c deleted file mode 100644 index ef5159a3..00000000 --- a/src/c/BuscaSequencialRecursiva.c +++ /dev/null @@ -1,25 +0,0 @@ -#include - -int buscaSequencialRecursiva(int vetor[], int i, int buscado, int size) { - - if (i == size) - { - return -1; - } - else if (vetor[i] == buscado) - { - return i; - } - else - { - return buscaSequencialRecursiva(vetor, i+1, buscado, size); - } -} - -int main(){ - - int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8}; - size_t n = sizeof(vetor) / sizeof(vetor[0]); - printf("Valor %d no índice %d\n", 1, buscaSequencialRecursiva(vetor, 0, 1, n)); - printf("Valor %d no índice %d\n", 10, buscaSequencialRecursiva(vetor, 0, 10, n)); -} diff --git a/src/c/CaixeiroViajante.c b/src/c/CaixeiroViajante.c deleted file mode 100644 index b7924423..00000000 --- a/src/c/CaixeiroViajante.c +++ /dev/null @@ -1,107 +0,0 @@ -/* -* Problema do Caixeiro Viajante em C -* Utilizando uma matriz de distância para representar um grafo não direcionado. -* Objetivo: Encontrar o menor caminho que passe por todos os vértices sem repetir nenhum, e chegar novamente ao vértice de início -* -* 6 -* (4)-----(0) -* | \ / \ -* | \ 3/ \2 -* | \/ \ -* 3| /\ (1) -* | / 3\ 4/ | -* | / \ / | -* (3)-----(2) | -* | 7 | -* | | 3 -* -------------- -* -* -* Matriz de Distância -* 0 1 2 3 4 -* 0 0 2 - 3 6 -* 1 2 0 4 3 - -* 2 - 4 0 7 3 -* 3 3 3 7 0 3 -* 4 6 - 3 3 0 -* -* -*/ - -#include - -#define VERTICES 5 -#define INFINITO 429496729 - -int tempSolucao[VERTICES]; -int melhorSolucao[VERTICES]; -bool visitados[VERTICES]; -int valorMelhorSolucao = INFINITO; -int valorSolucaoAtual = 0; - -int matriz[VERTICES][VERTICES] = {{ 0, 2, INFINITO, 3, 6 }, - { 2, 0, 4, 3, INFINITO }, - { INFINITO, 4, 0, 7, 3 }, - { 3, 3, 7, 0, 3 }, - { 6, INFINITO, 3, 3, 0 }}; - -void caixeiroViajanteAux(int x){ - // Se o valor da solução atual já estiver maior que o valor da melhor solução já para, pois já não pode mais ser a melhor solução - if( valorSolucaoAtual > valorMelhorSolucao ) - return; - - if( x == VERTICES ){ // Se x == VERTICES significa que o vetor da solução temporária está completo - int distancia = matriz[tempSolucao[x-1]][tempSolucao[0]]; - // Se encontrou uma solução melhor/menor - if( distancia < INFINITO && valorSolucaoAtual + distancia < valorMelhorSolucao ){ - valorMelhorSolucao = valorSolucaoAtual + distancia; // Substitui a melhor solução pela melhor encontrada agora - // Copia todo o vetor de solução temporária para o vetor de melhor solução encontrada - for (int i = 0; i < VERTICES; ++i){ - melhorSolucao[i] = tempSolucao[i]; - } - } - return; - } - - int ultimo = tempSolucao[x-1]; // Ultimo recebe o número do último vértice que se encontra na solução temporária - // For que percorre todas as colunas da matriz na linha do último vértice do vetor solução temporária - for (int i = 0; i < VERTICES; i++){ - // Se a posição i do vetor ainda não foi visitada, e se o valor da matriz na posição é menor que INFINITO - if( visitados[i] == false && matriz[ultimo][i] < INFINITO ){ - visitados[i] = true; // Marca como visitado - tempSolucao[x] = i; // Carrega o vértice que está passando no vetor de solução temporária - valorSolucaoAtual += matriz[ultimo][i]; // Incrementa o valor da matriz na variável que guarda o total do caminho percorrido - caixeiroViajanteAux(x+1); // Chama recursivamente para o próximo vértice - valorSolucaoAtual -= matriz[ultimo][i]; // Se ainda não terminou, diminuí o valor da váriavel que guarda o total da solução atual - visitados[i] = false; // Seta como false a posição para poder ser utilizado por outro vértice - } - - } - -} - -void caixeiroViajante(int inicial){ - visitados[inicial] = true; // Marca o primeiro vértice como visitado (0) - tempSolucao[0] = inicial; // Coloca o vértice 0 na primeira posição do vetor de solução temporária - caixeiroViajanteAux(1); // Chama o método auxiliar do caixeiro viajante -} - -void iniciaVetores(){ - for (int i = 0; i < VERTICES; i++){ - visitados[i] = false; - tempSolucao[i] = -1; - melhorSolucao[i] = -1; - } -} - -int main(){ - - iniciaVetores(); - caixeiroViajante(0); - - printf("Caminho mínimo: %d\n", valorMelhorSolucao); - for (int i = 0; i < VERTICES; i++){ - printf("%d, ", melhorSolucao[i]); - } - printf("\n\n"); -} \ No newline at end of file diff --git a/src/c/CalculatePi.c b/src/c/CalculatePi.c index a161cfbc..f104a9ff 100644 --- a/src/c/CalculatePi.c +++ b/src/c/CalculatePi.c @@ -1,30 +1,25 @@ /* Calculo de Pi em C -Bruno Dantas de Paiva - 2021 -https://github.com/DantasB */ #include -float leibniz_pi_calculation(int number) -{ - float denominador = 1.0f; - float operacao = 1.0f; - float pi = 0.0f; - for (int i = 0; i < number; i++) - { - pi += operacao * (4.0 / denominador); - denominador += 2.0; - operacao = operacao * -1.0; - } - return pi; +float leibniz_pi_calculation(int number) { + float denominador = 1.0f; + float operacao = 1.0f; + float pi = 0.0f; + for (int i = 0; i < number; i++) { + pi += operacao * (4.0 / denominador); + denominador += 2.0; + operacao = operacao * -1.0; + } + return pi; } -int main() -{ - int n_terms[4] = {10, 1000, 100000, 10000000}; - for (int n = 0; n < 4; n++) - printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n])); +int main() { + int n_terms[4] = {10, 1000, 100000, 10000000}; + for (int n = 0; n < 4; n++) + printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n])); - return 0; + return 0; } \ No newline at end of file diff --git a/src/c/CicloHamiltoniano.c b/src/c/CicloHamiltoniano.c deleted file mode 100644 index 8387b149..00000000 --- a/src/c/CicloHamiltoniano.c +++ /dev/null @@ -1,134 +0,0 @@ -/* -* -* Grafos - CICLO HAMILTONIANO em C -* Kelvin Salton do Prado - 2015 -* -* ----------------------------------- -* | | -* (A)---------------(B)-------------(E)---------------(F) -* | | | | -* | | | | -* | | | | -* (C)---------------(D)--------------- | -* | | -* ----------------------------------- -* -* 6 Vértices -* 9 Arestas -*/ - -#include -#include - -#define MAX_VERTICES 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA VARIÁVEL TAMBÉM -#define MAX_ARESTAS (MAX_VERTICES * (MAX_VERTICES-1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER - -// Estrutura que define cada Vértice do Grafo -typedef struct NO{ - char id; - int nroVizinhos; - struct NO* vizinhos[MAX_ARESTAS]; - bool visitado; -}*VERTICE; - -VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo hamiltoniano - -// Cria Vértice e retorna -VERTICE criaVertice(char id){ - VERTICE novoVertice = (VERTICE) malloc( sizeof(NO) ); // Aloca um novo Vértice - novoVertice->id = id; - novoVertice->nroVizinhos = 0; - novoVertice->visitado = false; - for (int i = 0; i < MAX_ARESTAS; i++){ - novoVertice->vizinhos[i] = NULL; - } - return novoVertice; -} - -// Liga os vértices passados como parâmetro -bool ligaVertices(VERTICE v1, VERTICE v2){ - int aux = 0; - while(v1->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos - aux++; - } - v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos - aux = 0; - while(v2->vizinhos[aux] != NULL){ // Busca a primeira posição 'vazia'(NULL) dos vizinhos - aux++; - } - v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos - v1->nroVizinhos++; // Incrementa o número de vizinhos - v2->nroVizinhos++; // Incrementa o número de vizinhos -} - -bool cicloHamiltonianoAuxiliar(int aux){ - - if( aux == MAX_VERTICES ){ - for (int i = 0; i < solucao[aux-1]->nroVizinhos; i++){ - if( solucao[aux-1]->vizinhos[i] == solucao[0] ){ - return true; - } - } - return false; - } - - VERTICE s = solucao[aux-1]; // Auxiliar para simplificar o código - - for (int i = 0; i < s->nroVizinhos; i++){ // Percorre todos os vizinhos do vértice de posição aux-1 no array solução - if( s->vizinhos[i]->visitado == false ){ - s->vizinhos[i]->visitado = true; - solucao[aux] = s->vizinhos[i]; - if( cicloHamiltonianoAuxiliar(aux+1) == true ){ - return true; - } - s->vizinhos[i]->visitado = false; - } - } - - return false; -} - -bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]){ - grafo[0]->visitado = true; // Marca a posição inicial como visitada - solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo - return cicloHamiltonianoAuxiliar(1); -} - -int main(){ - - // Grafo conjunto de vértices em um array - VERTICE GRAFO[MAX_VERTICES]; - GRAFO[0] = criaVertice('A'); - GRAFO[1] = criaVertice('B'); - GRAFO[2] = criaVertice('C'); - GRAFO[3] = criaVertice('D'); - GRAFO[4] = criaVertice('E'); - GRAFO[5] = criaVertice('F'); - - // Liga todos os vértices de acordo com o GRAFO apresentado na introdução - ligaVertices(GRAFO[0], GRAFO[1]); // A - B - ligaVertices(GRAFO[0], GRAFO[2]); // A - C - ligaVertices(GRAFO[1], GRAFO[3]); // B - D - ligaVertices(GRAFO[2], GRAFO[3]); // D - C - ligaVertices(GRAFO[1], GRAFO[4]); // B - E - ligaVertices(GRAFO[3], GRAFO[4]); // D - E - ligaVertices(GRAFO[4], GRAFO[5]); // E - F - ligaVertices(GRAFO[3], GRAFO[5]); // D - F - ligaVertices(GRAFO[1], GRAFO[5]); // B - F - - for (int i = 0; i < MAX_VERTICES; i++){ - solucao[i] = criaVertice('0'); - } - - if( cicloHamiltoniano(GRAFO) ){ - printf("Ciclo Hamiltoniano:\n"); - for (int i = 0; i < MAX_VERTICES; i++){ - printf("%c, ",solucao[i]->id); - } - printf("\n\n"); - }else{ - printf("Nao possui Ciclo Hamiltoniano\n"); - } - - return 0; -} \ No newline at end of file diff --git a/src/c/CircularLinkedList.c b/src/c/CircularLinkedList.c new file mode 100644 index 00000000..0593d07c --- /dev/null +++ b/src/c/CircularLinkedList.c @@ -0,0 +1,114 @@ +/* + * + * Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica) + * + */ + +#include +#include + +typedef int TIPOCHAVE; // Tipo de ID de cada nó da lista + +// Estrutura de dados que representa cada nó da lista +typedef struct AUX { + TIPOCHAVE chave; + struct AUX *prox; +} NO, *PONT; + +typedef struct { + PONT cab; // Nó cabeça +} LISTA; + +void inicializar(LISTA *L) { + // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como + // sentinela + L->cab = (PONT)malloc(sizeof(NO)); + L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular +} + +// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e +// não necessáriamente um ponteiro para ela +PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT *ant) { + *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta + // (->), o ant guarda o ponteiro para o nó encontrado + PONT pos = L.cab->prox; + L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como + // sentinela, será o último a ser comparado + while (pos->chave != ch) { + *ant = pos; // Guarda o ponteiro para o nó + pos = pos->prox; // Vai para o próximo nó + } + if (pos != L.cab) // Se o nó não é o nó cabeça é pq encontrou + return pos; // Retorna o nó + else + return NULL; // Senão não encontrou retorna NULL +} + +bool excluir(TIPOCHAVE ch, LISTA *L) { + PONT aux, ant; + aux = buscaSequencial(ch, *L, + &ant); // Busca o valor para excluir, o ant é passado + // como endereço de memória, assim a função busca + // altera ele, guardando o valor anterior + if (aux == NULL) + return false; // Não encontrou + ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo + // que o nó a ser excluído está apontando + free(aux); // Libera a memória + return true; +} + +void inserir(TIPOCHAVE ch, LISTA *L) { + PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior + PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual + + while (pos->chave < ch && pos != L->cab) { + ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior + pos = pos->prox; // Vai para o próximo nó + } + // Quando encontrou a posição correta na ordem crescente + PONT novo_no = (PONT)malloc(sizeof(NO)); // Cria um novo nó + novo_no->chave = ch; // Coloca a chave no nó + novo_no->prox = pos; // Aponta para o próximo nó + ant->prox = novo_no; // Nó anterior aponta para o novo nó +} + +PONT mostrarLista(LISTA L) { + PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça + while (pos != L.cab) { // Se não for o nó cabeça, a lista não está vazia + printf("[ %d ]->", pos->chave); // Mostra o valor do nó + pos = pos->prox; // Vai para o próximo nó + } + printf("\n"); +} + +int main() { + + LISTA lista; + inicializar(&lista); + + inserir(4, &lista); + inserir(6, &lista); + inserir(2, &lista); + inserir(3, &lista); + inserir(1, &lista); + inserir(5, &lista); + + mostrarLista(lista); + + excluir(2, &lista); + excluir(4, &lista); + excluir(6, &lista); + + mostrarLista(lista); + + // Exemplo de busca na lista + PONT aux; + int valor = 2; + if (buscaSequencial(valor, lista, &aux) != NULL) + printf("Valor %d encontrado.\n", valor); + else + printf("Valor %d não encontrado.\n", valor); + + return 0; +} \ No newline at end of file diff --git a/src/c/ComponentesConexos.c b/src/c/ComponentesConexos.c deleted file mode 100644 index 1d7b594f..00000000 --- a/src/c/ComponentesConexos.c +++ /dev/null @@ -1,69 +0,0 @@ -/* -* -* Grafos - Algoritmo para calcular o número de componentes conexos em um determinado Grafo -* Kelvin Salton do Prado - 2015 -* -* GRAFO -* (0) (1)-------------(4)---------------(5) -* | | | | -* | | | | -* | | | | -* (2) (3)--------------- | -* | | -* ----------------------------------- -* -* -* Matriz de Adjacência -* 0 1 2 3 4 5 -* 0 0 - 1 - - - -* 1 - 0 - 1 1 - -* 2 1 - 0 - - - -* 3 - 1 - 0 1 1 -* 4 - 1 - 1 0 1 -* 5 - - - 1 1 0 -* -* -* 6 Vértices -* 8 Arestas -*/ - -#include - -#define VERTICES 6 -#define INF -1 - -bool visitados[VERTICES]; -int componentes = 0; - -int matriz[VERTICES][VERTICES] = { { 0, INF, 1, INF, INF, INF }, - { INF, 0, INF, 1, 1, INF }, - { 1, INF, 0, INF, INF, INF }, - { INF, 1, INF, 0, 1, 1 }, - { INF, 1, INF, 1, 0, 1 }, - { INF, INF, INF, 1, 1, 0 } }; - -// Método recursivo que encontra os componentes conexos a partir de uma matriz de adjacências -void calculaComponentesConexos(int atual){ - for (int i = 0; i < VERTICES; i++){ - if( visitados[i] == false && matriz[atual][i] == 1 ){ - visitados[i] = true; - componentes++; - printf("(%d)-", i); - calculaComponentesConexos(i); - } - } -} - -int main(){ - for (int i = 0; i < VERTICES; i++) - visitados[i] = false; - - for (int i = 0; i < VERTICES; i++) - if( visitados[i] == false ){ - componentes = 0; - calculaComponentesConexos(i); - printf("\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n", i, componentes); - } - - return 0; -} \ No newline at end of file diff --git a/src/c/ConnectedComponents.c b/src/c/ConnectedComponents.c new file mode 100644 index 00000000..122f8575 --- /dev/null +++ b/src/c/ConnectedComponents.c @@ -0,0 +1,70 @@ +/* + * + * Grafos - Algoritmo para calcular o número de componentes conexos em um + *determinado Grafo + * + * GRAFO + * (0) (1)-------------(4)---------------(5) + * | | | | + * | | | | + * | | | | + * (2) (3)--------------- | + * | | + * ----------------------------------- + * + * + * Matriz de Adjacência + * 0 1 2 3 4 5 + * 0 0 - 1 - - - + * 1 - 0 - 1 1 - + * 2 1 - 0 - - - + * 3 - 1 - 0 1 1 + * 4 - 1 - 1 0 1 + * 5 - - - 1 1 0 + * + * + * 6 Vértices + * 8 Arestas + */ + +#include + +#define VERTICES 6 +#define INF -1 + +bool visitados[VERTICES]; +int componentes = 0; + +int matriz[VERTICES][VERTICES] = { + {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF}, + {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1}, + {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}}; + +// Método recursivo que encontra os componentes conexos a partir de uma matriz +// de adjacências +void calculaComponentesConexos(int atual) { + for (int i = 0; i < VERTICES; i++) { + if (visitados[i] == false && matriz[atual][i] == 1) { + visitados[i] = true; + componentes++; + printf("(%d)-", i); + calculaComponentesConexos(i); + } + } +} + +int main() { + for (int i = 0; i < VERTICES; i++) + visitados[i] = false; + + for (int i = 0; i < VERTICES; i++) + if (visitados[i] == false) { + componentes = 0; + calculaComponentesConexos(i); + printf( + "\nNumero de componentes conexos iniciando pelo vertice %d: %d\n\n", + i, componentes); + } + + return 0; +} \ No newline at end of file diff --git a/src/c/CountingSort.c b/src/c/CountingSort.c index 523fb7a4..bebad0e8 100644 --- a/src/c/CountingSort.c +++ b/src/c/CountingSort.c @@ -1,61 +1,66 @@ #include #include -// CountingSort - Ordenação por Contagem - Matheus Martins Batista - Universidade Federal de Itajuba - 2021 +// CountingSort - Ordenação por Contagem - Matheus Martins Batista - +// Universidade Federal de Itajuba - 2021 -// Necessário encontrar o maior elemento para alocar o vetor auxiliar de contagem -int findMax (int *arr, int tam) { - int max = arr[0]; +// Necessário encontrar o maior elemento para alocar o vetor auxiliar de +// contagem +int findMax(int *arr, int tam) { + int max = arr[0]; - for (int i = 1; i < tam; i++) { - if (arr[i] > max) { - max = arr[i]; - } + for (int i = 1; i < tam; i++) { + if (arr[i] > max) { + max = arr[i]; } + } - return max; + return max; } // Ordena os valores presentes em A e armazena em B void countingSort(int *arrA, int *arrB, int tam) { - // Vetor de contagem terá a frequência que um número aparece no vetor - // deve-se setar 0 para todos os elementos ou usar calloc - int max = findMax(arrA, tam); - int* count = calloc(max + 1, sizeof(int)); - - // Frequência que determinado valor aparece no vetor - for (int i = 0; i < tam; i++) { - count[arrA[i]]++; - } + // Vetor de contagem terá a frequência que um número aparece no vetor + // deve-se setar 0 para todos os elementos ou usar calloc + int max = findMax(arrA, tam); + int *count = calloc(max + 1, sizeof(int)); - // Acumulativo da frequência dos valores menores que um elemento i do vetor original (A) - for (int i = 1; i <= max; i++) { - count[i] += count[i - 1]; - } + // Frequência que determinado valor aparece no vetor + for (int i = 0; i < tam; i++) { + count[arrA[i]]++; + } - // Percorrer o vetor original com início no último elemento, subtituindo os indices nos elementos do vetor count e decrescendo a cada atribuição - for (int i = tam - 1; i >= 0; i--) { - arrB[count[arrA[i]] - 1] = arrA[i]; - count[arrA[i]]--; - } + // Acumulativo da frequência dos valores menores que um elemento i do vetor + // original (A) + for (int i = 1; i <= max; i++) { + count[i] += count[i - 1]; + } + + // Percorrer o vetor original com início no último elemento, subtituindo os + // indices nos elementos do vetor count e decrescendo a cada atribuição + for (int i = tam - 1; i >= 0; i--) { + arrB[count[arrA[i]] - 1] = arrA[i]; + count[arrA[i]]--; + } } int main() { - int *arrA, *arrB; - int tam = 10; - arrA = malloc(tam * sizeof(int)); - arrB = calloc(tam, sizeof(int)); + int *arrA, *arrB; + int tam = 10; + arrA = malloc(tam * sizeof(int)); + arrB = calloc(tam, sizeof(int)); - // Popular vetor A - srand(48+tam); - for(int j = 0; j < tam; j++) arrA[j] = rand()%100; + // Popular vetor A + srand(48 + tam); + for (int j = 0; j < tam; j++) + arrA[j] = rand() % 100; - countingSort(arrA, arrB, tam); + countingSort(arrA, arrB, tam); - printf("Vetor ordenado: "); - for (int i = 0; i < tam; i++) { - printf("%d ", arrB[i]); - } + printf("Vetor ordenado: "); + for (int i = 0; i < tam; i++) { + printf("%d ", arrB[i]); + } - return 0; + return 0; } diff --git a/src/c/Dijkstra.c b/src/c/Dijkstra.c new file mode 100644 index 00000000..107e0acf --- /dev/null +++ b/src/c/Dijkstra.c @@ -0,0 +1,110 @@ +/* + * Graphs - Dijkstra Algorithm in C + * Complexity: Theta(n^2) + * + * 1 for all - Edges with non-negative weights - Greedy algorithm + * Finds the shortest path from one vertex (start) to another (destination) + * + * Graph with 5 vertices and 6 edges + * + * 6 + * (0)-----------------(1) + * | | + * 10 | | 2 + * | 1 | + * (2)-----------------(3) + * \ / + * 3 \ / 8 + * \ / + * -----(4)----- + * + * Distance Matrix + * 0 1 2 3 4 + * 0 0 6 10 - - + * 1 6 0 - 2 - + * 2 10 - 0 1 3 + * 3 - 2 1 0 8 + * 4 - - 3 8 0 + * + * For infinite values, the value will be considered: 4294967295 + * The objective is to leave the starting point (0) and reach the destination + * (4) by the shortest route Response: (0)->(1)->(3)->(2)->(4) = 12 + * + */ + +#include +#include + +#define noVertices \ + 5 // Defines a constant 5 which is the number of vertices in the graph + +// Dijkstra's algorithm takes as parameters the distance matrix and the number +// of vertices +void Dijkstra(unsigned long int matrix[noVertices][noVertices], int n) { + + bool visited[n]; // Variable that holds true for visited vertices + + // The value 'i' from the for below is not used, as the for is only used to + // traverse the entire number of columns in the matrix + for (int i = 1; i < n; i++) { // Starts at 1 because you don't need to compare + // the vertex with itself + + int min = -1; // Variable that stores the position of the smallest value, + // starts at -1 as it is an invalid position + unsigned long int MinValue = + 4294967295; // Variable that stores the smallest value found, starts + // with 'infinity', so always on the first pass the value + // will be smaller than this variable + // For that loops through all rows in column [0] + for (int j = 1; j < n; j++) { + // If the vertex has not yet been visited and the value is less than the + // 'MinValor' + if (!visited[j] && matrix[j][0] < MinValue) { + min = j; // Saves the position of the smallest + MinValue = matrix[j][0]; // Save the smallest value + } + } + + visited[min] = true; // Mark the value of the minimum position as visited + + // Goes from 1 to n + for (int j = 1; j < n; j++) { + // If the value of column [0] + the value of the passing column is less + // than the value of the passing row and column [0] Update the first + // column of the matrix, which will be used for the next iterations + if ((matrix[min][0] + matrix[min][j]) < matrix[j][0]) { + matrix[j][0] = matrix[min][0] + matrix[min][j]; + } + } + } +} + +int main() { + + unsigned long int Matrix[noVertices][noVertices] = { + {0, 6, 10, 4294967295, 4294967295}, + {6, 0, 4294967295, 2, 4294967295}, + {10, 4294967295, 0, 1, 3}, + {4294967295, 2, 1, 0, 8}, + {4294967295, 4294967295, 3, 8, 0}}; + + Dijkstra(Matrix, noVertices); + + printf("Total shortest path from vertex 0 to 4: %lu\n", + Matrix[4][0]); // Shortest total path + + // Print the matrix with the updated values + printf("Matrix:\n"); + for (int i = 0; i < noVertices; ++i) { + for (int e = 0; e < noVertices; ++e) { + if (Matrix[i][e] < 10) + printf(" %lu ", Matrix[i][e]); + else + printf("%lu ", Matrix[i][e]); + } + printf("\n"); + } + printf("\n"); + + return 0; +} diff --git a/src/c/DoublyLinkedList.c b/src/c/DoublyLinkedList.c new file mode 100644 index 00000000..7be11ee4 --- /dev/null +++ b/src/c/DoublyLinkedList.c @@ -0,0 +1,144 @@ +/* + * Exemplo Lista Duplamente Encadeada em C + */ + +#include +#include + +/* Lista encadeada utilizando celula cabeça */ + +typedef struct cel celula; +struct cel { + int dado; + struct cel *prox; + struct cel *ant; +}; + +/* O ponteiro 'p' é a cabeça da lista*/ + +void insereInicio(int x, celula *p) /* Insere no inicio da lista*/ +{ + celula *nova, *q; + nova = malloc(sizeof(celula)); + nova->dado = x; + nova->prox = p->prox; + /* verifica se a lista está vazia*/ + if (p->prox != NULL) { + q = nova->prox; + q->ant = nova; + } + p->prox = nova; + nova->ant = p; +} + +void insereUltimo(int x, celula *p) /* Insere no final da lista*/ +{ + celula *q; + celula *nova; + nova = malloc(sizeof(celula)); + nova->dado = x; + q = p; + while (q->prox != NULL) + q = q->prox; + + q->prox = nova; + nova->ant = q; + nova->prox = NULL; +} + +void buscaEremove(int y, celula *p) { + celula *w, *q; + w = p; + q = p->prox; + while (q != NULL && q->dado != y) { + w = q; + q = q->prox; + } + if (q != NULL) { + w->prox = q->prox; + q->ant = w; + free(q); + } else { + printf("\nLista nao contem item\n\n"); + system("pause"); + } +} + +void imprime(celula *p) { + celula *q; + for (q = p->prox; q != NULL; q = q->prox) + printf("%d ", q->dado); +} + +void Menu() { + printf(" Menu Principal\n"); + printf("1 - Insere inicio\n"); + printf("2 - Insere ultimo\n"); + printf("3 - Retira\n"); + printf("4 - Sair\n"); + printf("\nOpcao: "); +} + +void libera(celula *ini) { + celula *p; + p = ini; + while (p != NULL) { + celula *q = p->prox; /* guarda referência para o próximo elemento*/ + free(p); /* libera a memória apontada por p */ + p = q; /* faz p apontar para o próximo */ + } +} + +int main() { + celula *p; + int op = 0, item; + // inicializa lista + p = malloc(sizeof(celula)); + p->ant = NULL; + p->prox = NULL; + // fim_inicializa + + do { + system("cls"); + printf("\nConteudo da lista: "); + if (p->prox != NULL) { + imprime(p); + } else { + printf("Lista VAZIA"); + } + printf("\n\n"); + Menu(); + scanf("%d", &op); + switch (op) { + case 1: + printf("Insere no inicio da lista: "); + scanf("%d", &item); + insereInicio(item, p); + break; + case 2: + printf("Insere na ultima posicao da lista: "); + scanf("%d", &item); + insereUltimo(item, p); + break; + case 3: + if (p->prox != NULL) { + printf("Retirar um elemento: "); + scanf("%d", &item); + buscaEremove(item, p); + } else { + printf("\nLista VAZIA\n\n"); + system("pause"); + } + break; + case 4: + break; + default: + printf("Opcao invalida!\n"); + system("pause"); + break; + } + + } while (op != 4); + libera(p); + return 0; +} diff --git a/src/c/DynamicQueue.c b/src/c/DynamicQueue.c new file mode 100644 index 00000000..074aebc6 --- /dev/null +++ b/src/c/DynamicQueue.c @@ -0,0 +1,72 @@ +/* + * Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C + */ + +#include +#include + +typedef int TIPOCHAVE; + +typedef struct NO { + TIPOCHAVE chave; + struct NO *prox; +} *PONT; + +PONT novoNO(TIPOCHAVE ch) { + PONT aux = (PONT)malloc(sizeof(NO)); + aux->chave = ch; + aux->prox = NULL; + return aux; +} + +PONT insere(TIPOCHAVE ch, PONT no) { + PONT aux = novoNO(ch); + aux->prox = no; + return aux; +} + +void mostraFila(PONT no) { + while (no != NULL) { + printf("[%d]->", no->chave); + no = no->prox; + } + printf("\n"); +} + +void remove(PONT no) { + PONT noAnterior = no; + while (no->prox != NULL) { + noAnterior = no; + no = no->prox; + } + noAnterior->prox = NULL; + free(no); +} + +int tamanhoFila(PONT no) { + int cont = 0; + while (no != NULL) { + cont++; + no = no->prox; + } + return cont; +} + +int main() { + PONT fila = novoNO(5); + fila = insere(8, fila); + fila = insere(1, fila); + fila = insere(3, fila); + fila = insere(5, fila); + fila = insere(4, fila); + fila = insere(2, fila); + + mostraFila(fila); + remove(fila); + mostraFila(fila); + remove(fila); + mostraFila(fila); + + printf("Tamanho da fila: %d\n", tamanhoFila(fila)); + return 0; +} \ No newline at end of file diff --git a/src/c/DynamicStack.c b/src/c/DynamicStack.c new file mode 100644 index 00000000..4e63e575 --- /dev/null +++ b/src/c/DynamicStack.c @@ -0,0 +1,82 @@ +/* + * Pilha Dinâmica utilizando uma Lista Ligada em C + */ + +#include +#include + +#define ERRO -1 + +typedef int TIPOCHAVE; + +typedef struct AUX { + TIPOCHAVE chave; + struct AUX *prox; +} *PILHA; + +PILHA CREATE(TIPOCHAVE ch) { + PILHA novaPilha = (PILHA)malloc(sizeof(PILHA)); + novaPilha->chave = ch; + novaPilha->prox = NULL; + return novaPilha; +} + +PILHA PUSH(TIPOCHAVE ch, PILHA pi) { + /*while( pi->prox != NULL ){ + pi = pi->prox; + }*/ + PILHA novo = CREATE(ch); + // pi->prox = novo; + novo->prox = pi; + return novo; +} + +PILHA POP(PILHA pi) { + PILHA sub = pi->prox; + free(pi); + return sub; +} + +void SHOW(PILHA pi) { + printf("PILHA:\n"); + while (pi->prox != NULL) { + printf("[ %d ]\n", pi->chave); + pi = pi->prox; + } + printf("[ %d ]\n", pi->chave); +} + +bool SEARCH(TIPOCHAVE ch, PILHA pi) { + bool vAchou = false; + while (pi != NULL) { + if (pi->chave == ch) + vAchou = true; + pi = pi->prox; + } + return vAchou; +} + +int main() { + PILHA vPilha; + + vPilha = PUSH(1, vPilha); + vPilha = PUSH(2, vPilha); + vPilha = PUSH(3, vPilha); + vPilha = PUSH(4, vPilha); + vPilha = PUSH(5, vPilha); + vPilha = PUSH(6, vPilha); + + SHOW(vPilha); + + vPilha = POP(vPilha); + vPilha = POP(vPilha); + + SHOW(vPilha); + + if (SEARCH(6, vPilha)) + printf("\nAchou\n"); + else + printf("\nNão achou\n"); + + return 0; +} \ No newline at end of file diff --git a/src/c/Exponenciacao.c b/src/c/Exponenciacao.c deleted file mode 100644 index fb59d362..00000000 --- a/src/c/Exponenciacao.c +++ /dev/null @@ -1,24 +0,0 @@ -#include - - - -int exponenciacao(int base, int expoente){ - - int i; - int result = base; - - for(i=0; i - - - -int exponenciacao(int base, int expoente){ - - if(expoente==0) return 1; - - return (base * exponenciacao(base, expoente-1)); - -} - - - -int main(){ - - printf("%d\n", exponenciacao(5, 3)); - - return 0; -} diff --git a/src/c/Exponentiation.c b/src/c/Exponentiation.c new file mode 100644 index 00000000..1abf4a77 --- /dev/null +++ b/src/c/Exponentiation.c @@ -0,0 +1,19 @@ +#include + +int exponenciacao(int base, int expoente) { + + int i; + int result = base; + + for (i = 0; i < expoente - 1; i++) + result *= base; + + return result; +} + +int main() { + + printf("%d\n", exponenciacao(5, 3)); + + return 0; +} diff --git a/src/c/ExponentiationRecursive.c b/src/c/ExponentiationRecursive.c new file mode 100644 index 00000000..5860daed --- /dev/null +++ b/src/c/ExponentiationRecursive.c @@ -0,0 +1,16 @@ +#include + +int exponenciacao(int base, int expoente) { + + if (expoente == 0) + return 1; + + return (base * exponenciacao(base, expoente - 1)); +} + +int main() { + + printf("%d\n", exponenciacao(5, 3)); + + return 0; +} diff --git a/src/c/Factorial.c b/src/c/Factorial.c new file mode 100644 index 00000000..bed39222 --- /dev/null +++ b/src/c/Factorial.c @@ -0,0 +1,25 @@ +#include +#include + +/* + * Exemplos de função para retornar o fatorial de um número n + * função recursiva + */ + +int main() { + int num; + printf("Digite um número: "); + scanf("%d", &num); + int result = fatorial(num); + printf("1 => "); + printf("%d! é : %d\n", num, result); + return (0); +} + +int fatorial(int num) { + if (num <= 1) { + return 1; + } + printf("%d * ", num); + return num * fatorial(num - 1); +} diff --git a/src/c/FactorialRecursive.c b/src/c/FactorialRecursive.c new file mode 100644 index 00000000..a4a2e4e6 --- /dev/null +++ b/src/c/FactorialRecursive.c @@ -0,0 +1,16 @@ +#include + +int fatorial(int n) { + + if (n == 1) + return 1; + + return (n * fatorial(n - 1)); +} + +int main() { + + printf("%d\n", fatorial(5)); + + return 0; +} diff --git a/src/c/Fatorial.c b/src/c/Fatorial.c deleted file mode 100644 index 7cbe49e3..00000000 --- a/src/c/Fatorial.c +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include - -/* -* Exemplos de função para retornar o fatorial de um número n -* função recursiva -* Jhonata Ribeiro - 2017 -*/ - -int main(){ - int num; - printf("Digite um número: "); - scanf("%d", &num); - int result = fatorial(num); - printf("1 => "); - printf("%d! é : %d\n", num, result); - return(0); -} - -int fatorial(int num){ - if(num <= 1 ){ - return 1; - } - printf("%d * ", num); - return num * fatorial(num - 1); -} diff --git a/src/c/FatorialRecursiva.c b/src/c/FatorialRecursiva.c deleted file mode 100644 index a2390927..00000000 --- a/src/c/FatorialRecursiva.c +++ /dev/null @@ -1,20 +0,0 @@ -#include - - - -int fatorial(int n){ - - if(n==1) return 1; - - return (n * fatorial(n-1)); - -} - - - -int main(){ - - printf("%d\n", fatorial(5)); - - return 0; -} diff --git a/src/c/FibonacciIterative.c b/src/c/FibonacciIterative.c index 24177b90..36c7d1c1 100644 --- a/src/c/FibonacciIterative.c +++ b/src/c/FibonacciIterative.c @@ -1,18 +1,18 @@ #include int fibonacci(int number) { - int last_number = 0; - int current_number = 1; + int last_number = 0; + int current_number = 1; - for (int index = 0; index < number; ++index) { - int temp = current_number; - current_number += last_number; - last_number = temp; - } - return last_number; + for (int index = 0; index < number; ++index) { + int temp = current_number; + current_number += last_number; + last_number = temp; + } + return last_number; } int main() { - printf("Fibonacci Iterative: %d\n", fibonacci(12)); - return 0; + printf("Fibonacci Iterative: %d\n", fibonacci(12)); + return 0; } diff --git a/src/c/FibonacciMemoization.c b/src/c/FibonacciMemoization.c index 43cdaf9b..f8afb46b 100644 --- a/src/c/FibonacciMemoization.c +++ b/src/c/FibonacciMemoization.c @@ -1,27 +1,28 @@ #include -#define MAX_N 100 // Define the maximum number for which you want to calculate Fibonacci +#define MAX_N \ + 100 // Define the maximum number for which you want to calculate Fibonacci int memo[MAX_N]; // Memoization table to store computed values int fibonacci(int number) { - if (number <= 1) { - return number; - } - if (memo[number] != -1) { - return memo[number]; - } - - memo[number] = fibonacci(number - 1) + fibonacci(number - 2); + if (number <= 1) { + return number; + } + if (memo[number] != -1) { return memo[number]; + } + + memo[number] = fibonacci(number - 1) + fibonacci(number - 2); + return memo[number]; } int main(void) { - // Initialize the memoization table with -1 (uncomputed) - for (int i = 0; i < MAX_N; i++) { - memo[i] = -1; - } + // Initialize the memoization table with -1 (uncomputed) + for (int i = 0; i < MAX_N; i++) { + memo[i] = -1; + } - printf("memoization: %d\n", fibonacci(12)); - return 0; + printf("memoization: %d\n", fibonacci(12)); + return 0; } diff --git a/src/c/FibonacciRecursive.c b/src/c/FibonacciRecursive.c index ecaff406..1054cc06 100644 --- a/src/c/FibonacciRecursive.c +++ b/src/c/FibonacciRecursive.c @@ -1,18 +1,18 @@ #include int fibonacci(int number) { - if (number == 0) { - return 0; - } else if (number == 1) { - return 1; - } else { - return fibonacci(number - 1) + fibonacci(number - 2); - } + if (number == 0) { + return 0; + } else if (number == 1) { + return 1; + } else { + return fibonacci(number - 1) + fibonacci(number - 2); + } } int main(void) { - int test_nbr = 12; + int test_nbr = 12; - printf("recursive: %d\n", fibonacci(test_nbr)); - return 0; + printf("recursive: %d\n", fibonacci(test_nbr)); + return 0; } diff --git a/src/c/Fila.c b/src/c/Fila.c deleted file mode 100644 index 1aa9e86d..00000000 --- a/src/c/Fila.c +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Exemplo de implementação de Fila em C -* Kelvin S. do Prado -*/ - -#include - -#define MAX 10 -#define ERRO -1 - -typedef int TIPOCHAVE; - -typedef struct{ - TIPOCHAVE chave; -}REGISTRO; - -typedef struct{ - REGISTRO A[MAX+1]; - int nroRegistros; -}FILA; - -void inicializa(FILA* F){ - int i = 0; - for (i; i < MAX-2; i++){ - F->A[i].chave = i*2; - } - F->nroRegistros = i; -} - -void mostraFila(FILA* F){ - int i = 0; - printf("FILA:\n"); - for (i; i < F->nroRegistros; i++){ - printf("[ %d ] ", F->A[i].chave); - } - printf("\n\n"); -} - -bool insereFila(TIPOCHAVE ch, FILA* F){ - if( F->nroRegistros >= MAX ) - return false; - F->A[F->nroRegistros].chave = ch; - F->nroRegistros++; - return true; -} - -bool removeFila(FILA* F){ - if( F->nroRegistros <= 0 ) - return false; - int i = 1; - for (i; i < F->nroRegistros; i++){ - F->A[i-1].chave = F->A[i].chave; - } - F->nroRegistros--; - return true; -} - -int buscaFila(TIPOCHAVE ch, FILA* F){ - F->A[F->nroRegistros].chave = ch; // Coloca a ch na ultima posição para fazer busca Sentinela - int i = 0; - while( F->A[i].chave != ch ) - i++; - if( i >= F->nroRegistros ) - return ERRO; - return i; -} - -int main(){ - FILA fi; - inicializa(&fi); - mostraFila(&fi); - - insereFila(15, &fi); - mostraFila(&fi); - - removeFila(&fi); - mostraFila(&fi); - - printf("A chave buscada se encontra na posicao %d da fila\n\n", buscaFila(8, &fi) ); - return 0; -} \ No newline at end of file diff --git a/src/c/FilaEncadeadaDinamica.c b/src/c/FilaEncadeadaDinamica.c deleted file mode 100644 index 7afbfe15..00000000 --- a/src/c/FilaEncadeadaDinamica.c +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Implementação de uma Estrutura de Fila Dinâmica Ligada/Encadeada em C -* Kelvin Salton do Prado - 2015 -*/ - -#include -#include - -typedef int TIPOCHAVE; - -typedef struct NO{ - TIPOCHAVE chave; - struct NO* prox; -}*PONT; - -PONT novoNO(TIPOCHAVE ch){ - PONT aux = (PONT) malloc( sizeof(NO) ); - aux->chave = ch; - aux->prox = NULL; - return aux; -} - -PONT insere(TIPOCHAVE ch, PONT no){ - PONT aux = novoNO(ch); - aux->prox = no; - return aux; -} - -void mostraFila(PONT no){ - while(no != NULL){ - printf("[%d]->", no->chave); - no = no->prox; - } - printf("\n"); -} - -void remove(PONT no){ - PONT noAnterior = no; - while(no->prox != NULL){ - noAnterior = no; - no = no->prox; - } - noAnterior->prox = NULL; - free(no); -} - -int tamanhoFila(PONT no){ - int cont = 0; - while(no != NULL){ - cont++; - no = no->prox; - } - return cont; -} - -int main(){ - PONT fila = novoNO(5); - fila = insere(8, fila); - fila = insere(1, fila); - fila = insere(3, fila); - fila = insere(5, fila); - fila = insere(4, fila); - fila = insere(2, fila); - - mostraFila(fila); - remove(fila); - mostraFila(fila); - remove(fila); - mostraFila(fila); - - printf("Tamanho da fila: %d\n", tamanhoFila(fila) ); - return 0; -} \ No newline at end of file diff --git a/src/c/FloydWarshall.c b/src/c/FloydWarshall.c new file mode 100644 index 00000000..1ce22edc --- /dev/null +++ b/src/c/FloydWarshall.c @@ -0,0 +1,90 @@ +/* + * Grafos - Algoritmo de Floyd-Warshall em C + * Complexidade: Teta de vértices ao cubo = Teta(n^3) + * + * Encontra o caminho de todos para todos os vértices + * + * Grafo com 5 vértices e 6 arestas + * + * 6 + * (0)-----------------(1) + * | | + * 10 | | 2 + * | 1 | + * (2)-----------------(3) + * \ / + * 3 \ / 8 + * \ / + * -----(4)----- + * + * Matriz de Distância + * 0 1 2 3 4 + * 0 0 6 10 - - + * 1 6 0 - 2 - + * 2 10 - 0 1 3 + * 3 - 2 1 0 8 + * 4 - - 3 8 0 + * + * Para valores infinitos será considerado o valor: 4294967295 + * + */ + +#include + +#define nroVertices \ + 5 // Define uma constante 5 que é a quantidade de vértices do grafo + +// Algoritmo de Floyd-Warshall recebe como parâmetro a matriz de distância e o +// número de vértices +void FloydWarshall(unsigned long int matriz[nroVertices][nroVertices], int n) { + for (int x = 0; x < n; x++) { + for (int y = 0; y < n; y++) { + for (int z = 0; z < n; z++) { + if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) + matriz[y][z] = matriz[y][x] + matriz[x][z]; + } + } + } +} + +int main() { + + unsigned long int Matriz[nroVertices][nroVertices] = { + {0, 6, 10, 4294967295, 4294967295}, + {6, 0, 4294967295, 2, 4294967295}, + {10, 4294967295, 0, 1, 3}, + {4294967295, 2, 1, 0, 8}, + {4294967295, 4294967295, 3, 8, 0}}; + + FloydWarshall(Matriz, nroVertices); + + // Mostra a matriz com os valores atualizados + printf("Matriz:\n"); + for (int i = 0; i < nroVertices; ++i) { + for (int e = 0; e < nroVertices; ++e) { + if (Matriz[i][e] < 10) + printf(" %lu ", Matriz[i][e]); + else + printf("%lu ", Matriz[i][e]); + } + printf("\n"); + } + printf("\n"); + + // printf("Total caminho mais curto do vertice 0 ao 4: %lu\n", Matriz[4][0]); + // // [destino] [origem] printf("Total caminho mais curto do vertice 2 ao 0: + // %lu\n", Matriz[0][2]); printf("Total caminho mais curto do vertice 4 ao 3: + // %lu\n\n", Matriz[3][4]); + + // Mostra todos os caminhos + printf("\n"); + for (int i = 0; i < nroVertices; ++i) { + for (int x = 0; x < nroVertices; ++x) { + printf("Menor distancia saindo do %d para chegar ao %d = %lu.\n", i, x, + Matriz[x][i]); + } + } + printf("\n\n"); + + return 0; +} \ No newline at end of file diff --git a/src/c/Grafos.c b/src/c/Grafos.c deleted file mode 100644 index bd46e85a..00000000 --- a/src/c/Grafos.c +++ /dev/null @@ -1,125 +0,0 @@ -/* -* -* -* --------------------- -* | | -* | | -* 5 V 8 | -* (A)------------->(B)------------ | 2 -* \ | | -* \ | | -* \ 6 4 V | -* ---------->(C)--------->(D)------ -* -* -*/ - -#include -#include - -#define MAX_VERTICES 20 // Constante que define o máximo de vertices que o grafo pode ter - -int nroVertices = 0; // Guarda o número de vértices atual -int matriz[MAX_VERTICES][MAX_VERTICES]; // Matriz de Distancia -int componentes; - -typedef struct NO{ - char id; - int nroVizinhos; - struct AUX* vizinhos[]; - bool visitado; - int indice; // Guarda a ordem em que o vértice foi criado -}*VERTICE; - -typedef struct AUX{ - VERTICE vizinho; - int valor; -}*ARESTA; - -VERTICE criaVertice(char id){ - matriz[nroVertices][nroVertices] = 0; - VERTICE novo = (VERTICE) malloc( sizeof(NO) ); - novo->id = id; - novo->nroVizinhos = 0; - novo->visitado = false; - novo->indice = nroVertices; - nroVertices++; - return novo; -} - -void ligaVertice(VERTICE v1, VERTICE v2, int valor){ - matriz[v1->indice][v2->indice] = valor; - ARESTA nova = (ARESTA) malloc( sizeof(AUX) ); - nova->vizinho = v2; - nova->valor = valor; - v1->vizinhos[v1->nroVizinhos] = nova; - v1->nroVizinhos++; -} - -void mostraMatrizDistancia(){ - printf("\nMatriz de Distancia\n"); - for(int l = 0; l < nroVertices; l++){ - for(int c = 0; c < nroVertices; c++){ - if( matriz[l][c] == -1 ) - printf("%d, ", matriz[l][c]); - else - printf(" %d, ", matriz[l][c]); - } - printf("\n"); - } - printf("\n"); -} - -void zeraVariaveis(){ - for(int l = 0; l < MAX_VERTICES; l++){ - for(int c = 0; c < MAX_VERTICES; c++){ - matriz[l][c] = -1; - } - } -} - -void visitaVizinhos(bool visitados[], int atual){ - for (int i = 0; i < nroVertices; i++){ - if( visitados[i] == false && matriz[atual][i] > 0 ){ - visitados[i] = true; - componentes++; - visitaVizinhos(visitados, i); - } - } -} - -void calculaComponentesConexos(){ - bool visitados[nroVertices]; - for (int i = 0; i < nroVertices; ++i){ - visitados[i] = false; - } - for (int i = 0; i < nroVertices; i++){ - if( visitados[i] == false ){ - visitaVizinhos(visitados, i); - } - } -} - -int main(){ - zeraVariaveis(); - - // Matriz de Distância funciona conforme a ordem inserida - VERTICE A = criaVertice('A'); - VERTICE B = criaVertice('B'); - VERTICE C = criaVertice('C'); - VERTICE D = criaVertice('D'); - VERTICE E = criaVertice('E'); - - ligaVertice(A, B, 5); - ligaVertice(A, C, 6); - ligaVertice(B, D, 8); - ligaVertice(C, D, 4); - ligaVertice(D, B, 2); - - calculaComponentesConexos(); - printf("\nComponentes Conexos: %d\n", componentes) ; - - mostraMatrizDistancia(); - - return 0; -} \ No newline at end of file diff --git a/src/c/GraphSearch.c b/src/c/GraphSearch.c new file mode 100644 index 00000000..7679dce2 --- /dev/null +++ b/src/c/GraphSearch.c @@ -0,0 +1,225 @@ +/* + * + * Grafos - Implementação de uma estrutura de Grafo não dirigido em C + * Métodos de Busca: Busca em Profundidade e Busca em Largura + * + * + * (A)---------------(B)-------------(E)---------------(F) + * | | | | + * | | | | + * | | | | + * (C)---------------(D)--------------- | + * | | + * ----------------------------------- + * + * 6 Vértices + * 8 Arestas + */ + +#include +#include + +#define MAX_VERTICES \ + 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA + // VARIÁVEL TAMBÉM +#define MAX_ARESTAS \ + (MAX_VERTICES * \ + (MAX_VERTICES - \ + 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER + +// Estrutura que define cada Vértice do Grafo +typedef struct NO { + char id; + int nroVizinhos; + struct NO *vizinhos[MAX_ARESTAS]; + bool visitado; +} *VERTICE; + +// Cria Vértice e retorna +VERTICE criaVertice(char id) { + VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice + novoVertice->id = id; + novoVertice->nroVizinhos = 0; + novoVertice->visitado = false; + for (int i = 0; i < MAX_ARESTAS; i++) { + novoVertice->vizinhos[i] = NULL; + } + return novoVertice; +} + +// Liga os vértices passados como parâmetro +bool ligaVertices(VERTICE v1, VERTICE v2) { + int aux = 0; + while (v1->vizinhos[aux] != + NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos + aux++; + } + v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos + aux = 0; + while (v2->vizinhos[aux] != + NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos + aux++; + } + v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos + v1->nroVizinhos++; // Incrementa o número de vizinhos + v2->nroVizinhos++; // Incrementa o número de vizinhos +} + +/* + * Busca em Profundidade - DFS - Depht First Search + * Percorre primeiro todos os vizinhos que foram ligados primeiro ao + *vértice + * + */ +int buscaEmProfundidade(VERTICE inicio, VERTICE destino, int visitados) { + inicio->visitado = + true; // Marca o Vértice que está passando inicio como já visitado + if (inicio == destino) + return visitados; // Se for o buscado (destino) retorna ele + + int aux = 0; + while (inicio->vizinhos[aux] != + NULL) { // Enquanto existe vizinhos a serem visitados + if (inicio->vizinhos[aux]->visitado == + false) { // Se o vizinho ainda não foi visitado + // Chama recursivamente passando novo vizinho como iniício, ou seja, irá + // percorrer todos os vizinhos dele, e assim, sucessivamente + int resposta = + buscaEmProfundidade(inicio->vizinhos[aux], destino, visitados + 1); + // Se o retorno for maior que -1 então é porque encontrou, sendo assim, já + // retorna a resposta + if (resposta != -1) + return resposta; + } + aux++; // Incrementa 1 na lista de vizinhos + } + + return -1; // Não encontrou o vértice +} + +/* + * Busca em Largura - BFS - Breadth First Search + * Implementada com o conceito de fila, porém utilizando um array simples + * Assim ela não excluí o 'vértice' do array, apenas pula uma posição para + *a frente Percorre todos os vértices por nível + */ +int buscaEmLargura(VERTICE inicio, VERTICE destino) { + int iniFila = 0; // Variável que controla a posição do inicio da fila, é + // utilizada para controlar o WHILE + int tamFila = 1; // Variável que controla o tamanho da fila + + VERTICE + FILA[MAX_VERTICES]; // Fila que irá guardar os vértices a serem comparados + for (int i = 0; i < MAX_VERTICES; + i++) { // Como a lista não é dinâmica, ela precisa ser 'limpa' primeiro + FILA[i] = NULL; + } + FILA[iniFila] = inicio; // Posição [0] da fila recebe o vértice de início + + // Enquanto não terminar a fila faça + while (iniFila < tamFila) { + // Se o elemento que está para 'sair' da fila for o buscado (destino) então + // retorna iniFila, que foi a distância percorrida para encontrar + if (FILA[iniFila] == destino) + return iniFila; + + /* + * Para todos os vizinhos do vértice que está para 'sair' da fila: + * Marca todos como visitado, para não coloca-los na fila novamente, + * e então os coloca na fila, e aumenta o tamanho da fila + */ + for (int i = 0; i < FILA[iniFila]->nroVizinhos; i++) { + if (FILA[iniFila]->vizinhos[i]->visitado == false) { + FILA[iniFila]->vizinhos[i]->visitado = true; + FILA[tamFila] = FILA[iniFila]->vizinhos[i]; + tamFila++; + } + } + iniFila++; // Incrementa 1 no inicio da fila, como se tivesse excluído o + // primeiro que entrou na fila (FIFO - First In First Out) + } + return -1; +} + +int main() { + + // Grafo conjunto de vértices independentes + VERTICE A = criaVertice('A'); + VERTICE B = criaVertice('B'); + VERTICE C = criaVertice('C'); + VERTICE D = criaVertice('D'); + VERTICE E = criaVertice('E'); + VERTICE F = criaVertice('F'); + + // Liga todos os vértices de acordo com o GRAFO apresentado na introdução + ligaVertices(A, B); + ligaVertices(A, C); + ligaVertices(B, D); + ligaVertices(C, D); + ligaVertices(B, E); + ligaVertices(D, E); + ligaVertices(E, F); + ligaVertices(D, F); + + // Realiza a busca em profundidade + int res = buscaEmProfundidade(A, F, 0); + if (res != -1) + printf("DFS - Encontrou. Distancia: %d.\n", res); + else + printf("DFS - Não encontrou.\n"); + + // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false' + A->visitado = false; + B->visitado = false; + C->visitado = false; + D->visitado = false; + E->visitado = false; + F->visitado = false; + + // Realiza a busca em largura + res = buscaEmLargura(A, F); + if (res != -1) + printf("BFS - Encontrou. Distancia: %d.\n", res); + else + printf("BFS - Não encontrou.\n"); + + // Grafo conjunto de vértices em um array + VERTICE GRAFO[MAX_VERTICES]; + GRAFO[0] = criaVertice('A'); + GRAFO[1] = criaVertice('B'); + GRAFO[2] = criaVertice('C'); + GRAFO[3] = criaVertice('D'); + GRAFO[4] = criaVertice('E'); + GRAFO[5] = criaVertice('F'); + + // Liga todos os vértices de acordo com o GRAFO apresentado na introdução + ligaVertices(GRAFO[0], GRAFO[1]); + ligaVertices(GRAFO[0], GRAFO[2]); + ligaVertices(GRAFO[1], GRAFO[3]); + ligaVertices(GRAFO[2], GRAFO[3]); + ligaVertices(GRAFO[1], GRAFO[4]); + ligaVertices(GRAFO[3], GRAFO[4]); + ligaVertices(GRAFO[4], GRAFO[5]); + ligaVertices(GRAFO[3], GRAFO[5]); + + // Realiza a busca em profundidade + res = buscaEmProfundidade(GRAFO[0], GRAFO[5], 0); + if (res != -1) + printf("DFS - Encontrou. Distancia: %d.\n", res); + else + printf("DFS - Não encontrou.\n"); + + // 'Zera' todos os atributos 'visitado' de todos os vértices para 'false' + for (int i = 0; i < MAX_VERTICES; i++) { + GRAFO[i]->visitado = false; + } + + // Realiza a busca em largura + res = buscaEmLargura(GRAFO[0], GRAFO[5]); + if (res != -1) + printf("BFS - Encontrou. Distancia: %d.\n", res); + else + printf("BFS - Não encontrou.\n"); + + return 0; +} \ No newline at end of file diff --git a/src/c/Graphs.c b/src/c/Graphs.c new file mode 100644 index 00000000..85495e11 --- /dev/null +++ b/src/c/Graphs.c @@ -0,0 +1,126 @@ +/* + * + * + * --------------------- + * | | + * | | + * 5 V 8 | + * (A)------------->(B)------------ | 2 + * \ | | + * \ | | + * \ 6 4 V | + * ---------->(C)--------->(D)------ + * + * + */ + +#include +#include + +#define MAX_VERTICES \ + 20 // Constante que define o máximo de vertices que o grafo pode ter + +int nroVertices = 0; // Guarda o número de vértices atual +int matriz[MAX_VERTICES][MAX_VERTICES]; // Matriz de Distancia +int componentes; + +typedef struct NO { + char id; + int nroVizinhos; + struct AUX *vizinhos[]; + bool visitado; + int indice; // Guarda a ordem em que o vértice foi criado +} *VERTICE; + +typedef struct AUX { + VERTICE vizinho; + int valor; +} *ARESTA; + +VERTICE criaVertice(char id) { + matriz[nroVertices][nroVertices] = 0; + VERTICE novo = (VERTICE)malloc(sizeof(NO)); + novo->id = id; + novo->nroVizinhos = 0; + novo->visitado = false; + novo->indice = nroVertices; + nroVertices++; + return novo; +} + +void ligaVertice(VERTICE v1, VERTICE v2, int valor) { + matriz[v1->indice][v2->indice] = valor; + ARESTA nova = (ARESTA)malloc(sizeof(AUX)); + nova->vizinho = v2; + nova->valor = valor; + v1->vizinhos[v1->nroVizinhos] = nova; + v1->nroVizinhos++; +} + +void mostraMatrizDistancia() { + printf("\nMatriz de Distancia\n"); + for (int l = 0; l < nroVertices; l++) { + for (int c = 0; c < nroVertices; c++) { + if (matriz[l][c] == -1) + printf("%d, ", matriz[l][c]); + else + printf(" %d, ", matriz[l][c]); + } + printf("\n"); + } + printf("\n"); +} + +void zeraVariaveis() { + for (int l = 0; l < MAX_VERTICES; l++) { + for (int c = 0; c < MAX_VERTICES; c++) { + matriz[l][c] = -1; + } + } +} + +void visitaVizinhos(bool visitados[], int atual) { + for (int i = 0; i < nroVertices; i++) { + if (visitados[i] == false && matriz[atual][i] > 0) { + visitados[i] = true; + componentes++; + visitaVizinhos(visitados, i); + } + } +} + +void calculaComponentesConexos() { + bool visitados[nroVertices]; + for (int i = 0; i < nroVertices; ++i) { + visitados[i] = false; + } + for (int i = 0; i < nroVertices; i++) { + if (visitados[i] == false) { + visitaVizinhos(visitados, i); + } + } +} + +int main() { + zeraVariaveis(); + + // Matriz de Distância funciona conforme a ordem inserida + VERTICE A = criaVertice('A'); + VERTICE B = criaVertice('B'); + VERTICE C = criaVertice('C'); + VERTICE D = criaVertice('D'); + VERTICE E = criaVertice('E'); + + ligaVertice(A, B, 5); + ligaVertice(A, C, 6); + ligaVertice(B, D, 8); + ligaVertice(C, D, 4); + ligaVertice(D, B, 2); + + calculaComponentesConexos(); + printf("\nComponentes Conexos: %d\n", componentes); + + mostraMatrizDistancia(); + + return 0; +} \ No newline at end of file diff --git a/src/c/HamiltonianCycle.c b/src/c/HamiltonianCycle.c new file mode 100644 index 00000000..aea872f6 --- /dev/null +++ b/src/c/HamiltonianCycle.c @@ -0,0 +1,143 @@ +/* + * + * Grafos - CICLO HAMILTONIANO em C + * + * ----------------------------------- + * | | + * (A)---------------(B)-------------(E)---------------(F) + * | | | | + * | | | | + * | | | | + * (C)---------------(D)--------------- | + * | | + * ----------------------------------- + * + * 6 Vértices + * 9 Arestas + */ + +#include +#include + +#define MAX_VERTICES \ + 6 // MÁXIMO DE VÉRTICES DO GRAFO, SE FOR ALTERAR O GRAFO PRECISA ALTERAR ESTA + // VARIÁVEL TAMBÉM +#define MAX_ARESTAS \ + (MAX_VERTICES * \ + (MAX_VERTICES - \ + 1)) // CALCULA O NÚMERO MÁXIMO DE ARESTAS QUE O GRAFO PODERÁ TER + +// Estrutura que define cada Vértice do Grafo +typedef struct NO { + char id; + int nroVizinhos; + struct NO *vizinhos[MAX_ARESTAS]; + bool visitado; +} *VERTICE; + +VERTICE solucao[MAX_VERTICES]; // Array que irá guardar a solução do ciclo + // hamiltoniano + +// Cria Vértice e retorna +VERTICE criaVertice(char id) { + VERTICE novoVertice = (VERTICE)malloc(sizeof(NO)); // Aloca um novo Vértice + novoVertice->id = id; + novoVertice->nroVizinhos = 0; + novoVertice->visitado = false; + for (int i = 0; i < MAX_ARESTAS; i++) { + novoVertice->vizinhos[i] = NULL; + } + return novoVertice; +} + +// Liga os vértices passados como parâmetro +bool ligaVertices(VERTICE v1, VERTICE v2) { + int aux = 0; + while (v1->vizinhos[aux] != + NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos + aux++; + } + v1->vizinhos[aux] = v2; // Adiciona o novo vizinho a lista de vizinhos + aux = 0; + while (v2->vizinhos[aux] != + NULL) { // Busca a primeira posição 'vazia'(NULL) dos vizinhos + aux++; + } + v2->vizinhos[aux] = v1; // Adiciona o novo vizinho a lista de vizinhos + v1->nroVizinhos++; // Incrementa o número de vizinhos + v2->nroVizinhos++; // Incrementa o número de vizinhos +} + +bool cicloHamiltonianoAuxiliar(int aux) { + + if (aux == MAX_VERTICES) { + for (int i = 0; i < solucao[aux - 1]->nroVizinhos; i++) { + if (solucao[aux - 1]->vizinhos[i] == solucao[0]) { + return true; + } + } + return false; + } + + VERTICE s = solucao[aux - 1]; // Auxiliar para simplificar o código + + for (int i = 0; i < s->nroVizinhos; + i++) { // Percorre todos os vizinhos do vértice de posição aux-1 no array + // solução + if (s->vizinhos[i]->visitado == false) { + s->vizinhos[i]->visitado = true; + solucao[aux] = s->vizinhos[i]; + if (cicloHamiltonianoAuxiliar(aux + 1) == true) { + return true; + } + s->vizinhos[i]->visitado = false; + } + } + + return false; +} + +bool cicloHamiltoniano(VERTICE grafo[MAX_VERTICES]) { + grafo[0]->visitado = true; // Marca a posição inicial como visitada + solucao[0] = grafo[0]; // Array que irá guardar a solução do ciclo + return cicloHamiltonianoAuxiliar(1); +} + +int main() { + + // Grafo conjunto de vértices em um array + VERTICE GRAFO[MAX_VERTICES]; + GRAFO[0] = criaVertice('A'); + GRAFO[1] = criaVertice('B'); + GRAFO[2] = criaVertice('C'); + GRAFO[3] = criaVertice('D'); + GRAFO[4] = criaVertice('E'); + GRAFO[5] = criaVertice('F'); + + // Liga todos os vértices de acordo com o GRAFO apresentado na introdução + ligaVertices(GRAFO[0], GRAFO[1]); // A - B + ligaVertices(GRAFO[0], GRAFO[2]); // A - C + ligaVertices(GRAFO[1], GRAFO[3]); // B - D + ligaVertices(GRAFO[2], GRAFO[3]); // D - C + ligaVertices(GRAFO[1], GRAFO[4]); // B - E + ligaVertices(GRAFO[3], GRAFO[4]); // D - E + ligaVertices(GRAFO[4], GRAFO[5]); // E - F + ligaVertices(GRAFO[3], GRAFO[5]); // D - F + ligaVertices(GRAFO[1], GRAFO[5]); // B - F + + for (int i = 0; i < MAX_VERTICES; i++) { + solucao[i] = criaVertice('0'); + } + + if (cicloHamiltoniano(GRAFO)) { + printf("Ciclo Hamiltoniano:\n"); + for (int i = 0; i < MAX_VERTICES; i++) { + printf("%c, ", solucao[i]->id); + } + printf("\n\n"); + } else { + printf("Nao possui Ciclo Hamiltoniano\n"); + } + + return 0; +} \ No newline at end of file diff --git a/src/c/Heapsort.c b/src/c/Heapsort.c new file mode 100644 index 00000000..4437c6e9 --- /dev/null +++ b/src/c/Heapsort.c @@ -0,0 +1,61 @@ +#include + +void heapify(int arr[], int n, int i) { + int largest = i; + int left = 2 * i + 1; + int right = 2 * i + 2; + + if (left < n && arr[left] > arr[largest]) + largest = left; + + // If the right child is larger than the largest so far + if (right < n && arr[right] > arr[largest]) + largest = right; + + // If the largest element is not the root + if (largest != i) { + // Swap the largest element with the root + int temp = arr[i]; + arr[i] = arr[largest]; + arr[largest] = temp; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +void heapsort(int arr[], int n) { + // Build a max heap + int i; + for (i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract elements from the heap + for (i = n - 1; i > 0; i--) { + // Move the current root to the end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +int main() { + int arr[] = {12, 21, 13, 5, 1, 7}; + int i; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("Original array: "); + for (i = 0; i < n; i++) + printf("%d ", arr[i]); + + heapsort(arr, n); + + printf("\nSorted array: "); + for (i = 0; i < n; i++) + printf("%d ", arr[i]); + + return 0; +} diff --git a/src/c/InsertionSort.c b/src/c/InsertionSort.c index 3d980e74..5605bd91 100644 --- a/src/c/InsertionSort.c +++ b/src/c/InsertionSort.c @@ -1,50 +1,51 @@ /* Algoritmo de ordenação Insertion Sort em C -Vinicios Barbosa da Silva - 2023 -https://github.com/ViniciosB */ #include // Necessário para usar input e output #include // Necessário para usar a função rand() -#include // Necessário para inicializar a semente de números aleatórios +#include // Necessário para inicializar a semente de números aleatórios -// Definimos a função insertion_sort que recebe como argumento o vetor a ser ordenado e seu tamanho n +// Definimos a função insertion_sort que recebe como argumento o vetor a ser +// ordenado e seu tamanho n void insertion_sort(int arr[], int n) { - int i, j, key; - // Percorremos todos os elementos do vetor a partir do segundo elemento - for (i = 1; i < n; i++) { - // Armazenamos o valor do elemento atual em key - key = arr[i]; - // Inicializamos o índice j como o elemento anterior ao elemento atual - j = i - 1; - // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o elemento na posição j do vetor, - // movemos o elemento na posição j uma posição para a direita e decrementamos j - while (j >= 0 && arr[j] > key) { - arr[j + 1] = arr[j]; - j = j - 1; - } - // Quando o loop interno termina, colocamos o elemento atual em sua posição correta - arr[j + 1] = key; + int i, j, key; + // Percorremos todos os elementos do vetor a partir do segundo elemento + for (i = 1; i < n; i++) { + // Armazenamos o valor do elemento atual em key + key = arr[i]; + // Inicializamos o índice j como o elemento anterior ao elemento atual + j = i - 1; + // Enquanto j é maior ou igual a 0 e o elemento atual é menor do que o + // elemento na posição j do vetor, movemos o elemento na posição j uma + // posição para a direita e decrementamos j + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; } + // Quando o loop interno termina, colocamos o elemento atual em sua posição + // correta + arr[j + 1] = key; + } } // Função principal int main() { - int i, n, arr[100]; - srand(time(NULL)); // Inicializa a semente de números aleatórios - printf("Entre com o numero de elementos no vetor: "); - scanf("%d", &n); - printf("Vetor de entrada:\n"); - for (i = 0; i < n; i++) { - arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99 - printf("%d ", arr[i]); // Imprime o valor gerado - } - printf("\n"); - insertion_sort(arr, n); - printf("Vetor ordenado em ordem crescente:\n"); - for (i = 0; i < n; i++) { - printf("%d ", arr[i]); - } - printf("\n"); - return 0; + int i, n, arr[100]; + srand(time(NULL)); // Inicializa a semente de números aleatórios + printf("Entre com o numero de elementos no vetor: "); + scanf("%d", &n); + printf("Vetor de entrada:\n"); + for (i = 0; i < n; i++) { + arr[i] = rand() % 100; // Gera um valor aleatório entre 0 e 99 + printf("%d ", arr[i]); // Imprime o valor gerado + } + printf("\n"); + insertion_sort(arr, n); + printf("Vetor ordenado em ordem crescente:\n"); + for (i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); + return 0; } \ No newline at end of file diff --git a/src/c/IterativeMinAndMax.c b/src/c/IterativeMinAndMax.c deleted file mode 100644 index 87fda2c0..00000000 --- a/src/c/IterativeMinAndMax.c +++ /dev/null @@ -1,23 +0,0 @@ -#include - -int main() { - int array[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; - - int min = array[0]; - int max = array[0]; - - size_t length = sizeof(array) / sizeof(array[0]); - - for (int i = 1; i < length; ++i) { - if (array[i] < min) { - min = array[i]; - } - if (array[i] > max) { - max = array[i]; - } - } - - printf("min: %d\n", min); - printf("max: %d\n", max); - return 0; -} diff --git a/src/c/LinearSearch.c b/src/c/LinearSearch.c new file mode 100644 index 00000000..39e5c991 --- /dev/null +++ b/src/c/LinearSearch.c @@ -0,0 +1,18 @@ +#include + +int buscaSequencial(int vetor[], int size, int buscado) { + for (int i = 0; i < size; i++) { + if (vetor[i] == buscado) { + return i; + } + } + return -1; +} + +int main() { + + int a[] = {1, 2, 3, 4, 5, 6, 7, 8}; + int n = sizeof(a) / sizeof(a[0]); + printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3)); + printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9)); +} diff --git a/src/c/LinearSearchRecursive.c b/src/c/LinearSearchRecursive.c new file mode 100644 index 00000000..ffdb2001 --- /dev/null +++ b/src/c/LinearSearchRecursive.c @@ -0,0 +1,22 @@ +#include + +int buscaSequencialRecursiva(int vetor[], int i, int buscado, int size) { + + if (i == size) { + return -1; + } else if (vetor[i] == buscado) { + return i; + } else { + return buscaSequencialRecursiva(vetor, i + 1, buscado, size); + } +} + +int main() { + + int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8}; + size_t n = sizeof(vetor) / sizeof(vetor[0]); + printf("Valor %d no índice %d\n", 1, + buscaSequencialRecursiva(vetor, 0, 1, n)); + printf("Valor %d no índice %d\n", 10, + buscaSequencialRecursiva(vetor, 0, 10, n)); +} diff --git a/src/c/LinearSearchSentinel.c b/src/c/LinearSearchSentinel.c new file mode 100644 index 00000000..37071d8b --- /dev/null +++ b/src/c/LinearSearchSentinel.c @@ -0,0 +1,50 @@ +/* + * Exemplo de Busca Sentinela em C + * Objetivo: Encontrar um valor em um vetor sem precisar testar todos os + *valores dentro do laço + */ + +#include +#include +#include + +#define TAM_VETOR 10 + +// Busca sentinela, realiza uma busca sequencial sem precisar testar a chave a +// cada passo do laço de busca +int buscaSentinela(int vetor[], int chave) { + vetor[TAM_VETOR] = + chave; // Coloca o valor buscado (chave) na última posição do vetor + int aux = 0; // Variável de controle do laço + while (vetor[aux] != + chave) // Enquanto não encontrar o valor (chave) incrementa 1 em aux + aux++; + if (aux == TAM_VETOR) // Caso o valor de aux seja igual ao tamanho do vetor, + // significa que foi até o final e não encontrou o valor + return -1; // Não encontrou + else // Caso aux seja diferente, significa que encontrou o valor e quebrou o + // laço, o aux é a posição do valor buscado + return aux; // Encontrou +} + +int main() { + + int vetor[TAM_VETOR + 1]; // Declara o vetor com +1 pois é a posição que será + // utilizada pela sentinela + + // Preenche o vetor com valores aleatórios 0-1000 + srand(time(NULL)); + for (int i = 0; i < TAM_VETOR; i++) { + vetor[i] = rand() % 1000; + printf("%d, ", vetor[i]); + } + + // Faz a busca, passando como parâmetro o vetor e a chave que deseja buscar + int res = buscaSentinela(vetor, vetor[TAM_VETOR - 2]); + if (res != -1) + printf("\n\nValor %d encontrado na posicao %d.\n\n", vetor[res], res); + else + printf("\n\nValor não encontrado no vetor\n\n"); + + return 0; +} diff --git a/src/c/ListaCircularLigada.c b/src/c/ListaCircularLigada.c deleted file mode 100644 index 6a664226..00000000 --- a/src/c/ListaCircularLigada.c +++ /dev/null @@ -1,105 +0,0 @@ -/* -* -* Lista Ligada com Nó Cabeça, Circular e Ordenada (Implementação Dinâmica) -* Kelvin Salton do Prado - 2015 -* -*/ - -#include -#include - -typedef int TIPOCHAVE; // Tipo de ID de cada nó da lista - -// Estrutura de dados que representa cada nó da lista -typedef struct AUX{ - TIPOCHAVE chave; - struct AUX* prox; -}NO, *PONT; - -typedef struct{ - PONT cab; // Nó cabeça -}LISTA; - -void inicializar(LISTA *L){ - // Nó cabeça não deixa a lista ficar vazia, também pode ser usado como sentinela - L->cab = (PONT) malloc( sizeof(NO) ); - L->cab->prox = L->cab; // Começa apontando para o próprio nó, pois é circular -} - -// Como neste método não irá alterar a lista, pode ser passado uma cópia dela e não necessáriamente um ponteiro para ela -PONT buscaSequencial(TIPOCHAVE ch, LISTA L, PONT* ant){ - *ant = L.cab; // Sendo uma cópia pode-se usar o ponto (.) no lugar de seta (->), o ant guarda o ponteiro para o nó encontrado - PONT pos = L.cab->prox; - L.cab->chave = ch; // Grava o valor no nó cabeça para ser utilizado como sentinela, será o último a ser comparado - while(pos->chave != ch){ - *ant = pos; // Guarda o ponteiro para o nó - pos = pos->prox; // Vai para o próximo nó - } - if( pos != L.cab ) // Se o nó não é o nó cabeça é pq encontrou - return pos; // Retorna o nó - else - return NULL; // Senão não encontrou retorna NULL -} - -bool excluir(TIPOCHAVE ch, LISTA *L){ - PONT aux, ant; - aux = buscaSequencial(ch, *L, &ant); // Busca o valor para excluir, o ant é passado como endereço de memória, assim a função busca altera ele, guardando o valor anterior - if( aux == NULL ) return false; // Não encontrou - ant->prox = aux->prox; // Nó anterior aponta para o próximo, no caso o próximo que o nó a ser excluído está apontando - free(aux); // Libera a memória - return true; -} - -void inserir(TIPOCHAVE ch, LISTA *L){ - PONT ant = L->cab; // O ant guarda o ponteiro para o nó anterior - PONT pos = L->cab->prox; // O pos guarda o ponteiro para o atual - - while(pos->chave < ch && pos != L->cab){ - ant = pos; // Guarda o ponteiro para o nó atual, que será o anterior - pos = pos->prox; // Vai para o próximo nó - } - // Quando encontrou a posição correta na ordem crescente - PONT novo_no = (PONT) malloc( sizeof(NO) ); // Cria um novo nó - novo_no->chave = ch; // Coloca a chave no nó - novo_no->prox = pos; // Aponta para o próximo nó - ant->prox = novo_no; // Nó anterior aponta para o novo nó -} - -PONT mostrarLista(LISTA L){ - PONT pos = L.cab->prox; // Pos recebe o primeiro elemento depois do nó cabeça - while(pos != L.cab){ // Se não for o nó cabeça, a lista não está vazia - printf("[ %d ]->", pos->chave); // Mostra o valor do nó - pos = pos->prox; // Vai para o próximo nó - }printf("\n"); -} - -int main(){ - - LISTA lista; - inicializar(&lista); - - inserir(4, &lista); - inserir(6, &lista); - inserir(2, &lista); - inserir(3, &lista); - inserir(1, &lista); - inserir(5, &lista); - - mostrarLista(lista); - - excluir(2, &lista); - excluir(4, &lista); - excluir(6, &lista); - - mostrarLista(lista); - - // Exemplo de busca na lista - PONT aux; - int valor = 2; - if( buscaSequencial(valor, lista, &aux) != NULL ) - printf("Valor %d encontrado.\n", valor ); - else - printf("Valor %d não encontrado.\n", valor); - - return 0; -} \ No newline at end of file diff --git a/src/c/ListaDuplamenteEncadeada.c b/src/c/ListaDuplamenteEncadeada.c deleted file mode 100644 index 46bfd404..00000000 --- a/src/c/ListaDuplamenteEncadeada.c +++ /dev/null @@ -1,158 +0,0 @@ -/* -* Exemplo Lista Duplamente Encadeada em C -* Luan Felipe dos S. da Silva -*/ - - -#include -#include - -/* Lista encadeada utilizando celula cabea */ - -typedef struct cel celula; -struct cel{ - int dado; - struct cel *prox; - struct cel *ant; -}; - -/* O ponteiro 'p' a cabea da lista*/ - -void insereInicio(int x, celula *p) /* Insere no inicio da lista*/ -{ - celula *nova, *q; - nova = malloc (sizeof (celula)); - nova->dado = x; - nova->prox = p->prox; - /* verifica se a lista est vazia*/ - if (p->prox != NULL) - { - q = nova->prox; - q->ant = nova; - } - p->prox = nova; - nova->ant = p; -} - -void insereUltimo(int x, celula *p) /* Insere no final da lista*/ -{ - celula *q; - celula *nova; - nova = malloc (sizeof (celula)); - nova->dado = x; - q = p; - while (q->prox != NULL) - q = q->prox; - - q->prox = nova; - nova->ant = q; - nova->prox = NULL; -} - - -void buscaEremove (int y, celula *p) -{ - celula *w, *q; - w = p; - q = p->prox; - while (q != NULL && q->dado != y) { - w = q; - q = q->prox; - } - if (q != NULL) { - w->prox = q->prox; - q->ant = w; - free (q); - } - else{ - printf("\nLista nao contem item\n\n"); - system("pause"); - } -} - - -void imprime (celula *p) -{ - celula *q; - for (q = p->prox; q != NULL; q = q->prox) - printf ("%d ", q->dado); -} - -void Menu () -{ - printf(" Menu Principal\n"); - printf("1 - Insere inicio\n"); - printf("2 - Insere ultimo\n"); - printf("3 - Retira\n"); - printf("4 - Sair\n"); - printf("\nOpcao: "); -} - -void libera (celula *ini) -{ - celula *p; - p=ini; - while (p != NULL) { - celula *q = p->prox; /* guarda referncia para o prximo elemento*/ - free(p); /* libera a memria apontada por p */ - p = q; /* faz p apontar para o prximo */ - } -} - - -int main() -{ - celula *p; - int op = 0,item; - //inicializa lista - p = malloc (sizeof (celula)); - p->ant = NULL; - p->prox = NULL; - //fim_inicializa - - do{ - system("cls"); - printf("\nConteudo da lista: "); - if (p->prox != NULL){ - imprime(p); - } - else{ - printf("Lista VAZIA"); - } - printf("\n\n"); - Menu(); - scanf("%d",&op); - switch (op){ - case 1: - printf("Insere no inicio da lista: "); - scanf("%d",&item); - insereInicio(item,p); - break; - case 2: - printf("Insere na ultima posicao da lista: "); - scanf("%d",&item); - insereUltimo(item,p); - break; - case 3: - if (p->prox != NULL){ - printf("Retirar um elemento: "); - scanf("%d",&item); - buscaEremove(item,p); - } - else{ - printf("\nLista VAZIA\n\n"); - system("pause"); - } - break; - case 4: - break; - default: - printf("Opcao invalida!\n"); - system("pause"); - break; - } - - }while(op!=4); - libera(p); - return 0; -} diff --git a/src/c/ListaEncadeada.c b/src/c/ListaEncadeada.c deleted file mode 100644 index b33f2c6e..00000000 --- a/src/c/ListaEncadeada.c +++ /dev/null @@ -1,274 +0,0 @@ -/* Author: Cleber Salustiano */ - -#include -#include - -typedef struct tno { - int dado; - struct tno * anterior; - struct tno * proximo; -} tipoNo; - -typedef tipoNo * pnoh; - -typedef struct { - int tamanho; - pnoh primeiro; - pnoh ultimo; -} tcabec; - -typedef tcabec * TLista; - -TLista criaLista() { - TLista c = (tcabec*) malloc(sizeof(tcabec)); - - c->tamanho = 0; - c->primeiro = NULL; - c->ultimo = NULL; - - return c; -} - -TLista appendLista(TLista lst, int dado) { - pnoh novono = (tipoNo*) malloc(sizeof(tipoNo)); - - novono->dado = dado; - novono->anterior = lst->ultimo; - novono->proximo = NULL; - - if (lst->tamanho == 0) { - lst->primeiro = novono; - } else { - lst->ultimo->proximo = novono; - } - - lst->ultimo = novono; - lst->tamanho++; - - return lst; -} - -int lenLista(TLista lst) { - return lst->tamanho; -} - -int primLista(TLista lst) { - return lst->primeiro->dado; -} - -int ultLista(TLista lst) { - return lst->ultimo->dado; -} - -TLista insertLista(TLista lst, int i, int dado) -{ - int tam = lenLista(lst); - - if ((i < 0) || (i > tam)) { - return NULL; - } - - if ((lenLista(lst) == 0) || (i == tam)) { - appendLista(lst, dado); - } else { - pnoh novono = (tipoNo*) malloc(sizeof(tipoNo)); - novono->dado = dado; - - if (i == 0) { - novono->proximo = lst->primeiro; - lst->primeiro = novono; - } else { - pnoh aux = lst->primeiro; - int pos = 0; - - while (pos != (i - 1)) - { - aux = aux->proximo; - pos++; - } - novono->proximo = aux->proximo; - aux->proximo = novono; - } - - lst->tamanho++; - } - - return lst; -} - -pnoh infoLista(TLista lst, int i) { - int tam = lenLista(lst); - - if ((tam == 0) || (i < 0) || (i > tam)) { - return NULL; - } - - if (i == 0) { - return lst->primeiro; - } - - if (i == tam - 1) { - return lst->ultimo; - } - - pnoh aux = lst->primeiro; - int pos = 0; - - while (pos != i) { - aux = aux->proximo; - pos++; - } - - return aux; -} - -void removeLista(TLista lst, int i) { - int tam = lenLista(lst); - - if ((i < 0) || (i > tam) || (tam == 0)) { - printf("Erro: indice inexistente dentro da Lista."); - return; - } - - if (tam == 1) { - pnoh aux = lst->primeiro; - lst->primeiro = NULL; - lst->ultimo = NULL; - lst->tamanho--; - - free(aux); - } else { - if (i == 0) { - pnoh aux = lst->primeiro; - lst->primeiro = aux->proximo; - lst->tamanho--; - - free(aux); - } else { - if (i == tam - 1) { - pnoh aux = lst->ultimo; - - pnoh penultimo = lst->primeiro; - int pos = 0; - - while (pos != i - 1) { - penultimo = penultimo->proximo; - pos++; - } - - penultimo->proximo = NULL; - lst->ultimo = penultimo; - - lst->tamanho--; - - free(aux); - } else { - pnoh anterior = lst->primeiro; - int pos = 0; - - while (pos != i - 1) { - anterior = anterior->proximo; - pos++; - } - - pnoh aux = anterior->proximo; - anterior->proximo = aux->proximo; - lst->tamanho--; - - free(aux); - } - } - } -} - -int indexLista(TLista lst, int dado) { - int tam = lenLista(lst); - int i, dadolst; - pnoh no_dadolst; - - if (tam == 0) { - return -1; - } - - i = 0; - no_dadolst = infoLista(lst, i); - dadolst = no_dadolst->dado; - while ((i < tam) && (dado != dadolst)) { - i++; - no_dadolst = infoLista(lst, i); - dadolst = no_dadolst->dado; - } - - if (i < tam) { - return i; - } - - return -1; -} - -TLista clearLista(TLista lst) { - int tam = lenLista(lst); - - if (tam == 0) { - return lst; - } - - while (lenLista(lst) > 0) { - removeLista(lst, 0); - } - - return lst; -} - -TLista clonaLista(TLista lst) { - TLista clone = criaLista(); - int tam = lenLista(lst); - - if (tam == 0) { - return clone; - } - - for (int i = 0; i < tam; i++) { - pnoh no = infoLista(lst, i); - if (no != NULL) { - appendLista(clone, no->dado); - } - } - - return clone; -} - -int main() { - TLista lista = criaLista(); - appendLista(lista, 3); - appendLista(lista, 5); - appendLista(lista, 7); - - printf("Lista criada e adicionado 3 numeros\n"); - int tamanho = lenLista(lista); - int primeiro = primLista(lista); - int ultimo = ultLista(lista); - pnoh valor = infoLista(lista, 1); - int valor_dado = valor->dado; - printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: %d\nSegundo valor: %d\n", tamanho, primeiro, ultimo, valor_dado); - - insertLista(lista, 2, 6); - valor = infoLista(lista, 2); - valor_dado = valor->dado; - printf("Adicionando 6 na posição 2: %d\n", valor_dado); - - removeLista(lista, 1); - tamanho = lenLista(lista); - printf("Novo tamanho após adicionar e remover: %d\n", tamanho); - - int index = indexLista(lista, 3); - printf("Index do elemento com valor 3 na lista: %d\n", index); - - TLista cloneLista = clonaLista(lista); - printf("Lista Duplicada\n"); - - clearLista(lista); - printf("Lista Apagada"); - - return 0; -} diff --git a/src/c/ListaLigadaNaoOrdenada.c b/src/c/ListaLigadaNaoOrdenada.c deleted file mode 100644 index 0fac109c..00000000 --- a/src/c/ListaLigadaNaoOrdenada.c +++ /dev/null @@ -1,86 +0,0 @@ -/* -* Exemplo de Lista Ligada Dinâmica Não Ordenada em C -* Kelvin Salton do Prado - 2015 -*/ - -#include -#include - -#define ERRO -1 - -typedef int TIPOCHAVE; - -typedef struct aux{ - TIPOCHAVE chave; - struct aux *prox; -}REGISTRO, *PONT; - -PONT criaRegistro(TIPOCHAVE ch){ - PONT rg = (PONT) malloc( sizeof(PONT) ); - rg->chave = ch; - rg->prox = NULL; - return rg; -} - -PONT insereRegistro(TIPOCHAVE ch, PONT rg){ - if( rg == NULL ) - return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo - while( rg->prox != NULL ) - rg = rg->prox; - rg->prox = criaRegistro(ch); - return NULL; -} - -void mostraLista(PONT rg){ - if( rg == NULL ) return; - printf("%d, ", rg->chave); - mostraLista(rg->prox); -} - -PONT buscaSequencial(TIPOCHAVE ch, PONT rg){ - while( rg != NULL ){ - if( rg->chave == ch ) - return rg; - rg = rg->prox; - } - return NULL; -} - -bool deletaRegistro(TIPOCHAVE ch, PONT rg){ - PONT ant; - while( rg != NULL ){ - if( rg->chave == ch ){ - ant->prox = rg->prox; - free(rg); - return true; - } - ant = rg; - rg = rg->prox; - } - printf("\nChave %d não encontrada.\n",ch); - return false; -} - -int main(){ - PONT RG = insereRegistro(23, RG); - insereRegistro(34, RG); - insereRegistro(12, RG); - insereRegistro(63, RG); - insereRegistro(45, RG); - - mostraLista(RG); - - TIPOCHAVE ch = 64; - if( buscaSequencial(ch, RG) != NULL ) - printf("\nEncontrou chave %d\n", ch); - else - printf("\nNão encontrou chave %d\n", ch); - - deletaRegistro(63, RG); - mostraLista(RG); - - printf("\n"); - deletaRegistro(34, RG); - mostraLista(RG); - return 0; -} \ No newline at end of file diff --git a/src/c/ListaSequencialOrdenada.c b/src/c/ListaSequencialOrdenada.c deleted file mode 100644 index e36cbbb5..00000000 --- a/src/c/ListaSequencialOrdenada.c +++ /dev/null @@ -1,105 +0,0 @@ -/* -* Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando sentinela -* Kelvin S. do Prado - 2015 -*/ - -#include - -#define MAX 10 -#define ERRO -1 - -typedef int TIPOCHAVE; // Define um nome TIPOCHAVE para um tipo inteiro - -typedef struct{ - TIPOCHAVE chave; -}REGISTRO; - -typedef struct{ - REGISTRO A[MAX+1]; // O +1 é a posição que será utilizada para a 'sentinela' - int nroElementos; -}LISTA; - -void inicializar(LISTA* L){ - L->nroElementos = 0; // Acessa a lista pelo endereço de memória - int i = 0; - for (i; i < MAX-2; ++i){ // Preenche a lista até -2 para deixar espaço para inserir mais depois - L->A[i].chave = i*2; - } - L->nroElementos = MAX-2; - // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o ponteiro -} - -/* A função do sentinela é adicionar a chave ao final da lista, ou seja, - * sempre irá encontrar a chave, mesmo que seja na útlima posição da lista. - * Caso seja o último elemento, significa que não encontrou. - * Deste modo elimina o 'if' dentro do laço, poupando várias comparações - */ -int buscaSentinela(TIPOCHAVE ch, LISTA* L){ // Poderia usar aqui busca binária, o que seria mais apropriado. - int i = 0; - L->A[L->nroElementos].chave = ch; // Atribui a 'chave'/valor buscado a ultima posição do array A - while(L->A[i].chave != ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado se encontra no array (senão será o sentinela) - i++; - if(i == L->nroElementos) // Se o valor chegou até o final, significa que não encontrou o valor, retorna ERRO (-1) - return ERRO; - return i; // Caso contrário retorna a posição do valor/'chave' no array -} - -bool inserirOrdenado(REGISTRO reg, LISTA* L){ - int i = 0; - if(L->nroElementos >= MAX) - return false; - L->A[L->nroElementos].chave = reg.chave; - while(L->A[i].chave < reg.chave) - i++; - int p = L->nroElementos-1; - while(p >= i){ - L->A[p+1] = L->A[p]; - p--; - } - L->A[i] = reg; - L->nroElementos++; - return true; -} - -bool deletaValor(REGISTRO reg, LISTA* L){ - int posicao = buscaSentinela(reg.chave, L); - if( posicao >= 0 ){ - for( posicao; posicao < L->nroElementos; posicao++ ){ - L->A[posicao] = L->A[posicao+1]; - } - L->nroElementos--; - return true; - }else{ - return false; - } -} - -void mostraLista(LISTA* L){ - int i = 0; - for (i; i < L->nroElementos; ++i){ // Percorre e mostra todos os valores do array - printf("%d, ", L->A[i].chave); - } - printf("\n\n"); -} - -int main(){ - - LISTA LISTA; - inicializar(&LISTA); - - printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA) ); - mostraLista(&LISTA); - - REGISTRO reg; - reg.chave = 7; - printf("Insere o valor: %d\n", reg.chave); - inserirOrdenado(reg, &LISTA); - mostraLista(&LISTA); - - reg.chave = 12; - printf("Deleta o valor: %d\n", reg.chave); - deletaValor(reg, &LISTA); - mostraLista(&LISTA); - - return 0; -} \ No newline at end of file diff --git a/src/c/MaxMinRecursivo.c b/src/c/MaxMinRecursivo.c deleted file mode 100644 index cbb47831..00000000 --- a/src/c/MaxMinRecursivo.c +++ /dev/null @@ -1,26 +0,0 @@ -/* -* Exemplo de algoritmo recursivo. -* Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando recursividade -* Kelvin Salton do Prado - 2015 -*/ - -#include - -#define TAM 10 - -void MaxMin(int vetor[], int min, int max, int indice){ - if( vetor[indice] < min ) - min = vetor[indice]; - if( vetor[indice] > max ) - max = vetor[indice]; - if( indice < TAM-1 ) - MaxMin(vetor, min, max, indice+1); - else - printf("Min: %d \nMax: %d\n\n", min, max); -} - -int main(){ - int vetor[TAM] = {9,2,1,8,6,3,4,5,0,7}; - MaxMin(vetor, vetor[0], vetor[0], 0); - return 0; -} \ No newline at end of file diff --git a/src/c/MaxRecursive.c b/src/c/MaxRecursive.c new file mode 100644 index 00000000..b173c575 --- /dev/null +++ b/src/c/MaxRecursive.c @@ -0,0 +1,70 @@ +/* + * Exemplos de funções para achar maior número de um vetor + * As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista + */ + +#include +#include + +#define MAX 10 + +// Maximo usando Divisão e Conquista +int MaxDC(int *vetor, int inicio, int fim) { + int aux1, aux2; + int meio = (inicio + fim) / 2; + + if (inicio == fim) { + return vetor[inicio]; + } + + aux1 = MaxDC(vetor, inicio, meio); + aux2 = MaxDC(vetor, meio + 1, fim); + + if (aux1 > aux2) { + return aux1; + } else { + return aux2; + } +} + +void max1(int *vetor, int maximo, int indice) { + if (vetor[indice] > maximo) { + maximo = vetor[indice]; + } + + if (indice < MAX - 1) { + max1(vetor, maximo, indice + 1); + } else { + printf("\n\nMax1: %d\n", maximo); + } +} + +int max2(int vetor[], int tamVetor) { + if (tamVetor == 1) { + return vetor[0]; // só tem 1 elemento + } else { + int x = max2(vetor, tamVetor - 1); + + if (x > vetor[tamVetor - 1]) { + return x; + } else { + return vetor[tamVetor - 1]; + } + } +} + +int main() { + int vetor[MAX]; + + for (int i = 0; i < MAX; ++i) { + vetor[i] = (rand() % 90) + 10; // 10 a 99 + printf("%d, ", vetor[i]); + } + + max1(vetor, vetor[0], 1); + + printf("\nMax2: %d\n", max2(vetor, MAX)); + printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX - 1)); + + return 0; +} diff --git a/src/c/MaxRecursivo.c b/src/c/MaxRecursivo.c deleted file mode 100644 index 41c391a2..00000000 --- a/src/c/MaxRecursivo.c +++ /dev/null @@ -1,90 +0,0 @@ -/* -* Exemplos de funções para achar maior número de um vetor -* As 3 são recursivas porém apenas a MaxDC utiliza divisão e conquista -* Kelvin Salton do Prado - 2015 -*/ - -#include -#include - -#define MAX 10 - -// Maximo usando Divisão e Conquista -int MaxDC(int *vetor, int inicio, int fim) -{ - int aux1, aux2; - int meio = ( inicio + fim ) / 2; - - if( inicio == fim ) - { - return vetor[inicio]; - } - - aux1 = MaxDC(vetor, inicio, meio); - aux2 = MaxDC(vetor, meio+1, fim); - - if( aux1 > aux2 ) - { - return aux1; - } - else - { - return aux2; - } -} - -void max1(int *vetor, int maximo, int indice) -{ - if( vetor[indice] > maximo ) - { - maximo = vetor[indice]; - } - - if( indice < MAX-1 ) - { - max1(vetor, maximo, indice+1); - } - else - { - printf("\n\nMax1: %d\n",maximo); - } -} - -int max2(int vetor[], int tamVetor) -{ - if (tamVetor == 1) - { - return vetor[0]; // só tem 1 elemento - } - else - { - int x = max2(vetor, tamVetor-1); - - if (x > vetor[tamVetor-1]) - { - return x; - } - else - { - return vetor[tamVetor-1]; - } - } -} - -int main() -{ - int vetor[MAX]; - - for (int i = 0; i < MAX; ++i) - { - vetor[i] = (rand() % 90) + 10; // 10 a 99 - printf("%d, ", vetor[i]); - } - - max1(vetor, vetor[0], 1); - - printf("\nMax2: %d\n", max2(vetor, MAX) ); - printf("\nMaxDC: %d\n\n", MaxDC(vetor, 0, MAX-1) ); - - return 0; -} diff --git a/src/c/MergeSort.c b/src/c/MergeSort.c index 94324340..f3470e26 100644 --- a/src/c/MergeSort.c +++ b/src/c/MergeSort.c @@ -1,14 +1,13 @@ /* -* Exemplo de Ordenação utilizando Merge Sort -* Kelvin Salton do Prado - 2015 -* -* Dividir para conquistar: -* -* Dividir: Dividir os dados em subsequências pequenas; -* Conquistar: Classificar as duas metades recursivamente aplicando o merge sort; -* Combinar: Juntar as duas metades em um único conjunto já classificado. -* -*/ + * Exemplo de Ordenação utilizando Merge Sort + * + * Dividir para conquistar: + * + * Dividir: Dividir os dados em subsequências pequenas; + * Conquistar: Classificar as duas metades recursivamente aplicando o merge + *sort; Combinar: Juntar as duas metades em um único conjunto já classificado. + * + */ #include #include @@ -21,54 +20,53 @@ void merge(int vetor[], int tamanho) { int i = 0, j = meio, k = 0; int aux[tamanho]; - while( i < meio && j < tamanho ){ - if( vetor[i] <= vetor[j] ) + while (i < meio && j < tamanho) { + if (vetor[i] <= vetor[j]) aux[k] = vetor[i++]; else aux[k] = vetor[j++]; k++; } - - if( i == meio ) - while( j < tamanho ) + + if (i == meio) + while (j < tamanho) aux[k++] = vetor[j++]; else - while( i < meio ) + while (i < meio) aux[k++] = vetor[i++]; - - for( i = 0; i < tamanho; i++ ) + + for (i = 0; i < tamanho; i++) vetor[i] = aux[i]; } - -int mergeSort(int vetor[], int tamanho){ - int meio = tamanho / 2; - if( tamanho > 1 ){ - mergeSort(vetor, meio); - mergeSort(vetor + meio, tamanho - meio); - merge(vetor, tamanho); - } +int mergeSort(int vetor[], int tamanho) { + int meio = tamanho / 2; + if (tamanho > 1) { + mergeSort(vetor, meio); + mergeSort(vetor + meio, tamanho - meio); + merge(vetor, tamanho); + } } -int main(){ +int main() { + + int vetor[TAM_VETOR]; - int vetor[TAM_VETOR]; - - // Preenche o vetor com valores aleatórios 0-1000 - srand(time(NULL)); - for(int i = 0; i < TAM_VETOR; i++){ - vetor[i] = rand()%1000; - printf("%d, ", vetor[i]); - } - - printf("\n\n"); - - mergeSort(vetor, TAM_VETOR); + // Preenche o vetor com valores aleatórios 0-1000 + srand(time(NULL)); + for (int i = 0; i < TAM_VETOR; i++) { + vetor[i] = rand() % 1000; + printf("%d, ", vetor[i]); + } + + printf("\n\n"); + + mergeSort(vetor, TAM_VETOR); + + for (int i = 0; i < TAM_VETOR; i++) { + printf("%d, ", vetor[i]); + } - for(int i = 0; i < TAM_VETOR; i++){ - printf("%d, ", vetor[i]); - } - - return 0; + return 0; } \ No newline at end of file diff --git a/src/c/MinMaxDC.c b/src/c/MinMaxDC.c index b45f0205..aac43e07 100644 --- a/src/c/MinMaxDC.c +++ b/src/c/MinMaxDC.c @@ -10,48 +10,48 @@ * @param max Pointer to store the maximum element */ -void MinAndMax(int arr[], int left, int right, int* min, int* max) { - // if there is only one element in the sub-array, set it as both min and max - if (left == right) { - *min = *max = arr[left]; - return; +void MinAndMax(int arr[], int left, int right, int *min, int *max) { + // if there is only one element in the sub-array, set it as both min and max + if (left == right) { + *min = *max = arr[left]; + return; + } + + // if there are two elements in the sub-array, compare and set min and max + if (right - left == 1) { + if (arr[left] < arr[right]) { + *min = arr[left]; + *max = arr[right]; + } else { + *min = arr[right]; + *max = arr[left]; } + return; + } - // if there are two elements in the sub-array, compare and set min and max - if (right - left == 1) { - if (arr[left] < arr[right]) { - *min = arr[left]; - *max = arr[right]; - } else { - *min = arr[right]; - *max = arr[left]; - } - return; - } - - // calculate the middle index of the sub-array - int mid = (left + right) / 2; - int leftMin, leftMax, rightMin, rightMax; + // calculate the middle index of the sub-array + int mid = (left + right) / 2; + int leftMin, leftMax, rightMin, rightMax; - // recursively find min and max in the left and right sub-arrays - MinAndMax(arr, left, mid, &leftMin, &leftMax); - MinAndMax(arr, mid + 1, right, &rightMin, &rightMax); + // recursively find min and max in the left and right sub-arrays + MinAndMax(arr, left, mid, &leftMin, &leftMax); + MinAndMax(arr, mid + 1, right, &rightMin, &rightMax); - // update the minimum and maximum values - *min = (leftMin < rightMin) ? leftMin : rightMin; - *max = (leftMax > rightMax) ? leftMax : rightMax; + // update the minimum and maximum values + *min = (leftMin < rightMin) ? leftMin : rightMin; + *max = (leftMax > rightMax) ? leftMax : rightMax; } int main() { - int arr[] = {10, 5, 20, 8, 15, 30, -12, 24}; - int arrSize = sizeof(arr) / sizeof(arr[0]); + int arr[] = {10, 5, 20, 8, 15, 30, -12, 24}; + int arrSize = sizeof(arr) / sizeof(arr[0]); - int min, max; + int min, max; - MinAndMax(arr, 0, arrSize - 1, &min, &max); + MinAndMax(arr, 0, arrSize - 1, &min, &max); - printf("Minimum element: %d\n", min); - printf("Maximum element: %d\n", max); + printf("Minimum element: %d\n", min); + printf("Maximum element: %d\n", max); - return 0; + return 0; } diff --git a/src/c/MinMaxIterative.c b/src/c/MinMaxIterative.c new file mode 100644 index 00000000..0ae3e0b9 --- /dev/null +++ b/src/c/MinMaxIterative.c @@ -0,0 +1,23 @@ +#include + +int main() { + int array[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + + int min = array[0]; + int max = array[0]; + + size_t length = sizeof(array) / sizeof(array[0]); + + for (int i = 1; i < length; ++i) { + if (array[i] < min) { + min = array[i]; + } + if (array[i] > max) { + max = array[i]; + } + } + + printf("min: %d\n", min); + printf("max: %d\n", max); + return 0; +} diff --git a/src/c/MinMaxRecursive.c b/src/c/MinMaxRecursive.c new file mode 100644 index 00000000..dcbdb235 --- /dev/null +++ b/src/c/MinMaxRecursive.c @@ -0,0 +1,26 @@ +/* + * Exemplo de algoritmo recursivo. + * Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando + *recursividade + */ + +#include + +#define TAM 10 + +void MaxMin(int vetor[], int min, int max, int indice) { + if (vetor[indice] < min) + min = vetor[indice]; + if (vetor[indice] > max) + max = vetor[indice]; + if (indice < TAM - 1) + MaxMin(vetor, min, max, indice + 1); + else + printf("Min: %d \nMax: %d\n\n", min, max); +} + +int main() { + int vetor[TAM] = {9, 2, 1, 8, 6, 3, 4, 5, 0, 7}; + MaxMin(vetor, vetor[0], vetor[0], 0); + return 0; +} \ No newline at end of file diff --git a/src/c/Palindromo.c b/src/c/Palindrome.c similarity index 90% rename from src/c/Palindromo.c rename to src/c/Palindrome.c index 6698f6dd..cdc59d0f 100644 --- a/src/c/Palindromo.c +++ b/src/c/Palindrome.c @@ -8,7 +8,7 @@ void calc_reverse(char *input, char *output) { char *last_char = input + len_input - 1; - for (int i=0; i < len_input; i++) { + for (int i = 0; i < len_input; i++) { output[i] = *(last_char - i); } output[len_input] = '\0'; @@ -21,7 +21,7 @@ int main() { printf("Digite uma palavra: "); fgets(input, MAX_SIZE_WORD, stdin); - //remove New Line from the end + // remove New Line from the end input[strlen(input) - 1] = '\0'; calc_reverse(input, reverse); diff --git a/src/c/Pilha.c b/src/c/Pilha.c deleted file mode 100644 index 88710399..00000000 --- a/src/c/Pilha.c +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Exemplo de implementação de Pilha em C - Utiliza Sentinela -* Kelvin S. do Prado - 2015 -*/ - -#include - -#define MAX 10 -#define ERRO -1 - -typedef int TIPOCHAVE; - -typedef struct{ - TIPOCHAVE chave; -}REGISTRO; - -typedef struct{ - REGISTRO A[MAX+1]; - int nroRegistros; -}PILHA; - -int inicializa(PILHA* p){ - p->nroRegistros = 0; - int i = 0; - for (i; i < MAX-2; i++){ // Preenche a Pilha *para testes - p->A[i].chave = i*2; // É um array de REGISTRO (semelhante a class), poderia ter mais campos, por isso se define A[i].chave, irá inserir o valor no campo chave - } - p->nroRegistros = i; -} - -bool inserePilha(int valor, PILHA* p){ - if( p->nroRegistros < MAX ){ - p->A[p->nroRegistros].chave = valor; - p->nroRegistros++; - return true; - }else{ - return false; - } -} - -bool removePilha(PILHA* p){ - p->nroRegistros--; -} - -void mostraPilha(PILHA* p){ - int i = p->nroRegistros-1; - printf("\nPilha:\n"); - for (i; i >= 0; i--){ - printf("%d = [ %d ]\n", i, p->A[i].chave); - } - printf("------------------\n"); -} - -int buscaPilha(int chave, PILHA* p){ - p->A[p->nroRegistros].chave = chave; - int aux = 0; - while( p->A[aux].chave != chave ) - aux++; - if( aux == p->nroRegistros ) - return ERRO; - return aux; -} - -int main(){ - PILHA vPilha; - inicializa(&vPilha); - - mostraPilha(&vPilha); - if( inserePilha(10, &vPilha) ){ - printf("Inserido com sucesso"); - }else{ - printf("Pilha cheia"); - } - - mostraPilha(&vPilha); - removePilha(&vPilha); - mostraPilha(&vPilha); - - int aux = buscaPilha(8, &vPilha); - if( aux != -1 ){ - printf("Valor 8 encontrado na posicao %d da pilha\n", aux); - }else{ - printf("Valor nao encontrado\n"); - } -} \ No newline at end of file diff --git a/src/c/PilhaLigadaDinamica.c b/src/c/PilhaLigadaDinamica.c deleted file mode 100644 index 5cfe03c0..00000000 --- a/src/c/PilhaLigadaDinamica.c +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Pilha Dinâmica utilizando uma Lista Ligada em C -* Kelvin Salton do Prado - 2015 -*/ - -#include -#include - -#define ERRO -1 - -typedef int TIPOCHAVE; - -typedef struct AUX{ - TIPOCHAVE chave; - struct AUX *prox; -}*PILHA; - -PILHA CREATE(TIPOCHAVE ch){ - PILHA novaPilha = (PILHA) malloc( sizeof(PILHA) ); - novaPilha->chave = ch; - novaPilha->prox = NULL; - return novaPilha; -} - -PILHA PUSH(TIPOCHAVE ch, PILHA pi){ - /*while( pi->prox != NULL ){ - pi = pi->prox; - }*/ - PILHA novo = CREATE(ch); - //pi->prox = novo; - novo->prox = pi; - return novo; -} - -PILHA POP(PILHA pi){ - PILHA sub = pi->prox; - free(pi); - return sub; -} - -void SHOW(PILHA pi){ - printf("PILHA:\n"); - while( pi->prox != NULL ){ - printf("[ %d ]\n", pi->chave); - pi = pi->prox; - } - printf("[ %d ]\n", pi->chave); -} - -bool SEARCH(TIPOCHAVE ch, PILHA pi){ - bool vAchou = false; - while(pi != NULL){ - if( pi->chave == ch ) - vAchou = true; - pi = pi->prox; - } - return vAchou; -} - -int main(){ - PILHA vPilha; - - vPilha = PUSH(1, vPilha); - vPilha = PUSH(2, vPilha); - vPilha = PUSH(3, vPilha); - vPilha = PUSH(4, vPilha); - vPilha = PUSH(5, vPilha); - vPilha = PUSH(6, vPilha); - - SHOW(vPilha); - - vPilha = POP(vPilha); - vPilha = POP(vPilha); - - SHOW(vPilha); - - if( SEARCH(6, vPilha) ) - printf("\nAchou\n"); - else - printf("\nNão achou\n"); - - return 0; -} \ No newline at end of file diff --git a/src/c/Queue.c b/src/c/Queue.c new file mode 100644 index 00000000..35ad7a8c --- /dev/null +++ b/src/c/Queue.c @@ -0,0 +1,82 @@ +/* + * Exemplo de implementação de Fila em C + */ + +#include + +#define MAX 10 +#define ERRO -1 + +typedef int TIPOCHAVE; + +typedef struct { + TIPOCHAVE chave; +} REGISTRO; + +typedef struct { + REGISTRO A[MAX + 1]; + int nroRegistros; +} FILA; + +void inicializa(FILA *F) { + int i = 0; + for (i; i < MAX - 2; i++) { + F->A[i].chave = i * 2; + } + F->nroRegistros = i; +} + +void mostraFila(FILA *F) { + int i = 0; + printf("FILA:\n"); + for (i; i < F->nroRegistros; i++) { + printf("[ %d ] ", F->A[i].chave); + } + printf("\n\n"); +} + +bool insereFila(TIPOCHAVE ch, FILA *F) { + if (F->nroRegistros >= MAX) + return false; + F->A[F->nroRegistros].chave = ch; + F->nroRegistros++; + return true; +} + +bool removeFila(FILA *F) { + if (F->nroRegistros <= 0) + return false; + int i = 1; + for (i; i < F->nroRegistros; i++) { + F->A[i - 1].chave = F->A[i].chave; + } + F->nroRegistros--; + return true; +} + +int buscaFila(TIPOCHAVE ch, FILA *F) { + F->A[F->nroRegistros].chave = + ch; // Coloca a ch na ultima posição para fazer busca Sentinela + int i = 0; + while (F->A[i].chave != ch) + i++; + if (i >= F->nroRegistros) + return ERRO; + return i; +} + +int main() { + FILA fi; + inicializa(&fi); + mostraFila(&fi); + + insereFila(15, &fi); + mostraFila(&fi); + + removeFila(&fi); + mostraFila(&fi); + + printf("A chave buscada se encontra na posicao %d da fila\n\n", + buscaFila(8, &fi)); + return 0; +} \ No newline at end of file diff --git a/src/c/QuickSort.c b/src/c/QuickSort.c index 98c49507..87fae0c9 100644 --- a/src/c/QuickSort.c +++ b/src/c/QuickSort.c @@ -1,87 +1,87 @@ -#include #include +#include void print_array(int array[], int size) { - printf("[ "); - for (int index = 0; index < size; ++index) { - printf("%d", array[index]); - if (index < size - 1) { - printf(", "); - } + printf("[ "); + for (int index = 0; index < size; ++index) { + printf("%d", array[index]); + if (index < size - 1) { + printf(", "); } - printf(" ]\n"); + } + printf(" ]\n"); } void swap(int array[], int src_index, int dest_index) { - int temp = array[src_index]; - array[src_index] = array[dest_index]; - array[dest_index] = temp; + int temp = array[src_index]; + array[src_index] = array[dest_index]; + array[dest_index] = temp; } int lomuto_partition(int array[], int low, int high) { - int pivot = array[high]; - int index = low; + int pivot = array[high]; + int index = low; - for (int j = low; j < high; ++j) { - if (array[j] < pivot) { - swap(array, index, j); - ++index; - } + for (int j = low; j < high; ++j) { + if (array[j] < pivot) { + swap(array, index, j); + ++index; } - swap(array, index, high); - return index; + } + swap(array, index, high); + return index; } void quicksort_lomuto(int array[], int low, int high) { - if (low < high) { - int pivot = lomuto_partition(array, low, high); - quicksort_lomuto(array, low, pivot - 1); - quicksort_lomuto(array, pivot + 1, high); - } + if (low < high) { + int pivot = lomuto_partition(array, low, high); + quicksort_lomuto(array, low, pivot - 1); + quicksort_lomuto(array, pivot + 1, high); + } } int hoare_partition(int array[], int low, int high) { - int pivot = array[low]; - int i = low - 1; - int j = high + 1; + int pivot = array[low]; + int i = low - 1; + int j = high + 1; - while (true) { - do { - ++i; - } while (array[i] < pivot); + while (true) { + do { + ++i; + } while (array[i] < pivot); - do { - --j; - } while (array[j] > pivot); + do { + --j; + } while (array[j] > pivot); - if (i >= j) { - return j; - } - swap(array, i, j); + if (i >= j) { + return j; } + swap(array, i, j); + } } void quicksort_hoare(int array[], int low, int high) { - if (low < high) { - int pivot = hoare_partition(array, low, high); - quicksort_hoare(array, low, pivot); - quicksort_hoare(array, pivot + 1, high); - } + if (low < high) { + int pivot = hoare_partition(array, low, high); + quicksort_hoare(array, low, pivot); + quicksort_hoare(array, pivot + 1, high); + } } int main() { - int example_lomuto[] = {5, 3, 1, 4, 2}; - int example_hoare[] = {5, 3, 1, 4, 2}; - int size = 5; + int example_lomuto[] = {5, 3, 1, 4, 2}; + int example_hoare[] = {5, 3, 1, 4, 2}; + int size = 5; - printf("lomuto quicksort partition:\n"); - print_array(example_lomuto, size); - quicksort_lomuto(example_lomuto, 0, size - 1); - print_array(example_lomuto, size); + printf("lomuto quicksort partition:\n"); + print_array(example_lomuto, size); + quicksort_lomuto(example_lomuto, 0, size - 1); + print_array(example_lomuto, size); - printf("hoare quicksort partition:\n"); - print_array(example_hoare, size); - quicksort_hoare(example_hoare, 0, size - 1); - print_array(example_hoare, size); - return 0; + printf("hoare quicksort partition:\n"); + print_array(example_hoare, size); + quicksort_hoare(example_hoare, 0, size - 1); + print_array(example_hoare, size); + return 0; } \ No newline at end of file diff --git a/src/c/RadixSort.c b/src/c/RadixSort.c index 2c63dc6b..b4382076 100644 --- a/src/c/RadixSort.c +++ b/src/c/RadixSort.c @@ -1,65 +1,54 @@ #include -void print_array(int array[], int size) -{ - printf("[ "); - for (int i = 0; i < size; i++) - { - printf("%d ", array[i]); - } - printf("]\n"); +void print_array(int array[], int size) { + printf("[ "); + for (int i = 0; i < size; i++) { + printf("%d ", array[i]); + } + printf("]\n"); } -int get_max(int array[], int size) -{ - int max = array[0]; - for (int i = 1; i < size; i++) - { - if (array[i] > max) - max = array[i]; - } - return max; +int get_max(int array[], int size) { + int max = array[0]; + for (int i = 1; i < size; i++) { + if (array[i] > max) + max = array[i]; + } + return max; } -void radix_sort(int array[], int size) -{ - int i; - int semi_sorted[size]; - int significant_digit = 1; - int largest_number = get_max(array, size); +void radix_sort(int array[], int size) { + int i; + int semi_sorted[size]; + int significant_digit = 1; + int largest_number = get_max(array, size); - while (largest_number / significant_digit > 0) - { - int bucket[10] = {0}; - for (i = 0; i < size; i++) - { - bucket[(array[i] / significant_digit) % 10]++; - } - for (i = 1; i < 10; i++) - { - bucket[i] += bucket[i - 1]; - } - for (i = size - 1; i >= 0; i--) - { - semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i]; - } - for (i = 0; i < size; i++) - { - array[i] = semi_sorted[i]; - } - significant_digit *= 10; - } + while (largest_number / significant_digit > 0) { + int bucket[10] = {0}; + for (i = 0; i < size; i++) { + bucket[(array[i] / significant_digit) % 10]++; + } + for (i = 1; i < 10; i++) { + bucket[i] += bucket[i - 1]; + } + for (i = size - 1; i >= 0; i--) { + semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i]; + } + for (i = 0; i < size; i++) { + array[i] = semi_sorted[i]; + } + significant_digit *= 10; + } } -int main() -{ - int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11}; - printf("Unsorted Array\n"); - print_array(array, 10); +int main() { + int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11}; + printf("Unsorted Array\n"); + print_array(array, 10); - radix_sort(array, 10); + radix_sort(array, 10); - printf("Sorted Array\n"); - print_array(array, 10); - return 0; + printf("Sorted Array\n"); + print_array(array, 10); + return 0; } diff --git a/src/c/SelectionSort.c b/src/c/SelectionSort.c index 8fc38542..4cbee813 100644 --- a/src/c/SelectionSort.c +++ b/src/c/SelectionSort.c @@ -1,41 +1,35 @@ #include -void swap(int array[], int i, int j) -{ - int temp = array[i]; - array[i] = array[j]; - array[j] = temp; +void swap(int array[], int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; } -void selection_sort(int array[], int n) -{ - int min, i, j; - for (i = 0; i < n; i++) - { - min = i; - for (j = i + 1; j < n; j++) - { - if (array[min] > array[j]) - { - min = j; - } - } - if (min != i) - swap(array, min, i); +void selection_sort(int array[], int n) { + int min, i, j; + for (i = 0; i < n; i++) { + min = i; + for (j = i + 1; j < n; j++) { + if (array[min] > array[j]) { + min = j; + } } + if (min != i) + swap(array, min, i); + } } -int main() -{ - int array_size = 10; - int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4}; +int main() { + int array_size = 10; + int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4}; - selection_sort(array, array_size); + selection_sort(array, array_size); - printf("Sorted Array:\n"); - int i; - for (i = 0; i < array_size; i++) - printf("%d ", array[i]); + printf("Sorted Array:\n"); + int i; + for (i = 0; i < array_size; i++) + printf("%d ", array[i]); - return 0; + return 0; } \ No newline at end of file diff --git a/src/c/SinglyLinkedList.c b/src/c/SinglyLinkedList.c new file mode 100644 index 00000000..5411563c --- /dev/null +++ b/src/c/SinglyLinkedList.c @@ -0,0 +1,266 @@ +#include +#include + +typedef struct tno { + int dado; + struct tno *anterior; + struct tno *proximo; +} tipoNo; + +typedef tipoNo *pnoh; + +typedef struct { + int tamanho; + pnoh primeiro; + pnoh ultimo; +} tcabec; + +typedef tcabec *TLista; + +TLista criaLista() { + TLista c = (tcabec *)malloc(sizeof(tcabec)); + + c->tamanho = 0; + c->primeiro = NULL; + c->ultimo = NULL; + + return c; +} + +TLista appendLista(TLista lst, int dado) { + pnoh novono = (tipoNo *)malloc(sizeof(tipoNo)); + + novono->dado = dado; + novono->anterior = lst->ultimo; + novono->proximo = NULL; + + if (lst->tamanho == 0) { + lst->primeiro = novono; + } else { + lst->ultimo->proximo = novono; + } + + lst->ultimo = novono; + lst->tamanho++; + + return lst; +} + +int lenLista(TLista lst) { return lst->tamanho; } + +int primLista(TLista lst) { return lst->primeiro->dado; } + +int ultLista(TLista lst) { return lst->ultimo->dado; } + +TLista insertLista(TLista lst, int i, int dado) { + int tam = lenLista(lst); + + if ((i < 0) || (i > tam)) { + return NULL; + } + + if ((lenLista(lst) == 0) || (i == tam)) { + appendLista(lst, dado); + } else { + pnoh novono = (tipoNo *)malloc(sizeof(tipoNo)); + novono->dado = dado; + + if (i == 0) { + novono->proximo = lst->primeiro; + lst->primeiro = novono; + } else { + pnoh aux = lst->primeiro; + int pos = 0; + + while (pos != (i - 1)) { + aux = aux->proximo; + pos++; + } + novono->proximo = aux->proximo; + aux->proximo = novono; + } + + lst->tamanho++; + } + + return lst; +} + +pnoh infoLista(TLista lst, int i) { + int tam = lenLista(lst); + + if ((tam == 0) || (i < 0) || (i > tam)) { + return NULL; + } + + if (i == 0) { + return lst->primeiro; + } + + if (i == tam - 1) { + return lst->ultimo; + } + + pnoh aux = lst->primeiro; + int pos = 0; + + while (pos != i) { + aux = aux->proximo; + pos++; + } + + return aux; +} + +void removeLista(TLista lst, int i) { + int tam = lenLista(lst); + + if ((i < 0) || (i > tam) || (tam == 0)) { + printf("Erro: indice inexistente dentro da Lista."); + return; + } + + if (tam == 1) { + pnoh aux = lst->primeiro; + lst->primeiro = NULL; + lst->ultimo = NULL; + lst->tamanho--; + + free(aux); + } else { + if (i == 0) { + pnoh aux = lst->primeiro; + lst->primeiro = aux->proximo; + lst->tamanho--; + + free(aux); + } else { + if (i == tam - 1) { + pnoh aux = lst->ultimo; + + pnoh penultimo = lst->primeiro; + int pos = 0; + + while (pos != i - 1) { + penultimo = penultimo->proximo; + pos++; + } + + penultimo->proximo = NULL; + lst->ultimo = penultimo; + + lst->tamanho--; + + free(aux); + } else { + pnoh anterior = lst->primeiro; + int pos = 0; + + while (pos != i - 1) { + anterior = anterior->proximo; + pos++; + } + + pnoh aux = anterior->proximo; + anterior->proximo = aux->proximo; + lst->tamanho--; + + free(aux); + } + } + } +} + +int indexLista(TLista lst, int dado) { + int tam = lenLista(lst); + int i, dadolst; + pnoh no_dadolst; + + if (tam == 0) { + return -1; + } + + i = 0; + no_dadolst = infoLista(lst, i); + dadolst = no_dadolst->dado; + while ((i < tam) && (dado != dadolst)) { + i++; + no_dadolst = infoLista(lst, i); + dadolst = no_dadolst->dado; + } + + if (i < tam) { + return i; + } + + return -1; +} + +TLista clearLista(TLista lst) { + int tam = lenLista(lst); + + if (tam == 0) { + return lst; + } + + while (lenLista(lst) > 0) { + removeLista(lst, 0); + } + + return lst; +} + +TLista clonaLista(TLista lst) { + TLista clone = criaLista(); + int tam = lenLista(lst); + + if (tam == 0) { + return clone; + } + + for (int i = 0; i < tam; i++) { + pnoh no = infoLista(lst, i); + if (no != NULL) { + appendLista(clone, no->dado); + } + } + + return clone; +} + +int main() { + TLista lista = criaLista(); + appendLista(lista, 3); + appendLista(lista, 5); + appendLista(lista, 7); + + printf("Lista criada e adicionado 3 numeros\n"); + int tamanho = lenLista(lista); + int primeiro = primLista(lista); + int ultimo = ultLista(lista); + pnoh valor = infoLista(lista, 1); + int valor_dado = valor->dado; + printf("Tamanho da lista: %d\nPrimeiro da Lista: %d\nUltimo da Lista: " + "%d\nSegundo valor: %d\n", + tamanho, primeiro, ultimo, valor_dado); + + insertLista(lista, 2, 6); + valor = infoLista(lista, 2); + valor_dado = valor->dado; + printf("Adicionando 6 na posição 2: %d\n", valor_dado); + + removeLista(lista, 1); + tamanho = lenLista(lista); + printf("Novo tamanho após adicionar e remover: %d\n", tamanho); + + int index = indexLista(lista, 3); + printf("Index do elemento com valor 3 na lista: %d\n", index); + + TLista cloneLista = clonaLista(lista); + printf("Lista Duplicada\n"); + + clearLista(lista); + printf("Lista Apagada"); + + return 0; +} diff --git a/src/c/SortedLinkedList.c b/src/c/SortedLinkedList.c new file mode 100644 index 00000000..8fc5b4ff --- /dev/null +++ b/src/c/SortedLinkedList.c @@ -0,0 +1,114 @@ +/* + * Exemplo de implementação de Lista Sequencial Ordenada em C - Utilizando + *sentinela + */ + +#include + +#define MAX 10 +#define ERRO -1 + +typedef int TIPOCHAVE; // Define um nome TIPOCHAVE para um tipo inteiro + +typedef struct { + TIPOCHAVE chave; +} REGISTRO; + +typedef struct { + REGISTRO A[MAX + 1]; // O +1 é a posição que será utilizada para a 'sentinela' + int nroElementos; +} LISTA; + +void inicializar(LISTA *L) { + L->nroElementos = 0; // Acessa a lista pelo endereço de memória + int i = 0; + for (i; i < MAX - 2; ++i) { // Preenche a lista até -2 para deixar espaço para + // inserir mais depois + L->A[i].chave = i * 2; + } + L->nroElementos = MAX - 2; + // (*L).nroElementos = 0; // Neste caso iria acessar a lista em si, e não o + // ponteiro +} + +/* A função do sentinela é adicionar a chave ao final da lista, ou seja, + * sempre irá encontrar a chave, mesmo que seja na útlima posição da lista. + * Caso seja o último elemento, significa que não encontrou. + * Deste modo elimina o 'if' dentro do laço, poupando várias comparações + */ +int buscaSentinela( + TIPOCHAVE ch, + LISTA *L) { // Poderia usar aqui busca binária, o que seria mais apropriado. + int i = 0; + L->A[L->nroElementos].chave = + ch; // Atribui a 'chave'/valor buscado a ultima posição do array A + while (L->A[i].chave != + ch) // Percorre todo o array A buscando se a 'chave'/valor pesquisado + // se encontra no array (senão será o sentinela) + i++; + if (i == L->nroElementos) // Se o valor chegou até o final, significa que não + // encontrou o valor, retorna ERRO (-1) + return ERRO; + return i; // Caso contrário retorna a posição do valor/'chave' no array +} + +bool inserirOrdenado(REGISTRO reg, LISTA *L) { + int i = 0; + if (L->nroElementos >= MAX) + return false; + L->A[L->nroElementos].chave = reg.chave; + while (L->A[i].chave < reg.chave) + i++; + int p = L->nroElementos - 1; + while (p >= i) { + L->A[p + 1] = L->A[p]; + p--; + } + L->A[i] = reg; + L->nroElementos++; + return true; +} + +bool deletaValor(REGISTRO reg, LISTA *L) { + int posicao = buscaSentinela(reg.chave, L); + if (posicao >= 0) { + for (posicao; posicao < L->nroElementos; posicao++) { + L->A[posicao] = L->A[posicao + 1]; + } + L->nroElementos--; + return true; + } else { + return false; + } +} + +void mostraLista(LISTA *L) { + int i = 0; + for (i; i < L->nroElementos; + ++i) { // Percorre e mostra todos os valores do array + printf("%d, ", L->A[i].chave); + } + printf("\n\n"); +} + +int main() { + + LISTA LISTA; + inicializar(&LISTA); + + printf("Valor 10 encontrado na posição: %d\n\n", buscaSentinela(10, &LISTA)); + mostraLista(&LISTA); + + REGISTRO reg; + reg.chave = 7; + printf("Insere o valor: %d\n", reg.chave); + inserirOrdenado(reg, &LISTA); + mostraLista(&LISTA); + + reg.chave = 12; + printf("Deleta o valor: %d\n", reg.chave); + deletaValor(reg, &LISTA); + mostraLista(&LISTA); + + return 0; +} \ No newline at end of file diff --git a/src/c/Stack.c b/src/c/Stack.c new file mode 100644 index 00000000..e3b290dd --- /dev/null +++ b/src/c/Stack.c @@ -0,0 +1,84 @@ +/* + * Exemplo de implementação de Pilha em C - Utiliza Sentinela + */ + +#include + +#define MAX 10 +#define ERRO -1 + +typedef int TIPOCHAVE; + +typedef struct { + TIPOCHAVE chave; +} REGISTRO; + +typedef struct { + REGISTRO A[MAX + 1]; + int nroRegistros; +} PILHA; + +int inicializa(PILHA *p) { + p->nroRegistros = 0; + int i = 0; + for (i; i < MAX - 2; i++) { // Preenche a Pilha *para testes + p->A[i].chave = i * 2; // É um array de REGISTRO (semelhante a class), + // poderia ter mais campos, por isso se define + // A[i].chave, irá inserir o valor no campo chave + } + p->nroRegistros = i; +} + +bool inserePilha(int valor, PILHA *p) { + if (p->nroRegistros < MAX) { + p->A[p->nroRegistros].chave = valor; + p->nroRegistros++; + return true; + } else { + return false; + } +} + +bool removePilha(PILHA *p) { p->nroRegistros--; } + +void mostraPilha(PILHA *p) { + int i = p->nroRegistros - 1; + printf("\nPilha:\n"); + for (i; i >= 0; i--) { + printf("%d = [ %d ]\n", i, p->A[i].chave); + } + printf("------------------\n"); +} + +int buscaPilha(int chave, PILHA *p) { + p->A[p->nroRegistros].chave = chave; + int aux = 0; + while (p->A[aux].chave != chave) + aux++; + if (aux == p->nroRegistros) + return ERRO; + return aux; +} + +int main() { + PILHA vPilha; + inicializa(&vPilha); + + mostraPilha(&vPilha); + if (inserePilha(10, &vPilha)) { + printf("Inserido com sucesso"); + } else { + printf("Pilha cheia"); + } + + mostraPilha(&vPilha); + removePilha(&vPilha); + mostraPilha(&vPilha); + + int aux = buscaPilha(8, &vPilha); + if (aux != -1) { + printf("Valor 8 encontrado na posicao %d da pilha\n", aux); + } else { + printf("Valor nao encontrado\n"); + } +} \ No newline at end of file diff --git a/src/c/Timsort.c b/src/c/Timsort.c index 51ab4c44..fba68ebc 100644 --- a/src/c/Timsort.c +++ b/src/c/Timsort.c @@ -2,127 +2,123 @@ const int THRESHOLD = 32; -int is_odd(int n) { - return n & 1; -} +int is_odd(int n) { return n & 1; } int get_fmin(int a, int b) { - if (a < b) { - return a; - } - return b; + if (a < b) { + return a; + } + return b; } -int get_floor(int n) { - return n / 2; -} +int get_floor(int n) { return n / 2; } void print_array(int array[], int size) { - printf("["); - for (int i = 0; i < size; i++) { - printf("%d", array[i]); - if (i != size - 1) { - printf(", "); - } + printf("["); + for (int i = 0; i < size; i++) { + printf("%d", array[i]); + if (i != size - 1) { + printf(", "); } - printf("]\n"); + } + printf("]\n"); } int get_run_length(int size_of_array) { - int run_length = size_of_array; - int remainder = 0; - - while (run_length >= THRESHOLD) { - if (is_odd(run_length)) { - remainder = 1; - } - run_length = get_floor(run_length / 2); + int run_length = size_of_array; + int remainder = 0; + + while (run_length >= THRESHOLD) { + if (is_odd(run_length)) { + remainder = 1; } - return run_length + remainder; + run_length = get_floor(run_length / 2); + } + return run_length + remainder; } void insertion_sort(int array[], int left_index, int right_index) { - for (int i = left_index + 1; i <= right_index; i++) { - int temp = array[i]; - int j = i - 1; - while (j >= left_index && array[j] > temp) { - array[j + 1] = array[j]; - j--; - } - array[j + 1] = temp; + for (int i = left_index + 1; i <= right_index; i++) { + int temp = array[i]; + int j = i - 1; + while (j >= left_index && array[j] > temp) { + array[j + 1] = array[j]; + j--; } + array[j + 1] = temp; + } } -void merge_runs(int array[], int left_index, int middle_index, int right_index) { - int left_size = middle_index - left_index + 1; - int right_size = right_index - middle_index; - int left[left_size]; - int right[right_size]; - - for (int i = 0; i < left_size; i++) { - left[i] = array[left_index + i]; - } - for (int j = 0; j < right_size; j++) { - right[j] = array[middle_index + 1 + j]; - } - - int i = 0; - int j = 0; - int k = left_index; - - while (i < left_size && j < right_size) { - if (left[i] <= right[j]) { - array[k] = left[i]; - i++; - } else { - array[k] = right[j]; - j++; - } - k++; - } - - while (i < left_size) { - array[k] = left[i]; - i++; - k++; - } - - while (j < right_size) { - array[k] = right[j]; - j++; - k++; +void merge_runs(int array[], int left_index, int middle_index, + int right_index) { + int left_size = middle_index - left_index + 1; + int right_size = right_index - middle_index; + int left[left_size]; + int right[right_size]; + + for (int i = 0; i < left_size; i++) { + left[i] = array[left_index + i]; + } + for (int j = 0; j < right_size; j++) { + right[j] = array[middle_index + 1 + j]; + } + + int i = 0; + int j = 0; + int k = left_index; + + while (i < left_size && j < right_size) { + if (left[i] <= right[j]) { + array[k] = left[i]; + i++; + } else { + array[k] = right[j]; + j++; } + k++; + } + + while (i < left_size) { + array[k] = left[i]; + i++; + k++; + } + + while (j < right_size) { + array[k] = right[j]; + j++; + k++; + } } void timsort(int array[], int size) { - int run_length = get_run_length(size); - - for (int i = 0; i < size; i += run_length) { - insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1))); - } - - for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) { - for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) { - int middle_index = left_index + size_of_run - 1; - int right_index = get_fmin((left_index + 2 * size_of_run - 1), (size - 1)); - merge_runs(array, left_index, middle_index, right_index); - } + int run_length = get_run_length(size); + + for (int i = 0; i < size; i += run_length) { + insertion_sort(array, i, get_fmin((i + run_length - 1), (size - 1))); + } + + for (int size_of_run = run_length; size_of_run < size; size_of_run *= 2) { + for (int left_index = 0; left_index < size; left_index += 2 * size_of_run) { + int middle_index = left_index + size_of_run - 1; + int right_index = + get_fmin((left_index + 2 * size_of_run - 1), (size - 1)); + merge_runs(array, left_index, middle_index, right_index); } + } } int main() { - int array[] = { 5, 2, -2147483648, 1, 4, 5323, -1, 0, 10, 9, 8, 7, 6, 2147483647, 4, 3, 2 }; - int size = sizeof(array) / sizeof(array[0]); + int array[] = {5, 2, -2147483648, 1, 4, 5323, -1, 0, 10, + 9, 8, 7, 6, 2147483647, 4, 3, 2}; + int size = sizeof(array) / sizeof(array[0]); - printf("Original array:\t"); - print_array(array, size); + printf("Original array:\t"); + print_array(array, size); - timsort(array, size); + timsort(array, size); - printf("Sorted array:\t"); - print_array(array, size); - return 0; + printf("Sorted array:\t"); + print_array(array, size); + return 0; } - - - diff --git a/src/c/TorreDeHanoi.c b/src/c/TorreDeHanoi.c deleted file mode 100644 index 0994a376..00000000 --- a/src/c/TorreDeHanoi.c +++ /dev/null @@ -1,26 +0,0 @@ -/* -Torre de Hanoi em C -Bruno Dantas de Paiva - 2021 -https://github.com/DantasB -*/ - -#include - -void hanoi(int pino0, int pino2, int pino1, int discos) -{ - if (discos == 1) - printf("Move de %i para %i\n", pino0, pino2); - - else - { - hanoi(pino0, pino1, pino2, discos - 1); - hanoi(pino0, pino2, pino1, 1); - hanoi(pino1, pino2, pino0, discos - 1); - } -} - -int main() -{ - hanoi(0, 2, 1, 3); - return 0; -} diff --git a/src/c/TowerOfHanoi.c b/src/c/TowerOfHanoi.c new file mode 100644 index 00000000..91ec0226 --- /dev/null +++ b/src/c/TowerOfHanoi.c @@ -0,0 +1,21 @@ +/* +Torre de Hanoi em C +*/ + +#include + +void hanoi(int pino0, int pino2, int pino1, int discos) { + if (discos == 1) + printf("Move de %i para %i\n", pino0, pino2); + + else { + hanoi(pino0, pino1, pino2, discos - 1); + hanoi(pino0, pino2, pino1, 1); + hanoi(pino1, pino2, pino0, discos - 1); + } +} + +int main() { + hanoi(0, 2, 1, 3); + return 0; +} diff --git a/src/c/TravellingSalesman.c b/src/c/TravellingSalesman.c new file mode 100644 index 00000000..d165ebe4 --- /dev/null +++ b/src/c/TravellingSalesman.c @@ -0,0 +1,116 @@ +/* + * Traveling Salesman Problem in C + * Using a distance matrix to represent an undirected graph. + * Objective: Find the shortest path that visits all vertices without + *repeating any, and returns to the starting vertex. + * + * 6 + * (4)-----(0) + * | \ / \ + * | \ 3/ \2 + * | \/ \ + * 3| /\ (1) + * | / 3\ 4/ | + * | / \ / | + * (3)-----(2) | + * | 7 | + * | | 3 + * -------------- + * + * Distance Matrix + * 0 1 2 3 4 + * 0 0 2 - 3 6 + * 1 2 0 4 3 - + * 2 - 4 0 7 3 + * 3 3 3 7 0 3 + * 4 6 - 3 3 0 + */ + +#include +#include + +#define VERTICES 5 +#define INFINITY 429496729 + +int tempSolution[VERTICES]; +int bestSolution[VERTICES]; +bool visited[VERTICES]; +int bestSolutionValue = INFINITY; +int currentSolutionValue = 0; + +int matrix[VERTICES][VERTICES] = {{0, 2, INFINITY, 3, 6}, + {2, 0, 4, 3, INFINITY}, + {INFINITY, 4, 0, 7, 3}, + {3, 3, 7, 0, 3}, + {6, INFINITY, 3, 3, 0}}; + +void travelingSalesmanAux(int x) { + // If the current solution value is already greater than the best solution, + // stop as it can't be the best solution + if (currentSolutionValue > bestSolutionValue) + return; + + if (x == VERTICES) { // If x == VERTICES, it means the temporary solution + // array is complete + int distance = matrix[tempSolution[x - 1]][tempSolution[0]]; + // If a better (shorter) solution is found + if (distance < INFINITY && + currentSolutionValue + distance < bestSolutionValue) { + bestSolutionValue = + currentSolutionValue + + distance; // Update the best solution with the new better one + // Copy the entire temporary solution array to the best solution array + for (int i = 0; i < VERTICES; ++i) { + bestSolution[i] = tempSolution[i]; + } + } + return; + } + + int last = tempSolution[x - 1]; // 'last' holds the number of the last vertex + // in the temporary solution array + // Loop through all columns in the matrix on the row of the last vertex in the + // temporary solution array + for (int i = 0; i < VERTICES; i++) { + // If the i-th vertex hasn't been visited, and the matrix value is less than + // INFINITY + if (!visited[i] && matrix[last][i] < INFINITY) { + visited[i] = true; // Mark as visited + tempSolution[x] = + i; // Add the current vertex to the temporary solution array + currentSolutionValue += matrix[last][i]; // Increment the path total + travelingSalesmanAux(x + 1); // Recursively call for the next vertex + currentSolutionValue -= + matrix[last][i]; // Decrease the path total if not finished yet + visited[i] = false; // Mark the vertex as unvisited so it can be used + // again by another vertex + } + } +} + +void travelingSalesman(int start) { + visited[start] = true; // Mark the starting vertex as visited (0) + tempSolution[0] = start; // Place vertex 0 in the first position of the + // temporary solution array + travelingSalesmanAux( + 1); // Call the auxiliary function for the traveling salesman problem +} + +void initializeArrays() { + for (int i = 0; i < VERTICES; i++) { + visited[i] = false; + tempSolution[i] = -1; + bestSolution[i] = -1; + } +} + +int main() { + initializeArrays(); + travelingSalesman(0); + + printf("Minimum path cost: %d\n", bestSolutionValue); + for (int i = 0; i < VERTICES; i++) { + printf("%d, ", bestSolution[i]); + } + printf("\n\n"); +} diff --git a/src/c/TwoSum.c b/src/c/TwoSum.c index 161240a0..ec52ae66 100644 --- a/src/c/TwoSum.c +++ b/src/c/TwoSum.c @@ -1,63 +1,59 @@ /* TwoSum Algorithm in C -Ricardo Ferreira Carvalheira - 2023 -https://github.com/ricardocarva - - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. - - You may assume that each input would have exactly one solution, and you may not use the same element twice. - - You can return the answer in any order. + + Given an array of integers nums and an integer target, return indices of +the two numbers such that they add up to target. + + You may assume that each input would have exactly one solution, and you +may not use the same element twice. + + You can return the answer in any order. */ #include #include -int* twoSum(int* nums, int numsSize, int target){ - - for(int i=0;i +#include + +#define ERRO -1 + +typedef int TIPOCHAVE; + +typedef struct aux { + TIPOCHAVE chave; + struct aux *prox; +} REGISTRO, *PONT; + +PONT criaRegistro(TIPOCHAVE ch) { + PONT rg = (PONT)malloc(sizeof(PONT)); + rg->chave = ch; + rg->prox = NULL; + return rg; +} + +PONT insereRegistro(TIPOCHAVE ch, PONT rg) { + if (rg == NULL) + return criaRegistro(ch); // Se não tem nenhum registro na lista cria um novo + while (rg->prox != NULL) + rg = rg->prox; + rg->prox = criaRegistro(ch); + return NULL; +} + +void mostraLista(PONT rg) { + if (rg == NULL) + return; + printf("%d, ", rg->chave); + mostraLista(rg->prox); +} + +PONT buscaSequencial(TIPOCHAVE ch, PONT rg) { + while (rg != NULL) { + if (rg->chave == ch) + return rg; + rg = rg->prox; + } + return NULL; +} + +bool deletaRegistro(TIPOCHAVE ch, PONT rg) { + PONT ant; + while (rg != NULL) { + if (rg->chave == ch) { + ant->prox = rg->prox; + free(rg); + return true; + } + ant = rg; + rg = rg->prox; + } + printf("\nChave %d não encontrada.\n", ch); + return false; +} + +int main() { + PONT RG = insereRegistro(23, RG); + insereRegistro(34, RG); + insereRegistro(12, RG); + insereRegistro(63, RG); + insereRegistro(45, RG); + + mostraLista(RG); + + TIPOCHAVE ch = 64; + if (buscaSequencial(ch, RG) != NULL) + printf("\nEncontrou chave %d\n", ch); + else + printf("\nNão encontrou chave %d\n", ch); + + deletaRegistro(63, RG); + mostraLista(RG); + + printf("\n"); + deletaRegistro(34, RG); + mostraLista(RG); + return 0; +} \ No newline at end of file diff --git a/src/cpp/BinarySearch.cpp b/src/cpp/BinarySearch.cpp index dcc7e6fc..5e7d778c 100644 --- a/src/cpp/BinarySearch.cpp +++ b/src/cpp/BinarySearch.cpp @@ -3,52 +3,39 @@ using namespace std; -int binarySearch(int value, vector &vec, int leftIndex, int rightIndex) -{ - int mid = (leftIndex + rightIndex) / 2; - - if (leftIndex <= rightIndex) - { - if (value > vec[mid]) - { - leftIndex = mid + 1; - return binarySearch(value, vec, leftIndex, rightIndex); - } - else if (value < vec[mid]) - { - rightIndex = mid - 1; - return binarySearch(value, vec, leftIndex, rightIndex); - } - else - { - return mid; - } - } - else - { - return -1; +int binarySearch(int value, vector &vec, int leftIndex, int rightIndex) { + int mid = (leftIndex + rightIndex) / 2; + + if (leftIndex <= rightIndex) { + if (value > vec[mid]) { + leftIndex = mid + 1; + return binarySearch(value, vec, leftIndex, rightIndex); + } else if (value < vec[mid]) { + rightIndex = mid - 1; + return binarySearch(value, vec, leftIndex, rightIndex); + } else { + return mid; } + } else { + return -1; + } } -int main() -{ - vector vec; - - for (int index = 1; index <= 50; index++) - { - vec.push_back(index); - } +int main() { + vector vec; - int value = 45; + for (int index = 1; index <= 50; index++) { + vec.push_back(index); + } - int index = binarySearch(value, vec, 0, vec.size()); + int value = 45; - if (index >= 0) - { - cout << "Value " << to_string(value) << " found at position " << to_string(index) << endl; - } - else - { - cout << "Could not find the value " << to_string(value) << endl; - } + int index = binarySearch(value, vec, 0, vec.size()); + + if (index >= 0) { + cout << "Value " << to_string(value) << " found at position " + << to_string(index) << endl; + } else { + cout << "Could not find the value " << to_string(value) << endl; + } } \ No newline at end of file diff --git a/src/cpp/BinarySearchTree.cpp b/src/cpp/BinarySearchTree.cpp new file mode 100644 index 00000000..9973dc0a --- /dev/null +++ b/src/cpp/BinarySearchTree.cpp @@ -0,0 +1,246 @@ +#include + +/* + * Structure for a binary tree node + */ +struct Node { + int data; ///< The integer data value stored in the node. + Node *left; ///< Pointer to the left child node. + Node *right; ///< Pointer to the right child node. + + /** + * Constructor to create a new node with the given data. + * + * @param value the data value for the new node. + */ + Node(int data) : data(data), left(nullptr), right(nullptr) {} +}; + +class BinarySearchTree { +public: + BinarySearchTree() : root(nullptr) {} + + Node *find(int x) const { return _find(this->root, x); } + + void insert(int x) { _insert(&(this->root), x); } + + void deleteNode(int x) { _delete(&(this->root), x); } + + void preorderTraversal() const { _printPreorder(this->root); } + + void inorderTraversal() const { _printInorder(this->root); } + + void postorderTraversal() const { _printPostorder(this->root); } + +private: + Node *root; + + /** + * @brief Find a node with a specific value in the binary search tree. + * + * This function searches the binary search tree starting from the given root + * node for a node that contains the specified value `x`. If a node with the + * value `x` is found, a pointer to that node is returned. If no such node + * exists in the tree, the function returns `nullptr`. + * + * @param root A pointer to the root node of the binary search tree. + * @param x The value to search for in the tree. + * @return A pointer to the node containing the value `x`, or `nullptr` if not + * found. + */ + Node *_find(Node *root, int x) const { + if (!root || root->data == x) { + return root; + } + if (x < root->data) { + return _find(root->left, x); + } else { + return _find(root->right, x); + } + } + + /** + * @brief Inserts a new node with the specified value into the binary search + * tree. + * + * This function inserts a new node containing the value `x` into the binary + * search tree. It traverses the tree starting from the given root node + * (passed as a pointer to a pointer) and inserts the new node at the + * appropriate position based on the value `x`. + * + * @param root A pointer to a pointer to the root node of the binary search + * tree. + * @param x The value to insert into the tree. + * @return A pointer to the updated root node of the tree after the insertion. + */ + Node *_insert(Node **root, int x) { + if (!(*root)) { + *root = new Node(x); + } else if (x <= (*root)->data) { + (*root)->left = _insert(&((*root)->left), x); + } else { + (*root)->right = _insert(&((*root)->right), x); + } + return *root; + } + + /** + * @brief Deletes a node with the specified value from the binary search tree. + * + * This function deletes a node containing the value `x` from the binary + * search tree. It traverses the tree starting from the given root node and + * removes the node with the specified value if it exists. + * + * After the deletion, the function may adjust the tree structure to maintain + * its binary search tree properties. + * + * @param root A pointer to a pointer to the root node of the binary search + * tree. + * @param x The value to delete from the tree. + * @return A pointer to the updated root node of the tree after the deletion. + */ + Node *_delete(Node **root, int x) { + if (!(*root)) { + return nullptr; + } + + if (x < (*root)->data) { + (*root)->left = _delete(&((*root)->left), x); + } else if (x > (*root)->data) { + (*root)->right = _delete(&((*root)->right), x); + } else { + // Case 1: Leaf node + if (!((*root)->left) && !((*root)->right)) { + delete *root; + *root = nullptr; + } + + // Case 2: Only one child + else if (!((*root)->left)) { + Node *tmp = *root; + *root = (*root)->right; + delete tmp; + } else if (!((*root)->right)) { + Node *tmp = *root; + *root = (*root)->left; + delete tmp; + } + + // Case 3: Two children + else { + // Could've been <<< Node *tmp = _find_max((*root)->left); >>> + Node *tmp = _find_min((*root)->right); + (*root)->data = tmp->data; + (*root)->right = _delete(&((*root)->right), tmp->data); + } + } + return *root; + } + + /** + * @brief Find the minimum node value in the binary search tree. + * + * This function searches the binary search tree starting from the given root + * node and returns a pointer to the node with the minimum value. The minimum + * value is found by recursively traversing the left child nodes until the + * smallest value is located. + * + * @param root A pointer to the root node of the binary search tree. + * @return A pointer to the node with the minimum value in the tree. + */ + Node *_find_min(Node *root) const { + while (root && root->left) { + root = root->left; + } + return root; + } + + /** + * @brief Find the maximum node value in the binary search tree. + * + * This function searches the binary search tree starting from the given root + * node and returns a pointer to the node with the maximum value. The maximum + * value is found by recursively traversing the right child nodes until the + * largest value is located. + * + * @param root A pointer to the root node of the binary search tree. + * @return A pointer to the node with the minimum value in the tree. + */ + Node *_find_max(Node *root) const { + while (root && root->right) { + root = root->right; + } + return root; + } + + /** + * @brief Prints the elements of the binary search tree in preorder traversal. + * + * The preorder traversal visits the current node first, followed by its left + * and right children - recursively. + * + * @param root A pointer to the root node of the binary search tree. + */ + void _printPreorder(Node *root) const { + if (root) { + std::cout << root->data << '\n'; + _printPreorder(root->left); + _printPreorder(root->right); + } + } + + /** + * @brief Prints the elements of the binary search tree in inorder traversal. + * + * The inorder traversal visits the left child, followed by the current node, + * and then the right child recursively. + * + * @param root A pointer to the root node of the binary search tree. + */ + void _printInorder(Node *root) const { + if (root) { + _printInorder(root->left); + std::cout << root->data << '\n'; + _printInorder(root->right); + } + } + + /** + * @brief Prints the elements of the binary search tree in postorder + * traversal. + * + * The postorder traversal visits the left and right children first, followed + * by the current node. + * + * @param root A pointer to the root node of the binary search tree. + */ + void _printPostorder(Node *root) const { + if (root) { + _printPostorder(root->left); + _printPostorder(root->right); + std::cout << root->data << '\n'; + } + } +}; + +int main(int argc, char *argv[]) { + auto bst = BinarySearchTree(); + + int arr[] = {30, 20, 10, 50, 40, 45, 80, 90}; + for (const auto &e : arr) { + bst.insert(e); + } + + std::cout << "inorder traversal:\n"; + bst.inorderTraversal(); + std::cout << "preorder traversal:\n"; + bst.preorderTraversal(); + std::cout << "postorder traversal:\n"; + bst.postorderTraversal(); + + bst.deleteNode(50); + std::cout << "preorder traversal:\n"; + bst.preorderTraversal(); + + return 0; +} diff --git a/src/cpp/BinaryTree.cpp b/src/cpp/BinaryTree.cpp new file mode 100644 index 00000000..3f77440a --- /dev/null +++ b/src/cpp/BinaryTree.cpp @@ -0,0 +1,110 @@ +#include + +using namespace std; + +// Create a class for the BinaryTree +class BinaryTree { + // Create a struct for the TreeNode + struct TreeNode { + // Variables for the TreeNode + int data; + TreeNode *left; + TreeNode *right; + + // Constructor for the TreeNode + TreeNode(int value) : data(value), left(nullptr), right(nullptr) {} + }; + + // Private Variables and Functions +private: + TreeNode *root; + + // Insert Function + TreeNode *insert(TreeNode *root, int value) { + if (root == nullptr) + return new TreeNode(value); + + if (value < root->data) + root->left = insert(root->left, value); + else + root->right = insert(root->right, value); + + return root; + } + + // Print Inorder Function + void printInorder(TreeNode *head) { + if (head != nullptr) { + printInorder(head->left); + cout << head->data << " "; + printInorder(head->right); + } + } + + // Print Preorder Function + void printPreorder(TreeNode *head) { + if (head != nullptr) { + cout << head->data << " "; + printPreorder(head->left); + printPreorder(head->right); + } + } + + // Print Postorder Function + void printPostorder(TreeNode *head) { + if (head != nullptr) { + printPostorder(head->left); + printPostorder(head->right); + cout << head->data << " "; + } + } + + // Public Functions +public: + // Constructor + BinaryTree() : root(nullptr) {} + + // Insert Function + void insert(int value) { root = insert(root, value); } + + // Print Inorder Function + void printInorder() { + printInorder(root); + cout << endl; + } + + // Print Preorder Function + void printPreorder() { + printPreorder(root); + cout << endl; + } + + // Print Postorder Function + void printPostorder() { + printPostorder(root); + cout << endl; + } +}; + +int main() { + // Create tree + BinaryTree binaryTree; + + binaryTree.insert(10); + binaryTree.insert(6); + binaryTree.insert(15); + binaryTree.insert(3); + binaryTree.insert(8); + binaryTree.insert(20); + + cout << "InOrder: "; + binaryTree.printInorder(); + + cout << "PreOrder: "; + binaryTree.printPreorder(); + + cout << "PostOrder: "; + binaryTree.printPostorder(); + + return 0; +} diff --git a/src/cpp/BubbleSort.cpp b/src/cpp/BubbleSort.cpp index 80614b00..5d4dafaa 100644 --- a/src/cpp/BubbleSort.cpp +++ b/src/cpp/BubbleSort.cpp @@ -3,45 +3,37 @@ using namespace std; -vector bubbleSort(vector vector) -{ - for (uint32_t end = vector.size()-1; end > 0; --end) - { - for (uint32_t index = 0; index < end; ++index) - { - if (vector[index] > vector[index+1]) - { - int temp = vector[index]; - vector[index] = vector[index+1]; - vector[index+1] = temp; - } - } +vector bubbleSort(vector vector) { + for (uint32_t end = vector.size() - 1; end > 0; --end) { + for (uint32_t index = 0; index < end; ++index) { + if (vector[index] > vector[index + 1]) { + int temp = vector[index]; + vector[index] = vector[index + 1]; + vector[index + 1] = temp; + } } - return vector; + } + return vector; } -void showVector(vector vector) -{ - for (uint32_t i = 0; i < vector.size(); ++i) - { - if (i +1 == vector.size()) - cout << vector[i]; - else - cout << vector[i] << ", "; - } - cout << "\n"; +void showVector(vector vector) { + for (uint32_t i = 0; i < vector.size(); ++i) { + if (i + 1 == vector.size()) + cout << vector[i]; + else + cout << vector[i] << ", "; + } + cout << "\n"; } -int main() -{ - vector vector; - for (uint32_t i = 0; i < 10; ++i) - { - vector.push_back(rand() % 100); - } - cout << "Initial Vector: "; - showVector(vector); - vector = bubbleSort(vector); - cout << "Sorted Vector: "; - showVector(vector); +int main() { + vector vector; + for (uint32_t i = 0; i < 10; ++i) { + vector.push_back(rand() % 100); + } + cout << "Initial Vector: "; + showVector(vector); + vector = bubbleSort(vector); + cout << "Sorted Vector: "; + showVector(vector); } diff --git a/src/cpp/CalculatePi.cpp b/src/cpp/CalculatePi.cpp new file mode 100644 index 00000000..25f92878 --- /dev/null +++ b/src/cpp/CalculatePi.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +float pi = 0.0; +float denominator = 1.0; +float operation = 1.0; + +float pi_calculator(int terms) { + for (int i = 0; i < terms; i++) { + pi += operation * (4.0 / denominator); + denominator += 2.0; + operation *= -1.0; + } + return pi; +} + +int main() { + float result = pi_calculator(100000); + cout << result; +} diff --git a/src/cpp/ConnectedComponents.cpp b/src/cpp/ConnectedComponents.cpp new file mode 100644 index 00000000..050222e3 --- /dev/null +++ b/src/cpp/ConnectedComponents.cpp @@ -0,0 +1,46 @@ +#include +#include + +#define VERTICES 6 +#define INF -1 + +std::vector visited(VERTICES, false); // Array to track visited vertices +int components = 0; + +// Adjacency matrix representing the graph +int matrix[VERTICES][VERTICES] = { + {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF}, + {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1}, + {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}}; + +// Recursive method to find connected components using adjacency matrix +void findConnectedComponents(int current) { + for (int i = 0; i < VERTICES; i++) { + if (!visited[i] && matrix[current][i] == 1) { + visited[i] = true; + components++; + std::cout << "(" << i << ")-"; + findConnectedComponents(i); + } + } +} + +int main() { + // Initialize all vertices as unvisited + for (int i = 0; i < VERTICES; i++) + visited[i] = false; + + // For each vertex, if it is unvisited, start a DFS and count components + for (int i = 0; i < VERTICES; i++) { + if (!visited[i]) { + components = 0; + visited[i] = true; + std::cout << "Starting at vertex (" << i << ")-"; + findConnectedComponents(i); + std::cout << "\nNumber of connected components starting from vertex " << i + << ": " << components << "\n\n"; + } + } + + return 0; +} diff --git a/src/cpp/CountingSort.cpp b/src/cpp/CountingSort.cpp index 400b6a54..1a6733fa 100644 --- a/src/cpp/CountingSort.cpp +++ b/src/cpp/CountingSort.cpp @@ -1,107 +1,105 @@ +#include #include #include -#include using namespace std; -vector counting_sort(vector& nums) { - - - // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} - // max = 9 - // The vector contains numbers between [0 .. max] - auto max = *max_element(nums.begin(), nums.end()); - - - // Creates a vector with max + 1 positions to count occurrences of each element - // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in the vector nums - // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - vector counting(max+1); - - - // Counts occurrences of each element - // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} - // - // 0 1 2 3 4 5 6 7 8 9 - // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1} - // - for(auto& i : nums) { - counting[i]++; - } - - - // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10} - // It will be used to determine the positions of the elements in the ordered vector - for (size_t i = 1; i < counting.size(); i++) { - - counting[i] += counting[i-1]; - } - - vector sorted(nums.size()); - - /* - - The next loop places the numbers in their proper positions in the ordered vector - i = iterates through the elements of nums - counting[i] -1 is the position that element i must assume in the ordered vector - - The first 3 steps would be: - - nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} - counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10} - sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - - Step 1: - i = 5 - counting[i] => counting[5] => 9 - sorted[9 - 1] => sorted[8] = i => sorted[8] = 5 - sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0} - - Step 2: - i = 0 - counting[i] => counting[0] => 2 - sorted[2 - 1] => sorted[1] = i => sorted[1] = 0 - sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0} - - Step 3: - i = 1 - counting[i] => counting[1] => 3 - sorted[3 - 1] => sorted[2] = i => sorted[2] = 1 - sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0} - */ - for(auto& i : nums) { - sorted[ counting[i]-1 ] = i; - counting[i]--; - } - - return sorted; +vector counting_sort(vector &nums) { + + // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} + // max = 9 + // The vector contains numbers between [0 .. max] + auto max = *max_element(nums.begin(), nums.end()); + + // Creates a vector with max + 1 positions to count occurrences of each + // element + // 0 1 2 3 4 5 6 7 8 9 -> possible elements to occur in + // the vector nums + // Counting = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + vector counting(max + 1); + + // Counts occurrences of each element + // nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} + // + // 0 1 2 3 4 5 6 7 8 9 + // counting = {2, 1, 1, 2, 1, 2, 0, 0, 0, 1} + // + for (auto &i : nums) { + counting[i]++; + } + + // Now, counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10} + // It will be used to determine the positions of the elements in the ordered + // vector + for (size_t i = 1; i < counting.size(); i++) { + + counting[i] += counting[i - 1]; + } + + vector sorted(nums.size()); + + /* + + The next loop places the numbers in their proper positions in the ordered + vector i = iterates through the elements of nums counting[i] -1 is the + position that element i must assume in the ordered vector + + The first 3 steps would be: + + nums = {5, 0, 1, 2, 3, 5, 3, 0, 9, 4} + counting = {2, 3, 4, 6, 7, 9, 9, 9, 9, 10} + sorted = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + + Step 1: + i = 5 + counting[i] => counting[5] => 9 + sorted[9 - 1] => sorted[8] = i => sorted[8] = 5 + sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0} + + Step 2: + i = 0 + counting[i] => counting[0] => 2 + sorted[2 - 1] => sorted[1] = i => sorted[1] = 0 + sorted = {0, 0, 0, 0, 0, 0, 0, 0, 5, 0} + + Step 3: + i = 1 + counting[i] => counting[1] => 3 + sorted[3 - 1] => sorted[2] = i => sorted[2] = 1 + sorted = {0, 0, 1, 0, 0, 0, 0, 0, 5, 0} + */ + for (auto &i : nums) { + sorted[counting[i] - 1] = i; + counting[i]--; + } + + return sorted; } void print_vector(vector vec) { - cout << "["; - for (size_t i = 0; i < vec.size(); i++) { - if(i != vec.size()-1) { - cout << vec[i] << ", "; - } - else { - cout << vec[i]; - } + cout << "["; + for (size_t i = 0; i < vec.size(); i++) { + if (i != vec.size() - 1) { + cout << vec[i] << ", "; + } else { + cout << vec[i]; } - cout << "]" << endl; + } + cout << "]" << endl; } int main() { - vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4}; + vector nums{5, 0, 1, 2, 3, 5, 3, 0, 9, 4}; - vector sorted = counting_sort(nums); + vector sorted = counting_sort(nums); - cout << "Original vector = "; - print_vector(nums); + cout << "Original vector = "; + print_vector(nums); - cout << "Sorted vector = "; - print_vector(sorted); + cout << "Sorted vector = "; + print_vector(sorted); - return 0; + return 0; } diff --git a/src/cpp/Dijkstras_MinHeap.cpp b/src/cpp/Dijkstras_MinHeap.cpp new file mode 100644 index 00000000..13ff75bb --- /dev/null +++ b/src/cpp/Dijkstras_MinHeap.cpp @@ -0,0 +1,101 @@ +/** + * Dijkstras_MinHeap.cpp + * + * This file implements Dijkstra's algorithm using a min-heap (priority queue). + * The algorithm finds the shortest paths from the source vertex to all other + * vertices in a weighted graph. + * + * Functions: + * - void dijkstra(const unordered_map>& graph, int + * start_vertex) + * - graph: An adjacency list representation of the graph. + * - key: vertex + * - value: unordered_map of connected vertices and their edge weights + * - start_vertex: The starting vertex for Dijkstra's algorithm. + * + * Example Usage: + * Uncomment the main function to run a sample test case. + * The sample graph used in the main function is represented as an adjacency + * list. + */ + +#include +#include +#include +#include +#include + +using namespace std; + +// A structure to represent a node in the priority queue +struct Node { + int vertex; + int distance; + bool operator>(const Node &other) const { return distance > other.distance; } +}; + +void dijkstra(const unordered_map> &graph, + int start_vertex) { + // Initialize distances and predecessors + unordered_map dist; + unordered_map pred; + for (const auto &pair : graph) { + dist[pair.first] = numeric_limits::max(); + pred[pair.first] = -1; + } + dist[start_vertex] = 0; + + // Priority queue to store vertices and their distances + priority_queue, greater> priority_queue; + priority_queue.push({start_vertex, 0}); + + while (!priority_queue.empty()) { + Node current = priority_queue.top(); + priority_queue.pop(); + + // If this distance is not updated, continue + if (current.distance > dist[current.vertex]) { + continue; + } + + // Visit each neighbor of the current vertex + for (const auto &neighbor_pair : graph.at(current.vertex)) { + int neighbor = neighbor_pair.first; + int weight = neighbor_pair.second; + int distance = current.distance + weight; + + // If a shorter path to the neighbor is found + if (distance < dist[neighbor]) { + dist[neighbor] = distance; + pred[neighbor] = current.vertex; + priority_queue.push({neighbor, distance}); + } + } + } + + // Print distances and predecessors + cout << "Distances: \n"; + for (const auto &pair : dist) { + cout << "Vertex " << pair.first << ": " << pair.second << endl; + } + cout << "\nPredecessors: \n"; + for (const auto &pair : pred) { + cout << "Vertex " << pair.first << ": " << pair.second << endl; + } +} + +// Uncomment the following main function to run a sample test case + +int main() { + // Example graph represented as an adjacency list + unordered_map> graph = { + {0, {{1, 1}, {2, 4}}}, + {1, {{0, 1}, {2, 2}, {3, 5}}}, + {2, {{0, 4}, {1, 2}, {3, 1}}}, + {3, {{1, 5}, {2, 1}}}}; + + // Running Dijkstra's algorithm from vertex 0 + dijkstra(graph, 0); + + return 0; +} diff --git a/src/cpp/DoublyLinkedList.cpp b/src/cpp/DoublyLinkedList.cpp index f75e2b9b..15dc333f 100644 --- a/src/cpp/DoublyLinkedList.cpp +++ b/src/cpp/DoublyLinkedList.cpp @@ -1,223 +1,190 @@ #include -class Node -{ +class Node { private: - int value; + int value; public: - Node *next{nullptr}; - Node *previous{nullptr}; + Node *next{nullptr}; + Node *previous{nullptr}; - // Node constructor - Node(int value) - { - this->value = value; - } + // Node constructor + Node(int value) { this->value = value; } - int getValue() { return this->value; }; + int getValue() { return this->value; }; }; -class DoublyLinkedList -{ +class DoublyLinkedList { private: - Node *first{nullptr}; - - // Receives the node reference and make the pointers around stop pointing to - void remove_pointers_to(Node *&node) - { - if (node->next) - { - node->next->previous = node->previous; - } - if (node->previous) - { - node->previous->next = node->next; - } - else - { - this->first = node->next; - } + Node *first{nullptr}; + + // Receives the node reference and make the pointers around stop pointing to + void remove_pointers_to(Node *&node) { + if (node->next) { + node->next->previous = node->previous; + } + if (node->previous) { + node->previous->next = node->next; + } else { + this->first = node->next; } + } public: - DoublyLinkedList() {} - - void push_front(int value) - { - // Initialize a pointier to a new node with received value - Node *node = new Node(value); - // Node points to the first - node->next = this->first; - - // If there is a first node, make him point to new node - if (this->first) - { - this->first->previous = node; - } - - // Node becomes the first - this->first = node; - } - - // Checks if there is a first node - bool isEmpty() - { - if (!this->first) - { - return true; - } - return false; - } - - void push_back(int value) - { - Node *node = new Node(value); - Node *selectedNode = this->first; - - if (this->isEmpty()) - { - this->first = node; - return; - } - - Node *aux{nullptr}; - while (selectedNode) - { - aux = selectedNode; - selectedNode = selectedNode->next; - } - - node->previous = aux; - aux->next = node; - }; - - void remove(int value) - { - // Throw exception to empty List - if (this->isEmpty()) - { - throw std::logic_error("List is empty, nothing to be removed!"); - } - - // Initialize a pointier to first element - Node *node = this->first; - - // Go through the list until find the value or the end - while ((node) && (node->getValue() != value)) - { - node = node->next; - } - // Throw exception if didn't find the value - if (!node) - { - throw std::logic_error("Value must be in the list!"); - } - - // Remove all pointier to the value if exists - this->remove_pointers_to(node); - - // Delete node - delete (node); - } - - // Removes the k-th element, where k it's an ordinal number - void remove_ordinary(int position) - { - if (this->isEmpty()) - { - throw std::logic_error("List is empty, nothing to be removed!"); - } - - if (position < 1) - { - throw std::logic_error("Invalid position!"); - } - - Node *selectedNode = this->first; - int aux = 1; - - while ((selectedNode) && (aux != position)) - { - selectedNode = selectedNode->next; - aux++; - } - - if (!selectedNode) - { - throw std::logic_error("Index out of bound!"); - } - - this->remove_pointers_to(selectedNode); - - delete (selectedNode); - } - - std::pair find(int value) - { - // Throw exception to empty List - if (this->isEmpty()) - { - throw std::logic_error("List is empty, nothing to be removed!"); - } - - // Initialize a pointier to first element - Node *node = this->first; - - // Go through the list until find the value or the end - while ((node) && (node->getValue() != value)) - { - node = node->next; - } - - if (!node) - { - return {false, nullptr}; - } - return {true, node}; - } - - void print() - { - Node *selectedNode = this->first; - std::cout << "[ "; - while (selectedNode) - { - std::cout << selectedNode->getValue() << " "; - selectedNode = selectedNode->next; - } - std::cout << "]" << std::endl; + DoublyLinkedList() {} + + void push_front(int value) { + // Initialize a pointier to a new node with received value + Node *node = new Node(value); + // Node points to the first + node->next = this->first; + + // If there is a first node, make him point to new node + if (this->first) { + this->first->previous = node; + } + + // Node becomes the first + this->first = node; + } + + // Checks if there is a first node + bool isEmpty() { + if (!this->first) { + return true; + } + return false; + } + + void push_back(int value) { + Node *node = new Node(value); + Node *selectedNode = this->first; + + if (this->isEmpty()) { + this->first = node; + return; + } + + Node *aux{nullptr}; + while (selectedNode) { + aux = selectedNode; + selectedNode = selectedNode->next; + } + + node->previous = aux; + aux->next = node; + }; + + void remove(int value) { + // Throw exception to empty List + if (this->isEmpty()) { + throw std::logic_error("List is empty, nothing to be removed!"); + } + + // Initialize a pointier to first element + Node *node = this->first; + + // Go through the list until find the value or the end + while ((node) && (node->getValue() != value)) { + node = node->next; + } + // Throw exception if didn't find the value + if (!node) { + throw std::logic_error("Value must be in the list!"); + } + + // Remove all pointier to the value if exists + this->remove_pointers_to(node); + + // Delete node + delete (node); + } + + // Removes the k-th element, where k it's an ordinal number + void remove_ordinary(int position) { + if (this->isEmpty()) { + throw std::logic_error("List is empty, nothing to be removed!"); + } + + if (position < 1) { + throw std::logic_error("Invalid position!"); + } + + Node *selectedNode = this->first; + int aux = 1; + + while ((selectedNode) && (aux != position)) { + selectedNode = selectedNode->next; + aux++; + } + + if (!selectedNode) { + throw std::logic_error("Index out of bound!"); + } + + this->remove_pointers_to(selectedNode); + + delete (selectedNode); + } + + std::pair find(int value) { + // Throw exception to empty List + if (this->isEmpty()) { + throw std::logic_error("List is empty, nothing to be removed!"); + } + + // Initialize a pointier to first element + Node *node = this->first; + + // Go through the list until find the value or the end + while ((node) && (node->getValue() != value)) { + node = node->next; + } + + if (!node) { + return {false, nullptr}; + } + return {true, node}; + } + + void print() { + Node *selectedNode = this->first; + std::cout << "[ "; + while (selectedNode) { + std::cout << selectedNode->getValue() << " "; + selectedNode = selectedNode->next; } + std::cout << "]" << std::endl; + } }; -int main() -{ - DoublyLinkedList *doubly_linked_list = new DoublyLinkedList(); +int main() { + DoublyLinkedList *doubly_linked_list = new DoublyLinkedList(); - std::cout << "Push_front(20, 30, 40):" << std::endl; - doubly_linked_list->push_front(20); - doubly_linked_list->push_front(30); - doubly_linked_list->push_front(40); + std::cout << "Push_front(20, 30, 40):" << std::endl; + doubly_linked_list->push_front(20); + doubly_linked_list->push_front(30); + doubly_linked_list->push_front(40); - doubly_linked_list->print(); + doubly_linked_list->print(); - std::cout << "Remove second!" << std::endl; + std::cout << "Remove second!" << std::endl; - doubly_linked_list->remove_ordinary(2); + doubly_linked_list->remove_ordinary(2); - doubly_linked_list->print(); + doubly_linked_list->print(); - std::cout << "Remove(20, 40)!" << std::endl; - doubly_linked_list->remove(20); - doubly_linked_list->remove(40); + std::cout << "Remove(20, 40)!" << std::endl; + doubly_linked_list->remove(20); + doubly_linked_list->remove(40); - std::cout << "List is empty: "; - doubly_linked_list->print(); + std::cout << "List is empty: "; + doubly_linked_list->print(); - std::cout << "Push_back(512, 123, 412)!" << std::endl; - doubly_linked_list->push_back(512); - doubly_linked_list->push_back(123); - doubly_linked_list->push_back(412); + std::cout << "Push_back(512, 123, 412)!" << std::endl; + doubly_linked_list->push_back(512); + doubly_linked_list->push_back(123); + doubly_linked_list->push_back(412); - doubly_linked_list->print(); + doubly_linked_list->print(); } diff --git a/src/cpp/DynamicQueue.cpp b/src/cpp/DynamicQueue.cpp index b0ad8c58..55da0122 100644 --- a/src/cpp/DynamicQueue.cpp +++ b/src/cpp/DynamicQueue.cpp @@ -9,11 +9,11 @@ struct Node { }; class DynamicQueue { - private: +private: Node *_begin; Node *_end; - public: +public: DynamicQueue() : _begin(nullptr), _end(nullptr) {} ~DynamicQueue() { @@ -83,11 +83,11 @@ int main(void) { queue.enqueue(5); queue.enqueue(1231); queue.enqueue(515); - queue.print(); // 42 5 1231 515 + queue.print(); // 42 5 1231 515 // Use 'delete' keyword to make the code leak-free queue.dequeue(); queue.dequeue(); - queue.print(); // 1231 515 + queue.print(); // 1231 515 return 0; } diff --git a/src/cpp/DynamicStack.cpp b/src/cpp/DynamicStack.cpp index 0be4e546..08e11178 100644 --- a/src/cpp/DynamicStack.cpp +++ b/src/cpp/DynamicStack.cpp @@ -23,9 +23,7 @@ class Stack { head = newNode; } - bool isEmpty() { - return head == nullptr; - } + bool isEmpty() { return head == nullptr; } int pop() { int value = emptyStack; diff --git a/src/cpp/Exponentiation.cpp b/src/cpp/Exponentiation.cpp index b5f07bc4..1e01d9ba 100644 --- a/src/cpp/Exponentiation.cpp +++ b/src/cpp/Exponentiation.cpp @@ -1,20 +1,18 @@ #include - int main() { - long long int n, exp; + long long int n, exp; - std::cin >> n >> exp; + std::cin >> n >> exp; - long long int result = 1; + long long int result = 1; - for (long long int i = 0; i < exp; i++) { - result *= n; - } + for (long long int i = 0; i < exp; i++) { + result *= n; + } - std::cout << result << std::endl; - + std::cout << result << std::endl; - return 0; + return 0; } diff --git a/src/cpp/ExponentiationRecursive.cpp b/src/cpp/ExponentiationRecursive.cpp index 5b2f1c42..a8fd83fb 100644 --- a/src/cpp/ExponentiationRecursive.cpp +++ b/src/cpp/ExponentiationRecursive.cpp @@ -2,22 +2,20 @@ long long int exp(int n, int pow) { - if(pow == 0) - return 1; + if (pow == 0) + return 1; - return n * exp(n, pow-1); + return n * exp(n, pow - 1); } - int main() { - long long int n, pow; + long long int n, pow; - std::cin >> n >> pow; + std::cin >> n >> pow; - n = exp(n, pow); - std::cout << n << std::endl; - + n = exp(n, pow); + std::cout << n << std::endl; - return 0; + return 0; } diff --git a/src/cpp/Factorial.cpp b/src/cpp/Factorial.cpp index e6eaa18c..4c082b3c 100644 --- a/src/cpp/Factorial.cpp +++ b/src/cpp/Factorial.cpp @@ -2,21 +2,21 @@ int factorial(int n) { - int fact = 1; - for (size_t i = 1; i <= n; i++) { - fact = i*fact; - } + int fact = 1; + for (size_t i = 1; i <= n; i++) { + fact = i * fact; + } - return fact; + return fact; } int main() { - int nums[] = {0, 1, 2, 3, 4, 5}; + int nums[] = {0, 1, 2, 3, 4, 5}; - for(auto i : nums) { - std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl; - } + for (auto i : nums) { + std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl; + } - return 0; + return 0; } diff --git a/src/cpp/FactorialRecursive.cpp b/src/cpp/FactorialRecursive.cpp index e222a2e4..2d584c65 100644 --- a/src/cpp/FactorialRecursive.cpp +++ b/src/cpp/FactorialRecursive.cpp @@ -2,21 +2,20 @@ int factorial(int n) { - if(n == 0) - return 1; - - else - return n * (factorial(n-1)); + if (n == 0) + return 1; + else + return n * (factorial(n - 1)); } int main() { - int nums[] = {0, 1, 2, 3, 4, 5}; + int nums[] = {0, 1, 2, 3, 4, 5}; - for(auto i : nums) { - std::cout << std::to_string(i)+"! = " << factorial(i) << std::endl; - } + for (auto i : nums) { + std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl; + } - return 0; + return 0; } diff --git a/src/cpp/FibonacciIterative.cpp b/src/cpp/FibonacciIterative.cpp index 5fbab951..3f5e04f8 100644 --- a/src/cpp/FibonacciIterative.cpp +++ b/src/cpp/FibonacciIterative.cpp @@ -3,16 +3,14 @@ using namespace std; int fibonacci(int n) { - int last = 0; - int curr = 1; - for (int index = 0; index < n; ++index) { - int temp = curr; - curr += last; - last = temp; - } - return last; + int last = 0; + int curr = 1; + for (int index = 0; index < n; ++index) { + int temp = curr; + curr += last; + last = temp; + } + return last; } -int main() { - cout << fibonacci(12) << endl; -} +int main() { cout << fibonacci(12) << endl; } diff --git a/src/cpp/FibonacciMemoization.cpp b/src/cpp/FibonacciMemoization.cpp index 9b8a6e91..0d133f65 100644 --- a/src/cpp/FibonacciMemoization.cpp +++ b/src/cpp/FibonacciMemoization.cpp @@ -6,23 +6,23 @@ using namespace std; vector memo; int fibonacci(int n) { - if (n <= 1) { - return n; - } - if (memo[n] != -1) { - return memo[n]; - } - - memo[n] = fibonacci(n - 1) + fibonacci(n - 2); + if (n <= 1) { + return n; + } + if (memo[n] != -1) { return memo[n]; + } + + memo[n] = fibonacci(n - 1) + fibonacci(n - 2); + return memo[n]; } int main() { - int test_nbr = 12; + int test_nbr = 12; - // Initialize the memoization table with -1 (uncomputed) - memo.assign(test_nbr + 1, -1); + // Initialize the memoization table with -1 (uncomputed) + memo.assign(test_nbr + 1, -1); - cout << "memoization: " << fibonacci(test_nbr) << endl; - return 0; + cout << "memoization: " << fibonacci(test_nbr) << endl; + return 0; } diff --git a/src/cpp/FibonacciRecursive.cpp b/src/cpp/FibonacciRecursive.cpp index b740c642..703ad130 100644 --- a/src/cpp/FibonacciRecursive.cpp +++ b/src/cpp/FibonacciRecursive.cpp @@ -3,12 +3,10 @@ using namespace std; int fibonacci(int n) { - if (n <= 1) { - return n; - } - return fibonacci(n-1) + fibonacci(n-2); + if (n <= 1) { + return n; + } + return fibonacci(n - 1) + fibonacci(n - 2); } -int main() { - cout << fibonacci(12) << endl; -} +int main() { cout << fibonacci(12) << endl; } diff --git a/src/cpp/FindDistinctSubsets.cpp b/src/cpp/FindDistinctSubsets.cpp new file mode 100644 index 00000000..c0af7813 --- /dev/null +++ b/src/cpp/FindDistinctSubsets.cpp @@ -0,0 +1,58 @@ +#include + +using namespace std; + +/* +Problem Statement: +Given an integer array nums of unique elements, return all possible +subsets (the power set). + +The solution set must not contain duplicate subsets. Return the solution in any +order. +*/ + +// Using Bit Manipulation +// 1) Traverse all subsets +// 2) Traverse all elements of nums +// 3) Check if jth bit is set in i +// It is like for 3 elements: +// 000, 001, 010, 011, 100, 101, 110, 111 +// where 1 means that element is present in the subset +// Time: O(n * 2ⁿ) +// Space: O(1) +vector> subsets(vector &nums) { + int n = nums.size(); + int total = 1 << n; // 2ⁿ + vector> ans(total); + + // Traverse all subsets + for (int i = 0; i < total; i++) // 2ⁿ + { + // Traverse elements of nums + for (int j = 0; j < n; j++) // n + { + // Check if jth bit is set in i + if ((1 << j) & i) { + ans[i].push_back(nums[j]); + } + } + } + + return ans; +} + +int main() { + vector nums = {1, 2, 3}; + vector> ans = subsets(nums); + + cout << "Subsets are: \n"; + for (auto v : ans) { + cout << "[ "; + for (auto i : v) { + cout << i << " "; + } + cout << "]\n"; + } + + return 0; +} diff --git a/src/cpp/FloydWarshall.cpp b/src/cpp/FloydWarshall.cpp new file mode 100644 index 00000000..3a6e53d2 --- /dev/null +++ b/src/cpp/FloydWarshall.cpp @@ -0,0 +1,67 @@ +#include + +using namespace std; + +// Function to display the matrix +void showMatrix(const vector> &matrix, int numVertices) { + for (int i = 0; i < numVertices; i++) { + for (int j = 0; j < numVertices; j++) { + if (matrix[i][j] < 10) // For better alignment + cout << " "; + cout << matrix[i][j] << " "; + } + cout << endl; + } + cout << endl; +} + +// Floyd-Warshall algorithm +void floydWarshall(vector> &matrix, int n) { + for (int k = 0; k < n; k++) // Intermediary vertex + { + for (int i = 0; i < n; i++) // Origin vertex + { + for (int j = 0; j < n; j++) // Destination vertex + { + if (matrix[i][k] != LONG_MAX && // i -> k exists + matrix[k][j] != LONG_MAX && // k -> j exists + matrix[i][j] > + matrix[i][k] + matrix[k][j]) // i -> j is shorter via k + { + matrix[i][j] = matrix[i][k] + matrix[k][j]; // Update i -> j + } + } + } + } +} + +int main() { + int numVertices = 5; + + // Initialize matrix with given values + vector> matrix = {{0, 2, 10, 5, 7}, + {2, 0, 3, 3, 1}, + {10, 3, 0, 1, 2}, + {5, 3, 1, 0, LONG_MAX}, + {7, 1, 2, 2, 0}}; + + // Display the original matrix + cout << "Original matrix:" << endl; + showMatrix(matrix, numVertices); + + // Apply Floyd-Warshall algorithm + floydWarshall(matrix, numVertices); + + // Display the updated matrix + cout << "Updated matrix:" << endl; + showMatrix(matrix, numVertices); + + // Show all shortest paths in 3 columns: source, destination, shortest + // distance + cout << "Source\tDestination\tShortest Distance" << endl; + for (int i = 0; i < numVertices; i++) + for (int j = 0; j < numVertices; j++) + cout << i << "\t" << j << "\t\t" << matrix[i][j] << endl; + + return 0; +} diff --git a/src/cpp/GraphSearch.cpp b/src/cpp/GraphSearch.cpp new file mode 100644 index 00000000..aa2aea1c --- /dev/null +++ b/src/cpp/GraphSearch.cpp @@ -0,0 +1,121 @@ +#include +#include +#include + +#define MAX_VERTICES 6 // Maximum number of vertices in the graph + +// Structure that defines each Vertex of the Graph +struct Vertex { + char id; + std::vector neighbors; // List of neighbors + bool visited; + + Vertex(char id) : id(id), visited(false) {} +}; + +// Creates a vertex and returns it +Vertex *createVertex(char id) { return new Vertex(id); } + +// Links two vertices (makes them neighbors) +void linkVertices(Vertex *v1, Vertex *v2) { + v1->neighbors.push_back(v2); // Add v2 as a neighbor of v1 + v2->neighbors.push_back(v1); // Add v1 as a neighbor of v2 +} + +/* + * Depth First Search (DFS) + * Recursively visits neighbors of the starting vertex + */ +int depthFirstSearch(Vertex *start, Vertex *destination, int steps) { + start->visited = true; // Mark the current vertex as visited + if (start == destination) + return steps; // If found, return the distance + + for (Vertex *neighbor : start->neighbors) { // Visit all neighbors + if (!neighbor->visited) { // If neighbor hasn't been visited + int result = depthFirstSearch(neighbor, destination, steps + 1); + if (result != -1) + return result; // If destination found, return result + } + } + return -1; // Destination not found +} + +/* + * Breadth First Search (BFS) + * Uses a queue to traverse level by level + */ +int breadthFirstSearch(Vertex *start, Vertex *destination) { + std::queue q; + q.push(start); // Enqueue starting vertex + start->visited = true; + + int steps = 0; + + while (!q.empty()) { + int qSize = q.size(); // Current queue size (level size) + + // Process all vertices at the current level + for (int i = 0; i < qSize; i++) { + Vertex *current = q.front(); + q.pop(); + + if (current == destination) + return steps; // If destination found, return steps + + // Enqueue all unvisited neighbors + for (Vertex *neighbor : current->neighbors) { + if (!neighbor->visited) { + neighbor->visited = true; + q.push(neighbor); + } + } + } + steps++; // Increment the level + } + return -1; // Destination not found +} + +int main() { + // Create vertices + Vertex *A = createVertex('A'); + Vertex *B = createVertex('B'); + Vertex *C = createVertex('C'); + Vertex *D = createVertex('D'); + Vertex *E = createVertex('E'); + Vertex *F = createVertex('F'); + + // Link vertices as per the graph structure + linkVertices(A, B); + linkVertices(A, C); + linkVertices(B, D); + linkVertices(C, D); + linkVertices(B, E); + linkVertices(D, E); + linkVertices(E, F); + linkVertices(D, F); + + // Perform Depth First Search + int result = depthFirstSearch(A, F, 0); + if (result != -1) + std::cout << "DFS - Found. Distance: " << result << std::endl; + else + std::cout << "DFS - Not Found." << std::endl; + + // Reset visited status for all vertices + A->visited = false; + B->visited = false; + C->visited = false; + D->visited = false; + E->visited = false; + F->visited = false; + + // Perform Breadth First Search + result = breadthFirstSearch(A, F); + if (result != -1) + std::cout << "BFS - Found. Distance: " << result << std::endl; + else + std::cout << "BFS - Not Found." << std::endl; + + return 0; +} diff --git a/src/cpp/InsertionSort.cpp b/src/cpp/InsertionSort.cpp index 566d659c..72a80c1a 100644 --- a/src/cpp/InsertionSort.cpp +++ b/src/cpp/InsertionSort.cpp @@ -5,38 +5,32 @@ using namespace std; void insertionSort(vector &vector) { - for (uint32_t index = 1; index < vector.size(); index++) - { - int key = vector[index]; - int i = index - 1; - - while (i >= 0 && vector[i] > key) - { - vector[i+1] = vector[i]; - i--; - } - - vector[i+1] = key; - } -} + for (uint32_t index = 1; index < vector.size(); index++) { + int key = vector[index]; + int i = index - 1; -void showVector(vector vector) -{ - for (uint32_t i = 0; i < vector.size(); ++i) - { - cout << vector[i] << ", "; + while (i >= 0 && vector[i] > key) { + vector[i + 1] = vector[i]; + i--; } - cout << "\n"; + + vector[i + 1] = key; + } } -int main() -{ - vector vector; - for (uint32_t i = 0; i < 10; ++i) - { - vector.push_back(rand() % 100); - } - showVector(vector); - insertionSort(vector); - showVector(vector); +void showVector(vector vector) { + for (uint32_t i = 0; i < vector.size(); ++i) { + cout << vector[i] << ", "; + } + cout << "\n"; +} + +int main() { + vector vector; + for (uint32_t i = 0; i < 10; ++i) { + vector.push_back(rand() % 100); + } + showVector(vector); + insertionSort(vector); + showVector(vector); } diff --git a/src/cpp/InterpolationSearch.cpp b/src/cpp/InterpolationSearch.cpp new file mode 100644 index 00000000..3026ffe7 --- /dev/null +++ b/src/cpp/InterpolationSearch.cpp @@ -0,0 +1,63 @@ +// Time Complexity: O(log(logn)) + +#include +#include +using namespace std; + +// If x is present in arr[0..n-1], then returns +// index of it, else returns -1. + +long long int interpolation_search(int arr[], int n, int x) { + int low = 0, high = n - 1; + + // Beacuse the array is sorted, element has to be present in range + // made by corner i.e low and high + + while ((low <= high) and (x >= arr[low]) and (x <= arr[high])) { + // Now we will enquire the position keeping in mind the uniform distribution + // in mind + int pos = low + (((double)(high - low) / (arr[high] - arr[low])) * + (x - arr[low])); + + // If x is larger, x is in upper part + if (arr[pos] < x) + low = pos + 1; + + // If x is smaller, x is in lower part + else if (arr[pos] > x) + high = pos - 1; + + // Target found + else + return pos; + } + return -1; +} + +int main() { + int n; + cout << "Please enter the number of elements in array\n"; + cin >> n; + int arr[n]; + + cout << "Please enter " << n << " numbers for arrays\n"; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + // For Interpolation search we need to sort the array + sort(arr, arr + n); + + cout << "Enter the number you want to search\n"; + int x; // Target number + cin >> x; + + int index = interpolation_search(arr, n, x); + + // If element was found + if (index != -1) + cout << "Element found at index " << index << " in sorted array\n"; + else + cout << "Element not found.\n"; + return 0; +} diff --git a/src/cpp/Interpolation_search.cpp b/src/cpp/Interpolation_search.cpp deleted file mode 100644 index ae046db2..00000000 --- a/src/cpp/Interpolation_search.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//Time Complexity: O(log(logn)) - -#include -#include -using namespace std; - -// If x is present in arr[0..n-1], then returns -// index of it, else returns -1. - -long long int interpolation_search(int arr[],int n,int x) -{ - int low=0,high=n-1; - - //Beacuse the array is sorted, element has to be present in range - //made by corner i.e low and high - - while ((low<=high) and (x>=arr[low]) and (x<=arr[high])) - { - // Now we will enquire the position keeping in mind the uniform distribution in mind - int pos=low+(((double)(high-low)/(arr[high]-arr[low]))*(x-arr[low])); - - // If x is larger, x is in upper part - if (arr[pos]x) - high=pos-1; - - // Target found - else - return pos; - } - return -1; -} - -int main() -{ - int n; - cout<<"Please enter the number of elements in array\n"; - cin>>n; - int arr[n]; - - cout<<"Please enter "<>arr[i]; - } - - // For Interpolation search we need to sort the array - sort(arr,arr+n); - - cout<<"Enter the number you want to search\n"; - int x;// Target number - cin>>x; - - int index=interpolation_search(arr, n, x); - - // If element was found - if (index != -1) - cout<<"Element found at index "< - -using namespace std; - -int main() { - - int arr[] = {1, 5, -20, 6, 15}; - - int min = arr[0]; - int max = arr[0]; - - for(auto& i : arr) { - if(i < min) min = i; - else if(i > max) max = i; - } - - cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl; - - return 0; -} diff --git a/src/cpp/LeibnizFormulaForPi.cpp b/src/cpp/LeibnizFormulaForPi.cpp deleted file mode 100644 index bbdb28db..00000000 --- a/src/cpp/LeibnizFormulaForPi.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include -using namespace std; - -float pi = 0.0; -float denominator = 1.0; -float operation = 1.0; - -float pi_calculator(int terms) -{ - for (int i = 0; i < terms; i++) - { - pi += operation * (4.0 / denominator); - denominator += 2.0; - operation *= -1.0; - } - return pi; -} - -int main() -{ - float result = pi_calculator(100000); - cout << result; -} diff --git a/src/cpp/LinearSearch.cpp b/src/cpp/LinearSearch.cpp index 98e1fe9f..a622cd6d 100644 --- a/src/cpp/LinearSearch.cpp +++ b/src/cpp/LinearSearch.cpp @@ -5,32 +5,31 @@ using namespace std; int linear_search(vector &nums, int target) { - for (size_t i = 0; i < nums.size(); i++) { - - if(nums[i] == target) - return i; - } - - return -1; + for (size_t i = 0; i < nums.size(); i++) { + + if (nums[i] == target) + return i; + } + + return -1; } int main() { - vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999}; - int target; - - cout << "Enter the number you would like to search in the vector: "; - cin >> target; - cout << "\n"; + vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999}; + int target; + + cout << "Enter the number you would like to search in the vector: "; + cin >> target; + cout << "\n"; - int pos = linear_search(nums, target); + int pos = linear_search(nums, target); - if(pos > -1) { - cout << "Number found in the vector in the position: " << pos << endl; - } - else { - cout << "Number not found in the vector." << endl; - } + if (pos > -1) { + cout << "Number found in the vector in the position: " << pos << endl; + } else { + cout << "Number not found in the vector." << endl; + } - return 0; + return 0; } \ No newline at end of file diff --git a/src/cpp/LinearSearchRecursive.cpp b/src/cpp/LinearSearchRecursive.cpp index 0d2c9281..6c0cfbce 100644 --- a/src/cpp/LinearSearchRecursive.cpp +++ b/src/cpp/LinearSearchRecursive.cpp @@ -6,7 +6,7 @@ int linearSearchRecursive(int arr[], int n, int index, int target) { if (index >= n) { return -1; } - + if (arr[index] == target) { return index; } diff --git a/src/cpp/MaxRecursive.cpp b/src/cpp/MaxRecursive.cpp new file mode 100644 index 00000000..19bc79f9 --- /dev/null +++ b/src/cpp/MaxRecursive.cpp @@ -0,0 +1,36 @@ +#include +#include + +int max_recursive(std::vector nums, int n) { + + if (n == 1) + return nums[0]; + else { + int aux = max_recursive(nums, n - 1); + + if (aux > nums[n - 1]) + return aux; + + return nums[n - 1]; + } +} + +int main() { + + std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10}; + + std::cout << "nums = {"; + for (auto &i : nums) { + + std::cout << i; + + if (&i != &nums.back()) { + std::cout << ","; + } + } + std::cout << "}" << std::endl; + + std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl; + + return 0; +} diff --git a/src/cpp/MaximumRecursive.cpp b/src/cpp/MaximumRecursive.cpp deleted file mode 100644 index 4a55b915..00000000 --- a/src/cpp/MaximumRecursive.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include -#include - - -int max_recursive(std::vector nums, int n) { - - if(n == 1) - return nums[0]; - else{ - int aux = max_recursive(nums, n-1); - - if(aux > nums[n-1]) - return aux; - - return nums[n-1]; - } -} - -int main() { - - std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10}; - - std::cout << "nums = {"; - for(auto& i : nums) { - - std::cout << i; - - if(&i != &nums.back()) { - std::cout << ","; - } - } - std::cout << "}" << std::endl; - - std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl; - - return 0; -} diff --git a/src/cpp/MergeSort.cpp b/src/cpp/MergeSort.cpp index 17a4c82f..84b0241e 100644 --- a/src/cpp/MergeSort.cpp +++ b/src/cpp/MergeSort.cpp @@ -12,55 +12,52 @@ * @param right The right index of the second sub-array */ -void merge(std::vector& arr, int left, int mid, int right) { - - int n1 = mid - left + 1; // size of the first sub-array. - int n2 = right - mid; // size of the second sub-array. - - // create temporary arrays to hold the data - std::vector leftSubarray(n1); - std::vector rightSubarray(n2); - - // copy data to temporary arrays leftSubarray[] and rightSubarray[] - for (int i = 0; i < n1; i++) { - leftSubarray[i] = arr[left + i]; - } - for (int j = 0; j < n2; j++) { - rightSubarray[j] = arr[mid + 1 + j]; - } - - // merge the two sub-arrays back into the original array arr[] - int i = 0, j = 0, k = left; - - while (i < n1 && j < n2) { - if (leftSubarray[i] <= rightSubarray[j]) { - arr[k] = leftSubarray[i]; - i++; - } - else { - arr[k] = rightSubarray[j]; - j++; - } - k++; - } - - // copy the remaining elements of leftSubarray[], if any - while (i < n1) { - arr[k] = leftSubarray[i]; - i++; - k++; - } - - // copy the remaining elements of rightSubarray[], if any - while (j < n2) { - arr[k] = rightSubarray[j]; - j++; - k++; +void merge(std::vector &arr, int left, int mid, int right) { + + int n1 = mid - left + 1; // size of the first sub-array. + int n2 = right - mid; // size of the second sub-array. + + // create temporary arrays to hold the data + std::vector leftSubarray(n1); + std::vector rightSubarray(n2); + + // copy data to temporary arrays leftSubarray[] and rightSubarray[] + for (int i = 0; i < n1; i++) { + leftSubarray[i] = arr[left + i]; + } + for (int j = 0; j < n2; j++) { + rightSubarray[j] = arr[mid + 1 + j]; + } + + // merge the two sub-arrays back into the original array arr[] + int i = 0, j = 0, k = left; + + while (i < n1 && j < n2) { + if (leftSubarray[i] <= rightSubarray[j]) { + arr[k] = leftSubarray[i]; + i++; + } else { + arr[k] = rightSubarray[j]; + j++; } + k++; + } + + // copy the remaining elements of leftSubarray[], if any + while (i < n1) { + arr[k] = leftSubarray[i]; + i++; + k++; + } + + // copy the remaining elements of rightSubarray[], if any + while (j < n2) { + arr[k] = rightSubarray[j]; + j++; + k++; + } } - - /** * Merge Sort algorithm * @@ -69,39 +66,39 @@ void merge(std::vector& arr, int left, int mid, int right) { * @param right The right index of the sub-array to be sorted */ -void mergeSort(std::vector& arr, int left, int right) { - if (left < right) { +void mergeSort(std::vector &arr, int left, int right) { + if (left < right) { - int mid = left + (right - left) / 2; // calculate the middle index + int mid = left + (right - left) / 2; // calculate the middle index - // sort the first and second halves - mergeSort(arr, left, mid); - mergeSort(arr, mid + 1, right); + // sort the first and second halves + mergeSort(arr, left, mid); + mergeSort(arr, mid + 1, right); - // merge the sorted halves - merge(arr, left, mid, right); - } + // merge the sorted halves + merge(arr, left, mid, right); + } } int main() { - std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11}; + std::vector arr = {12, 11, 13, 5, 6, 7, 9, 4, 10, 9, 11, 1, 11}; - int arrSize = arr.size(); + int arrSize = arr.size(); - std::cout << "Original array: "; - for (int num : arr) { - std::cout << num << " "; - } - std::cout << std::endl; + std::cout << "Original array: "; + for (int num : arr) { + std::cout << num << " "; + } + std::cout << std::endl; - mergeSort(arr, 0, arrSize - 1); + mergeSort(arr, 0, arrSize - 1); - std::cout << "Sorted array: "; - for (int num : arr) { - std::cout << num << " "; - } - std::cout << std::endl; + std::cout << "Sorted array: "; + for (int num : arr) { + std::cout << num << " "; + } + std::cout << std::endl; - return 0; + return 0; } diff --git a/src/cpp/MinMaxDC.cpp b/src/cpp/MinMaxDC.cpp index 2f4d6d3c..cdffb794 100644 --- a/src/cpp/MinMaxDC.cpp +++ b/src/cpp/MinMaxDC.cpp @@ -11,49 +11,50 @@ * @param max Reference to store the maximum element */ -void MinAndMax(const std::vector& arr, int left, int right, int& min, int& max) { - - // if there is only one element in the subarray, it is both the minimum and maximum - if (left == right) { - min = max = arr[left]; - return; +void MinAndMax(const std::vector &arr, int left, int right, int &min, + int &max) { + + // if there is only one element in the subarray, it is both the minimum and + // maximum + if (left == right) { + min = max = arr[left]; + return; + } + + // if there are two elements, compare and set min and max + if (right - left == 1) { + if (arr[left] < arr[right]) { + min = arr[left]; + max = arr[right]; + } else { + min = arr[right]; + max = arr[left]; } + return; + } - // if there are two elements, compare and set min and max - if (right - left == 1) { - if (arr[left] < arr[right]) { - min = arr[left]; - max = arr[right]; - } - else { - min = arr[right]; - max = arr[left]; - } - return; - } - - // calculate the middle index of the sub-array - int mid = (left + right) / 2; - int leftMin, leftMax, rightMin, rightMax; + // calculate the middle index of the sub-array + int mid = (left + right) / 2; + int leftMin, leftMax, rightMin, rightMax; - // recursively find min and max in the left and right sub-arrays - MinAndMax(arr, left, mid, leftMin, leftMax); - MinAndMax(arr, mid + 1, right, rightMin, rightMax); + // recursively find min and max in the left and right sub-arrays + MinAndMax(arr, left, mid, leftMin, leftMax); + MinAndMax(arr, mid + 1, right, rightMin, rightMax); - // update the minimum and maximum values - min = std::min(leftMin, rightMin); - max = std::max(leftMax, rightMax); + // update the minimum and maximum values + min = std::min(leftMin, rightMin); + max = std::max(leftMax, rightMax); } int main() { - std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24}; - int min, max; + std::vector arr = {10, 5, 20, 8, 15, 30, -12, 24}; + int min, max; - MinAndMax(arr, 0, arr.size() - 1, min, max); + MinAndMax(arr, 0, arr.size() - 1, min, max); - std::cout << "Minimum element: " << min << std::endl; - std::cout << "Maximum element: " << max << std::endl; + std::cout << "Minimum element: " << min << std::endl; + std::cout << "Maximum element: " << max << std::endl; - return 0; + return 0; } diff --git a/src/cpp/MinMaxIterative.cpp b/src/cpp/MinMaxIterative.cpp new file mode 100644 index 00000000..ea48d7ca --- /dev/null +++ b/src/cpp/MinMaxIterative.cpp @@ -0,0 +1,22 @@ +#include + +using namespace std; + +int main() { + + int arr[] = {1, 5, -20, 6, 15}; + + int min = arr[0]; + int max = arr[0]; + + for (auto &i : arr) { + if (i < min) + min = i; + else if (i > max) + max = i; + } + + cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl; + + return 0; +} diff --git a/src/cpp/Palindrome.cpp b/src/cpp/Palindrome.cpp index 8b8ac737..c8dd36c6 100644 --- a/src/cpp/Palindrome.cpp +++ b/src/cpp/Palindrome.cpp @@ -1,11 +1,11 @@ /* isPalindrome Algorithm in C++ -Ricardo Ferreira Carvalheira - 2023 -https://github.com/ricardocarva - A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. +A phrase is a palindrome if, after converting all uppercase letters into +lowercase letters and removing all non-alphanumeric characters, it reads the +same forward and backward. Alphanumeric characters include letters and numbers. - Given a string s, return true if it is a palindrome, or false otherwise. +Given a string s, return true if it is a palindrome, or false otherwise. */ #include @@ -14,43 +14,42 @@ Ricardo Ferreira Carvalheira - 2023 using namespace std; bool isPalindrome(string s) { - // Step 1: Convert all characters to lowercase - for (char& c : s) { - c = std::tolower(c); + // Step 1: Convert all characters to lowercase + for (char &c : s) { + c = std::tolower(c); + } + + // Step 2: Remove non-alphanumeric characters + std::string alphanumericStr; + for (char c : s) { + if (std::isalnum(c)) { + alphanumericStr.push_back(c); } + } - // Step 2: Remove non-alphanumeric characters - std::string alphanumericStr; - for (char c : s) { - if (std::isalnum(c)) { - alphanumericStr.push_back(c); - } - } - - // Step 3: Check if the resulting string is a palindrome - int left = 0; - int right = alphanumericStr.length() - 1; + // Step 3: Check if the resulting string is a palindrome + int left = 0; + int right = alphanumericStr.length() - 1; - while (left < right) { - if (alphanumericStr[left] != alphanumericStr[right]) { - return false; - } - left++; - right--; + while (left < right) { + if (alphanumericStr[left] != alphanumericStr[right]) { + return false; } - return true; + left++; + right--; + } + return true; } int main() { - std::string input; - std::cout << "Enter a string: "; - std::getline (std::cin, input); - - if (isPalindrome(input)) { - std::cout << "The string is a palindrome." << std::endl; - } - else { - std::cout << "The string is not a palindrome." << std::endl; - } - return 0; -} \ No newline at end of file + std::string input; + std::cout << "Enter a string: "; + std::getline(std::cin, input); + + if (isPalindrome(input)) { + std::cout << "The string is a palindrome." << std::endl; + } else { + std::cout << "The string is not a palindrome." << std::endl; + } + return 0; +} diff --git a/src/cpp/QuickSort.cpp b/src/cpp/QuickSort.cpp index 75daf1a0..ee9d726b 100644 --- a/src/cpp/QuickSort.cpp +++ b/src/cpp/QuickSort.cpp @@ -3,63 +3,50 @@ using namespace std; -int partition(vector &vector, int start, int end) -{ - int pivot = vector[end]; - int index = start; - - for (int i = start; i < end; i++) - { - if (vector[i] < pivot) - { - int temp = vector[i]; - vector[i] = vector[index]; - vector[index] = temp; - index++; - } +int partition(vector &vector, int start, int end) { + int pivot = vector[end]; + int index = start; + + for (int i = start; i < end; i++) { + if (vector[i] < pivot) { + int temp = vector[i]; + vector[i] = vector[index]; + vector[index] = temp; + index++; } + } - if (pivot <= vector[index]) - { - vector[end] = vector[index]; - vector[index] = pivot; - } + if (pivot <= vector[index]) { + vector[end] = vector[index]; + vector[index] = pivot; + } - return index; + return index; } -void quickSort(vector &vector, int start, int end) -{ - if (start < end) - { - int pivot = partition(vector, start, end); - quickSort(vector, start, pivot-1); - quickSort(vector, pivot+1, end); - } +void quickSort(vector &vector, int start, int end) { + if (start < end) { + int pivot = partition(vector, start, end); + quickSort(vector, start, pivot - 1); + quickSort(vector, pivot + 1, end); + } } -void quickSort(vector &vector) -{ - quickSort(vector, 0, vector.size()-1); -} +void quickSort(vector &vector) { quickSort(vector, 0, vector.size() - 1); } -void showVector(vector vector) -{ - for (uint32_t i = 0; i < vector.size(); ++i) - { - cout << vector[i] << ", "; - } - cout << "\n"; +void showVector(vector vector) { + for (uint32_t i = 0; i < vector.size(); ++i) { + cout << vector[i] << ", "; + } + cout << "\n"; } -int main() -{ - vector vector; - for (uint32_t i = 0; i < 10; ++i) - { - vector.push_back(rand() % 100); - } - showVector(vector); - quickSort(vector); - showVector(vector); +int main() { + vector vector; + for (uint32_t i = 0; i < 10; ++i) { + vector.push_back(rand() % 100); + } + showVector(vector); + quickSort(vector); + showVector(vector); } diff --git a/src/cpp/RottenOranges.cpp b/src/cpp/RottenOranges.cpp new file mode 100644 index 00000000..0ce17c90 --- /dev/null +++ b/src/cpp/RottenOranges.cpp @@ -0,0 +1,92 @@ +#include + +using namespace std; + +/* +Problem Statement: +Given an m x n grid, where each cell has the following values: +2 – Rotten orange +1 – Fresh orange +0 – Empty cell + +Every minute, if a Fresh orange is adjacent to a Rotten Orange in 4-direction +(upward, downwards, right, and left) it becomes Rotten. + +Return the minimum number of minutes required such that +none of the cells has a Fresh Orange. +If it's not possible, return -1. +*/ + +// Approach: BFS + +bool isValid(int nx, int ny, int m, int n) { + return (0 <= nx && nx < m) && (0 <= ny && ny < n); +} + +// Time: O(mn) x 4 +// Space: O(mn) +int orangesRotting(vector> &grid) { + int m = grid.size(); + int n = grid[0].size(); + + int total = 0; // fresh + rotten oranges + int count = 0; // rotten oranges + int mins = 0; // minutes elapsed + + queue> rotten; // {i, j}: position of rotten orange + + // Count the fresh & rotten oranges, push rotten oranges into queue + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] != 0) // Rotten or Fresh orange + total++; + if (grid[i][j] == 2) // Rotten + rotten.push({i, j}); // Push position of rotten orange + } + } + + int dx[] = {0, 0, -1, 1}; // 4-directions (x-axis) + int dy[] = {-1, 1, 0, 0}; // 4-directions (y-axis) + + while (!rotten.empty()) { + int size = rotten.size(); // rotten oranges in current minute + count += size; // add to total rotten oranges + + while (size--) // Each rotten orange in current minute + { + // Pop the front rotten orange + int x = rotten.front().first; + int y = rotten.front().second; + rotten.pop(); + + // Check for fresh oranges in 4-directions + for (int i = 0; i < 4; i++) { + // New coordinates + int nx = x + dx[i]; + int ny = y + dy[i]; + + // Valid, fresh orange + if (isValid(nx, ny, m, n) && grid[nx][ny] == 1) { + grid[nx][ny] = 2; // make it rotten + rotten.push({nx, ny}); // push it into queue + } + } + } + + if (!rotten.empty()) // if there are more rotten oranges + mins++; + } + + if (total != count) // fresh oranges left + return -1; + + return mins; +} + +int main() { + vector> grid = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}; + + cout << orangesRotting(grid) << endl; // 4 + + return 0; +} diff --git a/src/cpp/SelectionSort.cpp b/src/cpp/SelectionSort.cpp index a84b33f4..abffa69c 100644 --- a/src/cpp/SelectionSort.cpp +++ b/src/cpp/SelectionSort.cpp @@ -3,46 +3,38 @@ using namespace std; -void selectionSort(vector &vector) -{ - for (uint32_t index = 0; index < vector.size()-1; index++) - { - uint32_t min = index; - - for (uint32_t tempIndex = index+1; tempIndex < vector.size(); ++tempIndex) - { - if( vector[tempIndex] < vector[min] ) - { - min = tempIndex; - } - } - - if( min != index ) - { - int temp = vector[index]; - vector[index] = vector[min]; - vector[min] = temp; - } +void selectionSort(vector &vector) { + for (uint32_t index = 0; index < vector.size() - 1; index++) { + uint32_t min = index; + + for (uint32_t tempIndex = index + 1; tempIndex < vector.size(); + ++tempIndex) { + if (vector[tempIndex] < vector[min]) { + min = tempIndex; + } } -} -void showVector(vector vector) -{ - for (uint32_t i = 0; i < vector.size(); ++i) - { - cout << vector[i] << ", "; + if (min != index) { + int temp = vector[index]; + vector[index] = vector[min]; + vector[min] = temp; } - cout << "\n"; + } } -int main() -{ - vector vector; - for (uint32_t i = 0; i < 10; ++i) - { - vector.push_back(rand() % 100); - } - showVector(vector); - selectionSort(vector); - showVector(vector); +void showVector(vector vector) { + for (uint32_t i = 0; i < vector.size(); ++i) { + cout << vector[i] << ", "; + } + cout << "\n"; +} + +int main() { + vector vector; + for (uint32_t i = 0; i < 10; ++i) { + vector.push_back(rand() % 100); + } + showVector(vector); + selectionSort(vector); + showVector(vector); } \ No newline at end of file diff --git a/src/cpp/SinglyLinkedList.cpp b/src/cpp/SinglyLinkedList.cpp index 3b35c20f..ac5fbc0b 100644 --- a/src/cpp/SinglyLinkedList.cpp +++ b/src/cpp/SinglyLinkedList.cpp @@ -2,172 +2,173 @@ using namespace std; -struct Node{ +struct Node { - int val; - Node* next; + int val; + Node *next; - Node(int val) : val(val), next(nullptr) {} - Node(int val, Node *next) : val(val), next(next) {} + Node(int val) : val(val), next(nullptr) {} + Node(int val, Node *next) : val(val), next(next) {} }; void print_list(Node *head) { - auto aux = head; + auto aux = head; - cout << '['; - while(aux) { + cout << '['; + while (aux) { - cout << aux->val; + cout << aux->val; - if(aux->next) { - cout << ", "; - } - - aux = aux->next; + if (aux->next) { + cout << ", "; } - cout << ']' << endl; + + aux = aux->next; + } + cout << ']' << endl; } void push_back(Node **head, int val) { + Node *newNode = new Node(val); - Node *newNode = new Node(val); - - if(*head == nullptr) { - *head = newNode; - } - - else { + if (*head == nullptr) { + *head = newNode; + } - auto aux = *head; + else { - while(aux->next) { - aux = aux->next; - } + auto aux = *head; - aux->next = newNode; + while (aux->next) { + aux = aux->next; } + + aux->next = newNode; + } } void push_front(Node **head, int val) { - Node *newNode = new Node(val, *head); + Node *newNode = new Node(val, *head); - *head = newNode; + *head = newNode; } void insert_in_position(Node **head, int val, int pos) { - if(pos == 0) { - push_front(head, val); - return; - } + if (pos == 0) { + push_front(head, val); + return; + } - Node* newNode = new Node(val); + Node *newNode = new Node(val); - auto prev = *head; - auto curr = *head; + auto prev = *head; + auto curr = *head; - while(curr->next && pos) { - prev = curr; - curr = curr->next; - pos--; - } + while (curr->next && pos) { + prev = curr; + curr = curr->next; + pos--; + } - prev->next = newNode; - newNode->next = curr; + prev->next = newNode; + newNode->next = curr; } void pop_back(Node **head) { - if(*head == nullptr) { - return; - } + if (*head == nullptr) { + return; + } - auto prev = *head; - auto curr = prev->next; + auto prev = *head; + auto curr = prev->next; - while(curr->next) { - prev = prev->next; - curr = curr->next; - } + while (curr->next) { + prev = prev->next; + curr = curr->next; + } - prev->next = nullptr; + prev->next = nullptr; - delete(curr); + delete (curr); } void pop_front(Node **head) { - if(*head == nullptr) { - return; - } + if (*head == nullptr) { + return; + } - auto aux = *head; + auto aux = *head; - *head = aux->next; + *head = aux->next; - delete(aux); + delete (aux); } void remove_from_position(Node **head, int pos) { - if(*head == nullptr) { - return; - } + if (*head == nullptr) { + return; + } - if(pos == 0) { - pop_front(head); - return; - } + if (pos == 0) { + pop_front(head); + return; + } - auto prev = *head; - auto curr = *head; + auto prev = *head; + auto curr = *head; - while(curr->next && pos) { - prev = curr; - curr = curr->next; - pos--; - } + while (curr->next && pos) { + prev = curr; + curr = curr->next; + pos--; + } - if(pos == 0) { - prev->next = curr->next; - delete(curr); - } + if (pos == 0) { + prev->next = curr->next; + delete (curr); + } } int main() { - Node *head = nullptr; - - cout << "Inserting the elements at the end [1, 2, 3]:" << endl; - push_back(&head, 1); - push_back(&head, 2); - push_back(&head, 3); - print_list(head); - - cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl; - push_front(&head, 0); - push_front(&head, -1); - push_front(&head, -2); - print_list(head); - - cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] respectively:" << endl; - insert_in_position(&head, 997, 3); - insert_in_position(&head, 998, 4); - insert_in_position(&head, 999, 5); - print_list(head); - - cout << "Removing last element:" << endl; - pop_back(&head); - print_list(head); - - cout << "Removing first element:" << endl; - pop_front(&head); - print_list(head); - - cout << "Removing element in position 2:" << endl; - remove_from_position(&head, 2); - print_list(head); + Node *head = nullptr; + + cout << "Inserting the elements at the end [1, 2, 3]:" << endl; + push_back(&head, 1); + push_back(&head, 2); + push_back(&head, 3); + print_list(head); + + cout << "Inserting the elements at the beginning [0, -1, -2]:" << endl; + push_front(&head, 0); + push_front(&head, -1); + push_front(&head, -2); + print_list(head); + + cout << "Inserting in positions 3, 4, 5 the elements [997, 998, 999] " + "respectively:" + << endl; + insert_in_position(&head, 997, 3); + insert_in_position(&head, 998, 4); + insert_in_position(&head, 999, 5); + print_list(head); + + cout << "Removing last element:" << endl; + pop_back(&head); + print_list(head); + + cout << "Removing first element:" << endl; + pop_front(&head); + print_list(head); + + cout << "Removing element in position 2:" << endl; + remove_from_position(&head, 2); + print_list(head); } diff --git a/src/cpp/Stack.cpp b/src/cpp/Stack.cpp index c123b497..a22ed118 100644 --- a/src/cpp/Stack.cpp +++ b/src/cpp/Stack.cpp @@ -6,64 +6,64 @@ // Stack: Last In - First Out (LIFO) class Stack { - private: - int array[MAX]; - int index = 0; - - public: - Stack(){} +private: + int array[MAX]; + int index = 0; - void push(int element) { - if (this->index >= MAX) { - throw std::logic_error("Stack is full!"); - } - this->array[index] = element; - index++; +public: + Stack() {} + + void push(int element) { + if (this->index >= MAX) { + throw std::logic_error("Stack is full!"); } + this->array[index] = element; + index++; + } - bool isEmpty() { - if (!this->index) { - return true; - } - return false; + bool isEmpty() { + if (!this->index) { + return true; } + return false; + } - int pop() { - if (this->isEmpty()) { - throw std::logic_error("Stack is empty!"); - } - index--; - int value = this->array[this->index]; - this->array[this->index] = 0; - return value; + int pop() { + if (this->isEmpty()) { + throw std::logic_error("Stack is empty!"); } + index--; + int value = this->array[this->index]; + this->array[this->index] = 0; + return value; + } - void print() { - std::cout << "[ "; - for (int i = 0; i < this->index; i++) { - std::cout << this->array[i] << " "; - } - std::cout << "]" << std::endl; + void print() { + std::cout << "[ "; + for (int i = 0; i < this->index; i++) { + std::cout << this->array[i] << " "; } + std::cout << "]" << std::endl; + } }; int main() { - // Create a pointier to a new Stack instance - Stack* stack = new Stack(); + // Create a pointier to a new Stack instance + Stack *stack = new Stack(); - std::cout << "Push(1, 2, 4)" << std::endl; - stack->push(1); - stack->push(2); - stack->push(4); - stack->print(); + std::cout << "Push(1, 2, 4)" << std::endl; + stack->push(1); + stack->push(2); + stack->push(4); + stack->print(); - std::cout << "Pop()" << std::endl; - stack->pop(); - stack->print(); + std::cout << "Pop()" << std::endl; + stack->pop(); + stack->print(); - stack->pop(); - stack->pop(); + stack->pop(); + stack->pop(); - std::cout << "Empty Stack" << std::endl; - stack->print(); + std::cout << "Empty Stack" << std::endl; + stack->print(); } diff --git a/src/cpp/TowerOfHanoi.cpp b/src/cpp/TowerOfHanoi.cpp index 8cfa3f57..d44e0bd0 100644 --- a/src/cpp/TowerOfHanoi.cpp +++ b/src/cpp/TowerOfHanoi.cpp @@ -1,70 +1,68 @@ /* Recursive Towers of Hanoi Solution - Thomas Martin - 2023 - https://github.com/thomas-martin-uf Problem Description: (from wikipedia) - The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters, - which can slide onto any rod. + The Tower of Hanoi is a mathematical game or puzzle consisting of three rods + and a number of disks of various diameters, which can slide onto any rod. - The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, - thus approximating a conical shape. + The puzzle begins with the disks stacked on one rod in order of decreasing + size, the smallest at the top, thus approximating a conical shape. - The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules: + The objective of the puzzle is to move the entire stack to the last rod, + obeying the following rules: Only one disk may be moved at a time. - Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod. + Each move consists of taking the upper disk from one of the stacks and + placing it on top of another stack or on an empty rod. No disk may be placed on top of a disk that is smaller than it. With 3 disks, the puzzle can be solved in 7 moves. - The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks. + The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n + − 1, where n is the number of disks. */ #include using std::cout; -size_t solve_tower(int n, char first, char second, char third) -{ +size_t solve_tower(int n, char first, char second, char third) { - // recursive base case - if (n == 1) - { - cout << "Move disk 1 from " << first << " to " << third << "\n"; - return 1; - } + // recursive base case + if (n == 1) { + cout << "Move disk 1 from " << first << " to " << third << "\n"; + return 1; + } - // move n-1 disks from first to other using second as a placeholder - size_t num_moves = solve_tower(n - 1, first, third, second); + // move n-1 disks from first to other using second as a placeholder + size_t num_moves = solve_tower(n - 1, first, third, second); - // move the nth disk from first to second - cout << "Move disk " << n << " from " << first << " to " << third << "\n"; + // move the nth disk from first to second + cout << "Move disk " << n << " from " << first << " to " << third << "\n"; - // move the n-1 disks from third to second using first as an placeholder - num_moves += solve_tower(n - 1, second, first, third); + // move the n-1 disks from third to second using first as an placeholder + num_moves += solve_tower(n - 1, second, first, third); - // return the total moves plus 1 - return num_moves + 1; + // return the total moves plus 1 + return num_moves + 1; } -int main() -{ +int main() { - // names of rods - char a = 'A'; - char b = 'B'; - char c = 'C'; + // names of rods + char a = 'A'; + char b = 'B'; + char c = 'C'; - // number of disks to move in puzzle - size_t num_disk = 3; + // number of disks to move in puzzle + size_t num_disk = 3; - // find the total number of moves needed to solve - size_t num_moves = solve_tower(num_disk, a, b, c); + // find the total number of moves needed to solve + size_t num_moves = solve_tower(num_disk, a, b, c); - // output result - cout << "Total moves needed to solve: " << num_moves; - return 0; -} \ No newline at end of file + // output result + cout << "Total moves needed to solve: " << num_moves; + return 0; +} diff --git a/src/go/busca_binaria.go b/src/go/binary_search.go similarity index 100% rename from src/go/busca_binaria.go rename to src/go/binary_search.go diff --git a/src/go/bubble_sort.go b/src/go/bubble_sort.go index 62374a95..f63bb007 100644 --- a/src/go/bubble_sort.go +++ b/src/go/bubble_sort.go @@ -2,34 +2,34 @@ package main import "fmt" -// Iterativo -func BubbleSortIterativo(slice []int) { - for indice1 := len(slice) - 1; indice1 > 0; indice1-- { - for indice2 := 0; indice2 < indice1; indice2++ { - if slice[indice2] > slice[indice2+1] { - slice[indice2], slice[indice2+1] = slice[indice2+1], slice[indice2] +// Iterative +func BubbleSortIterative(slice []int) { + for index1 := len(slice) - 1; index1 > 0; index1-- { + for index2 := 0; index2 < index1; index2++ { + if slice[index2] > slice[index2+1] { + slice[index2], slice[index2+1] = slice[index2+1], slice[index2] } } } } -// Recursivo -func BubbleSortRecursivo(slice []int, tamanho int) { - trocas := 0 - for indice := 0; indice < tamanho-1; indice++ { - if slice[indice] > slice[indice+1] { - slice[indice], slice[indice+1] = slice[indice+1], slice[indice] - trocas++ +// Recursive +func BubbleSortRecursive(slice []int, size int) { + swaps := 0 + for index := 0; index < size-1; index++ { + if slice[index] > slice[index+1] { + slice[index], slice[index+1] = slice[index+1], slice[index] + swaps++ } } - if trocas != 0 { - BubbleSortRecursivo(slice, tamanho-1) + if swaps != 0 { + BubbleSortRecursive(slice, size-1) } } func main() { slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4} fmt.Println("Slice:", slice) - BubbleSortIterativo(slice) + BubbleSortIterative(slice) fmt.Println("BubbleSort:", slice) } diff --git a/src/go/caixeiro_viajante.go b/src/go/caixeiro_viajante.go deleted file mode 100644 index 184e8a16..00000000 --- a/src/go/caixeiro_viajante.go +++ /dev/null @@ -1,153 +0,0 @@ -/* - * O Problema do Caixeiro Viajante (PCV) eh um problema que tenta determinar a - * menor rota para percorrer uma serie de cidades (visitando uma unica vez cada - * uma delas), retornando a cidade de origem. - * - * Utilizando uma matriz de distancia para representar um grafo nao direcionado. - * - * Supondo que temos o seguinte grafo: - * - * 6 - * ------------------- - * | 3 1 | - * (000)-----(001)-----(002) - * | \ / | \ / | - * | \ 6/ | \2 / | - * | \ / | \ / | - * 2| / 8| / |5 - * | / \ | / \ | - * | / 3\ | /4 \ | - * | / \ | / \ | - * (003)-----(004)-----(005) - * | 6 4 | - * ------------------- - * 1 - * - * Matriz de Distancia - * 0 1 2 3 4 5 - * 0 0 3 6 2 3 - - * 1 3 0 1 6 8 2 - * 2 6 1 0 - 4 5 - * 3 2 6 - 0 6 1 - * 4 3 8 4 6 0 4 - * 5 - 2 5 1 4 0 - * - * Melhor solucao: - * 0 - 3 - 5 - 1 - 2 - 4 - 0: 13 - */ - -package main - -import "fmt" - -const vertices = 6 -const infinito = 99999999 - -var matrizDistancia [][]int - -var tempSolucao []int // Solucao temporaria -var melhorSolucao []int // Melhor solucao -var visitados []bool // Vertices visitados - -var valorMelhorSolucao int -var valorSolucaoAtual int - -func CaixeiroViajanteAux(x int) { - - // Significa que ja nao eh mais a melhor solucao podemos parar por aqui - if valorSolucaoAtual > valorMelhorSolucao { - return - } - - // Significa que o vetor da solucao temporaria esta completo - if x == vertices { - distancia := matrizDistancia[tempSolucao[x-1]][tempSolucao[0]] - - // Significa que encontrou uma solucao melhor - if distancia < infinito && (valorSolucaoAtual+distancia) < valorMelhorSolucao { - - // Temos uma solucao melhor - valorMelhorSolucao = valorSolucaoAtual + distancia - - // Copia todo o vetor para a melhor solucao - for i := 0; i < vertices; i++ { - melhorSolucao[i] = tempSolucao[i] - } - } - return - } - - // Ultimo vertice que se encontra na solucao temporaria - ultimo := tempSolucao[x-1] - - // Percorre todas as colunas da matriz de distancia na linha do ultimo vertice - for i := 0; i < vertices; i++ { - - // Se a posicao ainda nao foi visitada e o valor da matriz eh menor que infinito - if !visitados[i] && matrizDistancia[ultimo][i] < infinito { - // Marque a posicao como visitada - visitados[i] = true - // Carrega o vertice atual na solucao temporaria - tempSolucao[x] = i - // Incrementa o total do caminho percorrido com base na posicao da matriz - valorSolucaoAtual += matrizDistancia[ultimo][i] - // Chama recursivamente para o proximo vertice - CaixeiroViajanteAux(x + 1) - // Se ainda nao terminou decrementa o valor da variabel que guarta o total do caminho - valorSolucaoAtual -= matrizDistancia[ultimo][i] - // Define como nao visitada para poder ser acessada por outro vertice - visitados[i] = false - } - } -} - -func CaixeiroViajante(posicaoInicial int) { - // Verifica se a posicao eh valida - if posicaoInicial < vertices { - visitados[posicaoInicial] = true // Marca o primeiro vertice como visitado - tempSolucao[0] = posicaoInicial // Coloca a posicao inicial na primeira posicao da solucao temporaria - CaixeiroViajanteAux(1) // Chama o metodo auxiliar do caixeiro viajante - } else { - fmt.Println("Vertice inicial invalid") - } -} - -// Inicia os vetores e valores padrao -func inicia() { - - valorMelhorSolucao = infinito - valorSolucaoAtual = 0 - - for i := 0; i < vertices; i++ { - visitados = append(visitados, false) - tempSolucao = append(tempSolucao, -1) - melhorSolucao = append(melhorSolucao, -1) - } - - // Cria a matriz de distancia - linha0 := []int{0, 3, 6, 2, 3, infinito} - linha1 := []int{3, 0, 1, 6, 8, 2} - linha2 := []int{6, 1, 0, infinito, 4, 5} - linha3 := []int{2, 6, infinito, 0, 6, 1} - linha4 := []int{3, 8, 4, 6, 0, 4} - linha5 := []int{infinito, 2, 5, 1, 4, 0} - - matrizDistancia = append(matrizDistancia, linha0) - matrizDistancia = append(matrizDistancia, linha1) - matrizDistancia = append(matrizDistancia, linha2) - matrizDistancia = append(matrizDistancia, linha3) - matrizDistancia = append(matrizDistancia, linha4) - matrizDistancia = append(matrizDistancia, linha5) -} - -func main() { - inicia() - CaixeiroViajante(0) - - fmt.Println("Caixeiro Viajante") - fmt.Println("Caminho minimo:", valorMelhorSolucao) - for i := 0; i < vertices; i++ { - fmt.Print(melhorSolucao[i], ", ") - } - fmt.Println(melhorSolucao[0]) -} diff --git a/src/go/cocktail_sort.go b/src/go/cocktail_sort.go index b9ce9ad3..a9f4a920 100644 --- a/src/go/cocktail_sort.go +++ b/src/go/cocktail_sort.go @@ -5,12 +5,12 @@ import "fmt" func CocktailSort(slice []int) { swapped := true - begining := 0 + beginning := 0 ending := len(slice) - 1 - for begining < ending && swapped { + for beginning < ending && swapped { - for index := begining; index < ending; index++ { + for index := beginning; index < ending; index++ { if slice[index] > slice[index+1] { slice[index], slice[index+1] = slice[index+1], slice[index] swapped = true @@ -21,7 +21,7 @@ func CocktailSort(slice []int) { if swapped { swapped = false - for index := ending; index > begining; index-- { + for index := ending; index > beginning; index-- { if slice[index] < slice[index-1] { slice[index], slice[index-1] = slice[index-1], slice[index] swapped = true @@ -29,7 +29,7 @@ func CocktailSort(slice []int) { } } - begining++ + beginning++ } } diff --git a/src/go/dijkstra.go b/src/go/dijkstra.go index d8626d4b..8139253d 100644 --- a/src/go/dijkstra.go +++ b/src/go/dijkstra.go @@ -1,13 +1,12 @@ /* -* Grafos - Algoritmo de Dijkstra em Go -* Danilo Moura - 2020 -* Complexidade: Teta(n^2) -* Implementação utilizando matriz de adjacências (matriz de distância) +* Graphs - Dijkstra's Algorithm in Go +* Complexity: Theta(n^2) +* Implementation using adjacency matrix (distance matrix) * -* 1 para todos - Arestas de pesos não negativo - Algoritmo guloso -* Encontra o caminho mais curto de um vértice (inicio) a outro (destino) +* One to all - Non-negative weighted edges - Greedy algorithm +* Finds the shortest path from one vertex (start) to another (destination) * -* Grafo com 5 vértices e 6 arestas +* Graph with 5 vertices and 6 edges * * 6 * (0)-----------------(1) @@ -20,7 +19,7 @@ * \ / * -----(4)----- * -* Matriz de Distância +* Distance Matrix * 0 1 2 3 4 * 0 0 6 10 - - * 1 6 0 - 2 - @@ -28,10 +27,10 @@ * 3 - 2 1 0 8 * 4 - - 3 8 0 * -* O objetivo é sair do ponto inicial (0) e chegar ao destino (4) pelo caminho mais curto -* Resposta: (0)->(1)->(3)->(2)->(4) = 12 +* The goal is to start from the initial point (0) and reach the destination (4) by the shortest path +* Answer: (0)->(1)->(3)->(2)->(4) = 12 * -* link Go PlayGround: https://play.golang.org/p/HyWAcYJ3qXY +* Go PlayGround link: https://play.golang.org/p/HyWAcYJ3qXY */ package main @@ -40,43 +39,43 @@ import "fmt" var nroVertices = 5 -type Matriz [][]int +type Matrix [][]int var maxInt = 4294967295 -// Algoritmo de Dijkstra recebe como parâmetro a matriz de distância e o número de vértices -func Dijkstra(matriz Matriz, n int) { - visitados := make([]bool, n) // Variável que guarda true para os vértices visitados - // O valor 'i' do for abaixo não é utilizado, pois o for serve apenas para percorrer todo o número de colunas da matriz - for i := 1; i < n; i++ { // Começa em 1 pois não precisa comparar o vértice com ele mesmo +// Dijkstra's Algorithm takes the distance matrix and the number of vertices as parameters +func Dijkstra(matrix Matrix, n int) { + visited := make([]bool, n) // Variable that stores true for visited vertices + // The 'i' value in the for loop below is not used, as the loop is only used to iterate over the number of columns in the matrix + for i := 1; i < n; i++ { // Starts at 1 because there is no need to compare the vertex with itself - min := -1 // Variável que guarda a posição do menor valor, inicia em -1 pois é uma posição inválida - minValor := maxInt // Variável que guarda o menor valor encontrado, inicia com 'infinito', assim, sempre na primeira passada o valor será menor que esta variável + min := -1 // Variable that stores the position of the smallest value, starts at -1 because it is an invalid position + minValue := maxInt // Variable that stores the smallest value found, starts with 'infinity', so in the first pass the value will be smaller than this variable - // For que percorre todas as linhas na coluna [0] + // For loop that iterates over all rows in column [0] for j := 1; j < n; j++ { - // Se o vertice ainda não foi visitado e o valor for menor que o 'MinValor' - if !visitados[j] && matriz[j][0] < minValor { - min = j // Guarda a posição do menor - minValor = matriz[j][0] // Guarda o menor valor + // If the vertex has not been visited yet and the value is smaller than 'minValue' + if !visited[j] && matrix[j][0] < minValue { + min = j // Stores the position of the smallest value + minValue = matrix[j][0] // Stores the smallest value } } - visitados[min] = true // Marca o valor a posição do minimo como visitado + visited[min] = true // Marks the position of the minimum as visited - // For de 1 até n + // For loop from 1 to n for j := 1; j < n; j++ { - // Se o valor da coluna [0] + o valor da coluna que está passando for menor que o valor da linha que está passando e coluna [0] - // Atualiza a primeira coluna da matriz, que será utilizado para as próximas iterações - if (matriz[min][0] + matriz[min][j]) < matriz[j][0] { - matriz[j][0] = matriz[min][0] + matriz[min][j] + // If the value of column [0] + the value of the current column is smaller than the value of the current row and column [0] + // Updates the first column of the matrix, which will be used for the next iterations + if (matrix[min][0] + matrix[min][j]) < matrix[j][0] { + matrix[j][0] = matrix[min][0] + matrix[min][j] } } } } func main() { - matriz := Matriz{ + matrix := Matrix{ {0, 6, 10, maxInt, maxInt}, {6, 0, maxInt, 2, maxInt}, {10, maxInt, 0, 1, 3}, @@ -84,12 +83,12 @@ func main() { {maxInt, maxInt, 3, 8, 0}, } - Dijkstra(matriz, nroVertices) + Dijkstra(matrix, nroVertices) - fmt.Printf("Total caminho mais curto do vertice 0 ao 4: %v\n\n", matriz[4][0]) // Caminho total mais curto + fmt.Printf("Total shortest path from vertex 0 to 4: %v\n\n", matrix[4][0]) // Total shortest path - // Da print na matriz com os valores atualizados - fmt.Println("Matriz:") + // Prints the matrix with the updated values + fmt.Println("Matrix:") fmt.Printf("- | |v0 |v1 |v2 |v3 |v4\n") fmt.Println("_____________________________________________") @@ -101,10 +100,10 @@ func main() { fmt.Printf("v%v |", i) } - if matriz[i][j] == maxInt { + if matrix[i][j] == maxInt { fmt.Printf(" |inf") } else { - fmt.Printf(" |%v", matriz[i][j]) + fmt.Printf(" |%v", matrix[i][j]) } } fmt.Println() diff --git a/src/go/exponenciacao.go b/src/go/exponenciacao.go deleted file mode 100644 index f9d45448..00000000 --- a/src/go/exponenciacao.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import "fmt" - -func Exponenciacao(base int, expoente int) int { - for index := 0; index < (expoente - 1); index++ { - base *= expoente - } - return base -} - -func main() { - fmt.Println("Exponenciacao:", Exponenciacao(5, 5)) -} diff --git a/src/go/exponentiation.go b/src/go/exponentiation.go new file mode 100644 index 00000000..774b891c --- /dev/null +++ b/src/go/exponentiation.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func Exponentiation(base int, exponent int) int { + for index := 0; index < (exponent - 1); index++ { + base *= exponent + } + return base +} + +func main() { + fmt.Println("Exponentiation:", Exponentiation(5, 5)) +} diff --git a/src/go/factorial.go b/src/go/factorial.go new file mode 100644 index 00000000..6dbf1dd5 --- /dev/null +++ b/src/go/factorial.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func Factorial(value int) int { + if value == 1 { + return 1 + } + return value * Factorial(value-1) +} + +func main() { + fmt.Println("Factorial:", Factorial(6)) +} diff --git a/src/go/fatorial.go b/src/go/fatorial.go deleted file mode 100644 index 8c9658bf..00000000 --- a/src/go/fatorial.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import "fmt" - -func Fatorial(value int) int { - if value == 1 { - return 1 - } - return value * Fatorial(value-1) -} - -func main() { - fmt.Println("Fatorial:", Fatorial(6)) -} diff --git a/src/go/floyd_warshall.go b/src/go/floyd_warshall.go index 674f36c3..c4c91ffc 100644 --- a/src/go/floyd_warshall.go +++ b/src/go/floyd_warshall.go @@ -2,27 +2,25 @@ package main import "fmt" -// Grafos - Algoritmo de Floyd-Warshall em GO -// Douglas Oliveira - 2022 -// https://github.com/xDouglas90 -// link Go PlayGround: https://go.dev/play/p/tIRTHkNf7Fz +// Graphs - Floyd-Warshall Algorithm in GO +// Go PlayGround link: https://go.dev/play/p/tIRTHkNf7Fz -// Algoritmo de Floyd-Warshall +// Floyd-Warshall Algorithm func FloydWarshall(graph [][]int) [][]int { - // Inicializa a matriz de distancias + // Initialize the distance matrix dist := make([][]int, len(graph)) for i := range dist { dist[i] = make([]int, len(graph)) copy(dist[i], graph[i]) } - // Percorre os vértices + // Traverse the vertices for k := 0; k < len(graph); k++ { - // Percorre as linhas + // Traverse the rows for i := 0; i < len(graph); i++ { - // Percorre as colunas + // Traverse the columns for j := 0; j < len(graph); j++ { - // Verifica se o caminho passando pelo vértice k é menor + // Check if the path passing through vertex k is shorter if dist[i][k]+dist[k][j] < dist[i][j] { dist[i][j] = dist[i][k] + dist[k][j] } diff --git a/src/go/buscasequencial.go b/src/go/linear_search.go similarity index 100% rename from src/go/buscasequencial.go rename to src/go/linear_search.go diff --git a/src/go/lista_sequencial_nao_ordenada.go b/src/go/lista_sequencial_nao_ordenada.go deleted file mode 100644 index 69208a29..00000000 --- a/src/go/lista_sequencial_nao_ordenada.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -* Listas - Lista linear não ordenada -* Danilo Moura - 2020 -* -* Implementação da lista sequencial cujos elementos não estão ordenados -* -* link Go PlayGround: https://play.golang.org/p/3uFOquVlTD8 - */ - -package main - -import "fmt" - -var maxSize = 50 - -// Estrura que será guardada em cada posição da lista -type Registro struct { - valor int - // Outros campos podem ser adicionados aqui -} - -// Estrutura que guarda um arranjo de Registro, e o número de elementos no arranjo -type Lista struct { - arranjoRegistros []Registro - numeroElementos int -} - -// Cria uma nova lista -func criarLista() Lista { - lista := Lista{ - arranjoRegistros: make([]Registro, maxSize), - numeroElementos: 0, - } - - return lista -} - -// reseta o contador de elementos da lista -func inicializar(lista *Lista) { - lista.numeroElementos = 0 -} - -// Recupera a quantidade de elementos da lista -func tamanho(lista *Lista) int { - return lista.numeroElementos -} - -// Imprime valores dos elementos na lista -func imprimir(lista *Lista) { - for i := 0; i < lista.numeroElementos; i++ { - fmt.Printf("%v ", lista.arranjoRegistros[i].valor) - } - fmt.Println() -} - -// Realiza busca sequencial na lista, percorrendo item por item -func buscaSequencial(lista *Lista, valor int) int { - i := 0 - for i < lista.numeroElementos { - if valor == lista.arranjoRegistros[i].valor { - return i - } - i++ - } - return -1 -} - -// Realiza busca sentinela na lista, percorrendo item por item -func buscaSentinela(lista *Lista, valor int) int { - i := 0 - lista.arranjoRegistros[lista.numeroElementos].valor = valor - - for valor != lista.arranjoRegistros[i].valor { - i++ - } - - if i == lista.numeroElementos { - return -1 - } - return i -} - -// Insere elementos na lista, em uma posição específica, e move todos os outros elementos para a direita -func insereElemento(lista *Lista, registro Registro, posicao int) bool { - if (lista.numeroElementos == maxSize) || posicao < 0 || posicao > lista.numeroElementos { - return false - } - - for j := lista.numeroElementos; j > posicao; j-- { - lista.arranjoRegistros[j] = lista.arranjoRegistros[j-1] - } - - lista.arranjoRegistros[posicao] = registro - lista.numeroElementos++ - - return true -} - -// Exclui um elemento da lista -func excluirElemento(lista *Lista, valor int) bool { - posicao := buscaSequencial(lista, valor) - - if posicao == -1 { - return false - } - - for i := posicao; i < lista.numeroElementos-1; i++ { - lista.arranjoRegistros[i] = lista.arranjoRegistros[i+1] - } - - lista.numeroElementos-- - - return true -} - -func main() { - lista := criarLista() - - inicializar(&lista) - - fmt.Println("Inserindo valores na lista...") - insereElemento(&lista, Registro{valor: 20}, 0) - insereElemento(&lista, Registro{valor: 10}, 0) - insereElemento(&lista, Registro{valor: 70}, 0) - insereElemento(&lista, Registro{valor: 30}, 0) - insereElemento(&lista, Registro{valor: 60}, 0) - insereElemento(&lista, Registro{valor: 90}, 0) - insereElemento(&lista, Registro{valor: 80}, 0) - insereElemento(&lista, Registro{valor: 15}, 0) - insereElemento(&lista, Registro{valor: 1}, 0) - - fmt.Println() - fmt.Println("Imprimindo lista...") - imprimir(&lista) - fmt.Println("Tamanho da lista:", tamanho(&lista)) - - fmt.Println() - - fmt.Println("Excluindo elemento 80 da lista...") - excluirElemento(&lista, 80) - - fmt.Println() - fmt.Println("Imprimindo lista...") - imprimir(&lista) - fmt.Println("Tamanho da lista:", tamanho(&lista)) - - fmt.Println() - fmt.Println("Buscando valores na lista:") - fmt.Println() - - fmt.Println("Buscando posição do numero 15:") - fmt.Printf("Posição do número 15: %v \n\n", buscaSequencial(&lista, 15)) - - fmt.Println("Buscando posição do valor 100:") - fmt.Printf("Posição do número 100: %v \n\n", buscaSequencial(&lista, 100)) -} diff --git a/src/go/lista_sequencial_ordenada.go b/src/go/lista_sequencial_ordenada.go deleted file mode 100644 index b4ad1123..00000000 --- a/src/go/lista_sequencial_ordenada.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Listas - Lista linear ordenada -* Danilo Moura - 2020 -* -* Implementação da lista sequencial cujos elementos estão ordenados -* -* link Go PlayGround: https://play.golang.org/p/J6Jbi2_FWJk - */ - -package main - -import "fmt" - -var maxSize = 50 - -// Estrura que será guardada em cada posição da lista -type Registro struct { - valor int - // Outros campos podem ser adicionados aqui -} - -// Estrutura que guarda um arranjo de Registro, e o número de elementos no arranjo -type Lista struct { - arranjoRegistros []Registro - numeroElementos int -} - -// Cria uma nova lista -func criarLista() Lista { - lista := Lista{ - arranjoRegistros: make([]Registro, maxSize), - numeroElementos: 0, - } - - return lista -} - -// reseta o contador de elementos da lista -func inicializar(lista *Lista) { - lista.numeroElementos = 0 -} - -// Recupera a quantidade de elementos da lista -func tamanho(lista *Lista) int { - return lista.numeroElementos -} - -// Imprime valores dos elementos na lista -func imprimir(lista *Lista) { - for i := 0; i < lista.numeroElementos; i++ { - fmt.Printf("%v ", lista.arranjoRegistros[i].valor) - } - fmt.Println() -} - -// Realiza busca binária na lista -func buscaBinaria(lista *Lista, valor int) int { - esquerda := 0 - direita := lista.numeroElementos - 1 - - for esquerda <= direita { - meio := ((esquerda + direita) / 2) - if lista.arranjoRegistros[meio].valor == valor { - return meio - } - - if lista.arranjoRegistros[meio].valor < valor { - esquerda = meio + 1 - } else { - direita = meio - 1 - } - } - - return -1 -} - -// Insere elementos na lista em ordem crescente, garantindo com a lista esteja sempre ordenada -func insereRegistroOrdenado(lista *Lista, registro Registro) bool { - if lista.numeroElementos == maxSize { - return false - } - - posicao := lista.numeroElementos - - for posicao > 0 && lista.arranjoRegistros[posicao-1].valor > registro.valor { - lista.arranjoRegistros[posicao] = lista.arranjoRegistros[posicao-1] - posicao-- - } - - lista.arranjoRegistros[posicao] = registro - lista.numeroElementos++ - - return true -} - -// Exclui um elemento da lista -func excluirElemento(lista *Lista, valor int) bool { - posicao := buscaBinaria(lista, valor) - - if posicao == -1 { - return false - } - - for i := posicao; i < lista.numeroElementos-1; i++ { - lista.arranjoRegistros[i] = lista.arranjoRegistros[i+1] - } - - lista.numeroElementos-- - - return true -} - -func main() { - lista := criarLista() - - inicializar(&lista) - - fmt.Println("Inserindo valores na lista...") - insereRegistroOrdenado(&lista, Registro{valor: 20}) - insereRegistroOrdenado(&lista, Registro{valor: 10}) - insereRegistroOrdenado(&lista, Registro{valor: 70}) - insereRegistroOrdenado(&lista, Registro{valor: 30}) - insereRegistroOrdenado(&lista, Registro{valor: 60}) - insereRegistroOrdenado(&lista, Registro{valor: 90}) - insereRegistroOrdenado(&lista, Registro{valor: 80}) - insereRegistroOrdenado(&lista, Registro{valor: 15}) - insereRegistroOrdenado(&lista, Registro{valor: 1}) - - fmt.Println() - fmt.Println("Imprimindo lista...") - imprimir(&lista) - fmt.Println("Tamanho da lista:", tamanho(&lista)) - - fmt.Println() - - fmt.Println("Excluindo elemento 80 da lista...") - excluirElemento(&lista, 80) - - fmt.Println() - fmt.Println("Imprimindo lista...") - imprimir(&lista) - fmt.Println("Tamanho da lista:", tamanho(&lista)) - - fmt.Println() - fmt.Println("Buscando valores na lista:") - fmt.Println() - - fmt.Println("Buscando posição do numero 15:") - fmt.Printf("Posição do número 15: %v \n\n", buscaBinaria(&lista, 15)) - - fmt.Println("Buscando posição do valor 100:") - fmt.Printf("Posição do número 100: %v \n\n", buscaBinaria(&lista, 100)) -} diff --git a/src/go/maximo_minimo.go b/src/go/maximo_minimo.go deleted file mode 100644 index 40f10094..00000000 --- a/src/go/maximo_minimo.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import "fmt" - -func MaximoDivisaoEConquista(vetor []int, inicio int, fim int) int { - if inicio == fim { - return vetor[inicio] - } - - meio := (inicio + fim) / 2 - aux1 := MaximoDivisaoEConquista(vetor, inicio, meio) - aux2 := MaximoDivisaoEConquista(vetor, meio+1, fim) - - if aux1 > aux2 { - return aux1 - } - - return aux2 -} - -func MinimoMaximoRecursivo(vetor []int, minimo int, maximo int, indice int) { - if vetor[indice] < minimo { - minimo = vetor[indice] - } - if vetor[indice] > maximo { - maximo = vetor[indice] - } - if indice < len(vetor)-1 { - MinimoMaximoRecursivo(vetor, minimo, maximo, indice+1) - } else { - fmt.Println("Minimo:", minimo) - fmt.Println("Maximo:", maximo) - } -} - -func main() { - slice := []int{2, 3, 9, 1, 6, 8, 5} - MinimoMaximoRecursivo(slice, 999, 0, 0) -} diff --git a/src/go/min_max_recursive.go b/src/go/min_max_recursive.go new file mode 100644 index 00000000..586cff7d --- /dev/null +++ b/src/go/min_max_recursive.go @@ -0,0 +1,39 @@ +package main + +import "fmt" + +func MaxDivideAndConquer(array []int, start int, end int) int { + if start == end { + return array[start] + } + + middle := (start + end) / 2 + aux1 := MaxDivideAndConquer(array, start, middle) + aux2 := MaxDivideAndConquer(array, middle+1, end) + + if aux1 > aux2 { + return aux1 + } + + return aux2 +} + +func RecursiveMinMax(array []int, min int, max int, index int) { + if array[index] < min { + min = array[index] + } + if array[index] > max { + max = array[index] + } + if index < len(array)-1 { + RecursiveMinMax(array, min, max, index+1) + } else { + fmt.Println("Minimum:", min) + fmt.Println("Maximum:", max) + } +} + +func main() { + slice := []int{2, 3, 9, 1, 6, 8, 5} + RecursiveMinMax(slice, 999, 0, 0) +} diff --git a/src/go/sorted_linked_list.go b/src/go/sorted_linked_list.go new file mode 100644 index 00000000..bc1eefaa --- /dev/null +++ b/src/go/sorted_linked_list.go @@ -0,0 +1,152 @@ +/* +* Lists - Ordered linear list +* +* Implementation of a sequential list whose elements are ordered +* +* Go PlayGround link: https://play.golang.org/p/J6Jbi2_FWJk + */ + +package main + +import "fmt" + +var maxSize = 50 + +// Structure that will be stored in each position of the list +type Record struct { + value int + // Other fields can be added here +} + +// Structure that holds an array of Records and the number of elements in the array +type List struct { + recordArray []Record + numberOfElements int +} + +// Creates a new list +func createList() List { + list := List{ + recordArray: make([]Record, maxSize), + numberOfElements: 0, + } + + return list +} + +// Resets the list's element counter +func initialize(list *List) { + list.numberOfElements = 0 +} + +// Retrieves the number of elements in the list +func size(list *List) int { + return list.numberOfElements +} + +// Prints the values of the elements in the list +func show(list *List) { + for i := 0; i < list.numberOfElements; i++ { + fmt.Printf("%v ", list.recordArray[i].value) + } + fmt.Println() +} + +// Performs binary search on the list +func binarySearch(list *List, value int) int { + left := 0 + right := list.numberOfElements - 1 + + for left <= right { + middle := ((left + right) / 2) + if list.recordArray[middle].value == value { + return middle + } + + if list.recordArray[middle].value < value { + left = middle + 1 + } else { + right = middle - 1 + } + } + + return -1 +} + +// Inserts elements into the list in ascending order, ensuring that the list is always sorted +func insertRecordInOrder(list *List, record Record) bool { + if list.numberOfElements == maxSize { + return false + } + + position := list.numberOfElements + + for position > 0 && list.recordArray[position-1].value > record.value { + list.recordArray[position] = list.recordArray[position-1] + position-- + } + + list.recordArray[position] = record + list.numberOfElements++ + + return true +} + +// Deletes an element from the list +func deleteElement(list *List, value int) bool { + position := binarySearch(list, value) + + if position == -1 { + return false + } + + for i := position; i < list.numberOfElements-1; i++ { + list.recordArray[i] = list.recordArray[i+1] + } + + list.numberOfElements-- + + return true +} + +func main() { + list := createList() + + initialize(&list) + + fmt.Println("Inserting values into the list...") + insertRecordInOrder(&list, Record{value: 20}) + insertRecordInOrder(&list, Record{value: 10}) + insertRecordInOrder(&list, Record{value: 70}) + insertRecordInOrder(&list, Record{value: 30}) + insertRecordInOrder(&list, Record{value: 60}) + insertRecordInOrder(&list, Record{value: 90}) + insertRecordInOrder(&list, Record{value: 80}) + insertRecordInOrder(&list, Record{value: 15}) + insertRecordInOrder(&list, Record{value: 1}) + + fmt.Println() + fmt.Println("Printing the list...") + show(&list) + fmt.Println("Size of the list:", size(&list)) + + fmt.Println() + + fmt.Println("Deleting element 80 from the list...") + deleteElement(&list, 80) + + fmt.Println() + fmt.Println("Printing the list...") + show(&list) + fmt.Println("Size of the list:", size(&list)) + + fmt.Println() + fmt.Println("Searching values in the list:") + fmt.Println() + + fmt.Println("Searching position of number 15:") + fmt.Printf("Position of number 15: %v \n\n", binarySearch(&list, 15)) + + fmt.Println("Searching position of value 100:") + fmt.Printf("Position of number 100: %v \n\n", binarySearch(&list, 100)) +} diff --git a/src/go/stack.go b/src/go/stack.go index 771d9f8b..8e13a1ce 100644 --- a/src/go/stack.go +++ b/src/go/stack.go @@ -26,12 +26,12 @@ func (stack *Stack[T]) Show() { } func main() { - pilha := Stack[int]{} - pilha.Push(1) - pilha.Push(2) - pilha.Push(3) - pilha.Push(4) - pilha.Pop() + stack := Stack[int]{} + stack.Push(1) + stack.Push(2) + stack.Push(3) + stack.Push(4) + stack.Pop() fmt.Printf("Stack: ") - pilha.Show() + stack.Show() } diff --git a/src/go/hanoi.go b/src/go/tower_of_hanoi.go similarity index 76% rename from src/go/hanoi.go rename to src/go/tower_of_hanoi.go index 42f8a39e..72f37624 100644 --- a/src/go/hanoi.go +++ b/src/go/tower_of_hanoi.go @@ -4,7 +4,7 @@ import "fmt" func Hanoi(pino0 int, pino2 int, pino1 int, numero int) { if numero == 1 { - fmt.Println("Mover de ", pino0, " para ", pino2) + fmt.Println("Move from ", pino0, " to ", pino2) } else { Hanoi(pino0, pino1, pino2, numero-1) Hanoi(pino0, pino2, pino1, 1) @@ -13,6 +13,6 @@ func Hanoi(pino0 int, pino2 int, pino1 int, numero int) { } func main() { - fmt.Println("Torre de Hanoi:") + fmt.Println("Tower of Hanoi:") Hanoi(0, 2, 1, 3) } diff --git a/src/go/travelling_salesman.go b/src/go/travelling_salesman.go new file mode 100644 index 00000000..9d15564a --- /dev/null +++ b/src/go/travelling_salesman.go @@ -0,0 +1,152 @@ +/* + * The Traveling Salesman Problem (TSP) is a problem that tries to determine the + * shortest route to visit a series of cities (visiting each one only once), returning to the starting city. + * + * Using a distance matrix to represent an undirected graph. + * + * Assuming we have the following graph: + * + * 6 + * ------------------- + * | 3 1 | + * (000)-----(001)-----(002) + * | \ / | \ / | + * | \ 6/ | \2 / | + * | \ / | \ / | + * 2| / 8| / |5 + * | / \ | / \ | + * | / 3\ | /4 \ | + * | / \ | / \ | + * (003)-----(004)-----(005) + * | 6 4 | + * ------------------- + * 1 + * + * Distance Matrix + * 0 1 2 3 4 5 + * 0 0 3 6 2 3 - + * 1 3 0 1 6 8 2 + * 2 6 1 0 - 4 5 + * 3 2 6 - 0 6 1 + * 4 3 8 4 6 0 4 + * 5 - 2 5 1 4 0 + * + * Best solution: + * 0 - 3 - 5 - 1 - 2 - 4 - 0: 13 + */ + +package main + +import "fmt" + +const vertices = 6 +const infinity = 99999999 + +var distanceMatrix [][]int + +var tempSolution []int // Temporary solution +var bestSolution []int // Best solution +var visited []bool // Visited vertices + +var bestSolutionValue int +var currentSolutionValue int + +func TravelingSalesmanAux(x int) { + + // If the current solution value is greater than the best solution value, it means it's no longer the best solution, so we can stop here + if currentSolutionValue > bestSolutionValue { + return + } + + // If the temporary solution vector is complete + if x == vertices { + distance := distanceMatrix[tempSolution[x-1]][tempSolution[0]] + + // If a better solution is found + if distance < infinity && (currentSolutionValue+distance) < bestSolutionValue { + + // We have a better solution + bestSolutionValue = currentSolutionValue + distance + + // Copy the entire vector to the best solution + for i := 0; i < vertices; i++ { + bestSolution[i] = tempSolution[i] + } + } + return + } + + // Last vertex in the temporary solution + last := tempSolution[x-1] + + // Iterate through all columns of the distance matrix in the row of the last vertex + for i := 0; i < vertices; i++ { + + // If the position has not been visited and the value in the matrix is less than infinity + if !visited[i] && distanceMatrix[last][i] < infinity { + // Mark the position as visited + visited[i] = true + // Load the current vertex into the temporary solution + tempSolution[x] = i + // Increment the total distance traveled based on the position in the matrix + currentSolutionValue += distanceMatrix[last][i] + // Call recursively for the next vertex + TravelingSalesmanAux(x + 1) + // If it has not finished yet, decrement the value of the variable that stores the total distance + currentSolutionValue -= distanceMatrix[last][i] + // Set it as not visited so it can be accessed by another vertex + visited[i] = false + } + } +} + +func TravelingSalesman(initialPosition int) { + // Check if the position is valid + if initialPosition < vertices { + visited[initialPosition] = true // Mark the first vertex as visited + tempSolution[0] = initialPosition // Put the initial position in the first position of the temporary solution + TravelingSalesmanAux(1) // Call the auxiliary method for the traveling salesman + } else { + fmt.Println("Invalid initial vertex") + } +} + +// Initialize vectors and default values +func initialize() { + + bestSolutionValue = infinity + currentSolutionValue = 0 + + for i := 0; i < vertices; i++ { + visited = append(visited, false) + tempSolution = append(tempSolution, -1) + bestSolution = append(bestSolution, -1) + } + + // Create the distance matrix + row0 := []int{0, 3, 6, 2, 3, infinity} + row1 := []int{3, 0, 1, 6, 8, 2} + row2 := []int{6, 1, 0, infinity, 4, 5} + row3 := []int{2, 6, infinity, 0, 6, 1} + row4 := []int{3, 8, 4, 6, 0, 4} + row5 := []int{infinity, 2, 5, 1, 4, 0} + + distanceMatrix = append(distanceMatrix, row0) + distanceMatrix = append(distanceMatrix, row1) + distanceMatrix = append(distanceMatrix, row2) + distanceMatrix = append(distanceMatrix, row3) + distanceMatrix = append(distanceMatrix, row4) + distanceMatrix = append(distanceMatrix, row5) +} + +func main() { + initialize() + TravelingSalesman(0) + + fmt.Println("Traveling Salesman") + fmt.Println("Minimum path:", bestSolutionValue) + for i := 0; i < vertices; i++ { + fmt.Print(bestSolution[i], ", ") + } + fmt.Println(bestSolution[0]) +} diff --git a/src/go/unordered_linked_list.go b/src/go/unordered_linked_list.go new file mode 100644 index 00000000..b40eb68a --- /dev/null +++ b/src/go/unordered_linked_list.go @@ -0,0 +1,155 @@ +/* +* Lists - Unordered linear list +* +* Implementation of a sequential list where elements are not ordered +* +* Go Playground link: https://play.golang.org/p/3uFOquVlTD8 + */ + +package main + +import "fmt" + +var maxSize = 50 + +// Structure that will be stored in each position of the list +type Record struct { + value int + // Other fields can be added here +} + +// Structure that holds an array of Records and the number of elements in the array +type List struct { + recordArray []Record + numberOfElements int +} + +// Creates a new list +func createList() List { + list := List{ + recordArray: make([]Record, maxSize), + numberOfElements: 0, + } + + return list +} + +// Resets the list's element counter +func initialize(list *List) { + list.numberOfElements = 0 +} + +// Retrieves the number of elements in the list +func size(list *List) int { + return list.numberOfElements +} + +// Prints the values of the elements in the list +func show(list *List) { + for i := 0; i < list.numberOfElements; i++ { + fmt.Printf("%v ", list.recordArray[i].value) + } + fmt.Println() +} + +// Performs a sequential search in the list, iterating through each item +func sequentialSearch(list *List, value int) int { + i := 0 + for i < list.numberOfElements { + if value == list.recordArray[i].value { + return i + } + i++ + } + return -1 +} + +// Performs a sentinel search in the list, iterating through each item +func sentinelSearch(list *List, value int) int { + i := 0 + list.recordArray[list.numberOfElements].value = value + + for value != list.recordArray[i].value { + i++ + } + + if i == list.numberOfElements { + return -1 + } + return i +} + +// Inserts elements into the list at a specific position and moves all other elements to the right +func insertElement(list *List, record Record, position int) bool { + if (list.numberOfElements == maxSize) || position < 0 || position > list.numberOfElements { + return false + } + + for j := list.numberOfElements; j > position; j-- { + list.recordArray[j] = list.recordArray[j-1] + } + + list.recordArray[position] = record + list.numberOfElements++ + + return true +} + +// Deletes an element from the list +func deleteElement(list *List, value int) bool { + position := sequentialSearch(list, value) + + if position == -1 { + return false + } + + for i := position; i < list.numberOfElements-1; i++ { + list.recordArray[i] = list.recordArray[i+1] + } + + list.numberOfElements-- + + return true +} + +func main() { + list := createList() + + initialize(&list) + + fmt.Println("Inserting values into the list...") + insertElement(&list, Record{value: 20}, 0) + insertElement(&list, Record{value: 10}, 0) + insertElement(&list, Record{value: 70}, 0) + insertElement(&list, Record{value: 30}, 0) + insertElement(&list, Record{value: 60}, 0) + insertElement(&list, Record{value: 90}, 0) + insertElement(&list, Record{value: 80}, 0) + insertElement(&list, Record{value: 15}, 0) + insertElement(&list, Record{value: 1}, 0) + + fmt.Println() + fmt.Println("Printing the list...") + show(&list) + fmt.Println("Size of the list:", size(&list)) + + fmt.Println() + + fmt.Println("Deleting element 80 from the list...") + deleteElement(&list, 80) + + fmt.Println() + fmt.Println("Printing the list...") + show(&list) + fmt.Println("Size of the list:", size(&list)) + + fmt.Println() + fmt.Println("Searching for values in the list:") + fmt.Println() + + fmt.Println("Searching for the position of number 15:") + fmt.Printf("Position of number 15: %v \n\n", sequentialSearch(&list, 15)) + + fmt.Println("Searching for the position of value 100:") + fmt.Printf("Position of number 100: %v \n\n", sequentialSearch(&list, 100)) +} diff --git a/src/java/BogoSort.java b/src/java/BogoSort.java index 59086059..74e2f16e 100644 --- a/src/java/BogoSort.java +++ b/src/java/BogoSort.java @@ -1,6 +1,3 @@ -/* - * @author Marcelo Wischniowski - */ public class BogoSort { public static int[] bogoSort(int[] vector) { diff --git a/src/java/BucketSort.java b/src/java/BucketSort.java index 1caacf92..5f81a84a 100644 --- a/src/java/BucketSort.java +++ b/src/java/BucketSort.java @@ -1,6 +1,3 @@ -/* - * @author Marcelo Wischniowski - */ public class BucketSort { /** diff --git a/src/java/CountingSort.java b/src/java/CountingSort.java new file mode 100644 index 00000000..e2550735 --- /dev/null +++ b/src/java/CountingSort.java @@ -0,0 +1,54 @@ +public class CountingSort { + + int getMax(int[] a, int n) { + int max = a[0]; + for (int i = 1; i < n; i++) { + if (a[i] > max) max = a[i]; + } + return max; + } + + void countSort(int[] a, int n) { + int[] output = new int[n + 1]; + int max = getMax(a, n); + // int max = 42; + int[] count = new int[max + 1]; + + for (int i = 0; i <= max; ++i) { + count[i] = 0; + } + + for (int i = 0; i < n; i++) { + count[a[i]]++; + } + + for (int i = 1; i <= max; i++) count[i] += count[i - 1]; + + for (int i = n - 1; i >= 0; i--) { + output[count[a[i]] - 1] = a[i]; + count[a[i]]--; + } + + for (int i = 0; i < n; i++) { + a[i] = output[i]; + } + } + + /* Function to print the array elements */ + void printArray(int a[], int n) { + int i; + for (i = 0; i < n; i++) System.out.print(a[i] + " "); + } + + public static void main(String args[]) { + int a[] = {11, 30, 24, 7, 31, 16, 39, 41}; + int n = a.length; + CountingSort c1 = new CountingSort(); + System.out.println("\nBefore sorting array elements are - "); + c1.printArray(a, n); + c1.countSort(a, n); + System.out.println("\nAfter sorting array elements are - "); + c1.printArray(a, n); + System.out.println(); + } +} diff --git a/src/java/RecursiveExponentiation.java b/src/java/ExponentiationRecursive.java similarity index 100% rename from src/java/RecursiveExponentiation.java rename to src/java/ExponentiationRecursive.java diff --git a/src/java/RecursiveFactorial.java b/src/java/FactorialRecursive.java similarity index 100% rename from src/java/RecursiveFactorial.java rename to src/java/FactorialRecursive.java diff --git a/src/java/FloydWarshall.java b/src/java/FloydWarshall.java new file mode 100644 index 00000000..36e1bb34 --- /dev/null +++ b/src/java/FloydWarshall.java @@ -0,0 +1,66 @@ +/* + * Floyd-Warshall algorithm in Java + * All pairs shortest path algorithm + * Time Complexity: O(n³) + * Space Complexity: O(n²) + */ + +public class FloydWarshall { + + public static void showMatrix(long[][] matriz, int nroVertices) { + for (int i = 0; i < nroVertices; i++) { + for (int j = 0; j < nroVertices; j++) { + if (matriz[i][j] < 10) { + System.out.print(" " + matriz[i][j] + " "); + } else { + System.out.print(matriz[i][j] + " "); + } + } + + System.out.println(); + } + System.out.println(); + } + + public static void main(String[] args) { + int nroVertices = 5; + long[][] matriz = { + {0, 2, 10, 5, 7}, + {2, 0, 3, 3, 1}, + {10, 3, 0, 1, 2}, + {5, 3, 1, 0, Long.MAX_VALUE}, + {7, 1, 2, 2, 0} + }; + + // Display the original matrix + System.out.println("Original matrix:"); + showMatrix(matriz, nroVertices); + + floydWarshall(matriz, nroVertices); + + // Display the updated matrix + System.out.println("Updated matrix:"); + showMatrix(matriz, nroVertices); + + // Show all shortest paths + System.out.println(); + for (int i = 0; i < nroVertices; i++) { + for (int x = 0; x < nroVertices; x++) { + System.out.println("Shortest distance from " + i + " to " + x + " = " + matriz[x][i] + "."); + } + } + System.out.println(); + } + + public static void floydWarshall(long[][] matriz, int n) { + for (int x = 0; x < n; x++) { // Intermediary vertex + for (int y = 0; y < n; y++) { // Origin vertex + for (int z = 0; z < n; z++) { // Destination vertex + if (matriz[y][z] > (matriz[y][x] + matriz[x][z])) { + matriz[y][z] = matriz[y][x] + matriz[x][z]; + } + } + } + } + } +} diff --git a/src/java/HeapSort.java b/src/java/HeapSort.java index ca6ed5ea..c3074af5 100644 --- a/src/java/HeapSort.java +++ b/src/java/HeapSort.java @@ -1,6 +1,3 @@ -/* - * @author Marcelo Wischniowski - */ public class HeapSort { /** diff --git a/src/java/LinearSearchIterative.java b/src/java/LinearSearch.java similarity index 100% rename from src/java/LinearSearchIterative.java rename to src/java/LinearSearch.java diff --git a/src/java/MaxMinArray.java b/src/java/MaxRecursive.java similarity index 100% rename from src/java/MaxMinArray.java rename to src/java/MaxRecursive.java diff --git a/src/java/Mergesort.java b/src/java/MergeSort.java similarity index 100% rename from src/java/Mergesort.java rename to src/java/MergeSort.java diff --git a/src/java/IterativeMinMax.java b/src/java/MinMaxIterative.java similarity index 100% rename from src/java/IterativeMinMax.java rename to src/java/MinMaxIterative.java diff --git a/src/java/RecursiveMinMax.java b/src/java/MinMaxRecursive.java similarity index 100% rename from src/java/RecursiveMinMax.java rename to src/java/MinMaxRecursive.java diff --git a/src/java/Fila.java b/src/java/Queue.java similarity index 100% rename from src/java/Fila.java rename to src/java/Queue.java diff --git a/src/java/Quicksort.java b/src/java/QuickSort.java similarity index 100% rename from src/java/Quicksort.java rename to src/java/QuickSort.java diff --git a/src/java/RadixSort.java b/src/java/RadixSort.java index 80e7e34d..a8f5b29c 100644 --- a/src/java/RadixSort.java +++ b/src/java/RadixSort.java @@ -1,6 +1,3 @@ -/* - * @author Marcelo Wischniowski - */ public class RadixSort { /** diff --git a/src/java/ShellSort.java b/src/java/ShellSort.java index 3e091317..3af64c86 100644 --- a/src/java/ShellSort.java +++ b/src/java/ShellSort.java @@ -1,6 +1,3 @@ -/* - * @author Marcelo Wischniowski - */ public class ShellSort { /** diff --git a/src/java/Pilha.java b/src/java/Stack.java similarity index 100% rename from src/java/Pilha.java rename to src/java/Stack.java diff --git a/src/java/AddTwoNumbers.java b/src/java/TwoSum.java similarity index 95% rename from src/java/AddTwoNumbers.java rename to src/java/TwoSum.java index 1b4b714e..5860a557 100644 --- a/src/java/AddTwoNumbers.java +++ b/src/java/TwoSum.java @@ -3,11 +3,7 @@ import java.util.List; // Utilized OpenJDK 17.0.3 -/* - * @author Gabriel Nascimento. GitHub: Gabrielxdf - * - */ -public class AddTwoNumbers { +public class TwoSum { /** * This program takes a list of numbers and checks if there are two numbers whose sum is equal to * the expected value. diff --git a/src/javascript/Calculate_PI.js b/src/javascript/CalculatePi.js similarity index 100% rename from src/javascript/Calculate_PI.js rename to src/javascript/CalculatePi.js diff --git a/src/javascript/CountingSort.js b/src/javascript/CountingSort.js new file mode 100644 index 00000000..0874086d --- /dev/null +++ b/src/javascript/CountingSort.js @@ -0,0 +1,31 @@ +function countingSort(arr) { + // Find the maximum element in the array to determine the range + let max = Math.max(...arr); + + // Create a count array to store the count of each element + let count = new Array(max + 1).fill(0); + + // Count the occurrences of each element in the input array + for (let i = 0; i < arr.length; i++) { + count[arr[i]]++; + } + + // Modify the count array to store the actual position of each element + for (let i = 1; i <= max; i++) { + count[i] += count[i - 1]; + } + + // Create a new output array and store the elements in their sorted order + let output = new Array(arr.length); + for (let i = arr.length - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + count[arr[i]]--; + } + + return output; +} + +const arr = [4, 2, 2, 8, 3, 3, 1]; +const sortedArr = countingSort(arr); +console.log("Original array:", arr); +console.log("Sorted array:", sortedArr); diff --git a/src/javascript/DijkstrasAlgorithm.js b/src/javascript/Dijkstra.js similarity index 100% rename from src/javascript/DijkstrasAlgorithm.js rename to src/javascript/Dijkstra.js diff --git a/src/javascript/Factorial.js b/src/javascript/Factorial.js index 36fb6ed9..b361180b 100644 --- a/src/javascript/Factorial.js +++ b/src/javascript/Factorial.js @@ -1,6 +1,6 @@ /** - * - * @param {number} n + * + * @param {number} n */ function factorial(n) { let result = 1; @@ -11,7 +11,7 @@ function factorial(n) { } function main(){ - console.log('Fatorial => ', factorial(3)); + console.log('Factorial => ', factorial(3)); } -main(); \ No newline at end of file +main(); diff --git a/src/javascript/FactorialRecursive.js b/src/javascript/FactorialRecursive.js index 027cfbf0..02f0949a 100644 --- a/src/javascript/FactorialRecursive.js +++ b/src/javascript/FactorialRecursive.js @@ -1,6 +1,6 @@ /** - * - * @param {number} n + * + * @param {number} n */ function factorial(n) { if (n <= 1) { @@ -11,7 +11,7 @@ function factorial(n) { } function main(){ - console.log('Fatorial => ', factorial(3)); + console.log('Factorial => ', factorial(3)); } -main(); \ No newline at end of file +main(); diff --git a/src/javascript/FibonacciMemoization.js b/src/javascript/FibonacciMemoization.js new file mode 100644 index 00000000..c919d7fe --- /dev/null +++ b/src/javascript/FibonacciMemoization.js @@ -0,0 +1,26 @@ +const fibonacci = (function () { + const memo = {}; + + function fib(n) { + if (n <= 1) { + return n; + } + + if (memo[n] !== undefined) { + return memo[n]; + } + + memo[n] = fib(n - 1) + fib(n - 2); + + return memo[n]; + } + + return fib; +})(); + +function main() { + console.log('Fibonacci (memoization) of 30:', fibonacci(30)); +} + +main(); + diff --git a/src/javascript/InsertionSort.js b/src/javascript/InsertionSort.js index e0478d42..f08820a3 100644 --- a/src/javascript/InsertionSort.js +++ b/src/javascript/InsertionSort.js @@ -1,6 +1,3 @@ -//Diogo L.C. Felipe -//diogomem@outlook.com - /* Insertion Sort is a sorting algorithm that works as follows: 1. It iterates through the array from the second position onward. @@ -32,4 +29,4 @@ function swapPositions(array, firstPosition, secondPosition) { var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; let sortedArrayViaInsertionSort = insertionSort(unsortedArray, 0, unsortedArray.length); -console.log(sortedArrayViaInsertionSort); \ No newline at end of file +console.log(sortedArrayViaInsertionSort); diff --git a/src/javascript/InterpolationSearch.js b/src/javascript/InterpolationSearch.js index 68f8aa67..02f66c31 100644 --- a/src/javascript/InterpolationSearch.js +++ b/src/javascript/InterpolationSearch.js @@ -1,8 +1,5 @@ /** - * @author octaviolage - * @version 1.0 - * @date 2022-07-31 - * @description Busca por interpolação + * @description Interpolation Search * @reference https://en.wikipedia.org/wiki/Interpolation_search */ @@ -22,7 +19,7 @@ const interpolationSearch = (arr, first, last, value) => { return pos; else if (arr[pos] < value) return interpolationSearch(arr, pos + 1, last, value); - else + else return interpolationSearch(arr, first, pos - 1, value); } return -1; @@ -30,7 +27,7 @@ const interpolationSearch = (arr, first, last, value) => { const main = () => { // The array needs to be sorted - const arr = [10, 12, 13, 16, 18, 19, 20, 21, + const arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]; let n = arr.length; diff --git a/src/javascript/RecursiveLinearSearch.js b/src/javascript/LinearSearchRecursive.js similarity index 100% rename from src/javascript/RecursiveLinearSearch.js rename to src/javascript/LinearSearchRecursive.js diff --git a/src/javascript/SentinelSearch.js b/src/javascript/LinearSearchSentinel.js similarity index 100% rename from src/javascript/SentinelSearch.js rename to src/javascript/LinearSearchSentinel.js diff --git a/src/javascript/IterativeMinAndMax.js b/src/javascript/MinMaxIterative.js similarity index 100% rename from src/javascript/IterativeMinAndMax.js rename to src/javascript/MinMaxIterative.js diff --git a/src/javascript/RecursiveMinAndMax.js b/src/javascript/MinMaxRecursive.js similarity index 100% rename from src/javascript/RecursiveMinAndMax.js rename to src/javascript/MinMaxRecursive.js diff --git a/src/javascript/SelectionSort.js b/src/javascript/SelectionSort.js index b8abc7ab..734af9cd 100644 --- a/src/javascript/SelectionSort.js +++ b/src/javascript/SelectionSort.js @@ -1,6 +1,3 @@ -// Diogo L.C. Felipe -// diogomem@outlook.com - /* Selection Sort, or the selection sort algorithm, sorts a series of data as follows: @@ -16,14 +13,14 @@ function selectionSort(unsortedArray, start, end) { let smallestPosition = findSmallestPosition(unsortedArray, i, end); [unsortedArray[smallestPosition], unsortedArray[i]] = [unsortedArray[i], unsortedArray[smallestPosition]]; } - + return unsortedArray; } - + function findSmallestPosition(unsortedArray, start, end) { let smallestPosition = start; let smallest = unsortedArray[start]; - + for (let i = start; i < end; i++) { if (unsortedArray[i] < smallest) { smallest = unsortedArray[i]; @@ -32,9 +29,9 @@ function selectionSort(unsortedArray, start, end) { } return smallestPosition; } - + var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; let sortedArrayViaSelectionSort = selectionSort(unsortedArray, 0, unsortedArray.length); - + console.log(sortedArrayViaSelectionSort); - \ No newline at end of file + diff --git a/src/kotlin/ExponentiationRecursive.kt b/src/kotlin/ExponentiationRecursive.kt index 4e96bf1c..95b21122 100644 --- a/src/kotlin/ExponentiationRecursive.kt +++ b/src/kotlin/ExponentiationRecursive.kt @@ -4,21 +4,20 @@ * The *exponentiationRecursive* function presents the values of a number (*base*) raised by an *exponent*. * In this function, the concept of *recursion* is used, in which the created function is called within it, one or more times internally of the same. * - * @author Algorithm version for Kotlin: Alfredo Paes - * @see https://github.com/Alfredo-Paes - * * @param base is of type integer (Int) * @param exponent is of type integer (Int) * * @return will return the *base* number raised by the *exponent*. The function returns a value of type *Long*. */ -fun exponentiationRecursive(base: Int, exponent: Int): Long { - return if (exponent === 0) { +fun exponentiationRecursive( + base: Int, + exponent: Int, +): Long = + if (exponent === 0) { 1 - }; else { + } else { base * exponentiationRecursive(base, exponent - 1) } -} fun main() { println(exponentiationRecursive(2, 3)) diff --git a/src/kotlin/Factorial.kt b/src/kotlin/Factorial.kt index faf6756a..70cd954e 100644 --- a/src/kotlin/Factorial.kt +++ b/src/kotlin/Factorial.kt @@ -3,9 +3,6 @@ * * The *factorial* function presents the values of multiplying *n numbers* by their predecessors greater than or equal to 1. * - * @author Algorithm version for Kotlin: Alfredo Paes - * @see https://github.com/Alfredo-Paes - * * @param number is of type integer (Int) * * @return will return a number of type *Long* in which the type is assigned to the *factorial* variable. diff --git a/src/kotlin/FibonacciRecursive.kt b/src/kotlin/FibonacciRecursive.kt index 33a8433f..7874e0b5 100644 --- a/src/kotlin/FibonacciRecursive.kt +++ b/src/kotlin/FibonacciRecursive.kt @@ -4,20 +4,16 @@ * The *fibonacci* function displays the values of the Fibonacci sequence in which, the first two terms of this sequence are less than or equal to 1, and each term that follows next will be the sum of the two previous numbers (0, 1, 1, 2, 3, 5, 8...). * In this function, the concept of *recursion* is used, in which the created function is called within it, one or more times internally. * - * @author Algorithm version for Kotlin: Alfredo Paes - * @see https://github.com/Alfredo-Paes - * * @param number is of type integer (Int) * * @return will return a logical condition if *number* is less than or equal to 1, returns 1 otherwise, the sum of itself using the concept of *recursion* to execute this sum. */ -fun fibonacci(number: Int): Int { - return if (number <= 1) { +fun fibonacci(number: Int): Int = + if (number <= 1) { 1 - }; else { + } else { fibonacci(number - 1) + fibonacci(number - 2) } -} fun main() { println(fibonacci(5)) diff --git a/src/kotlin/MergeSort.kt b/src/kotlin/MergeSort.kt index dd874bae..93ce92b7 100644 --- a/src/kotlin/MergeSort.kt +++ b/src/kotlin/MergeSort.kt @@ -10,7 +10,10 @@ fun mergeSort(arr: IntArray): IntArray { return merge(mergeSort(left), mergeSort(right)) } -fun merge(left: IntArray, right: IntArray): IntArray { +fun merge( + left: IntArray, + right: IntArray, +): IntArray { var result = IntArray(left.size + right.size) var leftIndex = 0 var rightIndex = 0 diff --git a/src/pascal/bubble-sort.pas b/src/pascal/bubble-sort.pas deleted file mode 100644 index 5419c41f..00000000 --- a/src/pascal/bubble-sort.pas +++ /dev/null @@ -1,99 +0,0 @@ -program selection_sort; - -{dia 06/05 -Version: 0.5 -Nome: Wellington De Souza Silva -Método : Selection Sort} - -// bug com dois valores altos ??? - -uses crt; - -const - MAX = 10; - -type - Tdado = integer; - - Tvetor = array[1..MAX] of Tdado; - -var - vetor : Tvetor; - -//usado para tester -procedure preencher(var vetor : Tvetor); -begin - vetor[1] := 4; - vetor[2] := 3; - vetor[3] := 500; - vetor[4] := 7; - vetor[5] := 10; - vetor[6] := 1309; - vetor[7] := 8; - vetor[8] := 9; - vetor[9] := 2; - vetor[10] := 6; -end; - -procedure manual(var vetor:Tvetor); -var - i : integer; -begin - for i := 1 to MAX do - begin - writeln('informe o valor ',i); - readln(vetor[i]); - end; -end; -// acha o menor, nucleo do programa -procedure kernel(var vetor : Tvetor); -var - j: integer; - temp : integer; -begin - for j:= 1 to MAX do - begin - if vetor[j] > vetor[j+1] then - begin - temp := vetor[j]; - vetor[j] := vetor[j+1]; - vetor[j+1] := temp; - end; - end; -end; - -////////////////////////////// -procedure exibir(vetor: Tvetor); -var - i : integer; -begin - writeln; - write(' | '); - for i:=1 to MAX do - begin - write(vetor[i]); - write(' | '); - end; - writeln; -end; - -procedure repetir(); -var - i: integer; -begin - for i:=MAX downto 1 do - begin - kernel(vetor); - exibir(vetor); - end; -end; - -begin - preencher(vetor); - writeln('Vetor Original'); - exibir(vetor); - repetir(); - writeln; - writeln('Vetor Ordenado'); - exibir(vetor); -end. \ No newline at end of file diff --git a/src/pascal/busca-binaria.pas b/src/pascal/busca-binaria.pas deleted file mode 100644 index 328a8e47..00000000 --- a/src/pascal/busca-binaria.pas +++ /dev/null @@ -1,66 +0,0 @@ -program buscabinaria; - -const - MAX = 30000; - -type - Tdado = integer; - Tvetor = array[1..MAX]of integer; - Tarq = text; -var - vetor : Tvetor; - valor: Tdado; - -procedure preencher(var vetor : Tvetor); -var - i : integer; -begin - for i:= 1 to MAX do - begin - vetor[i] := i; - end; -end; - -procedure buscaBinariarec(vetor:Tvetor; valor:Tdado; inicio:integer; fim:integer); -var - meio : integer; -begin - meio := (inicio+fim) div 2; - - { - writeln; - writeln('--------------------------------'); - writeln('Passo a Passo'); - writeln('valor ',vetor[meio]); - writeln('posicao ',meio); - writeln('--------------------------------'); - writeln; - } - - if(valor = vetor[meio]) then - begin - writeln('Achou!!'); - //writeln('valor ',vetor[meio]); - writeln('posicao ',meio); - end else - if(meio=inicio) then write('error 404') else - begin - if((valor > vetor[meio]) and (meio <> inicio)) then - begin - //writeln('DIREITA'); - buscaBinariarec(vetor, valor, meio, MAX); - end; - - if((valor < vetor[meio]) and (meio <> inicio)) then - begin - //writeln('ESQUERDA'); - buscaBinariarec(vetor, valor, inicio, meio); - end; - end; -end; - -begin - valor := 21054; - preencher(vetor); - buscaBinariarec(vetor, valor, 0, MAX); -end. \ No newline at end of file diff --git a/src/pascal/fatorial-recusiva.pas b/src/pascal/fatorial-recusiva.pas deleted file mode 100644 index 40ca7a82..00000000 --- a/src/pascal/fatorial-recusiva.pas +++ /dev/null @@ -1,26 +0,0 @@ -program fatorial_recursiva; -var - num : longint; - -function fatorial (number : longint): longint; -begin - if (number = 1) then - fatorial := 1 - else - fatorial := number * fatorial(number-1) -end; - -function fatorialb(n:integer): integer; -begin - if n > 1 then - fatorial := fatorial(n-1) * n - else fatorial := 1; -end; - -begin - writeln('Informe um numero'); - readln(num); - writeln(' '); - - writeln(num,'! = ',fatorial(num)); -end. \ No newline at end of file diff --git a/src/pascal/fatorial.pas b/src/pascal/fatorial.pas deleted file mode 100644 index c0708ce4..00000000 --- a/src/pascal/fatorial.pas +++ /dev/null @@ -1,19 +0,0 @@ -program fatorial_pascal; -var - num, cont, soma : longint; -begin - soma := 1; - cont := 0; - writeln('Informe um numero'); - readln(num); - writeln(' '); - - for cont := num downto 2 do - begin - //writeln(num*num-1); - writeln(soma); - soma := soma*cont; - writeln(soma); - end; - writeln(num,'! = ',soma); -end. \ No newline at end of file diff --git a/src/pascal/heapsort.pas b/src/pascal/heapsort.pas deleted file mode 100644 index 245f7a2c..00000000 --- a/src/pascal/heapsort.pas +++ /dev/null @@ -1,98 +0,0 @@ -program HeapSort240616; - -const - MAX = 10; - -type - Tgiven = integer; - Tvector = array[0..MAX] of Tgiven; - -var - vector : Tvector; - -procedure auto(var vector:Tvector); -var - i : integer; -begin - for i := 0 to MAX-1 do - begin - vector[i]:=random(150); - end; -end; - -procedure display( vector: Tvector ); -var - i: integer; -begin - writeln; - write('=> | '); - for i := 0 to MAX-1 do write(vector[i],' | '); - writeln; -end; - -procedure swap( var a, b: integer ); -var - temp: integer; -begin - temp := a; - a := b; - b := temp; -end; - -procedure sink( var vector : Tvector; start, last: integer ); -var - root, child: integer; -begin - root := start; - while ( root * 2 + 1 <= last ) do begin - child := root * 2 + 1; - if ( child < last ) and ( vector[child] < vector[child + 1] ) then - child := child + 1; - if ( vector[root] < vector[child] ) then begin - swap ( vector[root], vector[child] ); - root := child; - end else - break; - end; -end; - -procedure heighten( var vector : Tvector; count: integer ); -var - start: integer; -begin - start := (count - 1) div 2; - while ( start >= 0 ) do - begin - sink (vector, start, count-1); - start := start - 1; - end; -end; - -procedure heapSort( var vector : Tvector; lastVector:integer ); -var - last : integer; -begin - heighten(vector, MAX ); - last := MAX - 1; - writeln; - writeln('Heap'); - display(vector); - while ( last > 0 ) do - begin - swap(vector[last], vector[0]); - last := last - 1; - sink(vector, 0, last); - end; -end; - -//program -begin - writeln; - auto(vector); - writeln('Original Vector'); - display(vector); - heapSort (vector, MAX); - writeln; - writeln('Sorted Vector'); - display(vector); -end. \ No newline at end of file diff --git a/src/pascal/mergesort.pas b/src/pascal/mergesort.pas deleted file mode 100644 index bf78762c..00000000 --- a/src/pascal/mergesort.pas +++ /dev/null @@ -1,105 +0,0 @@ -program mergeSort; - -const - MAX = 10; - SENTINELA = 3200; - -type - Tdado = integer; - - Tvetor = array[1..MAX] of Tdado; - TvetorSentinela = array[1..MAX+1] of Tdado; - -var - vetor : Tvetor; - -procedure auto(var vetor:Tvetor); -var - i : integer; -begin - for i := 1 to MAX do - begin - vetor[i]:=random(150); - end; -end; - -procedure exibir(vetor: Tvetor); -var - i : integer; -begin - writeln; - write(' | '); - for i:=1 to MAX do - begin - write(vetor[i]); - write(' | '); - end; - writeln; -end; - -procedure merge(var vetor:Tvetor; inicio:integer; meio:integer; fim:integer); -var - e, d, i : integer; - esquerda : integer; - direita : integer; - left : TvetorSentinela; - right : TvetorSentinela; - -begin - //final de cada vetor temporario - esquerda := (meio - inicio +1); - direita := (fim - meio); - // vetor temporario recebendo seus valores respectivos - for e := 1 to esquerda do - left[e] := vetor[inicio+e-1]; - for d := 1 to direita do - right[d] := vetor[meio+d]; - //para determinar qtos trocas - left[esquerda+1] := SENTINELA; - right[direita+1] := SENTINELA; - - e := 1; - d := 1; - //unir(merge) os vetores os ordena-os - for i := inicio to fim do - begin - // qual lado e maior q o outro - if (left[e] <= right[d]) then - begin - vetor[i] := left[e]; - e := e+1; - end else - begin - vetor[i] := right[d]; - d:= d+1; - end; - end; -end; - -procedure dividir(var vetor : Tvetor; inicio:integer; fim:integer); -var - meio : integer; -begin - //merge - //write('merge'); - //writeln; - //writeln(inicio); - //writeln(fim); - if (inicio < fim) then - begin - meio := (inicio+fim) div 2; - //esquerda - dividir(vetor, inicio, meio); - //direita - dividir(vetor, meio+1, fim); - //chama o merge, após termina as recursões acima. - merge(vetor,inicio, meio, fim); - end; -end; - -begin - auto(vetor); - exibir(vetor); - dividir(vetor, 1, MAX); - exibir(vetor); -end. \ No newline at end of file diff --git a/src/pascal/pilha.pas b/src/pascal/pilha.pas deleted file mode 100644 index 3612d2d3..00000000 --- a/src/pascal/pilha.pas +++ /dev/null @@ -1,68 +0,0 @@ -program exe_pilha; -const - MAX = 3; -type - Tvetor = array[1..MAX] of integer; -var - pilha : Tvetor; - condicao : char; - posicao, valor : integer; - -procedure push (valor : integer); -begin - if(posicao>MAX) then writeln('OverFlow') else - begin - posicao := posicao + 1; - pilha[posicao] := valor; - end; -end; - -function pop : integer; -begin - if(posicao<1) then writeln('UnderFlow') else - begin - pop := pilha[posicao]; - posicao := posicao - 1; - end; -end; - -procedure exibir; -begin - writeln('___________________________________ '); - - writeln('Posicao na pilha :'); - for posicao:=1 to MAX do - begin - writeln('Indice: ',posicao, ' = ',pilha[posicao]); - end; - writeln('___________________________________ '); - - writeln('Posicao na pilha a se retirada :'); - for posicao:=MAX downto 1 do - begin - writeln('Indice: ',posicao, ' = ',pilha[posicao]); - end; -end; - -begin - posicao := 0; - - repeat - writeln('Deseja [A]dicionar , [R]etirar ou [S]air ?'); - readln(condicao); - - case condicao of - 'A','a' : begin - writeln('Valor '); - readln(valor); - push(valor); - end; - - 'r','R' : begin - writeln('O valor = ',pop); - end; - end; - until(condicao = 's') or (condicao = 'S'); - - exibir; -end. \ No newline at end of file diff --git a/src/pascal/selectsort.pas b/src/pascal/selectsort.pas deleted file mode 100644 index 6eef0dc4..00000000 --- a/src/pascal/selectsort.pas +++ /dev/null @@ -1,96 +0,0 @@ -program selection_sort; - -uses crt; - -const - MAX = 10; - -type - Tdado = integer; - - Tvetor = array[1..MAX] of Tdado; - -var - vetor : Tvetor; - -//usado para tester -procedure preencher(var vetor : Tvetor); -begin - vetor[1] := 4; - vetor[2] := 3; - vetor[3] := 500; - vetor[4] := 7; - vetor[5] := 10; - vetor[6] := 1309; - vetor[7] := 8; - vetor[8] := 9; - vetor[9] := 2; - vetor[10] := 6; -end; - -procedure manual(var vetor:Tvetor); -var - i : integer; -begin - for i := 1 to MAX do - begin - writeln('informe o valor ',i); - readln(vetor[i]); - end; -end; -// acha o menor, nucleo do programa -procedure kernel(var vetor : Tvetor; pos : integer); -var - aux : integer=0; - j: integer; - menor : integer; -begin - menor := pos; - for j:= pos+1 to MAX do - begin - if vetor[menor] > vetor[j] then - begin - menor := j; - - end; - end; - - aux := vetor[pos]; - vetor[pos] := vetor[menor]; - vetor[menor] := aux; -end; - -////////////////////////////// -procedure exibir(vetor: Tvetor); -var - i : integer; -begin - writeln; - write(' | '); - for i:=1 to MAX do - begin - write(vetor[i]); - write(' | '); - end; - writeln; -end; - -procedure repetir(); -var - i: integer; -begin - for i:=1 to MAX-1 do - begin - kernel(vetor,i); - end; -end; - -begin - manual(vetor); - writeln('Vetor Original'); - exibir(vetor); - repetir(); - writeln; - writeln('Vetor Ordenado'); - exibir(vetor); -end. \ No newline at end of file diff --git a/src/python/binary_search.py b/src/python/binary_search.py new file mode 100644 index 00000000..acfc880c --- /dev/null +++ b/src/python/binary_search.py @@ -0,0 +1,30 @@ +""" Recursive Binary Search Algorithm in Python """ + + +def binary_search(value, vector, left, right): + """ + Implementation of a binary search algorithm with recursion. + + Arguments: + value: Any. Value to be searched for in the list + vector: List. Ordered list in which value will be searched for + left: Any. Leftmost index for binary search + right: Any. Rightmost index for binary search + + Returns the index of value in vector; returns -1 if value not found in vector + """ + middle = int((left + right) / 2) + + if left <= right: + if value > vector[middle]: + left = middle + 1 + return binary_search(value, vector, left, right) + elif value < vector[middle]: + right = middle - 1 + return binary_search(value, vector, left, right) + return middle + return -1 + + +list = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] +print(binary_search(12, list, 0, len(list) - 1)) diff --git a/src/python/arvore_binaria_de_busca.py b/src/python/binary_search_tree.py similarity index 98% rename from src/python/arvore_binaria_de_busca.py rename to src/python/binary_search_tree.py index 694f90fa..2b7fa910 100644 --- a/src/python/arvore_binaria_de_busca.py +++ b/src/python/binary_search_tree.py @@ -1,8 +1,4 @@ -""" -Arvore Binaria de Busca em Python -Kelvin Salton do Prado -2015 -""" +""" Binary Search Tree in Python """ class TreeNode: diff --git a/src/python/binary_tree.py b/src/python/binary_tree.py index 8945200a..ede3fa47 100644 --- a/src/python/binary_tree.py +++ b/src/python/binary_tree.py @@ -1,4 +1,4 @@ -""" Implementação de uma árvore binária """ +""" Binary Tree in Python """ class Node: diff --git a/src/python/bogosort.py b/src/python/bogosort.py new file mode 100644 index 00000000..90cbd222 --- /dev/null +++ b/src/python/bogosort.py @@ -0,0 +1,39 @@ +""" Implementation of the bogosort algorithm in Python. """ + +import random + + +def is_sorted(arr): + """Checks if an array is sorted. + + Args: + arr (list): The array to check. + + Returns: + bool: True if the array is sorted, False otherwise. + """ + return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) + + +# Time: O(n * n!) +# Space: O(1) +def bogosort(arr): + """Sorts an array using the bogosort algorithm. + + Args: + arr (list): The array to sort. + + Returns: + None: The array is sorted in place. + """ + while not is_sorted(arr): + random.shuffle(arr) + + +if __name__ == "__main__": + # Example usage + unsorted_list = [3, 1, 2, 5, 4] + print("Unsorted list:", unsorted_list) + + bogosort(unsorted_list) + print("Sorted list:", unsorted_list) diff --git a/src/python/bubble_sort.py b/src/python/bubble_sort.py index 232e310a..7730f855 100755 --- a/src/python/bubble_sort.py +++ b/src/python/bubble_sort.py @@ -1,4 +1,4 @@ -""" Implementation of the bubble sort algorithm with recursion """ +""" Recursive Bubble Sort in Python """ def bubble_sort(data, size): @@ -9,7 +9,7 @@ def bubble_sort(data, size): data: list. List to be sorted size: int. List size - Returns the ordered "date" list. + Returns the ordered "data" list. """ swap = False for i in range(0, size - 1): diff --git a/src/python/busca_binaria.py b/src/python/busca_binaria.py deleted file mode 100644 index b85e4262..00000000 --- a/src/python/busca_binaria.py +++ /dev/null @@ -1,30 +0,0 @@ -""" Implementação do algoritmo de busca binária com recursão """ - - -def busca_binaria(valor, vetor, esquerda, direita): - """ - Implementação de um algoritmo de busca binária com recursão. - - Argumentos: - valor: Any. Valor a ser buscado na lista - vetor: list. lista ordenada na qual o valor será buscado - esquerda: Any. Valor inicial da metade buscada - direita: Any. Valor final da metade buscada - - Retorna o índice do valor em "vetor" ou -1 caso não exista nela. - """ - meio = int((esquerda + direita) / 2) - - if esquerda <= direita: - if valor > vetor[meio]: - esquerda = meio + 1 - return busca_binaria(valor, vetor, esquerda, direita) - elif valor < vetor[meio]: - direita = meio - 1 - return busca_binaria(valor, vetor, esquerda, direita) - return meio - return -1 - - -lista = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] -print(busca_binaria(12, lista, 0, len(lista) - 1)) diff --git a/src/python/calculate_pi.py b/src/python/calculate_pi.py index 00892776..9a7ae1b4 100644 --- a/src/python/calculate_pi.py +++ b/src/python/calculate_pi.py @@ -1,14 +1,14 @@ -""" Implementaço de um algoritmo de cálculo do PI """ +""" Calculating PI in Python """ def calculate_pi(number): """ - Implementação de um algoritmo de cálculo do PI. + Implementation of a PI calculation algorithm. - Argumentos: + Arguments: number: int. - Retorna o valor de PI. + Returns the value of PI. """ denominator = 1.0 operation = 1.0 diff --git a/src/python/lista_encadeada_circular.py b/src/python/circular_linked_list.py similarity index 98% rename from src/python/lista_encadeada_circular.py rename to src/python/circular_linked_list.py index f4806b83..a65b2f61 100644 --- a/src/python/lista_encadeada_circular.py +++ b/src/python/circular_linked_list.py @@ -1,4 +1,4 @@ -""" implementação de uma lista encadeada circular """ +""" Implementation of a circular linked list in Python """ import unittest diff --git a/src/python/comb_sort.py b/src/python/comb_sort.py index 01a5810c..8adde32f 100644 --- a/src/python/comb_sort.py +++ b/src/python/comb_sort.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Created By : octaviolage -# Created Date: 2022-05-15 -# version ='1.0' -# ------------------------------- +""" Comb Sort in Python """ + + def comb_sort(arr: list) -> list: """ - Implementação de um algoritmo de ordenação combinada. + Implementation of comb sort algorithm """ gap = len(arr) shrink = 1.3 @@ -28,5 +24,5 @@ def comb_sort(arr: list) -> list: from random import randint my_list = [randint(0, 100) for _ in range(10)] - print(f"Lista: {my_list}") - print(f"Ordenada: {comb_sort(my_list)}") + print(f"List: {my_list}") + print(f"Sorted list: {comb_sort(my_list)}") diff --git a/src/python/counting_sort.py b/src/python/counting_sort.py index bfab29c3..fec1bae6 100644 --- a/src/python/counting_sort.py +++ b/src/python/counting_sort.py @@ -1,29 +1,27 @@ -# Algoritmo de ordenação Counting sort em Python -# Vinicios Barbosa da Silva - 2023 -# https://github.com/ViniciosB +""" Counting sort in Python """ import random def counting_sort(arr): - # Encontra o maior elemento na lista + """Finding the max element in the list""" k = max(arr) + 1 - # Inicializa o array de contagem com zeros + """ Initialing count array of len k with 0's """ count = [0] * k - # Conta a frequência de cada elemento + """ Counts frequency of each element """ for i in arr: count[i] += 1 - # Atualiza o array de contagem para refletir a posição correta de cada elemento na lista ordenada + """ Updates count array to reflect the correct position of each element in the sorted list """ for i in range(1, k): count[i] += count[i - 1] - # Inicializa o array de resultado com zeros + """ Initializing result list with 0's """ result = [0] * len(arr) - # Preenche o array de resultado com os elementos ordenados + """ Fill result array with the sorted elements""" for i in reversed(arr): result[count[i] - 1] = i count[i] -= 1 @@ -31,15 +29,15 @@ def counting_sort(arr): return result -# Gera uma lista de n números aleatórios +""" Generate a list of n random integers """ n = 10 -lista = [random.randint(0, 100) for _ in range(n)] +list = [random.randint(0, 100) for _ in range(n)] -# Imprime a lista original sem ordenação -print(f"Lista Original: {lista}") +""" Prints original, unsorted list""" +print(f"List: {list}") -# Ordena a lista utilizando o algoritmo de Counting Sort -lista_ordenada = counting_sort(lista) +""" Sorts list using counting sort algorithm """ +sorted_list = counting_sort(list) -# Imprime a lista ordenada -print(f"Lista Ordenada: {lista_ordenada}") +""" Prints sorted list """ +print(f"Sorted list: {sorted_list}") diff --git a/src/python/doubly_linked_list.py b/src/python/doubly_linked_list.py new file mode 100644 index 00000000..1f4b73d7 --- /dev/null +++ b/src/python/doubly_linked_list.py @@ -0,0 +1,107 @@ +""" +Doubly Linked List + +The 'head' of the list always points to the first node +The 'tail' of the list always points to the final node + +None <--- | 2 | ---> None +None <--- | 2 | <---> | 5 | ---> None +None <--- | 2 | <---> | 5 | <---> | 12 | ---> None +None <--- | 2 | <---> | 5 | <---> | 12 | <---> | 20 | ---> None +""" + + +class Node: + def __init__(self, data, prev, next): + self.data = data + self.prev = prev + self.next = next + + +class DoublyLinkedList: + head = None + tail = None + + def append(self, data): + # Creates a new node pointing to None (prev and next) + new_node = Node(data, None, None) + + # If the list is empty, both head and tail point to the new node + if self.head is None: + self.head = new_node + self.tail = new_node + else: + # For a non-empty list, adjust pointers to add the new node at the end + new_node.prev = self.tail # New node's prev points to the current tail + self.tail.next = new_node # Current tail's next points to the new node + self.tail = new_node # Update tail to be the new node + + # No additional 'new_node.next = None' is needed as it's already None by default + + def delete(self, data): + """Deletes a node from the list""" + """ Current node is first node in the list""" + curr_node = self.head + + # We search for the data we want to delete + # While current node is not invalid + while curr_node is not None: + # Verifica se eh o dado que estamos buscando + if curr_node.data == data: + # If data we are looking for is in first node + # If we do not have a previous node in the list + if curr_node.prev is None: + # Head points to next node in the list + self.head = curr_node.next + # And the previous of the next node does not point to None + curr_node.next.prev = None + else: + # Example: Deleting the value 5 + # ... <---> | 2 | <---> | 5 | <---> | 12 | <---> ... + # + # Next node of 2 will now point to 12 instead of 5 + # Previous node of 12 will not point to 2 instead of 5 + # --------------- + # ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ... + curr_node.prev.next = curr_node.next + curr_node.next.prev = curr_node.prev + + # If current node does not hold desired data, move to next node + curr_node = curr_node.next + + def display(self): + """Displays all data in the list""" + print("Doubly Linked List: ") + + # Current node is head of the list + curr_node = self.head + + node = "" + # For each valid node in the list + while curr_node is not None: + if curr_node.prev is None: + node += "None " + node += "<---> | " + str(curr_node.data) + " | " + if curr_node.next is None: + node += "<---> None" + + curr_node = curr_node.next + print(node) + print("=" * 80) + + +list = DoublyLinkedList() + +list.append(2) +list.display() +list.append(5) +list.display() +list.append(12) +list.display() +list.append(20) +list.display() + +list.delete(12) +list.display() +list.delete(5) +list.display() diff --git a/src/python/dynamic_stack.py b/src/python/dynamic_stack.py index e6743984..129b73a8 100644 --- a/src/python/dynamic_stack.py +++ b/src/python/dynamic_stack.py @@ -41,7 +41,7 @@ def show(self) -> None: def main() -> None: dynamic_stack = DynamicStack() - print(f"Push(1,2,4):") + print("Push(1,2,4):") dynamic_stack.push(1) dynamic_stack.push(2) dynamic_stack.push(4) diff --git a/src/python/exponenciacao.py b/src/python/exponenciacao.py deleted file mode 100644 index 17cf2d91..00000000 --- a/src/python/exponenciacao.py +++ /dev/null @@ -1,21 +0,0 @@ -""" Algoritmo de exponenciação """ - - -def exponenciacao(base, expoente): - """ - Implementação de um algoritmo de exponenciação. - - Argumentos: - base: int. Base da operação - expoente: int. Expoente da operação. - - Retorna o resultado da operação de exponenciação - """ - result = base - for _ in range(0, expoente - 1): - result *= base - return result - - -print(exponenciacao(5, 2)) -print(exponenciacao(5, 5)) diff --git a/src/python/exponenciacao_recursiva.py b/src/python/exponenciacao_recursiva.py deleted file mode 100644 index d38aacda..00000000 --- a/src/python/exponenciacao_recursiva.py +++ /dev/null @@ -1,22 +0,0 @@ -""" Algoritmo de exponenciação implementado com recursão. """ - - -def exponenciacao_recursiva(base, expoente): - """Implementação de um algoritmo de exponenciação. - - Args: - base (int): Base da operação - expoente (int): Expoente da operação - - Returns: - Retorna o resultado da operaçao de exponenciação. - """ - if expoente == 0: - return 1 - - return base * exponenciacao_recursiva(base, expoente - 1) - - -if __name__ == "__main__": - print(exponenciacao_recursiva(5, 2)) - print(exponenciacao_recursiva(5, 5)) diff --git a/src/python/exponentiation.py b/src/python/exponentiation.py new file mode 100644 index 00000000..e54f9f38 --- /dev/null +++ b/src/python/exponentiation.py @@ -0,0 +1,22 @@ +""" Iterative exponentiation algorithm """ + + +def exponentiation(base, exponent): + """ + Implementation of an exponentiation algorithm. + + Arguments: + base (int): Base of operation + exponent (int): Exponent of operation + + Returns: + Returns the result of the exponentiation operation. + """ + result = base + for _ in range(0, exponent - 1): + result *= base + return result + + +print(exponentiation(5, 2)) +print(exponentiation(5, 5)) diff --git a/src/python/exponentiation_recursive.py b/src/python/exponentiation_recursive.py new file mode 100644 index 00000000..1db76fd2 --- /dev/null +++ b/src/python/exponentiation_recursive.py @@ -0,0 +1,23 @@ +""" Recursive exponentiation algorithm """ + + +def exponentiation_recursive(base, exponent): + """ + Implementation of an exponentiation algorithm using recursion. + + Arguments: + base (int): Base of operation + exponent (int): Exponent of operation + + Returns: + Returns the result of the exponentiation operation. + """ + if exponent == 0: + return 1 + + return base * exponentiation_recursive(base, exponent - 1) + + +if __name__ == "__main__": + print(exponentiation_recursive(5, 2)) + print(exponentiation_recursive(5, 5)) diff --git a/src/python/factorial.py b/src/python/factorial.py new file mode 100644 index 00000000..48ef04c4 --- /dev/null +++ b/src/python/factorial.py @@ -0,0 +1,20 @@ +""" Iterative factorial algorithm """ + + +def factorial(num): + """ + Implementation of the factorial algorithm iteratively. + + Arguments: + num: int. the number of which you want to obtain the factorial. + + Returns the result of the factorial operation + """ + aux = 1 + for i in range(2, num + 1): + aux = aux * i + return aux + + +if __name__ == "__main__": + print(factorial(5)) diff --git a/src/python/factorial_recursive.py b/src/python/factorial_recursive.py new file mode 100644 index 00000000..d497d22d --- /dev/null +++ b/src/python/factorial_recursive.py @@ -0,0 +1,19 @@ +""" Recursive factorial algorithm """ + + +def factorial_recursive(num): + """ + Implementation of factorial algorithm using recursion + + Arguments: + num: int. the number of which you want to obtain the factorial. + + Returns the result of the factorial operation + """ + if num == 1: + return 1 + + return num * factorial_recursive(num - 1) + + +print(factorial_recursive(5)) diff --git a/src/python/fatorial.py b/src/python/fatorial.py deleted file mode 100644 index 31146ba8..00000000 --- a/src/python/fatorial.py +++ /dev/null @@ -1,20 +0,0 @@ -""" Uma implementação simples de um algoritmo fatorial """ - - -def fatorial(num): - """ - Uma implementação simples de um algoritmo de fatorial. - - Argumentos: - num: int. o número do qual deseja-se obter o fatorial. - - Retorna o resultado da operação. - """ - aux = 1 - for i in range(2, num + 1): - aux = aux * i - return aux - - -if __name__ == "__main__": - print(fatorial(5)) diff --git a/src/python/fatorial_recursiva.py b/src/python/fatorial_recursiva.py deleted file mode 100644 index cec8de56..00000000 --- a/src/python/fatorial_recursiva.py +++ /dev/null @@ -1,19 +0,0 @@ -""" Algoritmo de fatorial implementado com recursão """ - - -def fatorial_recursivo(numero): - """ - Implementação de um algoritmo de fatorial com recursão. - - Argumentos: - numero: int. o número do qual deseja-se obter o fatorial. - - Retorna o resultado da operação. - """ - if numero == 1: - return 1 - - return numero * fatorial_recursivo(numero - 1) - - -print(fatorial_recursivo(5)) diff --git a/src/python/fibonacci_iterative.py b/src/python/fibonacci_iterative.py index 2df05079..a7ad7dc9 100755 --- a/src/python/fibonacci_iterative.py +++ b/src/python/fibonacci_iterative.py @@ -1,11 +1,10 @@ """ -Implementaço de vários algoritmos Fibonacci +Iterative Fibonacci Algorithm -A lib "time" foi utilizada para marcar o tempo de -execução dos algoritmos em segundos +The lib "time" was used to mark the time of +execution of algorithms in seconds """ -import functools import time @@ -20,13 +19,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run iterative algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Iterativa", fibonacci) + main("Iterative", fibonacci) diff --git a/src/python/fibonacci_memoization.py b/src/python/fibonacci_memoization.py index 1ff01958..1a8c8e6e 100644 --- a/src/python/fibonacci_memoization.py +++ b/src/python/fibonacci_memoization.py @@ -1,10 +1,16 @@ +""" +Recursive Fibonacci Algorithm using a Cache +""" + import functools import time @functools.lru_cache(maxsize=None) def fibonacci(number): - """Fibonacci recursiva com cache.""" + """ + Recursive fibonacci algorithm with cache + """ if number < 2: return number return fibonacci(number - 1) + fibonacci(number - 2) @@ -12,13 +18,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Fibonacci Memoization:", fibonacci) + main("Memorization:", fibonacci) diff --git a/src/python/fibonacci_recursive.py b/src/python/fibonacci_recursive.py index 1bbba363..106d7f36 100644 --- a/src/python/fibonacci_recursive.py +++ b/src/python/fibonacci_recursive.py @@ -1,15 +1,18 @@ """ -Implementaço de vários algoritmos Fibonacci +Recursive Fibonacci Algorithm -A lib "time" foi utilizada para marcar o tempo de -execução dos algoritmos em segundos +The lib "time" was used to mark the time of +execution of algorithms in seconds """ import time def fibonacci(number): - """Fibonnaci recursiva.""" + """ + Recursive Fibonacci + """ + if number < 2: return number return fibonacci(number - 1) + fibonacci(number - 2) @@ -17,13 +20,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run the algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Recursiva", fibonacci) + main("Recursive", fibonacci) diff --git a/src/python/fila.py b/src/python/fila.py deleted file mode 100644 index 791d78a6..00000000 --- a/src/python/fila.py +++ /dev/null @@ -1,35 +0,0 @@ -""" Implementação da estrutura de dados "fila" """ - -import random - - -class Queue: - def __init__(self): - self.__queue = [] - - def enqueue(self, value): - self.__queue.append(value) - - def dequeue(self): - return self.__queue.pop(0) - - def show(self): - print(f"Queue: {self.__queue}") - - -def main(): - queue = Queue() - - for _ in range(0, 10): - queue.enqueue(random.randint(10, 99)) - - queue.show() - - queue.dequeue() - queue.dequeue() - - queue.show() - - -if __name__ == "__main__": - main() diff --git a/src/python/busca_em_grafo.py b/src/python/graph_search.py similarity index 94% rename from src/python/busca_em_grafo.py rename to src/python/graph_search.py index dfe40378..195b917f 100644 --- a/src/python/busca_em_grafo.py +++ b/src/python/graph_search.py @@ -1,6 +1,4 @@ # Grafos - Algoritmos de BFS e DFS em Python -# Bruno Dantas de Paiva - 2021 -# https://github.com/DantasB from collections import deque diff --git a/src/python/compressao_huffman.py b/src/python/huffman.py similarity index 100% rename from src/python/compressao_huffman.py rename to src/python/huffman.py diff --git a/src/python/insertion_sort.py b/src/python/insertion_sort.py index 431972e1..b97eef95 100644 --- a/src/python/insertion_sort.py +++ b/src/python/insertion_sort.py @@ -1,59 +1,63 @@ -"""Implementação do algoritmo insertion sort iterativo e recursivo.""" +""" Insertion Sort in Python (Iterative and Recursive) """ -def insertion_sort_iterativo(vetor): +def insertion_sort_iterative(vector): """ - Implementação do algoritmo de insertion sort iterativo. + Implementation of insertion sort iteratively. - Args: - vetor (list): lista que será ordenada. + Arguments: + vector (list): list to be sorted. Returns: - Retorna a lista ordenada. + Returns the sorted list. """ - for i in range(1, len(vetor)): - chave = vetor[i] + for i in range(1, len(vector)): + key = vector[i] aux = i - 1 - while aux >= 0 and vetor[aux] > chave: - vetor[aux + 1] = vetor[aux] + while aux >= 0 and vector[aux] > key: + vector[aux + 1] = vector[aux] aux -= 1 - vetor[aux + 1] = chave - return vetor + vector[aux + 1] = key + return vector -def insertion_sort_recursivo(vetor, indice): +def insertion_sort_recursive(vector, index): """ - Implementação do algoritmo de insertion sort recursivo. + Implementation of insertion sort recursively. - Args: - vetor (list): lista que será ordenada. - indice (int): índice do elemento a ser ordenado na lista. + Arguments: + vector (list): list to be sorted. + index (int): index of the element to be sorted in the list. Returns: - Retorna a lista ordenada. + Returns the sorted list. """ - aux = indice - while vetor[aux] < vetor[aux - 1]: - temp = vetor[aux] - vetor[aux] = vetor[aux - 1] - vetor[aux - 1] = temp + aux = index + while vector[aux] < vector[aux - 1]: + temp = vector[aux] + vector[aux] = vector[aux - 1] + vector[aux - 1] = temp aux -= 1 if aux == 0: break - if indice < len(vetor) - 1: - insertion_sort_recursivo(vetor, indice + 1) - return vetor + if index < len(vector) - 1: + insertion_sort_recursive(vector, index + 1) + return vector if __name__ == "__main__": - lista_nao_ordenada = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] - print("Lista não ordenada:") - print(lista_nao_ordenada) + list1 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] + print("Unsorted list: ") + print(list1) - lista_nao_ordenada = insertion_sort_iterativo(lista_nao_ordenada) - print("Lista ordenada com insertion sort iterativo:") - print(lista_nao_ordenada) + list1 = insertion_sort_iterative(list1) + print("Sorted list with iterative insertion sort: ") + print(list1) - lista_nao_ordenada = insertion_sort_recursivo(lista_nao_ordenada, 1) - print("Lista ordenada com insertion sort recursivo:") - print(lista_nao_ordenada) + list2 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] + print("Unsorted list: ") + print(list2) + + list2 = insertion_sort_recursive(list2, 1) + print("Sorted list with recursive insertion sort: ") + print(list2) diff --git a/src/python/interpolation_search.py b/src/python/interpolation_search.py index 76ac1dec..3cb5687c 100644 --- a/src/python/interpolation_search.py +++ b/src/python/interpolation_search.py @@ -1,6 +1,4 @@ # Busca por interpolação em Python -# Bruno Dantas de Paiva - 2021 -# https://github.com/DantasB def interpolation_search(array, x): diff --git a/src/python/passeio_do_cavalo.py b/src/python/knights_tour.py similarity index 100% rename from src/python/passeio_do_cavalo.py rename to src/python/knights_tour.py diff --git a/src/python/busca_sequencial.py b/src/python/linear_search.py similarity index 100% rename from src/python/busca_sequencial.py rename to src/python/linear_search.py diff --git a/src/python/busca_sequencial_recursiva.py b/src/python/linear_search_recursive.py similarity index 90% rename from src/python/busca_sequencial_recursiva.py rename to src/python/linear_search_recursive.py index f164b299..01efd74b 100644 --- a/src/python/busca_sequencial_recursiva.py +++ b/src/python/linear_search_recursive.py @@ -1,4 +1,3 @@ -""" Implementaçao do algoritmo de busca sequencial com recursão """ """Implementation of the sequential search algorithm with recursion.""" diff --git a/src/python/busca_sentinela.py b/src/python/linear_search_sentinel.py similarity index 100% rename from src/python/busca_sentinela.py rename to src/python/linear_search_sentinel.py diff --git a/src/python/lista_duplamente_encadeada.py b/src/python/lista_duplamente_encadeada.py deleted file mode 100644 index 7b800113..00000000 --- a/src/python/lista_duplamente_encadeada.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -Lista Duplamente Encadeada - -A cabeca da lista sempre 'aponta' para o primeiro no -O rabo da lista sempre 'aponta' para o ultimo no - -None <--- | 2 | ---> None -None <--- | 2 | <---> | 5 | ---> None -None <--- | 2 | <---> | 5 | <---> | 12 | ---> None -None <--- | 2 | <---> | 5 | <---> | 12 | <---> | 20 | ---> None -""" - - -class No: - def __init__(self, dado, anterior, proximo): - self.dado = dado - self.anterior = anterior - self.proximo = proximo - - -class ListaDuplamenteEncadeada: - cabeca = None - rabo = None - - def acrescentar(self, dado): - """Acrescenta um novo no a lista.""" - # Cria um novo no apontando para None (anterior e proximo) - novo_no = No(dado, None, None) - - # Se a cabeca eh None a lista esta vazia - # Tanto a cabeca quanto o rabo recebem o novo no - if self.cabeca is None: - self.cabeca = novo_no - self.rabo = novo_no - # Caso contrario, se ja existir algum valor na lista - else: - # O anterior 'aponta' para o rabo (ultimo no adicionado) - novo_no.anterior = self.rabo - # O proximo sempre aponta para None - novo_no.proximo = None - # O proximo do rabo sempre aponta para o novo no - self.rabo.proximo = novo_no - # O rabo agora eh o novo no - self.rabo = novo_no - - def remover(self, dado): - """Remove um no da lista.""" - # O no atual eh o primeiro no da lista - no_atual = self.cabeca - - # Vamos procurar pelo dado que queremos remover - # Equanto o no atual for valido - while no_atual is not None: - # Verifica se eh o dado que estamos buscando - if no_atual.dado == dado: - # Se o dado que estamos buscando esta no primeiro no - # da lista, nao temos anterior - if no_atual.anterior is None: - # A cabeca 'aponta' para o proximo no da lista - self.cabeca = no_atual.proximo - # E o anterior do proximo no aponta para None - no_atual.proximo.anterior = None - else: - # Exemplo: Removendo o valor 5 - # ... <---> | 2 | <---> | 5 | <---> | 12 | <---> ... - # - # O proximo do valor 2 passa a apontar para o 12 e - # o anterior do valor 12 passa a apontar para o 2 - # --------------- - # ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ... - no_atual.anterior.proximo = no_atual.proximo - no_atual.proximo.anterior = no_atual.anterior - - # Se nao eh o no que estamos buscando va para o proximo - no_atual = no_atual.proximo - - def mostrar(self): - """Mostra todos os dados da lista.""" - print("Lista Duplamente Encadeada:") - - # O no atual eh o primeiro no da lista - no_atual = self.cabeca - - no = "" - # Para cada no valido da lista - while no_atual is not None: - if no_atual.anterior is None: - no += "None " - no += "<---> | " + str(no_atual.dado) + " | " - if no_atual.proximo is None: - no += "<---> None" - - no_atual = no_atual.proximo - print(no) - print("=" * 80) - - -lista = ListaDuplamenteEncadeada() - -lista.acrescentar(2) -lista.mostrar() -lista.acrescentar(5) -lista.mostrar() -lista.acrescentar(12) -lista.mostrar() -lista.acrescentar(20) -lista.mostrar() - -lista.remover(12) -lista.mostrar() -lista.remover(5) -lista.mostrar() diff --git a/src/python/compressao_lz77.py b/src/python/lz77.py similarity index 99% rename from src/python/compressao_lz77.py rename to src/python/lz77.py index 249444f4..fba93b12 100644 --- a/src/python/compressao_lz77.py +++ b/src/python/lz77.py @@ -1,4 +1,3 @@ -import io import sys diff --git a/src/python/maximo_recursivo.py b/src/python/max_recursive.py similarity index 100% rename from src/python/maximo_recursivo.py rename to src/python/max_recursive.py diff --git a/src/python/busca_em_labirinto.py b/src/python/maze_solving.py similarity index 100% rename from src/python/busca_em_labirinto.py rename to src/python/maze_solving.py diff --git a/src/python/maximo_minimo_dc.py b/src/python/min_max_dc.py similarity index 89% rename from src/python/maximo_minimo_dc.py rename to src/python/min_max_dc.py index 47f22171..771ecd9e 100644 --- a/src/python/maximo_minimo_dc.py +++ b/src/python/min_max_dc.py @@ -1,6 +1,4 @@ # Mínimo e Máximo de um array usando divide & conquer -# Bruno Dantas de Paiva - 2021 -# https://github.com/DantasB import random diff --git a/src/python/min_max_iterativo.py b/src/python/min_max_iterative.py similarity index 100% rename from src/python/min_max_iterativo.py rename to src/python/min_max_iterative.py diff --git a/src/python/maximo_minimo_recursivo.py b/src/python/min_max_recursive.py similarity index 100% rename from src/python/maximo_minimo_recursivo.py rename to src/python/min_max_recursive.py diff --git a/src/python/palindromo.py b/src/python/palindrome.py similarity index 100% rename from src/python/palindromo.py rename to src/python/palindrome.py diff --git a/src/python/queue.py b/src/python/queue.py new file mode 100644 index 00000000..1730f820 --- /dev/null +++ b/src/python/queue.py @@ -0,0 +1,89 @@ +class Node: + def __init__(self, value): + self.value = value + self.left_ptr = None + + @property + def prev(self): + return self.left_ptr + + @prev.setter + def prev(self, ptr): + self.left_ptr = ptr + + @property + def get_value(self): + return self.value + + +class Queue: + def __init__(self): + self.head = None + self.tail = None + self.length = 0 + + def enqueue(self, value): + new = Node(value) + self.length += 1 + # if empty make new node both head and tail of queue + if self.head is None: + self.head = new + self.tail = new + # otherwise add new node to end of queue and update tail + else: + self.tail.prev = new + self.tail = new + + def dequeue(self): + if self.length == 0: + print("Queue is empty, cannot dequeue") + return + else: + tmp = self.head + self.head = self.head.prev + self.length -= 1 + return tmp.get_value + + def show(self): + # first element is the head of the queue + ptr = self.head + val = [] + while ptr is not None: + val.append(ptr.get_value) + ptr = ptr.prev + + print(val) + + def length(self): + return self.length + + +def main(): + queue = Queue() + + print("Queuing 1 and 7") + queue.enqueue(1) + queue.show() + print(f"Queue is length {queue.length}") + queue.enqueue(7) + queue.show() + print(f"Queue is length {queue.length}") + + print(f"Dequeuing {queue.dequeue()}") + queue.show() + print(f"Queue is length {queue.length}") + print(f"Dequeuing {queue.dequeue()}") + queue.show() + print(f"Queue is length {queue.length}") + + print(f"Dequeuing {queue.dequeue()}") + print(f"Queue is length {queue.length}") + + print("Queueing 12") + queue.enqueue(12) + queue.show() + print(f"Queue is length {queue.length}") + + +if __name__ == "__main__": + main() diff --git a/src/python/lista_com_pilhas.py b/src/python/queue_using_stacks.py similarity index 100% rename from src/python/lista_com_pilhas.py rename to src/python/queue_using_stacks.py diff --git a/src/python/quick_sort.py b/src/python/quick_sort.py index 7c1dd5bd..a1015cdd 100644 --- a/src/python/quick_sort.py +++ b/src/python/quick_sort.py @@ -1,15 +1,15 @@ -""" Implementaçao do algoritmo quick sort """ +""" Quick Sort in Python """ def swap(a_list, pos1, pos2): - """Troca a posição de dois itens em uma lista""" + """Swaps the position of two items in a list""" temp = a_list[pos1] a_list[pos1] = a_list[pos2] a_list[pos2] = temp def partition(a_list, start, end): - """Divide uma lista""" + """Splits a list""" pivot = a_list[start] while True: while a_list[start] < pivot: @@ -28,7 +28,7 @@ def partition(a_list, start, end): def quick_sort(a_list, start, end): - """Algoritmo de quick sort""" + """Quick sort algorithm""" if start < end: part = partition(a_list, start, end) quick_sort(a_list, start, part) diff --git a/src/python/radix_sort.py b/src/python/radix_sort.py new file mode 100644 index 00000000..fc91c414 --- /dev/null +++ b/src/python/radix_sort.py @@ -0,0 +1,55 @@ +import random + + +def radix_sort(arr): + # Find the maximum number to know the number of digits + max_num = max(arr) + + # Do counting sort for every digit, starting from the least significant digit + exp = 1 + while max_num // exp > 0: + counting_sort(arr, exp) + exp *= 10 + + +def counting_sort(arr, exp): + n = len(arr) + output = [0] * n + count = [0] * 10 + + for i in range(n): + index = arr[i] // exp + count[index % 10] += 1 + + for i in range(1, 10): + count[i] += count[i - 1] + + i = n - 1 + while i >= 0: + index = arr[i] // exp + output[count[index % 10] - 1] = arr[i] + count[index % 10] -= 1 + i -= 1 + + for i in range(n): + arr[i] = output[i] + + +def main(): + print("Fixed Testing Array") + arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66] + print("Unsorted array:", arr) + radix_sort(arr) + print("Sorted array:", arr) + + print("Random Testing Array") + arr = [] + for i in range(0, 10): + arr.append(random.randint(0, 20)) + print("Unsorted array:", arr) + radix_sort(arr) + print("Sorted array:", arr) + + +if __name__ == "__main__": + main() diff --git a/src/python/lista_encadeada.py b/src/python/singly_linked_list.py similarity index 97% rename from src/python/lista_encadeada.py rename to src/python/singly_linked_list.py index fed7cf5c..482d3037 100644 --- a/src/python/lista_encadeada.py +++ b/src/python/singly_linked_list.py @@ -1,8 +1,5 @@ """ -!/usr/bin/env python --*- coding: utf-8 -*- - -Lista Ligada: +Linked List: _________ _________ _________ _________ head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None --------- --------- --------- --------- diff --git a/src/python/skip_list.py b/src/python/skip_list.py new file mode 100644 index 00000000..1632a33f --- /dev/null +++ b/src/python/skip_list.py @@ -0,0 +1,471 @@ +""" +Skip list with: + - skip connections made at random + - sorted order + - removing a node leaves a pseudo dead node + - automatically rebuilds with only alive nodes once half of nodes are dead + - can be rebuilt whenever desired as well + - does not allow for duplicate numbers + +""" + +import random + + +class Node: + def __init__(self, value): + self.value = value + self._down = None + + # layer number, 1 if on bottom layer + self._layer = None + self._right = None + + self._isAlive = True + + @property + def status(self): + return self._isAlive + + @property + def kill(self): + self._isAlive = False + + @property + def next(self): + return self._right + + @next.setter + def next(self, ptr): + self._right = ptr + + @property + def get_value(self): + return self.value + + @property + def layer(self): + return self._layer + + @layer.setter + def layer(self, val): + self._layer = val + + @property + def down(self): + return self._down + + @down.setter + def down(self, ptr): + self._down = ptr + + +class Skip_List: + def __init__(self) -> None: + self.head = None + + # current height of skip list + self.height = 1 + + # these counts do not consider duplicate elements for skip connections + self.size = 0 # number of elements, alive or dead + self.num_alive = 0 # number of living elements + self.num_dead = 0 # number of dead elements + + def reset(self): + # reinitialize values + self.head = None + self.height = 1 + self.size = 0 + self.num_alive = 0 + self.num_dead = 0 + + def status(self): + print( + f"There are {self.size} element(s) in the skip list, of which " + f"{self.num_alive} are alive and {self.num_dead} are dead" + ) + print(f"The list has {self.height} layers") + + def insert(self, value): + new = Node(value) + # if empty + if self.size == 0: + # make new node the head + self.head = new + new.layer = 1 + + # if new value is less than head + elif value < self.head.get_value: + # update head + tmp = self.head + self.head = new + new.layer = tmp.layer + new.next = tmp + # create skip layers of new head + i = tmp.layer + if i > 1: + curr = tmp.down + prev_new = new + curr_new = Node(value) + curr_new.layer = curr.layer + while i > 1: + prev_new.down = curr_new + curr_new.next = curr + curr_new.layer = curr.layer + + curr = curr.down + prev_new = curr_new + curr_new = Node(value) + + i -= 1 + else: + curr = self.head + while True: + # move to the right if possible + if curr.next is not None: + # move to the right if next value is still smaller + if curr.next.get_value < value: + curr = curr.next + # element already exists in the list + elif curr.next.get_value == value: + print("This value is already in the list") + return + # if next value is larger you can move down a level + elif curr.down is not None: + curr = curr.down + # otherwise you have found your spot + else: + tmp = curr.next + curr.next = new + new.layer = 1 + new.next = tmp + break + # move down if you cannot move right + elif curr.down is not None: + curr = curr.down + # otherwise you have reached the end of the list + else: + curr.next = new + new.layer = 1 + break + + # coin flips to see if new element gets skip connections + coin = random.randint(0, 1) + if coin: + new_layer = 2 + prev_new = new + + while coin: + print(f"Skip connection added on {new_layer}!") + curr_new = Node(value) + + # if adding to skip list height + if new_layer > self.height: + # update head + new_head = Node(self.head.get_value) + new_head.layer = new_layer + new_head.down = self.head + self.head = new_head + self.height += 1 + + curr = self.head + + # start at head and move down to layer that gets new skip connection + while curr.layer != new_layer: + curr = curr.down + + # move along layer new connection is being added + while True: + # found spot at end of skip connections + if curr.next is None: + # insert + curr.next = curr_new + curr_new.layer = new_layer + + # update curr_new values + curr_new.down = prev_new + + # update previous new + prev_new = curr_new + break + # keep moving to the right + elif curr.next.get_value < value: + curr = curr.next + # found skip connection location between values + else: + # insert between + tmp = curr.next + curr.next = curr_new + curr_new.next = tmp + + # update new node values + curr_new.layer = new_layer + curr_new.down = prev_new + + # update previous new + prev_new = curr_new + break + + # flip another coin and increase list level + coin = random.randint(0, 1) + new_layer += 1 + + # update skip list values + self.size += 1 + self.num_alive += 1 + + def find(self, value): + """ + returns a pointer to the highest element in skip list with this value + if it is alive and exists, + otherwise returns none and not considered to be in the list + + """ + curr = self.head + if curr.get_value == value: + print(f"{value} is in the list") + return curr + + while True: + # if you can move right + if curr.next is not None: + # keep moving right if value not found yet and if it can still be in the list + if curr.next.get_value < value: + curr = curr.next + # if the next value is what you are looking + elif curr.next.get_value == value: + # check if it is a living node + if curr.next.status: + print(f"{value} is in the list") + return curr.next + else: + print(f"{value} is not in the list") + return None + elif curr.down is None: + # no need to keep looking all other values are larger and cant go down + print(f"{value} is not in the list") + return None + else: + curr = curr.down + # move down if you cant move right + elif curr.down is not None: + curr = curr.down + # no where else to go! end of the list + else: + print(f"{value} is not in the list") + return None + + def remove(self, value): + """ + psuedo deletes an element with a value of value if it exists + """ + curr = self.find(value) + + # remove highest occurance of this element + if curr is not None: + print(f"{value} was removed from the list") + self.num_dead += 1 + self.num_alive -= 1 + i = curr.layer + curr.kill + # remove all other occurances of this element + while i > 1: + curr = curr.down + curr.kill + i = curr.layer + + # check if rebuild is needed + if self.num_dead / self.size > 0.5: + self.rebuild() + + else: + print(f"{value} was not in the list") + + def show_layers(self, show_type="alive"): + """ + prints out each layer of the skip list + + show_type + - 'both' will print out both alive and dead elements + - 'alive' will only print alive elements + - 'dead' will only print dead elements + - treats anything else as 'both' + """ + if self.size == 0: + print("The list is empty") + return + + if show_type == "alive": + print("List contains these living nodes at the following Layers:") + elif show_type == "dead": + print("List contains these dead nodes at the following Layers:") + else: + print("List contains these living and dead nodes at the following Layers:") + + # for each layer + for curr_layer in range(self.height, 0, -1): + curr = self.head + vals = [] # values in this layer + # move down to layer curr_layer + while curr.layer != curr_layer: + curr = curr.down + + # add elements until reaching end of this layer + while curr is not None: + if show_type == "alive": + if curr.status: + vals.append(curr.get_value) + elif show_type == "dead": + if not curr.status: + vals.append(curr.get_value) + else: + vals.append(curr.get_value) + + curr = curr.next + + print(f"\tLayer {curr_layer}: {vals}") + + def rebuild(self): + """ + rebuild the data structure with only the alive nodes + """ + + print("\n\n\nRebuilding Skip List!\n\n\n") + vals = [] + + # find values of all living nodes + curr = self.head + + # move to layer 1 + while curr.layer != 1: + curr = curr.down + + # traverse list adding values of living elements + while curr is not None: + if curr.status: + vals.append(curr.get_value) + curr = curr.next + + # reinitalize values of skip list + self.reset() + + for val in vals: + self.insert(val) + + +def main(): + L = Skip_List() + + # testing first insert + print("\n\n-------- Inserting 3 --------") + L.insert(3) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing second insert + print("\n\n-------- Inserting 4 --------") + L.insert(4) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing insert of new minimum + print("\n\n-------- Inserting 1 --------") + L.insert(1) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing duplicate insert + print("\n\n-------- Inserting Duplicate 3 --------") + L.insert(3) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing removal + print("\n\n-------- Removing 3 --------") + L.remove(3) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing removal of non living element + print("\n\n-------- Removing 3 Again--------") + L.remove(3) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing removal of element not in list at all + print("\n\n-------- Removing 5 (was never inserted) --------") + L.remove(5) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing removal to empty and rebuilding + print("\n\n-------- Removing Until Empty --------") + L.remove(1) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + L.remove(4) + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing arbitrary inserts + print("\n\n------------ Arbitrary Inserts ------------\n\n") + vals = [] + for i in range(0, 50): + val = random.randint(0, 100) + print(f"\n\n---Inserting {val}---") + vals.append(val) + L.insert(val) + + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing arbitrary removals + print("\n\n------------ Arbitrary Removals ------------\n\n") + for i in range(0, 30): + idx = random.randint(0, len(vals) - 1) + val = vals.pop(idx) + print(f"\n\n---Removing {val}---") + L.remove(val) + + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + # testing arbitary removal of number not in list (dead or alive) + print("\n\n------------ Arbitrary Non-Existant Removals ------------\n\n") + for i in range(0, 10): + val = random.randint(100, 200) + print(f"\n\n---Removing {val}---") + L.remove(val) + + L.status() + L.show_layers() + L.show_layers("dead") + L.show_layers("both") + + +if __name__ == "__main__": + main() diff --git a/src/python/lista_sequencial_ordenada.py b/src/python/sorted_linked_list.py similarity index 100% rename from src/python/lista_sequencial_ordenada.py rename to src/python/sorted_linked_list.py diff --git a/src/python/pilha.py b/src/python/stack.py similarity index 100% rename from src/python/pilha.py rename to src/python/stack.py diff --git a/src/python/tim_sort.py b/src/python/timsort.py similarity index 100% rename from src/python/tim_sort.py rename to src/python/timsort.py diff --git a/src/python/torre_de_hanoi.py b/src/python/tower_of_hanoi.py similarity index 100% rename from src/python/torre_de_hanoi.py rename to src/python/tower_of_hanoi.py diff --git a/src/python/travelling_salesman.py b/src/python/travelling_salesman.py new file mode 100644 index 00000000..f937ffaa --- /dev/null +++ b/src/python/travelling_salesman.py @@ -0,0 +1,161 @@ +from itertools import permutations + + +def calculate_total_distance(path, distances): + """ + Calculate the total distance of a path through cities. + + Args: + path (list of int): A list representing the order of cities to visit. + distances (list of lists of int): A distance matrix between cities. + + Returns: + int: The total distance of the path. + + Example: + >>> distances = [[0, 2, 9, 10], [1, 0, 6, 4], [15, 7, 0, 8], [6, 3, 12, 0]] + >>> calculate_total_distance([0, 1, 2, 3, 0], distances) + 21 + """ + total_distance = 0 + for i in range(len(path) - 1): + total_distance += distances[path[i]][path[i + 1]] + total_distance += distances[path[-1]][path[0]] + return total_distance + + +def traveling_salesman_bruteforce(distances): + """ + Find the shortest path through cities using brute force. + + Args: + distances (list of lists of int): A distance matrix between cities. + + Returns: + tuple: A tuple containing the shortest path (list of int) and the shortest distance (int). + + Example: + >>> distances = [[0, 2, 9, 10], [1, 0, 6, 4], [15, 7, 0, 8], [6, 3, 12, 0]] + >>> traveling_salesman_bruteforce(distances) + ([0, 1, 3, 2], 21) + """ + num_cities = len(distances) + all_cities = list(range(num_cities)) + shortest_path = None + shortest_distance = float("inf") + + for path in permutations(all_cities): + distance = calculate_total_distance(path, distances) + if distance < shortest_distance: + shortest_distance = distance + shortest_path = path + + return shortest_path, shortest_distance + + +def create_distance_matrix(num_cities): + """ + Create a distance matrix for a given number of cities. + + Args: + num_cities (int): The number of cities. + + Returns: + list of lists of int: A distance matrix between cities. + + Example: + >>> create_distance_matrix(4) + [[0, 2, 9, 10], [2, 0, 6, 4], [9, 6, 0, 8], [10, 4, 8, 0]] + """ + distances = [] + for i in range(num_cities): + row = [] + for j in range(num_cities): + if i == j: + row.append(0) + elif j > i: + distance = int( + input(f"Enter distance between City {i + 1} and City {j + 1}: ") + ) + row.append(distance) + else: + row.append(distances[j][i]) + distances.append(row) + return distances + + +def print_distance_matrix(distances): + """ + Print the distance matrix. + + Args: + distances (list of lists of int): A distance matrix between cities. + + Example: + >>> distances = [[0, 2, 9, 10], [1, 0, 6, 4], [15, 7, 0, 8], [6, 3, 12, 0]] + >>> print_distance_matrix(distances) + Distance Matrix: + [0, 2, 9, 10] + [2, 0, 6, 4] + [9, 6, 0, 8] + [10, 4, 8, 0] + """ + print("Distance Matrix:") + for row in distances: + print(row) + + +def print_city_path(path): + """ + Print the shortest path through cities. + + Args: + path (list of int): A list representing the order of cities to visit. + + Example: + >>> print_city_path([0, 1, 3, 2]) + Shortest Path: City 1 -> City 2 -> City 4 -> City 3 + """ + city_path = [f"City {city + 1}" for city in path] + print("Shortest Path:", " -> ".join(city_path)) + + +def main_menu(): + """ + Display a menu for the traveling salesman problem and handle user input. + + Example: + >>> # This function interacts with the user, so no specific doctests are provided. + >>> # You can run this function manually to test the menu functionality. + >>> main_menu() + """ + while True: + print("\nMenu:") + print("1. Create a distance matrix") + print("2. Find the shortest path") + print("3. Exit") + + choice = input("Enter your choice: ") + + if choice == "1": + num_cities = int(input("Enter the number of cities: ")) + distances = create_distance_matrix(num_cities) + print_distance_matrix(distances) + elif choice == "2": + if "distances" in locals(): + shortest_path, shortest_distance = traveling_salesman_bruteforce( + distances + ) + print_city_path(shortest_path) + print("Shortest Distance:", shortest_distance) + else: + print("Please create a distance matrix first.") + elif choice == "3": + print("Goodbye!") + break + else: + print("Invalid choice. Please select a valid option.") + + +if __name__ == "__main__": + main_menu() diff --git a/src/python/soma_dois_numeros.py b/src/python/two_sum.py similarity index 100% rename from src/python/soma_dois_numeros.py rename to src/python/two_sum.py diff --git a/src/python/unordered_linked_list.py b/src/python/unordered_linked_list.py new file mode 100644 index 00000000..230547ed --- /dev/null +++ b/src/python/unordered_linked_list.py @@ -0,0 +1,113 @@ +class Node: + def __init__(self, value, rptr=None) -> None: + self.value = value + self.rptr = rptr + + @property + def get_value(self): + return self.value + + @property + def next(self): + return self.rptr + + @next.setter + def next(self, ptr): + self.rptr = ptr + + +class Unordered_Linked_List: + def __init__(self) -> None: + self.first_node = None + + def insert(self, value): + # inserts a new node with the given value + if self.first_node is None: + self.first_node = Node(value) + else: + tmp = Node(value) + tmp.next = self.first_node + self.first_node = tmp + + def find(self, value): + # returns true if the specified value is in your list + ptr = self.first_node + while ptr is not None: + if ptr.value == value: + print(f"{value} is in your list") + return True + else: + ptr = ptr.next + + print(f"{value} is not in your list") + return False + + def size(self): # returns size of the list + ptr = self.first_node + i = 0 + while ptr is not None: + ptr = ptr.next + i += 1 + print(f"Your list is of size {i}") + return i + + def remove(self, value): + # removes all instances of a given value + ptr = self.first_node + prev = None + while ptr is not None: + if ptr.value == value: + if ptr == self.first_node: + tmp = ptr.next + self.first_node = tmp + else: + prev.next = ptr.next + + prev = ptr + ptr = ptr.next + + def show(self): + ptr = self.first_node + val = [] + while ptr is not None: + val.append(ptr.get_value) + ptr = ptr.next + + print(val) + + +def main(): + list = Unordered_Linked_List() + + list.insert(1) + list.insert(3) + list.insert(5) + list.insert(2) + + list.size() + list.show() + + list.find(3) + list.find(9) + + list.remove(1) + list.remove(3) + list.remove(5) + list.remove(2) + + list.show() + + list.insert(1) + list.insert(3) + list.insert(5) + list.insert(3) + + list.show() + + list.remove(3) + + list.show() + + +if __name__ == "__main__": + main() diff --git a/src/ruby/busca_binaria.rb b/src/ruby/binary_search.rb similarity index 100% rename from src/ruby/busca_binaria.rb rename to src/ruby/binary_search.rb diff --git a/src/ruby/binary_search_tree.rb b/src/ruby/binary_search_tree.rb new file mode 100644 index 00000000..f51e6ad7 --- /dev/null +++ b/src/ruby/binary_search_tree.rb @@ -0,0 +1,215 @@ +# frozen_string_literal: true + +class BinarySearchTree + class Node + attr_accessor :left, :right, :value + + def initialize(value) + @left = nil + @right = nil + @value = value + end + end + + def initialize + @root = nil + end + + attr_reader :root + + def insert(value) + new_node = Node.new(value) + + if @root.nil? + @root = new_node + return self + end + + current_node = @root + + loop do + if value < current_node.value + if current_node.left.nil? + current_node.left = new_node + return self + end + current_node = current_node.left + else + if current_node.right.nil? + current_node.right = new_node + return self + end + current_node = current_node.right + end + end + + self + end + + def lookup(value) + return nil if @root.nil? + + current_node = @root + + until current_node.nil? + if value < current_node.value + current_node = current_node.left + elsif value > current_node.value + current_node = current_node.right + else + return current_node + end + end + + nil + end + + def remove(value) + return false if @root.nil? + + current_node = @root + parent_node = nil + + while current_node + if value < current_node.value + parent_node = current_node + current_node = current_node.left + elsif value > current_node.value + parent_node = current_node + current_node = current_node.right + elsif current_node.value == value + # We have a match, get to work! + + if current_node.right.nil? + update_parent_link(parent_node, current_node, current_node.left) + elsif current_node.right.left.nil? + current_node.right.left = current_node.left + update_parent_link(parent_node, current_node, current_node.right) + else + leftmost, leftmost_parent = find_leftmost(current_node.right) + leftmost_parent.left = leftmost.right + leftmost.left = current_node.left + leftmost.right = current_node.right + update_parent_link(parent_node, current_node, leftmost) + end + + return true + end + end + + false + end + + def traverse(node = @root) + return nil if node.nil? + + tree = { value: node.value } + tree[:left] = traverse(node.left) + tree[:right] = traverse(node.right) + + tree + end + + private + + def update_parent_link(parent_node, current_node, new_node) + if parent_node.nil? + @root = new_node + elsif current_node.value < parent_node.value + parent_node.left = new_node + else + parent_node.right = new_node + end + end + + def find_leftmost(node) + leftmost = node.left + leftmost_parent = node + + while leftmost.left + leftmost_parent = leftmost + leftmost = leftmost.left + end + + [leftmost, leftmost_parent] + end +end + +RSpec.describe BinarySearchTree do + let(:bst) { BinarySearchTree.new } + + before(:each) do + # Construct the following tree: + # + # 9 + # 4 20 + # 1 6 15 170 + # + bst.insert(9) + bst.insert(4) + bst.insert(6) + bst.insert(20) + bst.insert(170) + bst.insert(15) + bst.insert(1) + end + + describe "#insert" do + it "adds a value to the tree" do + expect(bst.traverse).to eq({ value: 9, + left: { value: 4, + left: { value: 1, left: nil, right: nil }, + right: { value: 6, left: nil, right: nil } }, + right: { value: 20, left: { value: 15, left: nil, right: nil }, + right: { value: 170, left: nil, right: nil } } }) + end + end + + describe "#lookup" do + it "finds a value in the tree" do + node = bst.lookup(15) + expect(node.value).to eq(15) + end + + it "returns nil for a value not in the tree" do + node = bst.lookup(100) + expect(node).to be_nil + end + end + + describe "#remove" do + it "removes a leaf node" do + expect(bst.remove(1)).to be true + + expect(bst.traverse).to eq({ value: 9, + left: { value: 4, left: nil, + right: { value: 6, left: nil, right: nil } }, + right: { value: 20, left: { value: 15, left: nil, right: nil }, + right: { value: 170, left: nil, right: nil } } }) + end + + it "removes a node with one child" do + expect(bst.remove(20)).to be true + + expect(bst.traverse).to eq({ value: 9, + left: { value: 4, left: { value: 1, left: nil, right: nil }, + right: { value: 6, left: nil, right: nil } }, + right: { value: 170, left: { value: 15, left: nil, right: nil }, + right: nil } }) + end + + it "removes a node with two children" do + expect(bst.remove(4)).to be true + + expect(bst.traverse).to eq({ value: 9, + left: { value: 6, left: { value: 1, left: nil, right: nil }, + right: nil }, + right: { value: 20, left: { value: 15, left: nil, right: nil }, + right: { value: 170, left: nil, right: nil } } }) + end + + it "returns false for a value not in the tree" do + expect(bst.remove(100)).to be false + end + end +end diff --git a/src/ruby/binary_tree.rb b/src/ruby/binary_tree.rb new file mode 100644 index 00000000..322d7234 --- /dev/null +++ b/src/ruby/binary_tree.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +require "test/unit/assertions" +include Test::Unit::Assertions + +class BinaryTree + attr_accessor :value + attr_writer :left, :right + + def left + @left ||= BinaryTree.new + end + + def right + @right ||= BinaryTree.new + end + + def search(received_value) + return value if value == received_value || value.nil? + + if received_value < value + left.search(received_value) + else + right.search(received_value) + end + end + + def insert(received_value) + return @value = received_value if value.nil? + return left.insert(received_value) if received_value <= value + + right.insert(received_value) + end + + def to_a + return [] if value.nil? + + left.to_a + [value] + right.to_a + end +end + +tree = BinaryTree.new + +tree.insert(42) +tree.insert(43) +tree.insert(44) + +assert_equal(42, tree.search(42)) +assert_equal(43, tree.search(43)) +assert_equal(44, tree.search(44)) +assert_equal(nil, tree.search(45)) + +tree = BinaryTree.new + +assert_equal([], tree.to_a) + +tree.insert(42) + +assert_equal([42], tree.to_a) + +tree.insert(43) + +assert_equal([42, 43], tree.to_a) + +tree.insert(41) + +assert_equal([41, 42, 43], tree.to_a) diff --git a/src/ruby/count_sort.rb b/src/ruby/counting_sort.rb similarity index 100% rename from src/ruby/count_sort.rb rename to src/ruby/counting_sort.rb diff --git a/src/ruby/lista_duplamente_encadeada.rb b/src/ruby/doubly_linked_list.rb similarity index 100% rename from src/ruby/lista_duplamente_encadeada.rb rename to src/ruby/doubly_linked_list.rb diff --git a/src/ruby/exponenciacao.rb b/src/ruby/exponentiation.rb similarity index 100% rename from src/ruby/exponenciacao.rb rename to src/ruby/exponentiation.rb diff --git a/src/ruby/exponenciacao_recursiva.rb b/src/ruby/exponentiation_recursive.rb similarity index 100% rename from src/ruby/exponenciacao_recursiva.rb rename to src/ruby/exponentiation_recursive.rb diff --git a/src/ruby/fatorial.rb b/src/ruby/factorial_recursive.rb similarity index 100% rename from src/ruby/fatorial.rb rename to src/ruby/factorial_recursive.rb diff --git a/src/ruby/busca_sequencial.rb b/src/ruby/linear_search.rb similarity index 100% rename from src/ruby/busca_sequencial.rb rename to src/ruby/linear_search.rb diff --git a/src/ruby/busca_sequencial_recursiva.rb b/src/ruby/linear_search_recursive.rb similarity index 100% rename from src/ruby/busca_sequencial_recursiva.rb rename to src/ruby/linear_search_recursive.rb diff --git a/src/ruby/busca_sentinela.rb b/src/ruby/linear_search_sentinel.rb similarity index 100% rename from src/ruby/busca_sentinela.rb rename to src/ruby/linear_search_sentinel.rb diff --git a/src/ruby/max_recursivo.rb b/src/ruby/max_recursive.rb similarity index 100% rename from src/ruby/max_recursivo.rb rename to src/ruby/max_recursive.rb diff --git a/src/ruby/min_max_iterativo.rb b/src/ruby/min_max_iterative.rb similarity index 100% rename from src/ruby/min_max_iterativo.rb rename to src/ruby/min_max_iterative.rb diff --git a/src/ruby/min_max_recursivo.rb b/src/ruby/min_max_recursive.rb similarity index 100% rename from src/ruby/min_max_recursivo.rb rename to src/ruby/min_max_recursive.rb diff --git a/src/ruby/palindromo.rb b/src/ruby/palindrome.rb similarity index 100% rename from src/ruby/palindromo.rb rename to src/ruby/palindrome.rb diff --git a/src/ruby/fila.rb b/src/ruby/queue.rb similarity index 100% rename from src/ruby/fila.rb rename to src/ruby/queue.rb diff --git a/src/ruby/lista_encadeada.rb b/src/ruby/singly_linked_list.rb similarity index 100% rename from src/ruby/lista_encadeada.rb rename to src/ruby/singly_linked_list.rb diff --git a/src/ruby/pilha.rb b/src/ruby/stack.rb similarity index 100% rename from src/ruby/pilha.rb rename to src/ruby/stack.rb diff --git a/src/ruby/hanoi.rb b/src/ruby/tower_of_hanoi.rb similarity index 100% rename from src/ruby/hanoi.rb rename to src/ruby/tower_of_hanoi.rb diff --git a/src/rust/Dijkstra.rs b/src/rust/Dijkstra.rs new file mode 100644 index 00000000..6544db99 --- /dev/null +++ b/src/rust/Dijkstra.rs @@ -0,0 +1,88 @@ +use std::collections::BinaryHeap; +use std::collections::HashMap; +use std::collections::HashSet; + +const INF: i32 = i32::MAX; + +#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] +struct Edge { + target: usize, + weight: i32, +} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +struct Graph { + nodes: usize, + edges: Vec>, +} + +impl Graph { + // Constructor to create a new graph with a given number of nodes. + fn new(nodes: usize) -> Self { + Graph { + nodes, + edges: vec![vec![]; nodes], + } + } + + // Add an edge to the graph from 'from' node to 'to' node with a given weight. + fn add_edge(&mut self, from: usize, to: usize, weight: i32) { + self.edges[from].push(Edge { target: to, weight }); + } + + // Find the shortest path from a specified starting node using Dijkstra's algorithm. + fn shortest_path(&self, start: usize) -> HashMap { + let mut distance: HashMap = (0..self.nodes).map(|i| (i, INF)).collect(); + let mut visited: HashSet = HashSet::new(); + + // Set the distance to the starting node to 0 and initialize a priority queue. + distance.insert(start, 0); + let mut min_heap: BinaryHeap<(i32, usize)> = BinaryHeap::new(); + min_heap.push((0, start)); + + while let Some((_dist, node)) = min_heap.pop() { + if visited.contains(&node) { + continue; + } + + visited.insert(node); + + // Explore neighboring nodes and update distances if a shorter path is found. + for edge in &self.edges[node] { + let new_dist = distance[&node] + edge.weight; + if new_dist < distance[&edge.target] { + distance.insert(edge.target, new_dist); + min_heap.push((new_dist, edge.target)); + } + } + } + + distance + } +} + +fn main() { + // Create a new graph. + let mut graph = Graph::new(5); + + // Add edges to the graph. + graph.add_edge(0, 1, 1); + graph.add_edge(0, 2, 4); + graph.add_edge(1, 2, 2); + graph.add_edge(1, 3, 5); + graph.add_edge(2, 3, 1); + graph.add_edge(3, 4, 3); + + let start_node = 0; + + // Find the shortest distances from the starting node. + let shortest_distances = graph.shortest_path(start_node); + + // Print the results. + for (node, distance) in shortest_distances.iter() { + println!( + "Shortest distance from node {} to node {}: {}", + start_node, node, distance + ); + } +} diff --git a/src/rust/busca_binaria.rs b/src/rust/binary_search.rs similarity index 100% rename from src/rust/busca_binaria.rs rename to src/rust/binary_search.rs diff --git a/src/rust/fatorial.rs b/src/rust/factorial.rs similarity index 100% rename from src/rust/fatorial.rs rename to src/rust/factorial.rs diff --git a/src/rust/fatorial_recursiva.rs b/src/rust/factorial_recursive.rs similarity index 100% rename from src/rust/fatorial_recursiva.rs rename to src/rust/factorial_recursive.rs diff --git a/src/rust/gnomesort.rs b/src/rust/gnome_sort.rs similarity index 100% rename from src/rust/gnomesort.rs rename to src/rust/gnome_sort.rs diff --git a/src/rust/grafo.rs b/src/rust/graph.rs similarity index 100% rename from src/rust/grafo.rs rename to src/rust/graph.rs diff --git a/src/rust/busca_sequencial.rs b/src/rust/linear_search.rs similarity index 100% rename from src/rust/busca_sequencial.rs rename to src/rust/linear_search.rs diff --git a/src/rust/busca_sequencial_recursiva.rs b/src/rust/linear_search_recursive.rs similarity index 100% rename from src/rust/busca_sequencial_recursiva.rs rename to src/rust/linear_search_recursive.rs diff --git a/src/rust/min_max_iterativo.rs b/src/rust/min_max_iterative.rs similarity index 100% rename from src/rust/min_max_iterativo.rs rename to src/rust/min_max_iterative.rs diff --git a/src/rust/min_max_recursivo.rs b/src/rust/min_max_recursive.rs similarity index 100% rename from src/rust/min_max_recursivo.rs rename to src/rust/min_max_recursive.rs diff --git a/src/rust/palindromo.rs b/src/rust/palindrome.rs similarity index 100% rename from src/rust/palindromo.rs rename to src/rust/palindrome.rs diff --git a/src/rust/fila.rs b/src/rust/queue.rs similarity index 100% rename from src/rust/fila.rs rename to src/rust/queue.rs diff --git a/src/rust/linked_list.rs b/src/rust/singly_linked_list.rs similarity index 100% rename from src/rust/linked_list.rs rename to src/rust/singly_linked_list.rs diff --git a/src/rust/pilha.rs b/src/rust/stack.rs similarity index 100% rename from src/rust/pilha.rs rename to src/rust/stack.rs diff --git a/src/rust/torre_hanoi.rs b/src/rust/tower_of_hanoi.rs similarity index 100% rename from src/rust/torre_hanoi.rs rename to src/rust/tower_of_hanoi.rs diff --git a/src/rust/soma_dois_numeros.rs b/src/rust/two_sum.rs similarity index 100% rename from src/rust/soma_dois_numeros.rs rename to src/rust/two_sum.rs diff --git a/src/scala/BinarySearch.scala b/src/scala/BinarySearch.scala new file mode 100644 index 00000000..2088863d --- /dev/null +++ b/src/scala/BinarySearch.scala @@ -0,0 +1,26 @@ +import scala.annotation.tailrec + +def binarySearch(data: Seq[Int], target: Int): Option[Int] = { + + @tailrec + def search(left: Int, right: Int): Option[Int] = { + if (left > right) { + None + } else { + val middle: Int = (left + right) / 2 + if (data(middle) == target) Some(middle) + else if (data(middle) < target) search(middle + 1, right) + else search(left, middle - 1) + } + } + + search(0, data.size) +} + +object Main extends App { + val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12) + val value: Int = 11 + println( + s"Value '$value' found in position '${binarySearch(data, value).get}'" + ) +} diff --git a/src/scala/Bogosort.scala b/src/scala/Bogosort.scala new file mode 100644 index 00000000..8a390de8 --- /dev/null +++ b/src/scala/Bogosort.scala @@ -0,0 +1,22 @@ +import scala.annotation.tailrec +import scala.util.Random + +@tailrec +def isSorted(data: Seq[Int]): Boolean = { + if (data.size < 2) true + else if (data(0) > data(1)) false + else isSorted(data.tail) +} + +@tailrec +def bogosort(data: Seq[Int]): Seq[Int] = { + val result: Seq[Int] = Random.shuffle(data) + if (isSorted(result)) result + else bogosort(data) +} + +object Main extends App { + val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10)) + println(s"Unsorted data: $data") + println(s"Sorted data: ${bogosort(data)}") +} diff --git a/src/scala/Exponentiation.scala b/src/scala/Exponentiation.scala new file mode 100644 index 00000000..0640a121 --- /dev/null +++ b/src/scala/Exponentiation.scala @@ -0,0 +1,9 @@ +def exponentiation(base: Int, exponent: Int): Int = { + (1 to exponent) + .map(_ => base) + .reduce(_ * _) +} + +object Main extends App { + println("5 ^ 3 = " + exponentiation(5, 3)) +} diff --git a/src/scala/ExponentiationRecursive.scala b/src/scala/ExponentiationRecursive.scala new file mode 100644 index 00000000..58f31682 --- /dev/null +++ b/src/scala/ExponentiationRecursive.scala @@ -0,0 +1,15 @@ +import scala.annotation.tailrec + +@tailrec +def exponentiationRecursive( + base: Int, + exponent: Int, + accumulator: Int = 1 +): Int = exponent match { + case 0 => accumulator + case _ => exponentiationRecursive(base, exponent - 1, accumulator * base) +} + +object Main extends App { + println("5 ^ 3 = " + exponentiationRecursive(5, 3)) +} diff --git a/src/scala/RecursiveLinearSearch.scala b/src/scala/LinearSearchRecursive.scala similarity index 100% rename from src/scala/RecursiveLinearSearch.scala rename to src/scala/LinearSearchRecursive.scala diff --git a/src/scala/Palindrome.scala b/src/scala/Palindrome.scala new file mode 100644 index 00000000..b8b80bb3 --- /dev/null +++ b/src/scala/Palindrome.scala @@ -0,0 +1,15 @@ +def isPalindrome(content: String): Boolean = { + val sanitizedContent: String = content.replaceAll("\\W", "").toLowerCase + sanitizedContent == sanitizedContent.reverse +} + +object Main extends App { + val data: Seq[String] = Seq( + "", + "a", + "abba", + "No lemon, no melon", + "Was it a palindrome?" + ) + data.foreach(x => println(s"'$x' is a palindrome? ${isPalindrome(x)}")) +} diff --git a/src/swift/binarySearch.swift b/src/swift/binarySearch.swift index 17a8da24..ce9c1f9b 100644 --- a/src/swift/binarySearch.swift +++ b/src/swift/binarySearch.swift @@ -1,10 +1,3 @@ -// -// binarySearch.swift -// -// -// Written by Roberto Martins on 07/10/2023 -// Based on the C code presented in the Portuguese Wikipedia article for Binary Search - func binarySearch(array: [Int], searchedElement: Int) -> Int { var firstIndex: Int = 0 var lastIndex: Int = array.count - 1 diff --git a/src/swift/calculatePi.swift b/src/swift/calculatePi.swift index 1869e5a0..0c38a451 100644 --- a/src/swift/calculatePi.swift +++ b/src/swift/calculatePi.swift @@ -1,21 +1,14 @@ -// -// calculatePi.swift -// -// -// Created by Matheus Torres on 14/11/20. -// - func calculatePi(_ number: Int) -> Float { var denominator: Float = 1 var operation: Float = 1 var pi: Float = 0 - + for _ in 0..(base: Number, power: Int) -> Number { var result = base if power == 0 { @@ -19,4 +15,4 @@ func main() { print(exponentiation(base: 50, power: 0)) } -main() \ No newline at end of file +main() diff --git a/src/swift/recursiveExponentiation.swift b/src/swift/exponentiationRecursive.swift similarity index 82% rename from src/swift/recursiveExponentiation.swift rename to src/swift/exponentiationRecursive.swift index 6f74b9e6..b7bd270b 100644 --- a/src/swift/recursiveExponentiation.swift +++ b/src/swift/exponentiationRecursive.swift @@ -1,7 +1,3 @@ -/* recursiveExponentiation.swift -Written by Roberto Martins on 10/10/2023 -*/ - func recursiveExponentiation(base: Number, power: Int) -> Number { if (power == 0) { return 1 @@ -15,4 +11,4 @@ func main() { print(recursiveExponentiation(base: 50, power: 0)) } -main() \ No newline at end of file +main() diff --git a/src/swift/factorial.swift b/src/swift/factorial.swift index 4ca454c8..7772d655 100644 --- a/src/swift/factorial.swift +++ b/src/swift/factorial.swift @@ -1,9 +1,3 @@ -// -// factorial.swift -// -// Created by Matheus Torres on 13/11/20. -// - func factorial(_ number: Int) -> Int { var result: Int = 1 for index in (1...number).reversed() { diff --git a/src/swift/recursiveFactorial.swift b/src/swift/factorialRecursive.swift similarity index 65% rename from src/swift/recursiveFactorial.swift rename to src/swift/factorialRecursive.swift index a682b170..fcada1cf 100644 --- a/src/swift/recursiveFactorial.swift +++ b/src/swift/factorialRecursive.swift @@ -1,9 +1,3 @@ -// -// factorial.swift -// -// Created by Matheus Torres on 13/11/20. -// - func factorial(_ number: Int) -> Int { if number <= 1 { return 1 } return number * factorial(number - 1) diff --git a/src/swift/insertionSort.swift b/src/swift/insertionSort.swift index a9c0b1c7..a48ca777 100644 --- a/src/swift/insertionSort.swift +++ b/src/swift/insertionSort.swift @@ -1,10 +1,3 @@ -// -// insertionSort.swift -// -// -// Created by Matheus Torres on 14/11/20. -// - func insertionSort(_ array: [Int]) -> [Int] { var newArray: [Int] = array for i in 1.. Int { for index in 0.. Bool { diff --git a/src/swift/queue.swift b/src/swift/queue.swift index 84ca19a3..fab2a748 100644 --- a/src/swift/queue.swift +++ b/src/swift/queue.swift @@ -1,24 +1,18 @@ -// -// fila.swift -// -// Created by Matheus Torres on 14/11/20. -// - class Queue { var queue: [Int] = [] - + func enqueue(_ value: Int) { self.queue.append(value) } - + func dequeue() { self.queue.removeFirst() } - + func show() { print(self.queue) } - + func clear() { self.queue = [] } diff --git a/src/swift/singlyLinkedList.swift b/src/swift/singlyLinkedList.swift index 59ca660a..0fbf0e1e 100644 --- a/src/swift/singlyLinkedList.swift +++ b/src/swift/singlyLinkedList.swift @@ -1,8 +1,4 @@ -/* singlyLinkedList.swift -Written by Roberto Martins on 09/10/2023 -*/ - -// Type: Equatable makes it so that you can have Nodes of any type and their values can be compared +// Type: Equatable makes it so that you can have Nodes of any type and their values can be compared // Use of generic "Type" makes it so you can have a Linked List of any type class Node { @@ -51,7 +47,7 @@ class LinkedList { currentNode = currentNode!.next } } - + func remove(value: Type) { var currentNode = self.head var previousNode: Node? = nil @@ -116,4 +112,4 @@ func main() { stringsLinkedList.printList() } -main() \ No newline at end of file +main() diff --git a/src/swift/stack.swift b/src/swift/stack.swift index f2ca4b9b..c7fdf2e6 100644 --- a/src/swift/stack.swift +++ b/src/swift/stack.swift @@ -1,10 +1,3 @@ -// -// stack.swift -// -// -// Created by Matheus Torres on 14/11/20. -// - class Stack { var stack: [Int] = [] diff --git a/src/swift/hanoi.swift b/src/swift/towerOfHanoi.swift similarity index 80% rename from src/swift/hanoi.swift rename to src/swift/towerOfHanoi.swift index 9e0b903e..b72503ee 100644 --- a/src/swift/hanoi.swift +++ b/src/swift/towerOfHanoi.swift @@ -1,9 +1,3 @@ -// -// hanoi.swift -// -// Created by Matheus Torres on 13/11/20. -// - func hanoi(_ p1: Int, _ p2: Int, _ p3: Int, disks: Int) { if disks == 1 { print("Move de \(p1) para \(p2)")