├── .github ├── linters │ ├── .golangci.yml │ └── .markdown-lint.yml ├── pull_request_template.md └── workflows │ ├── link-checker.yml │ └── lint-checker.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── logos ├── c.svg ├── cplusplus.svg ├── github.svg ├── golang.svg ├── java.svg ├── javascript.svg ├── kotlin.svg ├── python.svg ├── ruby.svg ├── rust.svg ├── scala.svg └── swift.svg └── src ├── c ├── BinarySearch.c ├── BinarySearchTree.c ├── BinaryTree.c ├── BubbleSort.c ├── CalculatePi.c ├── CircularLinkedList.c ├── ConnectedComponents.c ├── CountingSort.c ├── Dijkstra.c ├── DoublyLinkedList.c ├── DynamicQueue.c ├── DynamicStack.c ├── Exponentiation.c ├── ExponentiationRecursive.c ├── Factorial.c ├── FactorialRecursive.c ├── FibonacciIterative.c ├── FibonacciMemoization.c ├── FibonacciRecursive.c ├── FloydWarshall.c ├── GraphSearch.c ├── Graphs.c ├── HamiltonianCycle.c ├── Heapsort.c ├── InsertionSort.c ├── LinearSearch.c ├── LinearSearchRecursive.c ├── LinearSearchSentinel.c ├── MaxRecursive.c ├── MergeSort.c ├── MinMaxDC.c ├── MinMaxIterative.c ├── MinMaxRecursive.c ├── Palindrome.c ├── Queue.c ├── QuickSort.c ├── RadixSort.c ├── SelectionSort.c ├── SinglyLinkedList.c ├── SortedLinkedList.c ├── Stack.c ├── Timsort.c ├── TowerOfHanoi.c ├── TravellingSalesman.c ├── TwoSum.c └── UnorderedLinkedList.c ├── cpp ├── BinarySearch.cpp ├── BinarySearchTree.cpp ├── BinaryTree.cpp ├── BubbleSort.cpp ├── CalculatePi.cpp ├── ConnectedComponents.cpp ├── CountingSort.cpp ├── Dijkstras_MinHeap.cpp ├── DoublyLinkedList.cpp ├── DynamicQueue.cpp ├── DynamicStack.cpp ├── Exponentiation.cpp ├── ExponentiationRecursive.cpp ├── Factorial.cpp ├── FactorialRecursive.cpp ├── FibonacciIterative.cpp ├── FibonacciMemoization.cpp ├── FibonacciRecursive.cpp ├── FindDistinctSubsets.cpp ├── FloydWarshall.cpp ├── GraphSearch.cpp ├── InsertionSort.cpp ├── InterpolationSearch.cpp ├── LinearSearch.cpp ├── LinearSearchRecursive.cpp ├── MaxRecursive.cpp ├── MergeSort.cpp ├── MinMaxDC.cpp ├── MinMaxIterative.cpp ├── Palindrome.cpp ├── QuickSort.cpp ├── RottenOranges.cpp ├── SelectionSort.cpp ├── SinglyLinkedList.cpp ├── Stack.cpp ├── TowerOfHanoi.cpp └── TwoSum.cpp ├── go ├── binary_search.go ├── bubble_sort.go ├── calculate_pi.go ├── cocktail_sort.go ├── comb_sort.go ├── counting_sort.go ├── deque.go ├── dijkstra.go ├── doubly_linked_list.go ├── exponentiation.go ├── factorial.go ├── fibonacci_iterative.go ├── fibonacci_memoization.go ├── fibonacci_recursive.go ├── floyd_warshall.go ├── gnome_sort.go ├── heap_sort.go ├── insertion_sort.go ├── isogram.go ├── linear_search.go ├── merge_sort.go ├── min_max_recursive.go ├── quick_sort.go ├── radix_sort.go ├── selection_sort.go ├── shell_sort.go ├── singly_linked_list.go ├── sorted_linked_list.go ├── stack.go ├── tower_of_hanoi.go ├── travelling_salesman.go └── unordered_linked_list.go ├── java ├── BinarySearch.java ├── BinarySearchTree.java ├── BinaryTree.java ├── BogoSort.java ├── BubbleSort.java ├── BucketSort.java ├── CalculatePi.java ├── CountingSort.java ├── Dijkstra.java ├── DoublyLinkedList.java ├── Exponentiation.java ├── ExponentiationRecursive.java ├── Factorial.java ├── FactorialRecursive.java ├── FibonacciIterative.java ├── FibonacciMemoization.java ├── FibonacciRecursive.java ├── FloydWarshall.java ├── GnomeSort.java ├── HeapSort.java ├── InsertionSort.java ├── LinearSearch.java ├── MaxRecursive.java ├── MergeSort.java ├── MinMaxIterative.java ├── MinMaxRecursive.java ├── No.java ├── NoPilha.java ├── Palindrome.java ├── Queue.java ├── QuickSort.java ├── RadixSort.java ├── SelectionSort.java ├── ShellSort.java ├── Stack.java ├── TestMergeSort.java ├── TowerOfHanoi.java └── TwoSum.java ├── javascript ├── BinarySearch.js ├── BinarySearchTree.js ├── BubbleSort.js ├── CalculatePi.js ├── CombSort.js ├── CountingSort.js ├── Deque.js ├── Dijkstra.js ├── DoublyLinkedList.js ├── Exponentiation.js ├── ExponentiationRecursive.js ├── Factorial.js ├── FactorialRecursive.js ├── FibonacciIterative.js ├── FibonacciMemoization.js ├── FibonacciRecursive.js ├── GraphSearch.js ├── HeapSort.js ├── InsertionSort.js ├── InterpolationSearch.js ├── LinearSearch.js ├── LinearSearchRecursive.js ├── LinearSearchSentinel.js ├── MaxRecursive.js ├── MergeSort.js ├── MinMaxIterative.js ├── MinMaxRecursive.js ├── Palindrome.js ├── Queue.js ├── QuickSort.js ├── RadixSort.js ├── SelectionSort.js ├── ShellSort.js ├── SinglyLinkedList.js ├── Stack.js └── TowerOfHanoi.js ├── kotlin ├── ExponentiationRecursive.kt ├── Factorial.kt ├── FibonacciIterative.kt ├── FibonacciMemoization.kt ├── FibonacciRecursive.kt └── MergeSort.kt ├── python ├── binary_search.py ├── binary_search_tree.py ├── binary_tree.py ├── bogosort.py ├── bubble_sort.py ├── calculate_pi.py ├── circular_linked_list.py ├── comb_sort.py ├── counting_sort.py ├── deque.py ├── dijkstra.py ├── doubly_linked_list.py ├── dynamic_queue.py ├── dynamic_stack.py ├── exponentiation.py ├── exponentiation_recursive.py ├── factorial.py ├── factorial_recursive.py ├── fibonacci_iterative.py ├── fibonacci_memoization.py ├── fibonacci_recursive.py ├── floyd_warshall.py ├── genetic_algorithm.py ├── gnome_sort.py ├── graph_search.py ├── hash_table.py ├── heap_sort.py ├── huffman.py ├── insertion_sort.py ├── interpolation_search.py ├── knights_tour.py ├── linear_search.py ├── linear_search_recursive.py ├── linear_search_sentinel.py ├── lista_encadeada_desordenada.py ├── lz77.py ├── max_recursive.py ├── maze_solving.py ├── merge_sort.py ├── min_max_dc.py ├── min_max_iterative.py ├── min_max_recursive.py ├── palindrome.py ├── queue.py ├── queue_using_stacks.py ├── quick_sort.py ├── radix_sort.py ├── ring_buffer.py ├── selection_sort.py ├── shell_sort.py ├── singly_linked_list.py ├── skip_list.py ├── sorted_linked_list.py ├── stack.py ├── timsort.py ├── tower_of_hanoi.py ├── travelling_salesman.py ├── two_sum.py └── unordered_linked_list.py ├── ruby ├── binary_search.rb ├── binary_search_tree.rb ├── binary_tree.rb ├── bubble_sort.rb ├── bucket_sort.rb ├── calculate_pi.rb ├── comb_sort.rb ├── counting_sort.rb ├── deque.rb ├── dijkstra.rb ├── doubly_linked_list.rb ├── exponentiation.rb ├── exponentiation_recursive.rb ├── factorial.rb ├── factorial_recursive.rb ├── fibonacci_iterative.rb ├── fibonacci_memoization.rb ├── fibonacci_recursive.rb ├── gnome_sort.rb ├── hash_table.rb ├── heap_sort.rb ├── insertion_sort.rb ├── interpolation_search.rb ├── linear_search.rb ├── linear_search_recursive.rb ├── linear_search_sentinel.rb ├── max_recursive.rb ├── merge_sort.rb ├── min_max_dc.rb ├── min_max_iterative.rb ├── min_max_recursive.rb ├── palindrome.rb ├── queue.rb ├── quick_sort.rb ├── radix_sort.rb ├── selection_sort.rb ├── singly_linked_list.rb ├── stack.rb └── tower_of_hanoi.rb ├── rust ├── Dijkstra.rs ├── binary_search.rs ├── bogo_sort.rs ├── bubble_sort.rs ├── calculate_pi.rs ├── deque.rs ├── doubly_linked_list.rs ├── exponentiation_recursive.rs ├── factorial.rs ├── factorial_recursive.rs ├── fibonacci_iterative.rs ├── fibonacci_memoization.rs ├── fibonacci_recursive.rs ├── gnome_sort.rs ├── graph.rs ├── insertion_sort.rs ├── linear_search.rs ├── linear_search_recursive.rs ├── min_max_iterative.rs ├── min_max_recursive.rs ├── palindrome.rs ├── queue.rs ├── quick_sort.rs ├── singly_linked_list.rs ├── stack.rs ├── tower_of_hanoi.rs └── two_sum.rs ├── scala ├── BinarySearch.scala ├── Bogosort.scala ├── BubbleSort.scala ├── CalculatePi.scala ├── Dijkstra.scala ├── Exponentiation.scala ├── ExponentiationRecursive.scala ├── Factorial.scala ├── FactorialRecursive.scala ├── FibonacciIterative.scala ├── FibonacciMemoization.scala ├── FibonacciRecursive.scala ├── LinearSearch.scala ├── LinearSearchRecursive.scala ├── MaxRecursive.scala ├── MinMaxIterative.scala ├── MinMaxRecursive.scala ├── Palindrome.scala ├── Queue.scala ├── Stack.scala └── TowerOfHanoi.scala └── swift ├── binarySearch.swift ├── calculatePi.swift ├── deque.swift ├── exponentiation.swift ├── exponentiationRecursive.swift ├── factorial.swift ├── factorialRecursive.swift ├── fibonacciIterative.swift ├── fibonacciMemoization.swift ├── fibonacciRecursive.swift ├── insertionSort.swift ├── linearSearch.swift ├── palindrome.swift ├── queue.swift ├── singlyLinkedList.swift ├── stack.swift └── towerOfHanoi.swift /.github/linters/.golangci.yml: -------------------------------------------------------------------------------- 1 | linters: 2 | enable: 3 | - gofmt 4 | - goimports 5 | -------------------------------------------------------------------------------- /.github/linters/.markdown-lint.yml: -------------------------------------------------------------------------------- 1 | MD013: false 2 | MD045: false 3 | MD033: false 4 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Instructions 2 | 3 | Before opening a Pull Request, please read the following items: 4 | 5 | 1. Make sure you have read the [CONTRIBUTING](../CONTRIBUTING.md) guidelines 6 | 2. Make sure no other PR is implementing the same change 7 | 3. Make sure the Continuous Integration workflows (Github Actions) are all passing 8 | 4. If in doubt about how to approach another contributor, read our [CODE OF CONDUCT](../CODE_OF_CONDUCT.md) guidelines 9 | 10 | 11 | 12 | ## Description 13 | 14 | 15 | -------------------------------------------------------------------------------- /.github/workflows/link-checker.yml: -------------------------------------------------------------------------------- 1 | name: Link Checker 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | link-checker: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout Code 10 | uses: actions/checkout@main 11 | - name: Check Links 12 | uses: lycheeverse/lychee-action@v1.7.0 13 | with: 14 | fail: true 15 | -------------------------------------------------------------------------------- /.github/workflows/lint-checker.yml: -------------------------------------------------------------------------------- 1 | name: Lint Checker 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | lint-checker: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout Code 10 | uses: actions/checkout@v4 11 | with: 12 | fetch-depth: 0 13 | - name: Check Code 14 | uses: super-linter/super-linter@v7.1.0 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | VALIDATE_GO: true 18 | VALIDATE_RUBY: true 19 | VALIDATE_JSON: true 20 | VALIDATE_YAML: true 21 | VALIDATE_KOTLIN: true 22 | VALIDATE_MARKDOWN: true 23 | VALIDATE_SCALAFMT: true 24 | VALIDATE_RUST_2021: true 25 | VALIDATE_RUST_CLIPPY: true 26 | VALIDATE_PYTHON_RUFF: true 27 | VALIDATE_PYTHON_BLACK: true 28 | VALIDATE_PYTHON_ISORT: true 29 | VALIDATE_CLANG_FORMAT: true 30 | VALIDATE_JAVASCRIPT_ES: true 31 | VALIDATE_JSON_PRETTIER: true 32 | VALIDATE_YAML_PRETTIER: true 33 | VALIDATE_MARKDOWN_PRETTIER: true 34 | VALIDATE_GOOGLE_JAVA_FORMAT: true 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .metals 2 | __pycache__/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Kelvin S. do Prado 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /logos/c.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /logos/github.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /logos/java.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /logos/javascript.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /logos/kotlin.svg: -------------------------------------------------------------------------------- 1 | 2 | file_type_kotlin -------------------------------------------------------------------------------- /logos/swift.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/c/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int BinarySearch(int array[], int size, int value) { 4 | int start = 0; 5 | int end = size - 1; 6 | int middle = end / 2; 7 | 8 | while (start < end && array[middle] != value) { 9 | // new start 10 | if (value > array[middle]) 11 | start = middle + 1; 12 | 13 | // new end 14 | if (value < array[middle]) 15 | end = middle - 1; 16 | 17 | // new middle 18 | middle = (start + end) / 2; 19 | } 20 | 21 | if (array[middle] == value) 22 | return middle; 23 | 24 | return -1; 25 | } 26 | 27 | int main() { 28 | int value; 29 | int array[] = {1, 5, 10, 12, 18, 22, 87, 90, 112, 129}; 30 | size_t size = sizeof(array) / sizeof(array[0]); 31 | 32 | printf("Please provide the number you want to value for: "); 33 | scanf("%d", &value); 34 | 35 | int pos = BinarySearch(array, size, value); 36 | 37 | if (pos != -1) 38 | printf("Found in position = %d.\nValue = %d\n", pos, array[pos]); 39 | else 40 | printf("Not found\n"); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /src/c/BubbleSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int array[], int j) { 4 | int t = array[j]; 5 | array[j] = array[j + 1]; 6 | array[j + 1] = t; 7 | } 8 | 9 | void bubble_sort(int array[], int n) { 10 | for (int i = 0; i < n - 1; i++) { 11 | for (int j = 0; j < n - i - 1; j++) { 12 | if (array[j] > array[j + 1]) { 13 | swap(array, j); 14 | } 15 | } 16 | } 17 | } 18 | 19 | int main() { 20 | int array_size = 9; 21 | int array[10] = {99, 33, 22, 10, 5, 7, 9, 0, 15, 27}; 22 | 23 | bubble_sort(array, array_size); 24 | 25 | printf("Lista ordenada:\n"); 26 | for (int i = 0; i < array_size - 1; i++) 27 | printf("%d, ", array[i]); 28 | 29 | printf("%d\n", array[array_size - 1]); 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /src/c/CalculatePi.c: -------------------------------------------------------------------------------- 1 | /* 2 | Calculo de Pi em C 3 | */ 4 | 5 | #include 6 | 7 | float leibniz_pi_calculation(int number) { 8 | float denominador = 1.0f; 9 | float operacao = 1.0f; 10 | float pi = 0.0f; 11 | for (int i = 0; i < number; i++) { 12 | pi += operacao * (4.0 / denominador); 13 | denominador += 2.0; 14 | operacao = operacao * -1.0; 15 | } 16 | return pi; 17 | } 18 | 19 | int main() { 20 | int n_terms[4] = {10, 1000, 100000, 10000000}; 21 | for (int n = 0; n < 4; n++) 22 | printf("PI (%i): {%f}\n", n, leibniz_pi_calculation(n_terms[n])); 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /src/c/Exponentiation.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int exponenciacao(int base, int expoente) { 4 | 5 | int i; 6 | int result = base; 7 | 8 | for (i = 0; i < expoente - 1; i++) 9 | result *= base; 10 | 11 | return result; 12 | } 13 | 14 | int main() { 15 | 16 | printf("%d\n", exponenciacao(5, 3)); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/c/ExponentiationRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int exponenciacao(int base, int expoente) { 4 | 5 | if (expoente == 0) 6 | return 1; 7 | 8 | return (base * exponenciacao(base, expoente - 1)); 9 | } 10 | 11 | int main() { 12 | 13 | printf("%d\n", exponenciacao(5, 3)); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/c/Factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | * Exemplos de função para retornar o fatorial de um número n 6 | * função recursiva 7 | */ 8 | 9 | int main() { 10 | int num; 11 | printf("Digite um número: "); 12 | scanf("%d", &num); 13 | int result = fatorial(num); 14 | printf("1 => "); 15 | printf("%d! é : %d\n", num, result); 16 | return (0); 17 | } 18 | 19 | int fatorial(int num) { 20 | if (num <= 1) { 21 | return 1; 22 | } 23 | printf("%d * ", num); 24 | return num * fatorial(num - 1); 25 | } 26 | -------------------------------------------------------------------------------- /src/c/FactorialRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fatorial(int n) { 4 | 5 | if (n == 1) 6 | return 1; 7 | 8 | return (n * fatorial(n - 1)); 9 | } 10 | 11 | int main() { 12 | 13 | printf("%d\n", fatorial(5)); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/c/FibonacciIterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fibonacci(int number) { 4 | int last_number = 0; 5 | int current_number = 1; 6 | 7 | for (int index = 0; index < number; ++index) { 8 | int temp = current_number; 9 | current_number += last_number; 10 | last_number = temp; 11 | } 12 | return last_number; 13 | } 14 | 15 | int main() { 16 | printf("Fibonacci Iterative: %d\n", fibonacci(12)); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/c/FibonacciMemoization.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_N \ 4 | 100 // Define the maximum number for which you want to calculate Fibonacci 5 | 6 | int memo[MAX_N]; // Memoization table to store computed values 7 | 8 | int fibonacci(int number) { 9 | if (number <= 1) { 10 | return number; 11 | } 12 | if (memo[number] != -1) { 13 | return memo[number]; 14 | } 15 | 16 | memo[number] = fibonacci(number - 1) + fibonacci(number - 2); 17 | return memo[number]; 18 | } 19 | 20 | int main(void) { 21 | // Initialize the memoization table with -1 (uncomputed) 22 | for (int i = 0; i < MAX_N; i++) { 23 | memo[i] = -1; 24 | } 25 | 26 | printf("memoization: %d\n", fibonacci(12)); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /src/c/FibonacciRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fibonacci(int number) { 4 | if (number == 0) { 5 | return 0; 6 | } else if (number == 1) { 7 | return 1; 8 | } else { 9 | return fibonacci(number - 1) + fibonacci(number - 2); 10 | } 11 | } 12 | 13 | int main(void) { 14 | int test_nbr = 12; 15 | 16 | printf("recursive: %d\n", fibonacci(test_nbr)); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/c/LinearSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int buscaSequencial(int vetor[], int size, int buscado) { 4 | for (int i = 0; i < size; i++) { 5 | if (vetor[i] == buscado) { 6 | return i; 7 | } 8 | } 9 | return -1; 10 | } 11 | 12 | int main() { 13 | 14 | int a[] = {1, 2, 3, 4, 5, 6, 7, 8}; 15 | int n = sizeof(a) / sizeof(a[0]); 16 | printf("Valor %d no índice %d\n", 3, buscaSequencial(a, n, 3)); 17 | printf("Valor %d no índice %d\n", 9, buscaSequencial(a, n, 9)); 18 | } 19 | -------------------------------------------------------------------------------- /src/c/LinearSearchRecursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int buscaSequencialRecursiva(int vetor[], int i, int buscado, int size) { 4 | 5 | if (i == size) { 6 | return -1; 7 | } else if (vetor[i] == buscado) { 8 | return i; 9 | } else { 10 | return buscaSequencialRecursiva(vetor, i + 1, buscado, size); 11 | } 12 | } 13 | 14 | int main() { 15 | 16 | int vetor[] = {1, 2, 3, 4, 5, 6, 7, 8}; 17 | size_t n = sizeof(vetor) / sizeof(vetor[0]); 18 | printf("Valor %d no índice %d\n", 1, 19 | buscaSequencialRecursiva(vetor, 0, 1, n)); 20 | printf("Valor %d no índice %d\n", 10, 21 | buscaSequencialRecursiva(vetor, 0, 10, n)); 22 | } 23 | -------------------------------------------------------------------------------- /src/c/MinMaxIterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int array[8] = {1, 2, 3, 4, 5, 6, 7, 8}; 5 | 6 | int min = array[0]; 7 | int max = array[0]; 8 | 9 | size_t length = sizeof(array) / sizeof(array[0]); 10 | 11 | for (int i = 1; i < length; ++i) { 12 | if (array[i] < min) { 13 | min = array[i]; 14 | } 15 | if (array[i] > max) { 16 | max = array[i]; 17 | } 18 | } 19 | 20 | printf("min: %d\n", min); 21 | printf("max: %d\n", max); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /src/c/MinMaxRecursive.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Exemplo de algoritmo recursivo. 3 | * Objetivo: encontrar o valor máximo e mínimo em um vetor, utilizando 4 | *recursividade 5 | */ 6 | 7 | #include 8 | 9 | #define TAM 10 10 | 11 | void MaxMin(int vetor[], int min, int max, int indice) { 12 | if (vetor[indice] < min) 13 | min = vetor[indice]; 14 | if (vetor[indice] > max) 15 | max = vetor[indice]; 16 | if (indice < TAM - 1) 17 | MaxMin(vetor, min, max, indice + 1); 18 | else 19 | printf("Min: %d \nMax: %d\n\n", min, max); 20 | } 21 | 22 | int main() { 23 | int vetor[TAM] = {9, 2, 1, 8, 6, 3, 4, 5, 0, 7}; 24 | MaxMin(vetor, vetor[0], vetor[0], 0); 25 | return 0; 26 | } -------------------------------------------------------------------------------- /src/c/Palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_SIZE_WORD 100 5 | 6 | void calc_reverse(char *input, char *output) { 7 | size_t len_input = strlen(input); 8 | 9 | char *last_char = input + len_input - 1; 10 | 11 | for (int i = 0; i < len_input; i++) { 12 | output[i] = *(last_char - i); 13 | } 14 | output[len_input] = '\0'; 15 | } 16 | 17 | int main() { 18 | char input[MAX_SIZE_WORD]; 19 | char reverse[MAX_SIZE_WORD]; 20 | 21 | printf("Digite uma palavra: "); 22 | 23 | fgets(input, MAX_SIZE_WORD, stdin); 24 | // remove New Line from the end 25 | input[strlen(input) - 1] = '\0'; 26 | 27 | calc_reverse(input, reverse); 28 | 29 | printf("Sua palavra invertida: %s\n", reverse); 30 | 31 | if (!strcmp(input, reverse)) 32 | puts("Sua palavra eh um palindromo!"); 33 | else 34 | puts("Sua palavra NAO eh um palindromo!"); 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /src/c/RadixSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void print_array(int array[], int size) { 4 | printf("[ "); 5 | for (int i = 0; i < size; i++) { 6 | printf("%d ", array[i]); 7 | } 8 | printf("]\n"); 9 | } 10 | 11 | int get_max(int array[], int size) { 12 | int max = array[0]; 13 | for (int i = 1; i < size; i++) { 14 | if (array[i] > max) 15 | max = array[i]; 16 | } 17 | return max; 18 | } 19 | 20 | void radix_sort(int array[], int size) { 21 | int i; 22 | int semi_sorted[size]; 23 | int significant_digit = 1; 24 | int largest_number = get_max(array, size); 25 | 26 | while (largest_number / significant_digit > 0) { 27 | int bucket[10] = {0}; 28 | for (i = 0; i < size; i++) { 29 | bucket[(array[i] / significant_digit) % 10]++; 30 | } 31 | for (i = 1; i < 10; i++) { 32 | bucket[i] += bucket[i - 1]; 33 | } 34 | for (i = size - 1; i >= 0; i--) { 35 | semi_sorted[--bucket[(array[i] / significant_digit) % 10]] = array[i]; 36 | } 37 | for (i = 0; i < size; i++) { 38 | array[i] = semi_sorted[i]; 39 | } 40 | significant_digit *= 10; 41 | } 42 | } 43 | 44 | int main() { 45 | int array[10] = {45, 75, 89, 12, 34, 9, 67, 23, 90, 11}; 46 | printf("Unsorted Array\n"); 47 | print_array(array, 10); 48 | 49 | radix_sort(array, 10); 50 | 51 | printf("Sorted Array\n"); 52 | print_array(array, 10); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /src/c/SelectionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int array[], int i, int j) { 4 | int temp = array[i]; 5 | array[i] = array[j]; 6 | array[j] = temp; 7 | } 8 | 9 | void selection_sort(int array[], int n) { 10 | int min, i, j; 11 | for (i = 0; i < n; i++) { 12 | min = i; 13 | for (j = i + 1; j < n; j++) { 14 | if (array[min] > array[j]) { 15 | min = j; 16 | } 17 | } 18 | if (min != i) 19 | swap(array, min, i); 20 | } 21 | } 22 | 23 | int main() { 24 | int array_size = 10; 25 | int array[10] = {45, 7, 125, 18, 3, 5, 11, 107, 60, 4}; 26 | 27 | selection_sort(array, array_size); 28 | 29 | printf("Sorted Array:\n"); 30 | int i; 31 | for (i = 0; i < array_size; i++) 32 | printf("%d ", array[i]); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /src/c/TowerOfHanoi.c: -------------------------------------------------------------------------------- 1 | /* 2 | Torre de Hanoi em C 3 | */ 4 | 5 | #include 6 | 7 | void hanoi(int pino0, int pino2, int pino1, int discos) { 8 | if (discos == 1) 9 | printf("Move de %i para %i\n", pino0, pino2); 10 | 11 | else { 12 | hanoi(pino0, pino1, pino2, discos - 1); 13 | hanoi(pino0, pino2, pino1, 1); 14 | hanoi(pino1, pino2, pino0, discos - 1); 15 | } 16 | } 17 | 18 | int main() { 19 | hanoi(0, 2, 1, 3); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /src/cpp/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int binarySearch(int value, vector &vec, int leftIndex, int rightIndex) { 7 | int mid = (leftIndex + rightIndex) / 2; 8 | 9 | if (leftIndex <= rightIndex) { 10 | if (value > vec[mid]) { 11 | leftIndex = mid + 1; 12 | return binarySearch(value, vec, leftIndex, rightIndex); 13 | } else if (value < vec[mid]) { 14 | rightIndex = mid - 1; 15 | return binarySearch(value, vec, leftIndex, rightIndex); 16 | } else { 17 | return mid; 18 | } 19 | } else { 20 | return -1; 21 | } 22 | } 23 | 24 | int main() { 25 | vector vec; 26 | 27 | for (int index = 1; index <= 50; index++) { 28 | vec.push_back(index); 29 | } 30 | 31 | int value = 45; 32 | 33 | int index = binarySearch(value, vec, 0, vec.size()); 34 | 35 | if (index >= 0) { 36 | cout << "Value " << to_string(value) << " found at position " 37 | << to_string(index) << endl; 38 | } else { 39 | cout << "Could not find the value " << to_string(value) << endl; 40 | } 41 | } -------------------------------------------------------------------------------- /src/cpp/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector bubbleSort(vector vector) { 7 | for (uint32_t end = vector.size() - 1; end > 0; --end) { 8 | for (uint32_t index = 0; index < end; ++index) { 9 | if (vector[index] > vector[index + 1]) { 10 | int temp = vector[index]; 11 | vector[index] = vector[index + 1]; 12 | vector[index + 1] = temp; 13 | } 14 | } 15 | } 16 | return vector; 17 | } 18 | 19 | void showVector(vector vector) { 20 | for (uint32_t i = 0; i < vector.size(); ++i) { 21 | if (i + 1 == vector.size()) 22 | cout << vector[i]; 23 | else 24 | cout << vector[i] << ", "; 25 | } 26 | cout << "\n"; 27 | } 28 | 29 | int main() { 30 | vector vector; 31 | for (uint32_t i = 0; i < 10; ++i) { 32 | vector.push_back(rand() % 100); 33 | } 34 | cout << "Initial Vector: "; 35 | showVector(vector); 36 | vector = bubbleSort(vector); 37 | cout << "Sorted Vector: "; 38 | showVector(vector); 39 | } 40 | -------------------------------------------------------------------------------- /src/cpp/CalculatePi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | float pi = 0.0; 5 | float denominator = 1.0; 6 | float operation = 1.0; 7 | 8 | float pi_calculator(int terms) { 9 | for (int i = 0; i < terms; i++) { 10 | pi += operation * (4.0 / denominator); 11 | denominator += 2.0; 12 | operation *= -1.0; 13 | } 14 | return pi; 15 | } 16 | 17 | int main() { 18 | float result = pi_calculator(100000); 19 | cout << result; 20 | } 21 | -------------------------------------------------------------------------------- /src/cpp/ConnectedComponents.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define VERTICES 6 5 | #define INF -1 6 | 7 | std::vector visited(VERTICES, false); // Array to track visited vertices 8 | int components = 0; 9 | 10 | // Adjacency matrix representing the graph 11 | int matrix[VERTICES][VERTICES] = { 12 | {0, INF, 1, INF, INF, INF}, {INF, 0, INF, 1, 1, INF}, 13 | {1, INF, 0, INF, INF, INF}, {INF, 1, INF, 0, 1, 1}, 14 | {INF, 1, INF, 1, 0, 1}, {INF, INF, INF, 1, 1, 0}}; 15 | 16 | // Recursive method to find connected components using adjacency matrix 17 | void findConnectedComponents(int current) { 18 | for (int i = 0; i < VERTICES; i++) { 19 | if (!visited[i] && matrix[current][i] == 1) { 20 | visited[i] = true; 21 | components++; 22 | std::cout << "(" << i << ")-"; 23 | findConnectedComponents(i); 24 | } 25 | } 26 | } 27 | 28 | int main() { 29 | // Initialize all vertices as unvisited 30 | for (int i = 0; i < VERTICES; i++) 31 | visited[i] = false; 32 | 33 | // For each vertex, if it is unvisited, start a DFS and count components 34 | for (int i = 0; i < VERTICES; i++) { 35 | if (!visited[i]) { 36 | components = 0; 37 | visited[i] = true; 38 | std::cout << "Starting at vertex (" << i << ")-"; 39 | findConnectedComponents(i); 40 | std::cout << "\nNumber of connected components starting from vertex " << i 41 | << ": " << components << "\n\n"; 42 | } 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /src/cpp/Exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | long long int n, exp; 6 | 7 | std::cin >> n >> exp; 8 | 9 | long long int result = 1; 10 | 11 | for (long long int i = 0; i < exp; i++) { 12 | result *= n; 13 | } 14 | 15 | std::cout << result << std::endl; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/cpp/ExponentiationRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long int exp(int n, int pow) { 4 | 5 | if (pow == 0) 6 | return 1; 7 | 8 | return n * exp(n, pow - 1); 9 | } 10 | 11 | int main() { 12 | 13 | long long int n, pow; 14 | 15 | std::cin >> n >> pow; 16 | 17 | n = exp(n, pow); 18 | std::cout << n << std::endl; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /src/cpp/Factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int factorial(int n) { 4 | 5 | int fact = 1; 6 | for (size_t i = 1; i <= n; i++) { 7 | fact = i * fact; 8 | } 9 | 10 | return fact; 11 | } 12 | 13 | int main() { 14 | 15 | int nums[] = {0, 1, 2, 3, 4, 5}; 16 | 17 | for (auto i : nums) { 18 | std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl; 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /src/cpp/FactorialRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int factorial(int n) { 4 | 5 | if (n == 0) 6 | return 1; 7 | 8 | else 9 | return n * (factorial(n - 1)); 10 | } 11 | 12 | int main() { 13 | 14 | int nums[] = {0, 1, 2, 3, 4, 5}; 15 | 16 | for (auto i : nums) { 17 | std::cout << std::to_string(i) + "! = " << factorial(i) << std::endl; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /src/cpp/FibonacciIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int fibonacci(int n) { 6 | int last = 0; 7 | int curr = 1; 8 | for (int index = 0; index < n; ++index) { 9 | int temp = curr; 10 | curr += last; 11 | last = temp; 12 | } 13 | return last; 14 | } 15 | 16 | int main() { cout << fibonacci(12) << endl; } 17 | -------------------------------------------------------------------------------- /src/cpp/FibonacciMemoization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | vector memo; 7 | 8 | int fibonacci(int n) { 9 | if (n <= 1) { 10 | return n; 11 | } 12 | if (memo[n] != -1) { 13 | return memo[n]; 14 | } 15 | 16 | memo[n] = fibonacci(n - 1) + fibonacci(n - 2); 17 | return memo[n]; 18 | } 19 | 20 | int main() { 21 | int test_nbr = 12; 22 | 23 | // Initialize the memoization table with -1 (uncomputed) 24 | memo.assign(test_nbr + 1, -1); 25 | 26 | cout << "memoization: " << fibonacci(test_nbr) << endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /src/cpp/FibonacciRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int fibonacci(int n) { 6 | if (n <= 1) { 7 | return n; 8 | } 9 | return fibonacci(n - 1) + fibonacci(n - 2); 10 | } 11 | 12 | int main() { cout << fibonacci(12) << endl; } 13 | -------------------------------------------------------------------------------- /src/cpp/FindDistinctSubsets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /* 6 | Problem Statement: 7 | Given an integer array nums of unique elements, return all possible 8 | subsets (the power set). 9 | 10 | The solution set must not contain duplicate subsets. Return the solution in any 11 | order. 12 | */ 13 | 14 | // Using Bit Manipulation 15 | // 1) Traverse all subsets 16 | // 2) Traverse all elements of nums 17 | // 3) Check if jth bit is set in i 18 | // It is like for 3 elements: 19 | // 000, 001, 010, 011, 100, 101, 110, 111 20 | // where 1 means that element is present in the subset 21 | // Time: O(n * 2ⁿ) 22 | // Space: O(1) 23 | vector> subsets(vector &nums) { 24 | int n = nums.size(); 25 | int total = 1 << n; // 2ⁿ 26 | vector> ans(total); 27 | 28 | // Traverse all subsets 29 | for (int i = 0; i < total; i++) // 2ⁿ 30 | { 31 | // Traverse elements of nums 32 | for (int j = 0; j < n; j++) // n 33 | { 34 | // Check if jth bit is set in i 35 | if ((1 << j) & i) { 36 | ans[i].push_back(nums[j]); 37 | } 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | 44 | int main() { 45 | vector nums = {1, 2, 3}; 46 | vector> ans = subsets(nums); 47 | 48 | cout << "Subsets are: \n"; 49 | for (auto v : ans) { 50 | cout << "[ "; 51 | for (auto i : v) { 52 | cout << i << " "; 53 | } 54 | cout << "]\n"; 55 | } 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /src/cpp/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void insertionSort(vector &vector) { 7 | 8 | for (uint32_t index = 1; index < vector.size(); index++) { 9 | int key = vector[index]; 10 | int i = index - 1; 11 | 12 | while (i >= 0 && vector[i] > key) { 13 | vector[i + 1] = vector[i]; 14 | i--; 15 | } 16 | 17 | vector[i + 1] = key; 18 | } 19 | } 20 | 21 | void showVector(vector vector) { 22 | for (uint32_t i = 0; i < vector.size(); ++i) { 23 | cout << vector[i] << ", "; 24 | } 25 | cout << "\n"; 26 | } 27 | 28 | int main() { 29 | vector vector; 30 | for (uint32_t i = 0; i < 10; ++i) { 31 | vector.push_back(rand() % 100); 32 | } 33 | showVector(vector); 34 | insertionSort(vector); 35 | showVector(vector); 36 | } 37 | -------------------------------------------------------------------------------- /src/cpp/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int linear_search(vector &nums, int target) { 7 | 8 | for (size_t i = 0; i < nums.size(); i++) { 9 | 10 | if (nums[i] == target) 11 | return i; 12 | } 13 | 14 | return -1; 15 | } 16 | 17 | int main() { 18 | 19 | vector nums = {1, 2, 3, 4, 5, 27, -1, 12, 999}; 20 | int target; 21 | 22 | cout << "Enter the number you would like to search in the vector: "; 23 | cin >> target; 24 | cout << "\n"; 25 | 26 | int pos = linear_search(nums, target); 27 | 28 | if (pos > -1) { 29 | cout << "Number found in the vector in the position: " << pos << endl; 30 | } else { 31 | cout << "Number not found in the vector." << endl; 32 | } 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /src/cpp/LinearSearchRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int linearSearchRecursive(int arr[], int n, int index, int target) { 6 | if (index >= n) { 7 | return -1; 8 | } 9 | 10 | if (arr[index] == target) { 11 | return index; 12 | } 13 | 14 | return linearSearchRecursive(arr, n, index + 1, target); 15 | } 16 | 17 | int main() { 18 | int n; 19 | cout << "Enter The size of array : "; 20 | cin >> n; 21 | int arr[n]; 22 | cout << "Enter the element of array : " << endl; 23 | for (int i = 0; i < n; i++) { 24 | cin >> arr[i]; 25 | } 26 | 27 | int target; 28 | cout << "Enter the element you need to search in the array : "; 29 | cin >> target; 30 | int answer = linearSearchRecursive(arr, n, 0, target); 31 | if (answer >= 0) { 32 | cout << "Target Element Found on index : " << answer << endl; 33 | } else { 34 | cout << "Target Element Not Found" << endl; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/cpp/MaxRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int max_recursive(std::vector nums, int n) { 5 | 6 | if (n == 1) 7 | return nums[0]; 8 | else { 9 | int aux = max_recursive(nums, n - 1); 10 | 11 | if (aux > nums[n - 1]) 12 | return aux; 13 | 14 | return nums[n - 1]; 15 | } 16 | } 17 | 18 | int main() { 19 | 20 | std::vector nums{1, 2, 3, 4, 32, 6, 7, 8, 9, 10}; 21 | 22 | std::cout << "nums = {"; 23 | for (auto &i : nums) { 24 | 25 | std::cout << i; 26 | 27 | if (&i != &nums.back()) { 28 | std::cout << ","; 29 | } 30 | } 31 | std::cout << "}" << std::endl; 32 | 33 | std::cout << "Max = " << max_recursive(nums, nums.size()) << std::endl; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /src/cpp/MinMaxIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | 7 | int arr[] = {1, 5, -20, 6, 15}; 8 | 9 | int min = arr[0]; 10 | int max = arr[0]; 11 | 12 | for (auto &i : arr) { 13 | if (i < min) 14 | min = i; 15 | else if (i > max) 16 | max = i; 17 | } 18 | 19 | cout << "Max = " + to_string(max) + "\nMin = " + to_string(min) << endl; 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /src/cpp/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int partition(vector &vector, int start, int end) { 7 | int pivot = vector[end]; 8 | int index = start; 9 | 10 | for (int i = start; i < end; i++) { 11 | if (vector[i] < pivot) { 12 | int temp = vector[i]; 13 | vector[i] = vector[index]; 14 | vector[index] = temp; 15 | index++; 16 | } 17 | } 18 | 19 | if (pivot <= vector[index]) { 20 | vector[end] = vector[index]; 21 | vector[index] = pivot; 22 | } 23 | 24 | return index; 25 | } 26 | 27 | void quickSort(vector &vector, int start, int end) { 28 | if (start < end) { 29 | int pivot = partition(vector, start, end); 30 | quickSort(vector, start, pivot - 1); 31 | quickSort(vector, pivot + 1, end); 32 | } 33 | } 34 | 35 | void quickSort(vector &vector) { quickSort(vector, 0, vector.size() - 1); } 36 | 37 | void showVector(vector vector) { 38 | for (uint32_t i = 0; i < vector.size(); ++i) { 39 | cout << vector[i] << ", "; 40 | } 41 | cout << "\n"; 42 | } 43 | 44 | int main() { 45 | vector vector; 46 | for (uint32_t i = 0; i < 10; ++i) { 47 | vector.push_back(rand() % 100); 48 | } 49 | showVector(vector); 50 | quickSort(vector); 51 | showVector(vector); 52 | } 53 | -------------------------------------------------------------------------------- /src/cpp/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void selectionSort(vector &vector) { 7 | for (uint32_t index = 0; index < vector.size() - 1; index++) { 8 | uint32_t min = index; 9 | 10 | for (uint32_t tempIndex = index + 1; tempIndex < vector.size(); 11 | ++tempIndex) { 12 | if (vector[tempIndex] < vector[min]) { 13 | min = tempIndex; 14 | } 15 | } 16 | 17 | if (min != index) { 18 | int temp = vector[index]; 19 | vector[index] = vector[min]; 20 | vector[min] = temp; 21 | } 22 | } 23 | } 24 | 25 | void showVector(vector vector) { 26 | for (uint32_t i = 0; i < vector.size(); ++i) { 27 | cout << vector[i] << ", "; 28 | } 29 | cout << "\n"; 30 | } 31 | 32 | int main() { 33 | vector vector; 34 | for (uint32_t i = 0; i < 10; ++i) { 35 | vector.push_back(rand() % 100); 36 | } 37 | showVector(vector); 38 | selectionSort(vector); 39 | showVector(vector); 40 | } -------------------------------------------------------------------------------- /src/cpp/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /*! 6 | * \brief Determine whether in the list of retrieved numbers there is a 7 | combination of two numbers that resulted in the target sum. 8 | * \return Two indexes of the list whose sum of elements results in the 9 | target value 10 | */ 11 | std::vector twoSum(std::vector &nums, int target) { 12 | std::unordered_map mapSum; // val, vect 13 | 14 | for (int i = 0; i < nums.size(); i++) { 15 | int compTarget = target - nums[i]; 16 | 17 | if (mapSum.count(compTarget)) { 18 | return {i, mapSum[compTarget]}; 19 | } else { 20 | mapSum.insert({nums[i], i}); 21 | } 22 | } 23 | 24 | return {}; 25 | } 26 | 27 | int main() { 28 | std::vector values{9, 1, 2, 5, 7, 11, 15}; 29 | int target = 9; 30 | 31 | auto sumIdxFor = twoSum(values, target); 32 | if (sumIdxFor.empty()) { 33 | std::cout << "no existent values with two sum: " << target << " in array" 34 | << std::endl; 35 | } else { 36 | std::cout << "Two sum for target: " << target << " in array is " 37 | << values[sumIdxFor[0]] << " and " << values[sumIdxFor[1]] 38 | << std::endl; 39 | } 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /src/go/binary_search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func BinarySearch(seq []int, element, start, end int) int { 6 | index := (start + end) / 2 7 | 8 | if index < len(seq) && seq[index] == element { 9 | return index 10 | } 11 | 12 | if start != end { 13 | if seq[index] < element { 14 | return BinarySearch(seq, element, index+1, end) 15 | } 16 | 17 | return BinarySearch(seq, element, start, index-1) 18 | } 19 | 20 | return -1 21 | } 22 | 23 | func main() { 24 | value := 7 25 | slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} 26 | fmt.Println("Slice:", slice) 27 | index := BinarySearch(slice, value, 0, len(slice)) 28 | fmt.Println("Value", value, "found in index:", index) 29 | } 30 | -------------------------------------------------------------------------------- /src/go/bubble_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Iterative 6 | func BubbleSortIterative(slice []int) { 7 | for index1 := len(slice) - 1; index1 > 0; index1-- { 8 | for index2 := 0; index2 < index1; index2++ { 9 | if slice[index2] > slice[index2+1] { 10 | slice[index2], slice[index2+1] = slice[index2+1], slice[index2] 11 | } 12 | } 13 | } 14 | } 15 | 16 | // Recursive 17 | func BubbleSortRecursive(slice []int, size int) { 18 | swaps := 0 19 | for index := 0; index < size-1; index++ { 20 | if slice[index] > slice[index+1] { 21 | slice[index], slice[index+1] = slice[index+1], slice[index] 22 | swaps++ 23 | } 24 | } 25 | if swaps != 0 { 26 | BubbleSortRecursive(slice, size-1) 27 | } 28 | } 29 | 30 | func main() { 31 | slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4} 32 | fmt.Println("Slice:", slice) 33 | BubbleSortIterative(slice) 34 | fmt.Println("BubbleSort:", slice) 35 | } 36 | -------------------------------------------------------------------------------- /src/go/calculate_pi.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func CalculatePi(terms []int) []float64 { 6 | var denominator float64 7 | var operation float64 8 | pi := make([]float64, len(terms)) 9 | 10 | for i := 0; i < len(terms); i++ { 11 | denominator = 1.0 12 | operation = 1.0 13 | for cont := 0; cont < terms[i]; cont++ { 14 | pi[i] += operation * (4 / denominator) 15 | denominator += 2 16 | operation *= -1 17 | } 18 | } 19 | return pi 20 | } 21 | 22 | func main() { 23 | slice := []int{10, 1000, 100000, 10000000} 24 | fmt.Println("Slice:", slice) 25 | fmt.Println("Pi:", CalculatePi(slice)) 26 | } 27 | -------------------------------------------------------------------------------- /src/go/cocktail_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func CocktailSort(slice []int) { 6 | 7 | swapped := true 8 | beginning := 0 9 | ending := len(slice) - 1 10 | 11 | for beginning < ending && swapped { 12 | 13 | for index := beginning; index < ending; index++ { 14 | if slice[index] > slice[index+1] { 15 | slice[index], slice[index+1] = slice[index+1], slice[index] 16 | swapped = true 17 | } 18 | } 19 | 20 | ending-- 21 | 22 | if swapped { 23 | swapped = false 24 | for index := ending; index > beginning; index-- { 25 | if slice[index] < slice[index-1] { 26 | slice[index], slice[index-1] = slice[index-1], slice[index] 27 | swapped = true 28 | } 29 | } 30 | } 31 | 32 | beginning++ 33 | } 34 | } 35 | 36 | func main() { 37 | slice := []int{1, 5, 8, 3, 7, 4, 9, 6, 2} 38 | fmt.Println("Slice:", slice) 39 | CocktailSort(slice) 40 | fmt.Println("CocktailSort:", slice) 41 | } 42 | -------------------------------------------------------------------------------- /src/go/comb_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func CombSort(slice []int) { 6 | shrinkFactor := 1.247330950103979 7 | gap := len(slice) 8 | swapped := true 9 | i := 0 10 | 11 | for gap > 1 || swapped { 12 | if gap > 1 { 13 | gap = int(float64(gap) / shrinkFactor) 14 | } 15 | 16 | swapped = false 17 | i = 0 18 | 19 | for gap+i < len(slice) { 20 | if slice[i]-slice[i+gap] > 0 { 21 | slice[i], slice[i+gap] = slice[i+gap], slice[i] 22 | swapped = true 23 | } 24 | i++ 25 | } 26 | } 27 | } 28 | 29 | func main() { 30 | slice := []int{6, 5, 8, 7, 3, 4, 2, 1, 9} 31 | fmt.Println("Slice:", slice) 32 | CombSort(slice) 33 | fmt.Println("CombSort:", slice) 34 | } 35 | -------------------------------------------------------------------------------- /src/go/counting_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func CountingSort(slice []int) { 6 | if len(slice) < 1 { 7 | return 8 | } 9 | 10 | higher := slice[0] 11 | 12 | for index := 1; index < len(slice); index++ { 13 | if slice[index] > higher { 14 | higher = slice[index] 15 | } 16 | } 17 | 18 | var temp = make([]int, higher) 19 | 20 | for index := 0; index < len(slice); index++ { 21 | temp[slice[index]-1]++ 22 | } 23 | 24 | for index := 1; index < len(temp); index++ { 25 | temp[index] += temp[index-1] 26 | } 27 | 28 | var temp2 = make([]int, len(slice)) 29 | 30 | for index := 0; index < len(temp2); index++ { 31 | temp2[temp[slice[index]-1]-1] = slice[index] 32 | temp[slice[index]-1]-- 33 | } 34 | 35 | for index := 0; index < len(temp2); index++ { 36 | slice[index] = temp2[index] 37 | } 38 | } 39 | 40 | func main() { 41 | slice := []int{9, 5, 8, 7, 3, 2, 1, 6, 4} 42 | fmt.Println("Slice:", slice) 43 | CountingSort(slice) 44 | fmt.Println("CountingSort:", slice) 45 | } 46 | -------------------------------------------------------------------------------- /src/go/deque.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Deque struct { 6 | Store []int 7 | } 8 | 9 | // Time complexity: O(1) 10 | func (deque *Deque) RPush(element int) { 11 | deque.Store = append(deque.Store, element) 12 | } 13 | 14 | // Time complexity: O(n) 15 | func (deque *Deque) LPush(element int) { 16 | deque.Store = append([]int{element}, deque.Store...) 17 | } 18 | 19 | // Time complexity: O(1) 20 | func (deque *Deque) RPop() *int { 21 | if len(deque.Store) == 0 { 22 | return nil 23 | } 24 | 25 | element := deque.Store[len(deque.Store)-1] 26 | deque.Store = deque.Store[:len(deque.Store)-1] 27 | 28 | return &element 29 | } 30 | 31 | // Time complexity: O(n) 32 | func (deque *Deque) LPop() *int { 33 | if len(deque.Store) == 0 { 34 | return nil 35 | } 36 | 37 | element := deque.Store[0] 38 | deque.Store = deque.Store[1:] 39 | 40 | return &element 41 | } 42 | 43 | func main() { 44 | deque := Deque{} 45 | 46 | fmt.Println("RPush(1, 2, 3)") 47 | 48 | deque.RPush(1) 49 | deque.RPush(2) 50 | deque.RPush(3) 51 | 52 | fmt.Println("RPop(): ", *deque.RPop()) 53 | fmt.Println("RPop(): ", *deque.RPop()) 54 | fmt.Println("RPop(): ", *deque.RPop()) 55 | 56 | fmt.Println("LPush(1, 2, 3)") 57 | 58 | deque.LPush(1) 59 | deque.LPush(2) 60 | deque.LPush(3) 61 | 62 | fmt.Println("RPop(): ", *deque.RPop()) 63 | fmt.Println("RPop(): ", *deque.RPop()) 64 | fmt.Println("RPop(): ", *deque.RPop()) 65 | } 66 | -------------------------------------------------------------------------------- /src/go/exponentiation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Exponentiation(base int, exponent int) int { 6 | for index := 0; index < (exponent - 1); index++ { 7 | base *= exponent 8 | } 9 | return base 10 | } 11 | 12 | func main() { 13 | fmt.Println("Exponentiation:", Exponentiation(5, 5)) 14 | } 15 | -------------------------------------------------------------------------------- /src/go/factorial.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Factorial(value int) int { 6 | if value == 1 { 7 | return 1 8 | } 9 | return value * Factorial(value-1) 10 | } 11 | 12 | func main() { 13 | fmt.Println("Factorial:", Factorial(6)) 14 | } 15 | -------------------------------------------------------------------------------- /src/go/fibonacci_iterative.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Fibonacci(n int) int { 6 | if n <= 1 { 7 | return 1 8 | } 9 | 10 | a, b := 1, 1 11 | for i := 2; i <= n; i++ { 12 | a, b = b, a+b 13 | } 14 | return b 15 | } 16 | 17 | func main() { 18 | n := 9 19 | fmt.Println("Fibonacci Iterative:", Fibonacci(n)) 20 | } 21 | -------------------------------------------------------------------------------- /src/go/fibonacci_memoization.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var memo = make(map[int]int) 6 | 7 | func Fibonacci(n int) int { 8 | if n <= 1 { 9 | return 1 10 | } 11 | 12 | // Check if the value is already memoized 13 | if val, ok := memo[n]; ok { 14 | return val 15 | } 16 | 17 | // Calculate Fibonacci recursively and store the result in memoization 18 | result := Fibonacci(n-1) + Fibonacci(n-2) 19 | memo[n] = result 20 | return result 21 | } 22 | 23 | func main() { 24 | n := 9 25 | fmt.Println("Fibonacci Memoization:", Fibonacci(n)) 26 | } 27 | -------------------------------------------------------------------------------- /src/go/fibonacci_recursive.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Fibonacci(value int) int { 6 | if value <= 1 { 7 | return 1 8 | } 9 | return Fibonacci(value-1) + Fibonacci(value-2) 10 | } 11 | 12 | func main() { 13 | fmt.Println("Fibonacci:", Fibonacci(9)) 14 | } 15 | -------------------------------------------------------------------------------- /src/go/floyd_warshall.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // Graphs - Floyd-Warshall Algorithm in GO 6 | // Go PlayGround link: https://go.dev/play/p/tIRTHkNf7Fz 7 | 8 | // Floyd-Warshall Algorithm 9 | func FloydWarshall(graph [][]int) [][]int { 10 | // Initialize the distance matrix 11 | dist := make([][]int, len(graph)) 12 | for i := range dist { 13 | dist[i] = make([]int, len(graph)) 14 | copy(dist[i], graph[i]) 15 | } 16 | 17 | // Traverse the vertices 18 | for k := 0; k < len(graph); k++ { 19 | // Traverse the rows 20 | for i := 0; i < len(graph); i++ { 21 | // Traverse the columns 22 | for j := 0; j < len(graph); j++ { 23 | // Check if the path passing through vertex k is shorter 24 | if dist[i][k]+dist[k][j] < dist[i][j] { 25 | dist[i][j] = dist[i][k] + dist[k][j] 26 | } 27 | } 28 | } 29 | } 30 | 31 | return dist 32 | } 33 | 34 | var graph = [][]int{ 35 | {0, 5, 999, 10}, 36 | {999, 0, 3, 999}, 37 | {999, 999, 0, 1}, 38 | {999, 999, 999, 0}, 39 | } 40 | 41 | func main() { 42 | fmt.Println(FloydWarshall(graph)) 43 | } 44 | -------------------------------------------------------------------------------- /src/go/gnome_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func GnomeSort(slice []int) { 6 | pivot := 0 7 | size := len(slice) 8 | 9 | for pivot < size-1 { 10 | if slice[pivot] > slice[pivot+1] { 11 | slice[pivot], slice[pivot+1] = slice[pivot+1], slice[pivot] 12 | if pivot > 0 { 13 | pivot -= 2 14 | } 15 | } 16 | pivot++ 17 | } 18 | } 19 | 20 | func main() { 21 | slice := []int{2, 5, 1, 7, 4, 9, 8, 6, 3} 22 | fmt.Println("Slice:", slice) 23 | GnomeSort(slice) 24 | fmt.Println("GnomeSort:", slice) 25 | } 26 | -------------------------------------------------------------------------------- /src/go/insertion_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func InsertionSort(slice []int) { 6 | for index1 := 1; index1 < len(slice); index1++ { 7 | currentValue := slice[index1] 8 | index2 := index1 - 1 9 | 10 | for index2 >= 0 && currentValue < slice[index2] { 11 | slice[index2+1] = slice[index2] 12 | index2-- 13 | } 14 | 15 | slice[index2+1] = currentValue 16 | } 17 | } 18 | 19 | func main() { 20 | slice := []int{9, 8, 7, 5, 1, 2, 4, 3, 6} 21 | fmt.Println("Slice:", slice) 22 | InsertionSort(slice) 23 | fmt.Println("InsertionSort:", slice) 24 | } 25 | -------------------------------------------------------------------------------- /src/go/isogram.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "unicode" 7 | ) 8 | 9 | /* 10 | Instructions 11 | 12 | Determine if a word or phrase is an isogram. 13 | 14 | An isogram (also known as a "non-pattern word") is a word or phrase without a repeating letter, 15 | however spaces and hyphens are allowed to appear multiple times. 16 | 17 | Examples of isograms: 18 | 19 | >> lumberjacks 20 | >> background 21 | >> downstream 22 | >> six-year-old 23 | 24 | The word isograms, however, is not an isogram, because the s repeats. 25 | */ 26 | func main() { 27 | fmt.Println(IsIsogram("isograms")) 28 | fmt.Println(IsIsogram("isogram")) 29 | } 30 | 31 | // IsIsogram returns true if the input s is an isogram 32 | func IsIsogram(word string) bool { 33 | word = strings.ToLower(word) 34 | for i, c := range word { 35 | if unicode.IsLetter(c) && strings.ContainsRune(word[i+1:], c) { 36 | return false 37 | } 38 | } 39 | return true 40 | } 41 | -------------------------------------------------------------------------------- /src/go/linear_search.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | myArray := []string{"c", "f", "g", "u"} 7 | fmt.Println("Element found: ", SearchPosition(myArray, "g")) 8 | fmt.Println("Element not found: ", SearchPosition(myArray, "i")) 9 | } 10 | 11 | func SearchPosition(myArray []string, element string) int { 12 | for i, v := range myArray { 13 | if v == element { 14 | return i 15 | } 16 | } 17 | return -1 18 | } 19 | -------------------------------------------------------------------------------- /src/go/merge_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func MergeSort(slice []int) { 6 | if len(slice) > 1 { 7 | half := len(slice) / 2 8 | 9 | var sliceLeftSide []int 10 | var sliceRightSide []int 11 | 12 | for index := 0; index < half; index++ { 13 | sliceLeftSide = append(sliceLeftSide, slice[index]) 14 | } 15 | 16 | for index := half; index < len(slice); index++ { 17 | sliceRightSide = append(sliceRightSide, slice[index]) 18 | } 19 | 20 | MergeSort(sliceLeftSide) 21 | MergeSort(sliceRightSide) 22 | 23 | i := 0 24 | j := 0 25 | k := 0 26 | 27 | for i < len(sliceLeftSide) && j < len(sliceRightSide) { 28 | if sliceLeftSide[i] < sliceRightSide[j] { 29 | slice[k] = sliceLeftSide[i] 30 | i++ 31 | } else { 32 | slice[k] = sliceRightSide[j] 33 | j++ 34 | } 35 | k++ 36 | } 37 | 38 | for i < len(sliceLeftSide) { 39 | slice[k] = sliceLeftSide[i] 40 | i++ 41 | k++ 42 | } 43 | 44 | for j < len(sliceRightSide) { 45 | slice[k] = sliceRightSide[j] 46 | j++ 47 | k++ 48 | } 49 | } 50 | } 51 | 52 | func main() { 53 | slice := []int{4, 6, 7, 1, 2, 3, 5, 9, 8} 54 | fmt.Println("Slice:", slice) 55 | MergeSort(slice) 56 | fmt.Println("MergeSort:", slice) 57 | } 58 | -------------------------------------------------------------------------------- /src/go/min_max_recursive.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func MaxDivideAndConquer(array []int, start int, end int) int { 6 | if start == end { 7 | return array[start] 8 | } 9 | 10 | middle := (start + end) / 2 11 | aux1 := MaxDivideAndConquer(array, start, middle) 12 | aux2 := MaxDivideAndConquer(array, middle+1, end) 13 | 14 | if aux1 > aux2 { 15 | return aux1 16 | } 17 | 18 | return aux2 19 | } 20 | 21 | func RecursiveMinMax(array []int, min int, max int, index int) { 22 | if array[index] < min { 23 | min = array[index] 24 | } 25 | if array[index] > max { 26 | max = array[index] 27 | } 28 | if index < len(array)-1 { 29 | RecursiveMinMax(array, min, max, index+1) 30 | } else { 31 | fmt.Println("Minimum:", min) 32 | fmt.Println("Maximum:", max) 33 | } 34 | } 35 | 36 | func main() { 37 | slice := []int{2, 3, 9, 1, 6, 8, 5} 38 | RecursiveMinMax(slice, 999, 0, 0) 39 | } 40 | -------------------------------------------------------------------------------- /src/go/quick_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func QuickSort(slice []int) { 6 | quick(slice, 0, len(slice)-1) 7 | } 8 | 9 | func quick(slice []int, start int, end int) { 10 | if start < end { 11 | pivotIndex := split(slice, start, end) 12 | quick(slice, start, pivotIndex-1) 13 | quick(slice, pivotIndex+1, end) 14 | } 15 | } 16 | 17 | func split(slice []int, start int, end int) int { 18 | pivot := slice[end] 19 | j := start 20 | 21 | for index := start; index < end; index++ { 22 | if slice[index] < pivot { 23 | slice[index], slice[j] = slice[j], slice[index] 24 | j++ 25 | } 26 | } 27 | 28 | if pivot <= slice[j] { 29 | slice[end] = slice[j] 30 | slice[j] = pivot 31 | } 32 | 33 | return j 34 | } 35 | 36 | func main() { 37 | slice := []int{2, 1, 8, 4, 3, 7, 6, 5, 9} 38 | fmt.Println("Slice:", slice) 39 | QuickSort(slice) 40 | fmt.Println("QuickSort:", slice) 41 | } 42 | -------------------------------------------------------------------------------- /src/go/radix_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func RadixSort(slice []int) { 6 | 7 | if len(slice) == 0 { 8 | return 9 | } 10 | 11 | length := len(slice) 12 | higher := slice[0] 13 | exp := 1 14 | var temp []int 15 | 16 | for index := 0; index < length; index++ { 17 | temp = append(temp, 0) 18 | if slice[index] > higher { 19 | higher = slice[index] 20 | } 21 | } 22 | 23 | for higher/exp > 0 { 24 | var bucket [10]int 25 | 26 | for index := 0; index < length; index++ { 27 | bucket[(slice[index]/exp)%10]++ 28 | } 29 | 30 | for index := 1; index < 10; index++ { 31 | bucket[index] += bucket[index-1] 32 | } 33 | 34 | for index := length - 1; index >= 0; index-- { 35 | bucket[(slice[index]/exp)%10]-- 36 | temp[bucket[(slice[index]/exp)%10]] = slice[index] 37 | } 38 | 39 | for index := 0; index < length; index++ { 40 | slice[index] = temp[index] 41 | } 42 | 43 | exp *= 10 44 | } 45 | } 46 | 47 | func main() { 48 | slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4} 49 | fmt.Println("Slice:", slice) 50 | RadixSort(slice) 51 | fmt.Println("RadixSort:", slice) 52 | } 53 | -------------------------------------------------------------------------------- /src/go/selection_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func SelectionSort(slice []int) { 6 | for index1 := 0; index1 < len(slice)-1; index1++ { 7 | indexMin := index1 8 | 9 | for index2 := index1 + 1; index2 < len(slice); index2++ { 10 | if slice[index2] < slice[indexMin] { 11 | indexMin = index2 12 | } 13 | } 14 | 15 | if index1 != indexMin { 16 | slice[index1], slice[indexMin] = slice[indexMin], slice[index1] 17 | } 18 | } 19 | } 20 | 21 | func main() { 22 | slice := []int{1, 3, 2, 9, 7, 8, 5, 6, 4} 23 | fmt.Println("Slice:", slice) 24 | SelectionSort(slice) 25 | fmt.Println("SelectionSort:", slice) 26 | } 27 | -------------------------------------------------------------------------------- /src/go/shell_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func ShellSort(slice []int) { 6 | size := len(slice) 7 | gap := 1 8 | var j int 9 | 10 | for gap < size { 11 | gap = 3*gap + 1 12 | } 13 | 14 | for gap > 1 { 15 | gap /= 3 16 | for index := gap; index < size; index++ { 17 | value := slice[index] 18 | j = index - gap 19 | 20 | for j >= 0 && value < slice[j] { 21 | slice[j+gap] = slice[j] 22 | j -= gap 23 | } 24 | slice[j+gap] = value 25 | } 26 | } 27 | } 28 | 29 | func main() { 30 | slice := []int{5, 1, 4, 2, 3, 6, 9, 7, 8} 31 | fmt.Println("Slice:", slice) 32 | ShellSort(slice) 33 | fmt.Println("ShellSort:", slice) 34 | } 35 | -------------------------------------------------------------------------------- /src/go/stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // A simple stack using generics 6 | type Stack[T any] struct { 7 | items []T 8 | } 9 | 10 | func (stack *Stack[T]) Push(value T) { 11 | stack.items = append(stack.items, value) 12 | } 13 | 14 | func (stack *Stack[T]) Pop() T { 15 | n := len(stack.items) 16 | if n <= 0 { 17 | panic("Cannot pop an empty stack!") 18 | } 19 | value := stack.items[n-1] 20 | stack.items = stack.items[:n-1] 21 | return value 22 | } 23 | 24 | func (stack *Stack[T]) Show() { 25 | fmt.Printf("%v\n", stack.items) 26 | } 27 | 28 | func main() { 29 | stack := Stack[int]{} 30 | stack.Push(1) 31 | stack.Push(2) 32 | stack.Push(3) 33 | stack.Push(4) 34 | stack.Pop() 35 | fmt.Printf("Stack: ") 36 | stack.Show() 37 | } 38 | -------------------------------------------------------------------------------- /src/go/tower_of_hanoi.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Hanoi(pino0 int, pino2 int, pino1 int, numero int) { 6 | if numero == 1 { 7 | fmt.Println("Move from ", pino0, " to ", pino2) 8 | } else { 9 | Hanoi(pino0, pino1, pino2, numero-1) 10 | Hanoi(pino0, pino2, pino1, 1) 11 | Hanoi(pino1, pino2, pino0, numero-1) 12 | } 13 | } 14 | 15 | func main() { 16 | fmt.Println("Tower of Hanoi:") 17 | Hanoi(0, 2, 1, 3) 18 | } 19 | -------------------------------------------------------------------------------- /src/java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BuscaBinaria { 2 | 3 | public int posicao; 4 | 5 | BuscaBinaria(int[] array, int Objetivo) { 6 | this.posicao = BinarySearch(Objetivo, array); 7 | } 8 | 9 | public int GetResultado() { 10 | return this.posicao; 11 | } 12 | 13 | public int BinarySearch(int objetivo, int[] array) { 14 | int comeco = 0; 15 | int fim = array.length - 1; 16 | 17 | while (comeco <= fim) { 18 | int meio = comeco + (fim - comeco) / 2; 19 | if (array[meio] == objetivo) return meio; 20 | if (array[meio] < objetivo) comeco = meio + 1; 21 | else fim = meio - 1; 22 | } 23 | return -1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSort { 2 | 3 | public static void main(String[] args) { 4 | 5 | int vector[] = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5}; 6 | 7 | System.out.println("Bubble Sort:"); 8 | System.out.println("Unordered vector:"); 9 | showVector(vector); 10 | 11 | vector = bubbleSort(vector); 12 | 13 | System.out.println("Sorted vector:"); 14 | showVector(vector); 15 | } 16 | 17 | public static int[] bubbleSort(int vector[]) { 18 | int swap = 0; 19 | for (int i = 0; i < vector.length - 1; i++) { 20 | if (vector[i] > vector[i + 1]) { 21 | int temp = vector[i]; 22 | vector[i] = vector[i + 1]; 23 | vector[i + 1] = temp; 24 | swap++; 25 | } 26 | } 27 | if (swap != 0) bubbleSort(vector); 28 | return vector; 29 | } 30 | 31 | public static int[] bubbleSort2(int vector[]) { 32 | for (int i = 1; i < vector.length; i++) { 33 | int length = vector.length; 34 | for (int j = 0; j < length - i; j++) { 35 | if (vector[j] > vector[j + 1]) { 36 | int temp = vector[j]; 37 | vector[j] = vector[j + 1]; 38 | vector[j + 1] = temp; 39 | } 40 | } 41 | } 42 | return vector; 43 | } 44 | 45 | public static void showVector(int vector[]) { 46 | for (int i = 0; i < vector.length; i++) { 47 | System.out.print(vector[i] + ", "); 48 | } 49 | System.out.println(""); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/java/BucketSort.java: -------------------------------------------------------------------------------- 1 | public class BucketSort { 2 | 3 | /** 4 | * @param vetor Vetor que será ordenado /** Aplica a ordenação BucketSorte no vetor 5 | */ 6 | public int[] sort(int[] vetor) { 7 | 8 | final int[] code = hash(vetor); 9 | 10 | List[] buckets = new List[code[1]]; 11 | for (int i = 0; i < code[1]; i++) { 12 | buckets[i] = new ArrayList(); 13 | } 14 | 15 | for (int i : vetor) { 16 | buckets[hash(i, code)].add(i); 17 | } 18 | 19 | for (List bucket : buckets) { 20 | Collections.sort(bucket); 21 | } 22 | int ndx = 0; 23 | 24 | for (int b = 0; b < buckets.length; b++) { 25 | for (int v : buckets[b]) { 26 | vetor[ndx++] = v; 27 | } 28 | } 29 | return vetor; 30 | } 31 | 32 | private int[] hash(int[] input) { 33 | int m = input[0]; 34 | for (int i = 1; i < input.length; i++) { 35 | if (m < input[i]) { 36 | m = input[i]; 37 | } 38 | } 39 | return new int[] {m, (int) Math.sqrt(input.length)}; 40 | } 41 | 42 | private int hash(int i, int[] code) { 43 | return (int) ((double) i / code[0] * (code[1] - 1)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/java/CalculatePi.java: -------------------------------------------------------------------------------- 1 | public class CalculatePi { 2 | public static void main(String[] args) { 3 | int[] terms = {10, 1000, 100000, 10000000}; 4 | 5 | for (int i = 0; i < terms.length; i++) { 6 | System.out.println("(" + terms[i] + "): " + leibniz_pi_calculation(terms[i])); 7 | } 8 | } 9 | 10 | public static double leibniz_pi_calculation(int number) { 11 | double denominador = 1.0; 12 | double operacao = 1.0; 13 | double pi = 0.0; 14 | 15 | for (int i = 0; i < number; i++) { 16 | pi += operacao * (4.0 / denominador); 17 | denominador += 2.0; 18 | operacao *= -1.0; 19 | } 20 | return pi; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/java/CountingSort.java: -------------------------------------------------------------------------------- 1 | public class CountingSort { 2 | 3 | int getMax(int[] a, int n) { 4 | int max = a[0]; 5 | for (int i = 1; i < n; i++) { 6 | if (a[i] > max) max = a[i]; 7 | } 8 | return max; 9 | } 10 | 11 | void countSort(int[] a, int n) { 12 | int[] output = new int[n + 1]; 13 | int max = getMax(a, n); 14 | // int max = 42; 15 | int[] count = new int[max + 1]; 16 | 17 | for (int i = 0; i <= max; ++i) { 18 | count[i] = 0; 19 | } 20 | 21 | for (int i = 0; i < n; i++) { 22 | count[a[i]]++; 23 | } 24 | 25 | for (int i = 1; i <= max; i++) count[i] += count[i - 1]; 26 | 27 | for (int i = n - 1; i >= 0; i--) { 28 | output[count[a[i]] - 1] = a[i]; 29 | count[a[i]]--; 30 | } 31 | 32 | for (int i = 0; i < n; i++) { 33 | a[i] = output[i]; 34 | } 35 | } 36 | 37 | /* Function to print the array elements */ 38 | void printArray(int a[], int n) { 39 | int i; 40 | for (i = 0; i < n; i++) System.out.print(a[i] + " "); 41 | } 42 | 43 | public static void main(String args[]) { 44 | int a[] = {11, 30, 24, 7, 31, 16, 39, 41}; 45 | int n = a.length; 46 | CountingSort c1 = new CountingSort(); 47 | System.out.println("\nBefore sorting array elements are - "); 48 | c1.printArray(a, n); 49 | c1.countSort(a, n); 50 | System.out.println("\nAfter sorting array elements are - "); 51 | c1.printArray(a, n); 52 | System.out.println(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/java/Exponentiation.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | 3 | public static long exponenciacao(int base, int expoente) { 4 | 5 | int i; 6 | int result = base; 7 | 8 | for (i = 0; i < expoente - 1; i++) result *= base; 9 | 10 | return result; 11 | } 12 | 13 | public static void main(String args[]) { 14 | System.out.println("5 ^ 3 = " + exponenciacao(5, 3)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/java/ExponentiationRecursive.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | 3 | public static long exponenciacao(long base, long expoente) { // exponenciacao recursiva 4 | if (expoente == 0) return 1; 5 | return (base * exponenciacao(base, expoente - 1)); 6 | } 7 | 8 | public static void main(String args[]) { 9 | System.out.println("5 ^ 3 = " + exponenciacao(5, 3)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/java/Factorial.java: -------------------------------------------------------------------------------- 1 | public class Fatorial { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Fatorial de 7 : " + Fatorial(7)); 5 | } 6 | 7 | public static int Fatorial(int x) { 8 | int total = 1; 9 | for (int i = 2; i < x + 1; i++) { 10 | total = total * i; 11 | } 12 | return total; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/java/FactorialRecursive.java: -------------------------------------------------------------------------------- 1 | public class FatorialRecursiva { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Fatorial de 0 : " + Fatorial(0)); 5 | System.out.println("Fatorial de 1 : " + Fatorial(1)); 6 | System.out.println("Fatorial de 3 : " + Fatorial(3)); 7 | System.out.println("Fatorial de 7 : " + Fatorial(7)); 8 | } 9 | 10 | public static int Fatorial(int x) { 11 | if (x <= 1) return 1; 12 | else return x * Fatorial(x - 1); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/java/FibonacciIterative.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Fib(16) : " + Fibonacci(16)); 5 | } 6 | 7 | public static int Fibonacci(int x) { 8 | if (x <= 1) { 9 | return 1; 10 | } else { 11 | int n = 1, prox = 1; 12 | for (int i = 0; i < x - 1; i++) { 13 | int temp = prox; 14 | prox = prox + n; 15 | n = temp; 16 | } 17 | return n; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/java/FibonacciMemoization.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class Fibonacci { 4 | 5 | // Create a memoization HashMap to store computed Fibonacci values 6 | private static HashMap memo = new HashMap<>(); 7 | 8 | public static void main(String[] args) { 9 | int n = 16; 10 | System.out.println("Fib(" + n + ") : " + fibonacci(n)); 11 | } 12 | 13 | public static int fibonacci(int n) { 14 | if (n <= 1) { 15 | return 1; 16 | } 17 | 18 | // Check if the value is already computed and stored in the memoization HashMap 19 | if (memo.containsKey(n)) { 20 | return memo.get(n); 21 | } 22 | 23 | // Calculate Fibonacci recursively and store the result in memoization 24 | int result = fibonacci(n - 1) + fibonacci(n - 2); 25 | memo.put(n, result); 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/java/FibonacciRecursive.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Fib(16) : " + Fibonacci(16)); 5 | } 6 | 7 | public static int Fibonacci(int x) { 8 | if (x <= 1) return 1; 9 | else return Fibonacci(x - 1) + Fibonacci(x - 2); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/java/GnomeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class GnomeSort { 4 | public static void main(String[] args) { 5 | int vetor[] = {10, -10, -9, 9, 8, -8, 7, -7, 6, -6, 5, -5, 4, -4, 3, -3, 2, -2, 1, -1, 0}; 6 | System.out.println("Vetor antes da ordenação:" + Arrays.toString(vetor)); 7 | 8 | gnomeSort(vetor); 9 | System.out.println( 10 | "Vetor após ordenação com o algoritmo Gnome Sort: " + Arrays.toString(vetor)); 11 | } 12 | 13 | static void gnomeSort(int[] vetor) { 14 | int i = 0; 15 | while (i < vetor.length) { 16 | if (i == 0 || vetor[i] >= vetor[i - 1]) { 17 | i++; 18 | 19 | } else { 20 | int auxiliar = vetor[i]; 21 | vetor[i] = vetor[i - 1]; 22 | vetor[i - 1] = auxiliar; 23 | 24 | i--; 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/java/HeapSort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | 3 | /** 4 | * @param vetor Vetor que será ordenado Aplica a ordenação HeapSorte no vetor 5 | */ 6 | public int[] sort(int[] vetor) { 7 | 8 | for (int i = vetor.length / 2 - 1; i >= 0; i--) { 9 | heapify(vetor, vetor.length, i); 10 | } 11 | 12 | for (int i = vetor.length - 1; i >= 0; i--) { 13 | 14 | int temp = vetor[0]; 15 | vetor[0] = vetor[i]; 16 | vetor[i] = temp; 17 | 18 | heapify(vetor, i, 0); 19 | } 20 | return vetor; 21 | } 22 | 23 | void heapify(int arr[], int arrayLength, int rootElementIndex) { 24 | 25 | int leftIndex = 2 * rootElementIndex + 1; 26 | int rightIndex = 2 * rootElementIndex + 2; 27 | 28 | int largest = rootElementIndex; 29 | 30 | if (leftIndex < arrayLength && arr[leftIndex] > arr[largest]) largest = leftIndex; 31 | 32 | if (rightIndex < arrayLength && arr[rightIndex] > arr[largest]) largest = rightIndex; 33 | 34 | if (largest != rootElementIndex) { 35 | 36 | int swap = arr[rootElementIndex]; 37 | arr[rootElementIndex] = arr[largest]; 38 | arr[largest] = swap; 39 | 40 | heapify(arr, arrayLength, largest); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | 3 | public static void main(String[] args) { 4 | 5 | int vetor[] = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5}; 6 | 7 | System.out.println("Insertion Sort:"); 8 | System.out.println("Vetor não ordenado:"); 9 | mostraVetor(vetor); 10 | 11 | vetor = insertionSort(vetor); 12 | 13 | System.out.println("Vetor ordenado:"); 14 | mostraVetor(vetor); 15 | } 16 | 17 | public static int[] insertionSort(int vetor[]) { 18 | int chave, aux; 19 | for (int i = 0; i < vetor.length; i++) { 20 | chave = vetor[i]; 21 | aux = i - 1; 22 | while (aux >= 0 && vetor[aux] > chave) { 23 | vetor[aux + 1] = vetor[aux]; 24 | aux -= 1; 25 | } 26 | vetor[aux + 1] = chave; 27 | } 28 | return vetor; 29 | } 30 | 31 | public static void mostraVetor(int vetor[]) { 32 | for (int i = 0; i < vetor.length; i++) { 33 | System.out.print(vetor[i] + ", "); 34 | } 35 | System.out.println(""); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | public class LinearSearchIterative { 2 | public static void main(String[] args) { 3 | int array[] = {1, 2, 40, 233, 78, 83, 456}; 4 | System.out.println(LinearSearch(array, 40)); 5 | System.out.println(LinearSearch(array, 3)); 6 | } 7 | 8 | public static int LinearSearch(int array[], int value) { 9 | for (int i = 0; i < array.length; i++) { 10 | if (array[i] == value) { 11 | return i; 12 | } 13 | } 14 | return -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/java/MaxRecursive.java: -------------------------------------------------------------------------------- 1 | public class MaxMinArray { 2 | 3 | public static void main(String[] args) { 4 | int vetor[] = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5}; 5 | MaxMinRecursivo(vetor, vetor[0], vetor[0], 0); 6 | System.out.println("---------"); 7 | MaxMinIterativo(vetor); 8 | } 9 | 10 | public static void MaxMinRecursivo(int vetor[], int max, int min, int indice) { 11 | if (vetor[indice] > max) max = vetor[indice]; 12 | if (vetor[indice] < min) min = vetor[indice]; 13 | if (indice < vetor.length - 1) MaxMinRecursivo(vetor, max, min, indice + 1); 14 | else { 15 | System.out.println("Max : " + max); 16 | System.out.println("Min : " + min); 17 | } 18 | } 19 | 20 | public static void MaxMinIterativo(int vetor[]) { 21 | int max = vetor[0], min = vetor[0]; 22 | if (vetor.length > 1) { 23 | for (int i = 0; i < vetor.length; i++) { 24 | if (vetor[i] > max) max = vetor[i]; 25 | else if (vetor[i] < min) min = vetor[i]; 26 | } 27 | } 28 | System.out.println("Max : " + max); 29 | System.out.println("Min : " + min); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/java/MergeSort.java: -------------------------------------------------------------------------------- 1 | class MergeSort { 2 | void merge(int vetor[], int inicio, int meio, int fim) { 3 | int n1 = meio - inicio + 1; 4 | int n2 = fim - meio; 5 | int Inicial[] = new int[n1]; 6 | int Final[] = new int[n2]; 7 | for (int i = 0; i < n1; ++i) Inicial[i] = vetor[inicio + i]; 8 | for (int j = 0; j < n2; ++j) Final[j] = vetor[meio + 1 + j]; 9 | int i = 0, j = 0; 10 | int k = inicio; 11 | while (i < n1 && j < n2) { 12 | if (Inicial[i] <= Final[j]) { 13 | vetor[k] = Inicial[i]; 14 | i++; 15 | } else { 16 | vetor[k] = Final[j]; 17 | j++; 18 | } 19 | k++; 20 | } 21 | while (i < n1) { 22 | vetor[k] = Inicial[i]; 23 | i++; 24 | k++; 25 | } 26 | while (j < n2) { 27 | vetor[k] = Final[j]; 28 | j++; 29 | k++; 30 | } 31 | } 32 | 33 | void sort(int vetor[], int inicio, int fim) { 34 | if (inicio < fim) { 35 | int meio = (inicio + fim) / 2; 36 | sort(vetor, inicio, meio); 37 | sort(vetor, meio + 1, fim); 38 | merge(vetor, inicio, meio, fim); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/java/MinMaxIterative.java: -------------------------------------------------------------------------------- 1 | public class MinMaxIterativo { 2 | public static void main(String[] args) { 3 | int arr[] = {1, 5, -20, 6, 15}; 4 | int min = arr[0]; 5 | int max = arr[0]; 6 | 7 | for (int i : arr) { 8 | if (i < min) min = i; 9 | else if (i > max) max = i; 10 | } 11 | System.out.println("Max: " + max + "\nMin: " + min); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/java/MinMaxRecursive.java: -------------------------------------------------------------------------------- 1 | public class MinMaxRecursivo { 2 | 3 | public static void main(String[] args) { 4 | int[] arr = {9, 8, 13, 33, 18, 20, 88, 14, 40, 77}; 5 | MinMax(arr, arr[0], arr[0], 0); 6 | } 7 | 8 | public static void MinMax(int vect[], int minimo, int maximo, int indice) { 9 | if (vect[indice] < minimo) { 10 | minimo = vect[indice]; 11 | } 12 | if (vect[indice] > maximo) { 13 | maximo = vect[indice]; 14 | } 15 | if (indice < vect.length - 1) { 16 | MinMax(vect, minimo, maximo, indice + 1); 17 | } else { 18 | System.out.println("Mínimo :" + minimo + "\nMáximo: " + maximo); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/java/No.java: -------------------------------------------------------------------------------- 1 | public class No { 2 | int chave; 3 | No esq, dir; 4 | 5 | public No(int chave) { 6 | this.chave = chave; 7 | this.esq = null; 8 | this.dir = null; 9 | } 10 | 11 | public int getChave() { 12 | return chave; 13 | } 14 | 15 | public void setChave(int chave) { 16 | this.chave = chave; 17 | } 18 | 19 | public No getEsq() { 20 | return esq; 21 | } 22 | 23 | public void setEsq(No esq) { 24 | this.esq = esq; 25 | } 26 | 27 | public No getDir() { 28 | return dir; 29 | } 30 | 31 | public void setDir(No dir) { 32 | this.dir = dir; 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return "No{" + "chave: " + chave + ", esq: " + esq + ", dir: " + dir + '}'; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/java/NoPilha.java: -------------------------------------------------------------------------------- 1 | public class NoPilha { 2 | int chave; 3 | NoPilha prox; 4 | 5 | public NoPilha(int chave) { 6 | this.chave = chave; 7 | } 8 | 9 | public int getChave() { 10 | return chave; 11 | } 12 | 13 | public void setChave(int chave) { 14 | this.chave = chave; 15 | } 16 | 17 | public NoPilha getProx() { 18 | return prox; 19 | } 20 | 21 | public void setProx(NoPilha prox) { 22 | this.prox = prox; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/java/Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Palindromo { 2 | public static void main(String[] args) { 3 | String palavra, palavraInvertida = ""; 4 | palavra = "A grama é amarga"; 5 | 6 | for (int i = palavra.length() - 1; i >= 0; i--) { 7 | palavraInvertida += palavra.toLowerCase().charAt(i); 8 | } 9 | 10 | if (palavra.replace(" ", "").toLowerCase().equals(palavraInvertida.replace(" ", ""))) 11 | System.out.println("palavra é um palindromo!"); 12 | else System.out.println("palavra não é um palindromo!"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/java/Queue.java: -------------------------------------------------------------------------------- 1 | public class fila { 2 | 3 | public processo processoAtual; 4 | public fila proximaFila; 5 | 6 | public fila() { 7 | this.processoAtual = null; 8 | this.proximaFila = null; 9 | } 10 | 11 | public void inserirfila(processo processoNovo) { 12 | if (this.processoAtual == null) { 13 | this.processoAtual = processoNovo; 14 | this.proximaFila = new fila(); 15 | } else { 16 | this.proximaFila.inserirfila(processoNovo); 17 | } 18 | } 19 | 20 | public processo removerfila() { 21 | processo removido = this.processoAtual; 22 | this.processoAtual = this.proximaFila.processoAtual; 23 | this.proximaFila = this.proximaFila.proximaFila; 24 | return removido; 25 | } 26 | 27 | public String checkfila(String vazia) { 28 | if (this.proximaFila.proximaFila == null) { 29 | vazia = 30 | vazia + " " + this.processoAtual.getPrioridade() + " " + this.processoAtual.getTempo(); 31 | } else { 32 | vazia = 33 | vazia 34 | + " " 35 | + this.processoAtual.getPrioridade() 36 | + " " 37 | + this.processoAtual.getTempo() 38 | + " &&" 39 | + this.proximaFila.checkfila(vazia); 40 | } 41 | return vazia; 42 | } 43 | 44 | public boolean vaziafila() { 45 | if (this.proximaFila == null) { 46 | return true; 47 | } 48 | return false; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/java/QuickSort.java: -------------------------------------------------------------------------------- 1 | class QuickSort { 2 | 3 | int partition(int arr[], int low, int high) { 4 | int pivot = arr[high]; 5 | int i = (low - 1); 6 | for (int j = low; j < high; j++) { 7 | if (arr[j] <= pivot) { 8 | i++; 9 | int temp = arr[i]; 10 | arr[i] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | } 14 | int temp = arr[i + 1]; 15 | arr[i + 1] = arr[high]; 16 | arr[high] = temp; 17 | 18 | return i + 1; 19 | } 20 | 21 | void sort(int arr[], int low, int high) { 22 | if (low < high) { 23 | int pi = partition(arr, low, high); 24 | sort(arr, low, pi - 1); 25 | sort(arr, pi + 1, high); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/java/RadixSort.java: -------------------------------------------------------------------------------- 1 | public class RadixSort { 2 | 3 | /** 4 | * @param vetor Vetor que será ordenado Aplica a ordenação RadixSorte no vetor 5 | */ 6 | public int[] sort(int[] vetor) { 7 | int length = vetor.length, i, exp = 1, higher = vetor[0]; 8 | int[] temp = new int[10]; 9 | 10 | for (i = 1; i < length; i++) if (vetor[i] > higher) higher = vetor[i]; 11 | 12 | while (higher / exp > 0) { 13 | int[] bucket = new int[10]; 14 | 15 | for (i = 0; i < length; i++) bucket[(vetor[i] / exp) % 10]++; 16 | 17 | for (i = 1; i < 10; i++) bucket[i] += bucket[i - 1]; 18 | 19 | for (i = length - 1; i >= 0; i--) temp[--bucket[(vetor[i] / exp) % 10]] = vetor[i]; 20 | 21 | for (i = 0; i < length; i++) vetor[i] = temp[i]; 22 | 23 | exp = exp * 10; 24 | } 25 | return vetor; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | 3 | public static void main(String[] args) { 4 | 5 | int vetor[] = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5}; 6 | 7 | System.out.println("Selection Sort:"); 8 | System.out.println("Vetor não ordenado:"); 9 | mostraVetor(vetor); 10 | 11 | vetor = selectionSort(vetor, 0); 12 | 13 | System.out.println("Vetor ordenado:"); 14 | mostraVetor(vetor); 15 | } 16 | 17 | public static int[] selectionSort(int vetor[], int indice) { 18 | if (indice >= vetor.length - 1) return vetor; 19 | 20 | int minIndice = indice; 21 | 22 | for (int i = indice + 1; i < vetor.length; i++) if (vetor[i] < vetor[minIndice]) minIndice = i; 23 | 24 | int temp = vetor[indice]; 25 | vetor[indice] = vetor[minIndice]; 26 | vetor[minIndice] = temp; 27 | 28 | selectionSort(vetor, indice + 1); 29 | 30 | return vetor; 31 | } 32 | 33 | public static void mostraVetor(int vetor[]) { 34 | for (int i = 0; i < vetor.length; i++) { 35 | System.out.print(vetor[i] + ", "); 36 | } 37 | System.out.println(""); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/java/ShellSort.java: -------------------------------------------------------------------------------- 1 | public class ShellSort { 2 | 3 | /** 4 | * Aplica a ordenação ShellSort no vetor 5 | * 6 | * @param vetor Vetor que será ordenado 7 | */ 8 | public int[] sort(int[] vetor) { 9 | int i, j, h = 1, temp; 10 | 11 | do { 12 | h = 3 * h + 1; 13 | } while (h < vetor.length); 14 | 15 | do { 16 | h /= 3; 17 | 18 | for (i = h; i < vetor.length; i++) { 19 | temp = vetor[i]; 20 | j = i - h; 21 | while (j >= 0 && temp < vetor[j]) { 22 | vetor[j + h] = vetor[j]; 23 | j -= h; 24 | } 25 | vetor[j + h] = temp; 26 | } 27 | } while (h > 1); 28 | return vetor; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/java/TestMergeSort.java: -------------------------------------------------------------------------------- 1 | public class teste { 2 | public static void main(String[] args) { 3 | int[] arrayteste = {10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9}; 4 | MergeSort ordem = new MergeSort(); 5 | ordem.sort(arrayteste, 0, arrayteste.length - 1); 6 | for (int i = 0; i < arrayteste.length; i++) { 7 | System.out.print(arrayteste[i] + " "); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/java/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | public class TorreDeHanoi { 2 | 3 | public static void main(String[] args) { 4 | TorreDeHanoi(0, 2, 1, 8); 5 | } 6 | 7 | public static void TorreDeHanoi(int ori, int dst, int aux, int qnt) { 8 | if (qnt == 1) { 9 | System.out.println("Move de " + ori + " para " + dst); 10 | } else { 11 | TorreDeHanoi(ori, aux, dst, qnt - 1); 12 | TorreDeHanoi(ori, dst, aux, 1); 13 | TorreDeHanoi(aux, dst, ori, qnt - 1); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/javascript/BubbleSort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(unsortedArray, start, end) { 2 | let swapped; 3 | 4 | do { 5 | swapped = false; 6 | for (var i = start; i < end - 1; i++) { 7 | if (unsortedArray[i] > unsortedArray[i + 1]) { 8 | [unsortedArray[i], unsortedArray[i + 1]] = [unsortedArray[i + 1], unsortedArray[i]]; 9 | swapped = true; 10 | } 11 | } 12 | } while (swapped); 13 | 14 | return unsortedArray; 15 | } 16 | 17 | var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; 18 | let sortedArrayViaBubbleSort = bubbleSort(unsortedArray, 0, unsortedArray.length); 19 | 20 | console.log(sortedArrayViaBubbleSort); -------------------------------------------------------------------------------- /src/javascript/CalculatePi.js: -------------------------------------------------------------------------------- 1 | function calculate_pi(number) { 2 | let denominator = 1; 3 | let operation = 1; 4 | let pi = 0; 5 | 6 | for (let cont = 0; cont < number; cont++) { 7 | pi += operation * (4 / denominator); 8 | denominator += 2; 9 | operation *= -1; 10 | } 11 | 12 | return pi; 13 | } 14 | 15 | function main() { 16 | const terms = [10, 1000, 100000, 10000000]; 17 | terms.map((term) => { 18 | console.log(`PI ${term}: ${calculate_pi(term)}`); 19 | }); 20 | } 21 | 22 | main(); 23 | -------------------------------------------------------------------------------- /src/javascript/CombSort.js: -------------------------------------------------------------------------------- 1 | function combSort(unsortedArray, start, end) { 2 | let gap = end; 3 | let swapped; 4 | 5 | do { 6 | swapped = false; 7 | gap = parseInt(gap / 1.24733095); 8 | 9 | for (let i = start; i < end - gap; i++) { 10 | if (unsortedArray[i] > unsortedArray[i + gap]) { 11 | [unsortedArray[i], unsortedArray[i + gap]] = [unsortedArray[i + gap], unsortedArray[i]]; 12 | swapped = true; 13 | } 14 | } 15 | } while (gap > 1 || swapped); 16 | 17 | return unsortedArray; 18 | } 19 | 20 | var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; 21 | let sortedArrayViaCombSort = combSort(unsortedArray, 0, unsortedArray.length); 22 | 23 | console.log(sortedArrayViaCombSort); -------------------------------------------------------------------------------- /src/javascript/CountingSort.js: -------------------------------------------------------------------------------- 1 | function countingSort(arr) { 2 | // Find the maximum element in the array to determine the range 3 | let max = Math.max(...arr); 4 | 5 | // Create a count array to store the count of each element 6 | let count = new Array(max + 1).fill(0); 7 | 8 | // Count the occurrences of each element in the input array 9 | for (let i = 0; i < arr.length; i++) { 10 | count[arr[i]]++; 11 | } 12 | 13 | // Modify the count array to store the actual position of each element 14 | for (let i = 1; i <= max; i++) { 15 | count[i] += count[i - 1]; 16 | } 17 | 18 | // Create a new output array and store the elements in their sorted order 19 | let output = new Array(arr.length); 20 | for (let i = arr.length - 1; i >= 0; i--) { 21 | output[count[arr[i]] - 1] = arr[i]; 22 | count[arr[i]]--; 23 | } 24 | 25 | return output; 26 | } 27 | 28 | const arr = [4, 2, 2, 8, 3, 3, 1]; 29 | const sortedArr = countingSort(arr); 30 | console.log("Original array:", arr); 31 | console.log("Sorted array:", sortedArr); 32 | -------------------------------------------------------------------------------- /src/javascript/Deque.js: -------------------------------------------------------------------------------- 1 | class Deque { 2 | constructor() { 3 | this.deque = []; 4 | } 5 | 6 | addFront(value) { 7 | this.deque.unshift(value); 8 | } 9 | 10 | addEnd(value) { 11 | this.deque.push(value); 12 | } 13 | 14 | removeFront() { 15 | this.deque.shift(); 16 | } 17 | 18 | removeEnd() { 19 | this.deque.pop(); 20 | } 21 | 22 | readFromFront() { 23 | console.log(this.deque); 24 | } 25 | 26 | readFromEnd() { 27 | let dequeCopy = this.deque.slice(); 28 | console.log(dequeCopy.reverse()); 29 | } 30 | } -------------------------------------------------------------------------------- /src/javascript/Exponentiation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} base 3 | * @param {number} exponent 4 | */ 5 | function exponentiation(base, exponent) { 6 | const baseNumber = base; 7 | for (let index = 0; index < exponent-1; index++) 8 | base *= baseNumber; 9 | 10 | return base; 11 | } 12 | 13 | function main(){ 14 | // Sample: 3³ = 3*3*3 = 27 15 | console.log('Exponentiation 3³ => ', exponentiation(3, 3)); 16 | } 17 | 18 | main(); -------------------------------------------------------------------------------- /src/javascript/ExponentiationRecursive.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} base 3 | * @param {number} exponent 4 | */ 5 | function exponentiationRecursive(base, exponent) { 6 | if (exponent <= 1) return base; 7 | 8 | return base * exponentiationRecursive(base, exponent -1); 9 | } 10 | 11 | function main(){ 12 | // Sample: 3³ = 3*3*3 = 27 13 | console.log('Exponentiation 3³ => ', exponentiationRecursive(3, 3)); 14 | } 15 | 16 | main(); -------------------------------------------------------------------------------- /src/javascript/Factorial.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {number} n 4 | */ 5 | function factorial(n) { 6 | let result = 1; 7 | for (let index = n; index > 1; index--) 8 | result = result * index; 9 | 10 | return result; 11 | } 12 | 13 | function main(){ 14 | console.log('Factorial => ', factorial(3)); 15 | } 16 | 17 | main(); 18 | -------------------------------------------------------------------------------- /src/javascript/FactorialRecursive.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @param {number} n 4 | */ 5 | function factorial(n) { 6 | if (n <= 1) { 7 | return 1; 8 | } 9 | 10 | return n * factorial(n - 1); 11 | } 12 | 13 | function main(){ 14 | console.log('Factorial => ', factorial(3)); 15 | } 16 | 17 | main(); 18 | -------------------------------------------------------------------------------- /src/javascript/FibonacciIterative.js: -------------------------------------------------------------------------------- 1 | function fibonacci(n) { 2 | if (n <= 1) { 3 | return n; 4 | } 5 | 6 | let a = 0; 7 | let b = 1; 8 | let result; 9 | 10 | for (let i = 2; i <= n; i++) { 11 | result = a + b; 12 | a = b; 13 | b = result; 14 | } 15 | 16 | return result; 17 | } 18 | 19 | function main() { 20 | console.log('Fibonacci (iterative) of 30:', fibonacci(30)); 21 | } 22 | 23 | main(); 24 | -------------------------------------------------------------------------------- /src/javascript/FibonacciMemoization.js: -------------------------------------------------------------------------------- 1 | const fibonacci = (function () { 2 | const memo = {}; 3 | 4 | function fib(n) { 5 | if (n <= 1) { 6 | return n; 7 | } 8 | 9 | if (memo[n] !== undefined) { 10 | return memo[n]; 11 | } 12 | 13 | memo[n] = fib(n - 1) + fib(n - 2); 14 | 15 | return memo[n]; 16 | } 17 | 18 | return fib; 19 | })(); 20 | 21 | function main() { 22 | console.log('Fibonacci (memoization) of 30:', fibonacci(30)); 23 | } 24 | 25 | main(); 26 | 27 | -------------------------------------------------------------------------------- /src/javascript/FibonacciRecursive.js: -------------------------------------------------------------------------------- 1 | function fibonacci(n) { 2 | return n < 2 ? n : (fibonacci(n - 1) + fibonacci(n - 2)); 3 | } 4 | 5 | function main(){ 6 | console.log('fibonacci 30 -> ', fibonacci(30)) 7 | } 8 | 9 | main(); 10 | -------------------------------------------------------------------------------- /src/javascript/InsertionSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | Insertion Sort is a sorting algorithm that works as follows: 3 | 1. It iterates through the array from the second position onward. 4 | 2. Compares the current value with the previous one: 5 | - If it's smaller, it swaps the two values and continues comparing with the previous one. 6 | - If it's larger, it proceeds to analyze the next unsorted element in the array. 7 | */ 8 | 9 | function insertionSort(unsortedArray, start, end) { 10 | for (var i = start + 1; i < end; i++) { 11 | let currentPosition = i; 12 | 13 | while (currentPosition > 0 && unsortedArray[currentPosition] < unsortedArray[currentPosition - 1]) { 14 | swapPositions(unsortedArray, currentPosition, currentPosition - 1); 15 | currentPosition--; 16 | } 17 | } 18 | return unsortedArray; 19 | } 20 | 21 | function swapPositions(array, firstPosition, secondPosition) { 22 | let firstValue = array[firstPosition]; 23 | let secondValue = array[secondPosition]; 24 | 25 | array[firstPosition] = secondValue; 26 | array[secondPosition] = firstValue; 27 | } 28 | 29 | var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; 30 | let sortedArrayViaInsertionSort = insertionSort(unsortedArray, 0, unsortedArray.length); 31 | 32 | console.log(sortedArrayViaInsertionSort); 33 | -------------------------------------------------------------------------------- /src/javascript/InterpolationSearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @description Interpolation Search 3 | * @reference https://en.wikipedia.org/wiki/Interpolation_search 4 | */ 5 | 6 | /** 7 | * @param {Array} arr - Array of elements to be searched 8 | * @param {Array} first - First index of the array 9 | * @param {Array} last - Last index of the array 10 | * @param {Number} value - Value to be searched 11 | * @return {Number} - Index of the searched element or -1 if not found 12 | * @throws {Error} - If the array is empty 13 | */ 14 | const interpolationSearch = (arr, first, last, value) => { 15 | let pos; 16 | if (first <= last && value >= arr[first] && value <= arr[last]) { 17 | pos = first + Math.floor((last - first) * (value - arr[first]) / (arr[last] - arr[first])); 18 | if (arr[pos] === value) 19 | return pos; 20 | else if (arr[pos] < value) 21 | return interpolationSearch(arr, pos + 1, last, value); 22 | else 23 | return interpolationSearch(arr, first, pos - 1, value); 24 | } 25 | return -1; 26 | } 27 | 28 | const main = () => { 29 | // The array needs to be sorted 30 | const arr = [10, 12, 13, 16, 18, 19, 20, 21, 31 | 22, 23, 24, 33, 35, 42, 47]; 32 | let n = arr.length; 33 | 34 | // Searching for the value 18 35 | let x = 18 36 | let index = interpolationSearch(arr, 0, n - 1, x); 37 | 38 | if (index !== -1) 39 | console.log(`Index of the searched element: ${index}`); 40 | else 41 | console.log("Element not found"); 42 | } 43 | 44 | main(); 45 | -------------------------------------------------------------------------------- /src/javascript/LinearSearch.js: -------------------------------------------------------------------------------- 1 | function linearSearch(array, targetValue) { 2 | for (let i = 0; i < array.length; i++) { 3 | if (array[i] == targetValue) { 4 | return i; 5 | } 6 | } 7 | return -1; 8 | } 9 | 10 | var array = [54, 42, 11, 33, 24, 99, 77, 80]; 11 | console.log(linearSearch(array, 11)); 12 | 13 | -------------------------------------------------------------------------------- /src/javascript/LinearSearchRecursive.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} vector 3 | * @param {number} wanted 4 | * @param {number} index 5 | */ 6 | function recursiveLinearSearch(vector, wanted, index){ 7 | if (index >= 0 && index < vector.length){ 8 | if (vector[index] === wanted) return index; 9 | else return recursiveLinearSearch(vector, wanted, index + 1); 10 | } 11 | throw new Error(`Value: ${wanted} - Not Found`) 12 | } 13 | 14 | function main(){ 15 | const vector = [10, 90, 15, 50, 72, 99, 101, 2, 3, 4, 20, 25]; 16 | try { 17 | console.log(`Wanted: 3\nPosition: ${recursiveLinearSearch(vector, 3, 0)}`); 18 | } catch (error) { 19 | console.log(error.message) 20 | } 21 | } 22 | 23 | main(); -------------------------------------------------------------------------------- /src/javascript/LinearSearchSentinel.js: -------------------------------------------------------------------------------- 1 | // Implementation of sentinel search using JavaScript. 2 | 3 | function sentinelSearch(array, wantedValue) { 4 | array.push(wantedValue); 5 | let index = 0; 6 | 7 | while (array[index] != wantedValue) { 8 | index++; 9 | } 10 | 11 | if (index == array.length - 1) { 12 | return -1; 13 | } else { 14 | return index; 15 | } 16 | } 17 | 18 | function main() { 19 | array = [32, 45, 31, 87, 32, 12, 76, 32, 16, 47, 54, 90]; 20 | wantedValue = 54; 21 | 22 | foundIndex = sentinelSearch(array, wantedValue); 23 | 24 | if (foundIndex >= 0) { 25 | console.log(`Value found at index "${foundIndex}".`) 26 | } else { 27 | console.log("Value not found.") 28 | } 29 | } 30 | 31 | main(); 32 | 33 | -------------------------------------------------------------------------------- /src/javascript/MinMaxIterative.js: -------------------------------------------------------------------------------- 1 | const MAX_LENGTH = 10; 2 | 3 | /** 4 | * @param {number[]} vector 5 | */ 6 | function MinMaxIterative(vector){ 7 | let min = max = vector[0]; 8 | 9 | vector.forEach(value => { 10 | if (value > max) max = value; 11 | if(value < min) min = value; 12 | }); 13 | 14 | return { 15 | min, 16 | max 17 | } 18 | } 19 | 20 | function main(){ 21 | let vector = []; 22 | let values = "["; 23 | for (let index = 0; index < MAX_LENGTH; index++) { 24 | let value = Math.floor(Math.random() * 99); // 0 - 99 25 | vector.push(value); 26 | values += `${value}, `; 27 | } 28 | values += "]" 29 | 30 | console.log(values); 31 | const result = MinMaxIterative(vector); 32 | console.log(`Min: ${result.min}\nMax: ${result.max}`); 33 | } 34 | 35 | main(); -------------------------------------------------------------------------------- /src/javascript/MinMaxRecursive.js: -------------------------------------------------------------------------------- 1 | const MAX_LENGTH = 10; 2 | 3 | /** 4 | * @param {number[]} vector 5 | * @param {number} min 6 | * @param {number} max 7 | * @param {number} index 8 | */ 9 | function MinMaxRecursive(vector, min, max, index){ 10 | if (vector[index] < min) min = vector[index]; 11 | if (vector[index] > max) max = vector[index]; 12 | 13 | if (index < vector.length - 1) { 14 | const result = MinMaxRecursive(vector, min, max, index + 1); 15 | min = result.min; 16 | max = result.max; 17 | } 18 | 19 | return { 20 | min, 21 | max 22 | } 23 | } 24 | 25 | function main(){ 26 | let vector = []; 27 | let values = "["; 28 | for (let index = 0; index < MAX_LENGTH; index++) { 29 | let value = Math.floor(Math.random() * 99); // 0 - 99 30 | vector.push(value); 31 | values += `${value}, `; 32 | } 33 | values += "]" 34 | 35 | console.log(values); 36 | const result = MinMaxRecursive(vector, vector[0], vector[0], 1); 37 | console.log(`Min: ${result.min}\nMax: ${result.max}`); 38 | } 39 | 40 | main(); -------------------------------------------------------------------------------- /src/javascript/Palindrome.js: -------------------------------------------------------------------------------- 1 | function is_palindrome(string) { 2 | string = string.toLowerCase().replace(/\s/g, ""); 3 | 4 | const reversedString = string 5 | .split("") 6 | .reverse() 7 | .join("") 8 | .toLowerCase() 9 | .replace(/\s/g, ""); 10 | 11 | if (string.length <= 1) true; 12 | 13 | return string == reversedString; 14 | } 15 | 16 | function main() { 17 | console.log(is_palindrome("")); 18 | console.log(is_palindrome("a")); 19 | console.log(is_palindrome("abba")); 20 | console.log(is_palindrome("abbas")); 21 | console.log(is_palindrome("tattarrattat")); 22 | console.log(is_palindrome("Was it a palindrome?")); 23 | console.log(is_palindrome("No lemon, no melon")); 24 | } 25 | 26 | main(); -------------------------------------------------------------------------------- /src/javascript/Queue.js: -------------------------------------------------------------------------------- 1 | class Queue { 2 | constructor() { 3 | this.queue = []; 4 | } 5 | 6 | enqueue(value) { 7 | this.queue.push(value); 8 | } 9 | 10 | dequeue() { 11 | this.queue.shift(0); 12 | } 13 | 14 | read() { 15 | console.log(this.queue); 16 | } 17 | 18 | empty() { 19 | this.queue = []; 20 | } 21 | } -------------------------------------------------------------------------------- /src/javascript/QuickSort.js: -------------------------------------------------------------------------------- 1 | function quickSort(unsortedArray, start, end){ 2 | let numPositions = end - start; 3 | 4 | if(numPositions > 1){ 5 | let pivotPosition = partition(unsortedArray, start, end); 6 | quickSort(unsortedArray, start, pivotPosition); 7 | quickSort(unsortedArray, pivotPosition + 1, end); 8 | } 9 | 10 | return unsortedArray; 11 | } 12 | 13 | function partition(array, start, end){ 14 | let pivot = array[end - 1]; 15 | let foundSmaller = 0; 16 | 17 | for (var i = start; i < end - 1; i++) { 18 | if(array[i] <= pivot){ 19 | [array[i], array[foundSmaller]] = [array[foundSmaller], array[i]]; 20 | foundSmaller++; 21 | } 22 | } 23 | 24 | [array[end - 1], array[foundSmaller]] = [array[foundSmaller], array[end - 1]]; 25 | return foundSmaller; 26 | } 27 | 28 | var unsortedArray = [54,42,11,33,24,99,77,80]; 29 | 30 | let sortedArrayViaQuickSort = quickSort(unsortedArray, 0, unsortedArray.length); 31 | 32 | console.log(sortedArrayViaQuickSort); 33 | -------------------------------------------------------------------------------- /src/javascript/RadixSort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} vector 3 | */ 4 | function RadixSort(vector) { 5 | let i = 0; 6 | let b = new Int32Array(vector.length); 7 | let bigger = vector[0]; 8 | let exp = 1; 9 | 10 | for (i = 0; i < vector.length; i++) { 11 | if (vector[i] > bigger) 12 | bigger = vector[i]; 13 | } 14 | 15 | while(parseInt(bigger / exp) > 0){ 16 | let bucket = new Int32Array(10); 17 | 18 | for (i = 0; i < vector.length; i++) 19 | bucket[parseInt(parseInt((vector[i] / exp)) % 10)]++; 20 | for (i = 1; i < 10; i++) 21 | bucket[i] += bucket[i - 1]; 22 | for (i = vector.length - 1; i >= 0; i--) 23 | b[--bucket[parseInt(parseInt((vector[i] / exp)) % 10)]] = vector[i]; 24 | for (i = 0; i < vector.length; i++) 25 | vector[i] = b[i]; 26 | 27 | exp *= 10; 28 | } 29 | } 30 | 31 | function main() { 32 | const MAX_LENGTH = 20; 33 | let vector = []; 34 | let values = "["; 35 | for (let index = 0; index < MAX_LENGTH; index++) { 36 | let value = Math.floor(Math.random() * 99); // 0 - 99 37 | vector.push(value); 38 | values += `${value}, `; 39 | } 40 | values += "]"; 41 | 42 | console.log(values); 43 | 44 | RadixSort(vector); 45 | values = "["; 46 | vector.forEach(v => values+=`${v}, `); 47 | values += "]"; 48 | console.log(values); 49 | } 50 | 51 | main(); -------------------------------------------------------------------------------- /src/javascript/SelectionSort.js: -------------------------------------------------------------------------------- 1 | /* 2 | Selection Sort, or the selection sort algorithm, sorts a series of data 3 | as follows: 4 | 1. Finds the smallest value in the array starting from position 'i'; 5 | 2. Swaps this value with the value at position 'i'; 6 | 3. Increments the starting position (i = i + 1); 7 | 4. Repeats the algorithm until the penultimate position of the array. 8 | */ 9 | 10 | function selectionSort(unsortedArray, start, end) { 11 | 12 | for (let i = start; i < end - 1; i++) { 13 | let smallestPosition = findSmallestPosition(unsortedArray, i, end); 14 | [unsortedArray[smallestPosition], unsortedArray[i]] = [unsortedArray[i], unsortedArray[smallestPosition]]; 15 | } 16 | 17 | return unsortedArray; 18 | } 19 | 20 | function findSmallestPosition(unsortedArray, start, end) { 21 | let smallestPosition = start; 22 | let smallest = unsortedArray[start]; 23 | 24 | for (let i = start; i < end; i++) { 25 | if (unsortedArray[i] < smallest) { 26 | smallest = unsortedArray[i]; 27 | smallestPosition = i; 28 | } 29 | } 30 | return smallestPosition; 31 | } 32 | 33 | var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; 34 | let sortedArrayViaSelectionSort = selectionSort(unsortedArray, 0, unsortedArray.length); 35 | 36 | console.log(sortedArrayViaSelectionSort); 37 | 38 | -------------------------------------------------------------------------------- /src/javascript/ShellSort.js: -------------------------------------------------------------------------------- 1 | function shellSort(unsortedArray, start, end) { 2 | let gap = 1; 3 | 4 | while (gap < end) { 5 | gap = gap * 3 + 1; 6 | } 7 | 8 | gap = parseInt(gap / 3); 9 | 10 | let j; 11 | while (gap > 0) { 12 | for (let i = gap; i < end; i += 1) { 13 | j = i; 14 | while (j >= gap && unsortedArray[j - gap] > unsortedArray[j]) { 15 | [unsortedArray[j - gap], unsortedArray[j]] = [unsortedArray[j], unsortedArray[j - gap]]; 16 | } 17 | } 18 | gap = gap / 2; 19 | } 20 | 21 | return unsortedArray; 22 | } 23 | 24 | var unsortedArray = [54, 42, 11, 33, 24, 99, 77, 80]; 25 | let sortedArrayViaShellSort = shellSort(unsortedArray, 0, unsortedArray.length); 26 | 27 | console.log(sortedArrayViaShellSort); -------------------------------------------------------------------------------- /src/javascript/Stack.js: -------------------------------------------------------------------------------- 1 | class Stack { 2 | constructor() { 3 | this.stack = []; 4 | } 5 | 6 | push(value) { 7 | this.stack.push(value); 8 | } 9 | 10 | pop() { 11 | this.stack.pop(); 12 | } 13 | 14 | read() { 15 | console.log(this.stack); 16 | } 17 | 18 | clear() { 19 | this.stack = []; 20 | } 21 | } -------------------------------------------------------------------------------- /src/javascript/TowerOfHanoi.js: -------------------------------------------------------------------------------- 1 | function hanoi(sourcePin, targetPin, auxiliaryPin, numberOfDisks) { 2 | if (numberOfDisks === 1) { 3 | console.log(`Move from ${sourcePin} to ${targetPin}`); 4 | } else { 5 | hanoi(sourcePin, auxiliaryPin, targetPin, numberOfDisks - 1); 6 | hanoi(sourcePin, targetPin, auxiliaryPin, 1); 7 | hanoi(auxiliaryPin, targetPin, sourcePin, numberOfDisks - 1); 8 | } 9 | } 10 | 11 | hanoi(0, 2, 1, 3); 12 | -------------------------------------------------------------------------------- /src/kotlin/ExponentiationRecursive.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * "exponentiationRecursive" function 3 | * 4 | * The *exponentiationRecursive* function presents the values of a number (*base*) raised by an *exponent*. 5 | * 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. 6 | * 7 | * @param base is of type integer (Int) 8 | * @param exponent is of type integer (Int) 9 | * 10 | * @return will return the *base* number raised by the *exponent*. The function returns a value of type *Long*. 11 | */ 12 | fun exponentiationRecursive( 13 | base: Int, 14 | exponent: Int, 15 | ): Long = 16 | if (exponent === 0) { 17 | 1 18 | } else { 19 | base * exponentiationRecursive(base, exponent - 1) 20 | } 21 | 22 | fun main() { 23 | println(exponentiationRecursive(2, 3)) 24 | } 25 | -------------------------------------------------------------------------------- /src/kotlin/Factorial.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * "factorial" function 3 | * 4 | * The *factorial* function presents the values of multiplying *n numbers* by their predecessors greater than or equal to 1. 5 | * 6 | * @param number is of type integer (Int) 7 | * 8 | * @return will return a number of type *Long* in which the type is assigned to the *factorial* variable. 9 | */ 10 | 11 | fun factorial(number: Int) { 12 | val initialNumber: Int = number 13 | var factorial: Long = 1 14 | 15 | for (i in 1..initialNumber) { 16 | factorial *= i.toLong() 17 | } 18 | 19 | println("Factorial of $number! is $factorial") 20 | } 21 | 22 | fun main() { 23 | factorial(7) 24 | } 25 | -------------------------------------------------------------------------------- /src/kotlin/FibonacciIterative.kt: -------------------------------------------------------------------------------- 1 | // Function to calculate Fibonacci numbers iteratively 2 | fun fibonacci(n: Int): Long { 3 | if (n <= 1) { 4 | return n.toLong() 5 | } 6 | 7 | var a = 0L 8 | var b = 1L 9 | var result = 0L 10 | 11 | for (i in 2..n) { 12 | result = a + b 13 | a = b 14 | b = result 15 | } 16 | 17 | return result 18 | } 19 | 20 | fun main() { 21 | val index = 15 22 | println("Fibonacci (iterative) of $index is: ${fibonacci(index)}") 23 | } 24 | -------------------------------------------------------------------------------- /src/kotlin/FibonacciMemoization.kt: -------------------------------------------------------------------------------- 1 | // Memoization dictionary to store computed Fibonacci numbers 2 | val memo = mutableMapOf() 3 | 4 | // Function to calculate Fibonacci numbers using memoization 5 | fun fibonacci(n: Int): Long { 6 | if (n <= 1) { 7 | return n.toLong() 8 | } 9 | 10 | // Check if the result is already memoized 11 | if (memo.containsKey(n)) { 12 | return memo[n]!! 13 | } 14 | 15 | // Calculate Fibonacci recursively and store the result in memoization 16 | val result = fibonacci(n - 1) + fibonacci(n - 2) 17 | memo[n] = result 18 | 19 | return result 20 | } 21 | 22 | fun main() { 23 | val index = 15 24 | println("Fibonacci (memoization) of $index is: ${fibonacci(index)}") 25 | } 26 | -------------------------------------------------------------------------------- /src/kotlin/FibonacciRecursive.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * "fibonacci" function 3 | * 4 | * 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...). 5 | * In this function, the concept of *recursion* is used, in which the created function is called within it, one or more times internally. 6 | * 7 | * @param number is of type integer (Int) 8 | * 9 | * @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. 10 | */ 11 | fun fibonacci(number: Int): Int = 12 | if (number <= 1) { 13 | 1 14 | } else { 15 | fibonacci(number - 1) + fibonacci(number - 2) 16 | } 17 | 18 | fun main() { 19 | println(fibonacci(5)) 20 | } 21 | -------------------------------------------------------------------------------- /src/kotlin/MergeSort.kt: -------------------------------------------------------------------------------- 1 | fun mergeSort(arr: IntArray): IntArray { 2 | if (arr.size <= 1) { 3 | return arr 4 | } 5 | 6 | val middle = arr.size / 2 7 | val left = arr.copyOfRange(0, middle) 8 | val right = arr.copyOfRange(middle, arr.size) 9 | 10 | return merge(mergeSort(left), mergeSort(right)) 11 | } 12 | 13 | fun merge( 14 | left: IntArray, 15 | right: IntArray, 16 | ): IntArray { 17 | var result = IntArray(left.size + right.size) 18 | var leftIndex = 0 19 | var rightIndex = 0 20 | var resultIndex = 0 21 | 22 | while (leftIndex < left.size && rightIndex < right.size) { 23 | if (left[leftIndex] < right[rightIndex]) { 24 | result[resultIndex] = left[leftIndex] 25 | leftIndex++ 26 | } else { 27 | result[resultIndex] = right[rightIndex] 28 | rightIndex++ 29 | } 30 | resultIndex++ 31 | } 32 | 33 | while (leftIndex < left.size) { 34 | result[resultIndex] = left[leftIndex] 35 | leftIndex++ 36 | resultIndex++ 37 | } 38 | 39 | while (rightIndex < right.size) { 40 | result[resultIndex] = right[rightIndex] 41 | rightIndex++ 42 | resultIndex++ 43 | } 44 | 45 | return result 46 | } 47 | 48 | fun main() { 49 | val arr = intArrayOf(12, 11, 13, 5, 6, 7) 50 | val sortedArray = mergeSort(arr) 51 | println("Sorted array: ${sortedArray.joinToString(", ")}") 52 | } 53 | -------------------------------------------------------------------------------- /src/python/binary_search.py: -------------------------------------------------------------------------------- 1 | """ Recursive Binary Search Algorithm in Python """ 2 | 3 | 4 | def binary_search(value, vector, left, right): 5 | """ 6 | Implementation of a binary search algorithm with recursion. 7 | 8 | Arguments: 9 | value: Any. Value to be searched for in the list 10 | vector: List. Ordered list in which value will be searched for 11 | left: Any. Leftmost index for binary search 12 | right: Any. Rightmost index for binary search 13 | 14 | Returns the index of value in vector; returns -1 if value not found in vector 15 | """ 16 | middle = int((left + right) / 2) 17 | 18 | if left <= right: 19 | if value > vector[middle]: 20 | left = middle + 1 21 | return binary_search(value, vector, left, right) 22 | elif value < vector[middle]: 23 | right = middle - 1 24 | return binary_search(value, vector, left, right) 25 | return middle 26 | return -1 27 | 28 | 29 | list = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] 30 | print(binary_search(12, list, 0, len(list) - 1)) 31 | -------------------------------------------------------------------------------- /src/python/bogosort.py: -------------------------------------------------------------------------------- 1 | """ Implementation of the bogosort algorithm in Python. """ 2 | 3 | import random 4 | 5 | 6 | def is_sorted(arr): 7 | """Checks if an array is sorted. 8 | 9 | Args: 10 | arr (list): The array to check. 11 | 12 | Returns: 13 | bool: True if the array is sorted, False otherwise. 14 | """ 15 | return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)) 16 | 17 | 18 | # Time: O(n * n!) 19 | # Space: O(1) 20 | def bogosort(arr): 21 | """Sorts an array using the bogosort algorithm. 22 | 23 | Args: 24 | arr (list): The array to sort. 25 | 26 | Returns: 27 | None: The array is sorted in place. 28 | """ 29 | while not is_sorted(arr): 30 | random.shuffle(arr) 31 | 32 | 33 | if __name__ == "__main__": 34 | # Example usage 35 | unsorted_list = [3, 1, 2, 5, 4] 36 | print("Unsorted list:", unsorted_list) 37 | 38 | bogosort(unsorted_list) 39 | print("Sorted list:", unsorted_list) 40 | -------------------------------------------------------------------------------- /src/python/bubble_sort.py: -------------------------------------------------------------------------------- 1 | """ Recursive Bubble Sort in Python """ 2 | 3 | 4 | def bubble_sort(data, size): 5 | """ 6 | Implementation of a bubble sort algorithm with recursion. 7 | 8 | Arguments: 9 | data: list. List to be sorted 10 | size: int. List size 11 | 12 | Returns the ordered "data" list. 13 | """ 14 | swap = False 15 | for i in range(0, size - 1): 16 | if data[i] > data[i + 1]: 17 | data[i], data[i + 1] = data[i + 1], data[i] 18 | swap = True 19 | if swap: 20 | bubble_sort(data, size - 1) 21 | 22 | 23 | if __name__ == "__main__": 24 | data = [2, 9, 8, 0, 1, 3, 5, 4, 6, 7] 25 | print(data) 26 | bubble_sort(data, len(data)) 27 | print(data) 28 | -------------------------------------------------------------------------------- /src/python/calculate_pi.py: -------------------------------------------------------------------------------- 1 | """ Calculating PI in Python """ 2 | 3 | 4 | def calculate_pi(number): 5 | """ 6 | Implementation of a PI calculation algorithm. 7 | 8 | Arguments: 9 | number: int. 10 | 11 | Returns the value of PI. 12 | """ 13 | denominator = 1.0 14 | operation = 1.0 15 | pi = 0.0 16 | for _ in range(number): 17 | pi += operation * (4.0 / denominator) 18 | denominator += 2.0 19 | operation *= -1.0 20 | return pi 21 | 22 | 23 | if __name__ == "__main__": 24 | n_terms = [10, 1000, 100000, 10000000] 25 | for n in n_terms: 26 | print(f"PI ({n}): {calculate_pi(n)}") 27 | -------------------------------------------------------------------------------- /src/python/comb_sort.py: -------------------------------------------------------------------------------- 1 | """ Comb Sort in Python """ 2 | 3 | 4 | def comb_sort(arr: list) -> list: 5 | """ 6 | Implementation of comb sort algorithm 7 | """ 8 | gap = len(arr) 9 | shrink = 1.3 10 | swapped = True 11 | while gap > 1 or swapped: 12 | gap = int(gap / shrink) 13 | if gap < 1: 14 | gap = 1 15 | swapped = False 16 | for i in range(len(arr) - gap): 17 | if arr[i] > arr[i + gap]: 18 | arr[i], arr[i + gap] = arr[i + gap], arr[i] 19 | swapped = True 20 | return arr 21 | 22 | 23 | if __name__ == "__main__": 24 | from random import randint 25 | 26 | my_list = [randint(0, 100) for _ in range(10)] 27 | print(f"List: {my_list}") 28 | print(f"Sorted list: {comb_sort(my_list)}") 29 | -------------------------------------------------------------------------------- /src/python/counting_sort.py: -------------------------------------------------------------------------------- 1 | """ Counting sort in Python """ 2 | 3 | import random 4 | 5 | 6 | def counting_sort(arr): 7 | """Finding the max element in the list""" 8 | k = max(arr) + 1 9 | 10 | """ Initialing count array of len k with 0's """ 11 | count = [0] * k 12 | 13 | """ Counts frequency of each element """ 14 | for i in arr: 15 | count[i] += 1 16 | 17 | """ Updates count array to reflect the correct position of each element in the sorted list """ 18 | for i in range(1, k): 19 | count[i] += count[i - 1] 20 | 21 | """ Initializing result list with 0's """ 22 | result = [0] * len(arr) 23 | 24 | """ Fill result array with the sorted elements""" 25 | for i in reversed(arr): 26 | result[count[i] - 1] = i 27 | count[i] -= 1 28 | 29 | return result 30 | 31 | 32 | """ Generate a list of n random integers """ 33 | n = 10 34 | list = [random.randint(0, 100) for _ in range(n)] 35 | 36 | """ Prints original, unsorted list""" 37 | print(f"List: {list}") 38 | 39 | """ Sorts list using counting sort algorithm """ 40 | sorted_list = counting_sort(list) 41 | 42 | """ Prints sorted list """ 43 | print(f"Sorted list: {sorted_list}") 44 | -------------------------------------------------------------------------------- /src/python/exponentiation.py: -------------------------------------------------------------------------------- 1 | """ Iterative exponentiation algorithm """ 2 | 3 | 4 | def exponentiation(base, exponent): 5 | """ 6 | Implementation of an exponentiation algorithm. 7 | 8 | Arguments: 9 | base (int): Base of operation 10 | exponent (int): Exponent of operation 11 | 12 | Returns: 13 | Returns the result of the exponentiation operation. 14 | """ 15 | result = base 16 | for _ in range(0, exponent - 1): 17 | result *= base 18 | return result 19 | 20 | 21 | print(exponentiation(5, 2)) 22 | print(exponentiation(5, 5)) 23 | -------------------------------------------------------------------------------- /src/python/exponentiation_recursive.py: -------------------------------------------------------------------------------- 1 | """ Recursive exponentiation algorithm """ 2 | 3 | 4 | def exponentiation_recursive(base, exponent): 5 | """ 6 | Implementation of an exponentiation algorithm using recursion. 7 | 8 | Arguments: 9 | base (int): Base of operation 10 | exponent (int): Exponent of operation 11 | 12 | Returns: 13 | Returns the result of the exponentiation operation. 14 | """ 15 | if exponent == 0: 16 | return 1 17 | 18 | return base * exponentiation_recursive(base, exponent - 1) 19 | 20 | 21 | if __name__ == "__main__": 22 | print(exponentiation_recursive(5, 2)) 23 | print(exponentiation_recursive(5, 5)) 24 | -------------------------------------------------------------------------------- /src/python/factorial.py: -------------------------------------------------------------------------------- 1 | """ Iterative factorial algorithm """ 2 | 3 | 4 | def factorial(num): 5 | """ 6 | Implementation of the factorial algorithm iteratively. 7 | 8 | Arguments: 9 | num: int. the number of which you want to obtain the factorial. 10 | 11 | Returns the result of the factorial operation 12 | """ 13 | aux = 1 14 | for i in range(2, num + 1): 15 | aux = aux * i 16 | return aux 17 | 18 | 19 | if __name__ == "__main__": 20 | print(factorial(5)) 21 | -------------------------------------------------------------------------------- /src/python/factorial_recursive.py: -------------------------------------------------------------------------------- 1 | """ Recursive factorial algorithm """ 2 | 3 | 4 | def factorial_recursive(num): 5 | """ 6 | Implementation of factorial algorithm using recursion 7 | 8 | Arguments: 9 | num: int. the number of which you want to obtain the factorial. 10 | 11 | Returns the result of the factorial operation 12 | """ 13 | if num == 1: 14 | return 1 15 | 16 | return num * factorial_recursive(num - 1) 17 | 18 | 19 | print(factorial_recursive(5)) 20 | -------------------------------------------------------------------------------- /src/python/fibonacci_iterative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Iterative Fibonacci Algorithm 3 | 4 | The lib "time" was used to mark the time of 5 | execution of algorithms in seconds 6 | """ 7 | 8 | import time 9 | 10 | 11 | def fibonacci(number): 12 | """Fibonacci iterativa.""" 13 | last = 0 14 | curr = 1 15 | for _ in range(0, number): 16 | last, curr = curr, curr + last 17 | return last 18 | 19 | 20 | def main(name, func, number=35): 21 | """ 22 | Run iterative algorithm and show its execution time 23 | """ 24 | start_time = time.time() 25 | result = func(number) 26 | diff_time = time.time() - start_time 27 | print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") 28 | 29 | 30 | if __name__ == "__main__": 31 | main("Iterative", fibonacci) 32 | -------------------------------------------------------------------------------- /src/python/fibonacci_memoization.py: -------------------------------------------------------------------------------- 1 | """ 2 | Recursive Fibonacci Algorithm using a Cache 3 | """ 4 | 5 | import functools 6 | import time 7 | 8 | 9 | @functools.lru_cache(maxsize=None) 10 | def fibonacci(number): 11 | """ 12 | Recursive fibonacci algorithm with cache 13 | """ 14 | if number < 2: 15 | return number 16 | return fibonacci(number - 1) + fibonacci(number - 2) 17 | 18 | 19 | def main(name, func, number=35): 20 | """ 21 | Run algorithm and show its execution time 22 | """ 23 | start_time = time.time() 24 | result = func(number) 25 | diff_time = time.time() - start_time 26 | print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") 27 | 28 | 29 | if __name__ == "__main__": 30 | main("Memorization:", fibonacci) 31 | -------------------------------------------------------------------------------- /src/python/fibonacci_recursive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Recursive Fibonacci Algorithm 3 | 4 | The lib "time" was used to mark the time of 5 | execution of algorithms in seconds 6 | """ 7 | 8 | import time 9 | 10 | 11 | def fibonacci(number): 12 | """ 13 | Recursive Fibonacci 14 | """ 15 | 16 | if number < 2: 17 | return number 18 | return fibonacci(number - 1) + fibonacci(number - 2) 19 | 20 | 21 | def main(name, func, number=35): 22 | """ 23 | Run the algorithm and show its execution time 24 | """ 25 | start_time = time.time() 26 | result = func(number) 27 | diff_time = time.time() - start_time 28 | print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") 29 | 30 | 31 | if __name__ == "__main__": 32 | main("Recursive", fibonacci) 33 | -------------------------------------------------------------------------------- /src/python/gnome_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementação do Gnome Sort ou Stupid Sort 3 | """ 4 | 5 | 6 | def gnomesort(lista): 7 | i = 0 8 | while i < len(lista): 9 | # caso a posição de i for 0 ou se o valor de i for maior ou igual 10 | # ao seu anterior, o gnomo apenas avançará uma casa 11 | if i == 0 or lista[i] >= lista[i - 1]: 12 | i += 1 13 | 14 | # caso o conteúdo da posição i seja menor ou igual a do seu anterior, 15 | # o gnomo trocará os valores de lugar e voltará uma posição 16 | # para validar a ordem 17 | else: 18 | lista[i], lista[i - 1] = lista[i - 1], lista[i] 19 | i -= 1 20 | 21 | return lista 22 | 23 | 24 | def main(): 25 | lista = [-1, 1, 0, -7, 7, -5, 5, 2, -2, 4, -4, 9, -9, -6, 6, -8, 8, -3, 3] 26 | # imprime a lista não ordenada 27 | print(f"Lista antes de ser ordenada: {lista}") 28 | lista = gnomesort(lista) 29 | # imprime a lista ordenada 30 | print(f"Lista após ordenação com Gnome Sort: {lista}") 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /src/python/heap_sort.py: -------------------------------------------------------------------------------- 1 | """ Heap sort algorithm implementation """ 2 | 3 | 4 | def heap_sort(data): 5 | """Sort a list (data) in-place using HeapSort. 6 | 7 | Args: 8 | data (list): lista to be sorted. 9 | """ 10 | length = len(data) 11 | index = length // 2 12 | parent = 0 13 | child = 0 14 | temp = 0 15 | while True: 16 | if index > 0: 17 | index -= 1 18 | temp = data[index] 19 | else: 20 | length -= 1 21 | if length == 0: 22 | return 23 | temp = data[length] 24 | data[length] = data[0] 25 | 26 | parent = index 27 | child = index * 2 + 1 28 | 29 | while child < length: 30 | if (child + 1) < length and data[child + 1] > data[child]: 31 | child += 1 32 | if data[child] > temp: 33 | data[parent] = data[child] 34 | parent = child 35 | child = parent * 2 + 1 36 | else: 37 | break 38 | data[parent] = temp 39 | 40 | 41 | if __name__ == "__main__": 42 | list_to_sort = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] 43 | print("Unsorted list: {}".format(list_to_sort)) 44 | heap_sort(list_to_sort) 45 | print("Sorted list: {}".format(list_to_sort)) 46 | -------------------------------------------------------------------------------- /src/python/interpolation_search.py: -------------------------------------------------------------------------------- 1 | # Busca por interpolação em Python 2 | 3 | 4 | def interpolation_search(array, x): 5 | """Executa a busca por interpolação 6 | 7 | Args: 8 | array (list): lista com os elementos 9 | x (int): elemento a ser encontrado 10 | 11 | Returns: 12 | int: posição do elemento 13 | """ 14 | low = 0 15 | high = len(array) - 1 16 | 17 | array_low = array[low] 18 | array_high = array[high] 19 | 20 | while (low <= high) and (x >= array_low) and (x <= array_high): 21 | array_low = array[low] 22 | array_high = array[high] 23 | pos = (int)(low + ((high - low) / (array_high - array_low)) * (x - array_low)) 24 | 25 | if array[pos] < x: 26 | low = pos + 1 27 | 28 | elif array[pos] > x: 29 | high = pos - 1 30 | 31 | else: 32 | return pos 33 | 34 | return -1 35 | 36 | 37 | if __name__ == "__main__": 38 | array = [1, 4, 6, 23, 2, 9, 5, 78, 123, 5444, 54535, 64, 3, 0, 12, 14, 15, 31, 25] 39 | array.sort() 40 | 41 | element_to_be_found = 5444 42 | 43 | index = interpolation_search(array, element_to_be_found) 44 | 45 | if index != -1: 46 | print(f"Elemento encontrado no indice {index} do array ordenado.") 47 | else: 48 | print("Elemento não foi encontrado.") 49 | -------------------------------------------------------------------------------- /src/python/linear_search.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementação dos algoritmos de busca sequencial e 3 | busca sentinela 4 | """ 5 | 6 | 7 | def sequential_search(value, array): 8 | """ 9 | Implementação de um algoritmo de busca sequencial. 10 | 11 | Argumentos: 12 | value: Any. Valor a ser buscado na lista 13 | array: list. lista na qual o valor será buscado 14 | 15 | Retorna o índice do valor em "array" ou -1 caso não exista nela. 16 | """ 17 | for i in range(0, len(array)): 18 | if array[i] == value: 19 | return i 20 | return -1 21 | 22 | 23 | def sentinel_search(value, array): 24 | """ 25 | Implementação de um algoritmo de busca sentinela. 26 | 27 | Argumentos: 28 | value: Any. Valor a ser buscado na lista 29 | array: list. lista na qual o valor será buscado 30 | 31 | Retorna o índice do valor em "array" ou -1 caso não exista nela. 32 | """ 33 | array.append(value) 34 | index = 0 35 | while array[index] != value: 36 | index += 1 37 | array.pop() 38 | if index == len(array) - 1: 39 | return -1 40 | return index 41 | 42 | 43 | some_list = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] 44 | print(sequential_search(54, some_list)) 45 | print(sentinel_search(98, some_list)) 46 | -------------------------------------------------------------------------------- /src/python/linear_search_recursive.py: -------------------------------------------------------------------------------- 1 | """Implementation of the sequential search algorithm with recursion.""" 2 | 3 | 4 | def sequential_search(value, lst, index): 5 | """Recursive sequential search. 6 | 7 | Returns: 8 | Returns the index of the value in the list. 9 | If not found, returns -1. 10 | """ 11 | if len(lst) == 0 or index == len(lst): 12 | return -1 13 | if lst[index] == value: 14 | return index 15 | return sequential_search(value, lst, index + 1) 16 | 17 | 18 | if __name__ == "__main__": 19 | a_list = [1, 9, 39, 4, 12, 38, 94, 37] 20 | for index, value_in_list in enumerate(a_list): 21 | print("Testing value {} at index {}".format(value_in_list, index)) 22 | assert sequential_search(value_in_list, a_list, 0) == index 23 | -------------------------------------------------------------------------------- /src/python/linear_search_sentinel.py: -------------------------------------------------------------------------------- 1 | """ Implementacao do algoritmo de busca sentinela """ 2 | 3 | 4 | def busca_sentinela(list_to_search, value): 5 | """ 6 | Implementacao de um algoritmo de busca sentinela. 7 | 8 | Argumentos: 9 | value: Any. Valor a ser buscado na lista 10 | list_to_search: list. lista na qual o valor sera buscado 11 | 12 | Retorna o indice do valor em "list_to_search" ou -1 caso nao exista nela. 13 | """ 14 | list_to_search.append(value) 15 | list_index = 0 16 | while list_to_search[list_index] != value: 17 | list_index = list_index + 1 18 | list_to_search.pop() 19 | if list_index == len(list_to_search): 20 | return -1 21 | return list_index 22 | 23 | 24 | if __name__ == "__main__": 25 | some_list = [1, 9, 2, 8, 7, 4, 5, 6, 4, 3, 10, 0] 26 | NUMBER_TO_FIND = 4 27 | NUMBER_INDEX = busca_sentinela(some_list, NUMBER_TO_FIND) 28 | print(some_list) 29 | if NUMBER_INDEX >= 0: 30 | print("Found value {} at position {}.".format(NUMBER_TO_FIND, NUMBER_INDEX)) 31 | else: 32 | print("Could not find value {}.".format(NUMBER_TO_FIND)) 33 | -------------------------------------------------------------------------------- /src/python/lista_encadeada_desordenada.py: -------------------------------------------------------------------------------- 1 | """ Implementação de uma lista encadeada desordenada """ 2 | 3 | 4 | class Node: 5 | def __init__(self, value, next_node=None): 6 | self.__value = value 7 | self.next_node = next_node 8 | 9 | @property 10 | def value(self): 11 | return self.__value 12 | 13 | 14 | class LinkedList: 15 | def __init__(self, *nodes): 16 | self.nodes = nodes 17 | 18 | def sorted(self): 19 | tmp_nodes = {node.next_node: node for node in self.nodes} 20 | sorted_nodes = list() 21 | current_node = None 22 | while current_node in tmp_nodes: 23 | current_node = tmp_nodes[current_node] 24 | sorted_nodes.insert(0, current_node) 25 | return sorted_nodes 26 | 27 | 28 | if __name__ == "__main__": 29 | e = Node(5) 30 | d = Node(4, next_node=e) 31 | c = Node(3, next_node=d) 32 | b = Node(2, next_node=c) 33 | a = Node(1, next_node=b) 34 | 35 | linked_list = LinkedList(c, a, d, b, e) 36 | 37 | print("Unsorted linked list:") 38 | for node in linked_list.nodes: 39 | print(node.value) 40 | 41 | print("Sorted linked list:") 42 | for node in linked_list.sorted(): 43 | print(node.value) 44 | -------------------------------------------------------------------------------- /src/python/max_recursive.py: -------------------------------------------------------------------------------- 1 | """Exemplo de Máximo, utilizando recursão.""" 2 | 3 | 4 | def max_recursivo(vetor, maximo, indice): 5 | """Busca o valor máximo através usando recursão.""" 6 | if vetor[indice] > maximo: 7 | maximo = vetor[indice] 8 | if indice < len(vetor) - 1: 9 | maximo = max_recursivo(vetor, maximo, indice + 1) 10 | return maximo 11 | 12 | 13 | if __name__ == "__main__": 14 | lista = [19, 32, 43, 58, 12, 28, 98, 19, 12, 10] 15 | print(lista) 16 | print(f"Max: {max_recursivo(lista, lista[0], 0)}") 17 | -------------------------------------------------------------------------------- /src/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ Merge sort algorithm implementation """ 2 | 3 | 4 | def merge_sort(data): 5 | """ 6 | Sorts a list (data) in-place using merge sort approach. 7 | Args: 8 | data (list): unsorted list. 9 | """ 10 | if len(data) < 2: 11 | return 12 | mid = len(data) // 2 13 | 14 | left_data = data[:mid] 15 | right_data = data[mid:] 16 | 17 | merge_sort(left_data) 18 | merge_sort(right_data) 19 | 20 | left_index = 0 21 | right_index = 0 22 | data_index = 0 23 | 24 | while left_index < len(left_data) and right_index < len(right_data): 25 | if left_data[left_index] < right_data[right_index]: 26 | data[data_index] = left_data[left_index] 27 | left_index += 1 28 | else: 29 | data[data_index] = right_data[right_index] 30 | right_index += 1 31 | data_index += 1 32 | 33 | while left_index < len(left_data): 34 | data[data_index] = left_data[left_index] 35 | left_index += 1 36 | data_index += 1 37 | 38 | while right_index < len(right_data): 39 | data[data_index] = right_data[right_index] 40 | right_index += 1 41 | data_index += 1 42 | 43 | 44 | if __name__ == "__main__": 45 | some_list = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] 46 | print("Unsorted list: {}".format(some_list)) 47 | merge_sort(some_list) 48 | print("Sorted list: {}".format(some_list)) 49 | -------------------------------------------------------------------------------- /src/python/min_max_dc.py: -------------------------------------------------------------------------------- 1 | # Mínimo e Máximo de um array usando divide & conquer 2 | 3 | import random 4 | 5 | 6 | def min_max_dc(vetor, inicio, fim): 7 | """Encontra o valor mínimo e máximo em um vetor usando D&C.""" 8 | if inicio == fim: 9 | return vetor[inicio], vetor[inicio] 10 | 11 | meio = (inicio + fim) // 2 12 | vetor_min1, vetor_max1 = min_max_dc(vetor, inicio, meio) 13 | vetor_min2, vetor_max2 = min_max_dc(vetor, meio + 1, fim) 14 | return min(vetor_min1, vetor_min2), max(vetor_max1, vetor_max2) 15 | 16 | 17 | if __name__ == "__main__": 18 | vetor = [random.randrange(10, 100) for _ in range(0, 10)] 19 | print(vetor) 20 | 21 | minimo, maximo = min_max_dc(vetor, 0, len(vetor) - 1) 22 | 23 | print(f"Min DC: {minimo}") 24 | print(f"Max DC: {maximo}") 25 | -------------------------------------------------------------------------------- /src/python/min_max_iterative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implementação de um algoritmo que busca os valores máximo e mínimo 3 | em um array 4 | """ 5 | 6 | 7 | def min_max_array(vetor): 8 | """Busca os valores máximo e mínimo em vetor""" 9 | minimo = vetor[0] 10 | maximo = vetor[0] 11 | 12 | for i in range(1, len(vetor)): 13 | if vetor[i] < minimo: 14 | minimo = vetor[i] 15 | elif vetor[i] > maximo: 16 | maximo = vetor[i] 17 | 18 | print("Minimo : " + str(minimo)) 19 | print("Maximo : " + str(maximo)) 20 | 21 | 22 | uma_lista = [2, 94, 83, 10, 0, 2, 48, 1, 24] 23 | min_max_array(uma_lista) 24 | -------------------------------------------------------------------------------- /src/python/min_max_recursive.py: -------------------------------------------------------------------------------- 1 | """ Implementação do algoritmo de máximo e mínimo com recursão """ 2 | 3 | 4 | def max_min(vetor, minimo, maximo, indice): 5 | """ 6 | Imprime os valores máximo e mínimo de um vetor 7 | """ 8 | if vetor[indice] < minimo: 9 | minimo = vetor[indice] 10 | if vetor[indice] > maximo: 11 | maximo = vetor[indice] 12 | if indice < len(vetor) - 1: 13 | max_min(vetor, minimo, maximo, indice + 1) 14 | else: 15 | print(minimo) 16 | print(maximo) 17 | 18 | 19 | um_vetor = [2, 94, 83, 10, 0, 2, 48, 1, 24] 20 | max_min(um_vetor, um_vetor[0], um_vetor[0], 0) 21 | -------------------------------------------------------------------------------- /src/python/palindrome.py: -------------------------------------------------------------------------------- 1 | # A simple way to resolve the palindrome problem 2 | # Note: this example does not deal with punctuation 3 | 4 | 5 | def is_palindrome(content): 6 | processed_content = "".join(content.lower().split()) 7 | return processed_content == processed_content[::-1] 8 | 9 | 10 | if __name__ == "__main__": 11 | assert is_palindrome("ovo") 12 | assert is_palindrome("osso") 13 | assert is_palindrome("Arara") 14 | assert is_palindrome("Amor a Roma") 15 | assert is_palindrome("O lobo ama o bolo") 16 | assert is_palindrome("A grama é amarga") 17 | 18 | assert not is_palindrome("Sentido") 19 | assert not is_palindrome("Algoritmos") 20 | -------------------------------------------------------------------------------- /src/python/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ Quick Sort in Python """ 2 | 3 | 4 | def swap(a_list, pos1, pos2): 5 | """Swaps the position of two items in a list""" 6 | temp = a_list[pos1] 7 | a_list[pos1] = a_list[pos2] 8 | a_list[pos2] = temp 9 | 10 | 11 | def partition(a_list, start, end): 12 | """Splits a list""" 13 | pivot = a_list[start] 14 | while True: 15 | while a_list[start] < pivot: 16 | start = start + 1 17 | 18 | while a_list[end] > pivot: 19 | end = end - 1 20 | 21 | if start >= end: 22 | return end 23 | 24 | swap(a_list, start, end) 25 | 26 | start = start + 1 27 | end = end - 1 28 | 29 | 30 | def quick_sort(a_list, start, end): 31 | """Quick sort algorithm""" 32 | if start < end: 33 | part = partition(a_list, start, end) 34 | quick_sort(a_list, start, part) 35 | quick_sort(a_list, part + 1, end) 36 | 37 | 38 | if __name__ == "__main__": 39 | a = [9, 8, 5, 7, 6, 2, 4, 3, 1] 40 | print(a) 41 | quick_sort(a, 0, len(a) - 1) 42 | print(a) 43 | -------------------------------------------------------------------------------- /src/python/radix_sort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def radix_sort(arr): 5 | # Find the maximum number to know the number of digits 6 | max_num = max(arr) 7 | 8 | # Do counting sort for every digit, starting from the least significant digit 9 | exp = 1 10 | while max_num // exp > 0: 11 | counting_sort(arr, exp) 12 | exp *= 10 13 | 14 | 15 | def counting_sort(arr, exp): 16 | n = len(arr) 17 | output = [0] * n 18 | count = [0] * 10 19 | 20 | for i in range(n): 21 | index = arr[i] // exp 22 | count[index % 10] += 1 23 | 24 | for i in range(1, 10): 25 | count[i] += count[i - 1] 26 | 27 | i = n - 1 28 | while i >= 0: 29 | index = arr[i] // exp 30 | output[count[index % 10] - 1] = arr[i] 31 | count[index % 10] -= 1 32 | i -= 1 33 | 34 | for i in range(n): 35 | arr[i] = output[i] 36 | 37 | 38 | def main(): 39 | print("Fixed Testing Array") 40 | arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66] 41 | print("Unsorted array:", arr) 42 | radix_sort(arr) 43 | print("Sorted array:", arr) 44 | 45 | print("Random Testing Array") 46 | arr = [] 47 | for i in range(0, 10): 48 | arr.append(random.randint(0, 20)) 49 | print("Unsorted array:", arr) 50 | radix_sort(arr) 51 | print("Sorted array:", arr) 52 | 53 | 54 | if __name__ == "__main__": 55 | main() 56 | -------------------------------------------------------------------------------- /src/python/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ Implementação de um algoritmo de selection sort com recursão """ 2 | 3 | 4 | def selection_sort(vetor, indice): 5 | """ 6 | Implementação de um algoritmo de selection sort com recursão. 7 | 8 | Argumentos: 9 | vetor: lista. Lista que será ordenada 10 | indice: int. Indice do elemento a ser ordenado na lista 11 | 12 | Retorna a lista "vetor" ordenada. 13 | """ 14 | if indice >= len(vetor) - 1: 15 | return -1 16 | 17 | # minIndice guarda a posicao onde esta o menor valor em relacao ao indice 18 | min_indice = indice 19 | 20 | for i in range(indice + 1, len(vetor)): 21 | if vetor[i] < vetor[min_indice]: 22 | min_indice = i 23 | 24 | temp = vetor[indice] 25 | vetor[indice] = vetor[min_indice] 26 | vetor[min_indice] = temp 27 | 28 | selection_sort(vetor, indice + 1) 29 | 30 | return vetor 31 | 32 | 33 | lista_nao_ordenada = [82, 83, 92, 12, 23, 45, 64, 91, 73] 34 | 35 | print(lista_nao_ordenada) 36 | lista_nao_ordenada = selection_sort(lista_nao_ordenada, 0) 37 | print(lista_nao_ordenada) 38 | -------------------------------------------------------------------------------- /src/python/sorted_linked_list.py: -------------------------------------------------------------------------------- 1 | """ Lista Sequencial Dinamica e Ordenada """ 2 | 3 | import random 4 | 5 | lista = [] 6 | 7 | 8 | def inserir_lista(chave, lista): 9 | """ 10 | Insere a chave na lista 11 | """ 12 | lista.append(chave) 13 | i, p = 0, 0 14 | while lista[i] < chave: 15 | i += 1 16 | p = len(lista) - 2 17 | while p >= i: 18 | lista[p + 1] = lista[p] 19 | p -= 1 20 | lista[i] = chave 21 | 22 | 23 | def busca_sentinela(chave, lista): 24 | """Algoritmo de busca sentinela""" 25 | lista.append(chave) 26 | i = 0 27 | while lista[i] != chave: 28 | i += 1 29 | if i == len(lista) - 1: 30 | lista.pop() 31 | return -1 32 | lista.pop() 33 | return i 34 | 35 | 36 | def deleta_valor(chave, lista): 37 | """Deleta uma chave na lista""" 38 | posicao = busca_sentinela(chave, lista) 39 | if posicao >= 0: 40 | lista.pop(posicao) 41 | return True 42 | return False 43 | 44 | 45 | def mostra_lista(lista): 46 | """Imprime a lista""" 47 | print(lista) 48 | 49 | 50 | for _ in range(0, 50): 51 | inserir_lista(random.randint(10, 99), lista) 52 | 53 | print("Valor na posicao: " + str(busca_sentinela(25, lista))) 54 | 55 | mostra_lista(lista) 56 | deleta_valor(10, lista) 57 | mostra_lista(lista) 58 | -------------------------------------------------------------------------------- /src/python/stack.py: -------------------------------------------------------------------------------- 1 | """Implementação da estrutura de dados 'Pilha'""" 2 | 3 | import random 4 | 5 | 6 | class Stack: 7 | """ 8 | Essa classe implementa a estrutura de dados chamada "pilha" 9 | """ 10 | 11 | def __init__(self): 12 | self.__stack = [] 13 | 14 | def push(self, value): 15 | """Adiciona o valor (value) ao final da pilha""" 16 | self.__stack.append(value) 17 | 18 | def pop(self): 19 | """Remove o último valor da pilha""" 20 | return self.__stack.pop() 21 | 22 | def show(self): 23 | """Imprime a pilha no console""" 24 | print(f"Stack: {self.__stack}") 25 | 26 | 27 | def main(): 28 | """ 29 | Cria uma pilha e utiliza os métodos show, pop e push 30 | """ 31 | stack = Stack() 32 | 33 | for _ in range(0, 10): 34 | stack.push(random.randint(10, 99)) 35 | 36 | stack.show() 37 | 38 | stack.pop() 39 | stack.pop() 40 | 41 | stack.show() 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | -------------------------------------------------------------------------------- /src/python/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | """Implementaçao do algoritmo Torre de Hanoi""" 2 | 3 | 4 | def hanoi(pino0, pino2, pino1, discos): 5 | """ 6 | Mostra os passos da torre de hanoi de forma recursiva. 7 | Parametros: from, to, helper, numero de discos 8 | """ 9 | if discos == 1: 10 | print("Move de {} para {}".format(pino0, pino2)) 11 | else: 12 | hanoi(pino0, pino1, pino2, discos - 1) 13 | hanoi(pino0, pino2, pino1, 1) 14 | hanoi(pino1, pino2, pino0, discos - 1) 15 | 16 | 17 | if __name__ == "__main__": 18 | hanoi(0, 2, 1, 3) 19 | -------------------------------------------------------------------------------- /src/ruby/binary_search.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | def binary_search(value, array, left, right) 3 | middle = ((left + right) / 2).truncate 4 | 5 | return -1 unless left <= right 6 | 7 | if value > array[middle] 8 | binary_search(value, array, middle + 1, right) 9 | elsif value < array[middle] 10 | binary_search(value, array, left, middle - 1) 11 | else 12 | middle 13 | end 14 | end 15 | 16 | array = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] 17 | puts binary_search(12, array, 0, array.length) 18 | -------------------------------------------------------------------------------- /src/ruby/binary_tree.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test/unit/assertions" 4 | include Test::Unit::Assertions 5 | 6 | class BinaryTree 7 | attr_accessor :value 8 | attr_writer :left, :right 9 | 10 | def left 11 | @left ||= BinaryTree.new 12 | end 13 | 14 | def right 15 | @right ||= BinaryTree.new 16 | end 17 | 18 | def search(received_value) 19 | return value if value == received_value || value.nil? 20 | 21 | if received_value < value 22 | left.search(received_value) 23 | else 24 | right.search(received_value) 25 | end 26 | end 27 | 28 | def insert(received_value) 29 | return @value = received_value if value.nil? 30 | return left.insert(received_value) if received_value <= value 31 | 32 | right.insert(received_value) 33 | end 34 | 35 | def to_a 36 | return [] if value.nil? 37 | 38 | left.to_a + [value] + right.to_a 39 | end 40 | end 41 | 42 | tree = BinaryTree.new 43 | 44 | tree.insert(42) 45 | tree.insert(43) 46 | tree.insert(44) 47 | 48 | assert_equal(42, tree.search(42)) 49 | assert_equal(43, tree.search(43)) 50 | assert_equal(44, tree.search(44)) 51 | assert_equal(nil, tree.search(45)) 52 | 53 | tree = BinaryTree.new 54 | 55 | assert_equal([], tree.to_a) 56 | 57 | tree.insert(42) 58 | 59 | assert_equal([42], tree.to_a) 60 | 61 | tree.insert(43) 62 | 63 | assert_equal([42, 43], tree.to_a) 64 | 65 | tree.insert(41) 66 | 67 | assert_equal([41, 42, 43], tree.to_a) 68 | -------------------------------------------------------------------------------- /src/ruby/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the BubbleSort algorithm 4 | class Bubblesort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | bubble_sort(array) 13 | end 14 | 15 | private 16 | 17 | def bubble_sort(array) 18 | return nil if array.empty? 19 | 20 | n = array.length - 1 21 | loop do 22 | swapped = false 23 | 24 | n.times do |i| 25 | if array[i] > array[i + 1] 26 | array[i], array[i + 1] = array[i + 1], array[i] 27 | swapped = true 28 | end 29 | end 30 | break unless swapped 31 | end 32 | @array_sorted = array 33 | end 34 | end 35 | 36 | # test 37 | b_s = Bubblesort.new 38 | b_s.init([1, 4, 10, 2, 3, 32, 0]) 39 | p b_s.array_sorted 40 | -------------------------------------------------------------------------------- /src/ruby/bucket_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "./insertion_sort" 4 | 5 | # Sort an array using the BucketSort algorithm 6 | class BucketSort 7 | attr_reader :array_sorted 8 | 9 | def initialize 10 | @array_sorted = [] 11 | @insertion = InsertionSort.new 12 | end 13 | 14 | def init(array) 15 | bucket_sort(array, array.length) 16 | end 17 | 18 | private 19 | 20 | def bucket_sort(array, bucket_size) 21 | return nil if array.empty? 22 | 23 | min, max = array.minmax 24 | bucket_count = ((max - min) / bucket_size).floor + 1 25 | buckets = Array.new(bucket_count) 26 | 27 | (0..buckets.length - 1).each do |i| 28 | buckets[i] = [] 29 | end 30 | (0..array.length - 1).each do |i| 31 | buckets[((array[i] - min) / bucket_size).floor].push(array[i]) 32 | end 33 | array.clear 34 | (0..buckets.length - 1).each do |i| 35 | @insertion.init(buckets[i]) 36 | buckets[i].each do |value| 37 | array.push(value) 38 | end 39 | end 40 | @array_sorted = array 41 | end 42 | end 43 | 44 | # test 45 | bu_s = BucketSort.new 46 | bu_s.init([1, 4, 10, 2, 3, 32, 0]) 47 | p bu_s.array_sorted 48 | -------------------------------------------------------------------------------- /src/ruby/calculate_pi.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Calculo do PI (Leibniz) em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def calculate_pi(number) 8 | denominator = 1.0 9 | operation = 1.0 10 | pi = 0 11 | 12 | (1..number).each do |_count| 13 | pi += operation * (4.0 / denominator) 14 | denominator += 2.0 15 | operation *= -1.0 16 | end 17 | 18 | pi 19 | end 20 | 21 | def main 22 | terms = [10, 1000, 100_000, 10_000_000] 23 | 24 | terms.each do |term| 25 | puts "PI #{term}: #{calculate_pi(term)}" 26 | end 27 | end 28 | 29 | main 30 | -------------------------------------------------------------------------------- /src/ruby/comb_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Algoritmo de Comb sort em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def comb_sort(arr) 8 | gap = arr.length 9 | shrink = 1.3 10 | swapped = true 11 | 12 | while gap > 1 || swapped 13 | gap = (gap / shrink).floor 14 | gap = 1 if gap < 1 15 | swapped = false 16 | 17 | (0..(arr.length - gap) - 1).each do |i| 18 | if arr[i] > arr[i + gap] 19 | arr[i], arr[i + gap] = arr[i + gap], arr[i] 20 | swapped = true 21 | end 22 | end 23 | end 24 | 25 | arr 26 | end 27 | 28 | array = [86, 16, 10, 39, 49, 6, 32, 57, 72, 29] 29 | print "Lista: #{array} \n" 30 | print "Lista Ordenada: #{comb_sort(array)}" 31 | -------------------------------------------------------------------------------- /src/ruby/counting_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the CountSort algorithm 4 | class CountSort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | # min_max[0] = menor valor 12 | # min_max[1] = maior valor 13 | def init(array) 14 | min_max = array_max_min(array) 15 | count_sort(array, min_max[0], min_max[1]) 16 | end 17 | 18 | private 19 | 20 | def array_max_min(array) 21 | array.minmax 22 | end 23 | 24 | def count_sort(array, min, max) 25 | return "algo deu errado pqp" if min > max 26 | 27 | n = max - min + 1 28 | size = array.length 29 | aux = Array.new(size) 30 | count = Array.new(n, 0) 31 | 32 | (0...size).each do |i| 33 | count[array[i] - min] += 1 34 | end 35 | (1...n).each do |i| 36 | count[i] += count[i - 1] 37 | end 38 | (0...size).each do |i| 39 | aux[count[array[i] - min] - 1] = array[i] 40 | count[array[i] - min] -= 1 41 | end 42 | (0...size).each do |i| 43 | array[i] = aux[i] 44 | end 45 | 46 | @array_sorted = array 47 | end 48 | end 49 | 50 | # test 51 | c_s = CountSort.new 52 | c_s.init([1, 4, 10, 2, 3, 32, 0]) 53 | p c_s.array_sorted 54 | -------------------------------------------------------------------------------- /src/ruby/dijkstra.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Algoritmo de Dijkstra em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def dijkstra(matrix, vertices) 8 | visited = Array.new(vertices) 9 | 10 | (1..vertices - 1).each do |_i| 11 | min = nil 12 | min_value = nil 13 | 14 | (1..vertices - 1).each do |j| 15 | if !visited[j] && (!min_value || matrix[j][0] < min_value) 16 | min = j 17 | min_value = matrix[j][0] 18 | end 19 | end 20 | 21 | visited[min] = true 22 | 23 | (1..vertices - 1).each do |j| 24 | matrix[j][0] = matrix[min][0] + matrix[min][j] if matrix[min][0] + matrix[min][j] < matrix[j][0] 25 | end 26 | end 27 | end 28 | 29 | def main 30 | n_vertices = 5 31 | 32 | matrix = [] 33 | ignore = 4_294_967_295 34 | 35 | matrix.push([0, 6, 10, ignore, ignore]) 36 | matrix.push([6, 0, ignore, 2, ignore]) 37 | matrix.push([10, ignore, 0, 1, 3]) 38 | matrix.push([ignore, 2, 1, 0, 8]) 39 | matrix.push([ignore, ignore, 3, 8, 0]) 40 | 41 | matrix.to_a.each { |row| puts row.inspect } 42 | 43 | dijkstra(matrix, n_vertices) 44 | 45 | puts "============================================================" 46 | puts "Total caminho mais curto do vertice 0 ao 4: #{matrix[4][0]}" 47 | puts "============================================================" 48 | 49 | matrix.to_a.each { |row| puts row.inspect } 50 | end 51 | 52 | main 53 | -------------------------------------------------------------------------------- /src/ruby/exponentiation.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def exponenciacao(base, expoente) 4 | result = base 5 | expoente.pred.times { result *= base } 6 | result 7 | end 8 | 9 | puts exponenciacao(5, 2) 10 | puts exponenciacao(5, 5) 11 | -------------------------------------------------------------------------------- /src/ruby/exponentiation_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def exponenciacao(base, expoente) 4 | return 1 if expoente.zero? 5 | 6 | base * exponenciacao(base, expoente.pred) 7 | end 8 | 9 | puts exponenciacao(5, 2) 10 | puts exponenciacao(5, 5) 11 | -------------------------------------------------------------------------------- /src/ruby/factorial.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Fatorial em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def factorial(value) 8 | aux = 1 9 | (1..value).each do |i| 10 | aux *= i 11 | end 12 | 13 | aux 14 | end 15 | 16 | def main 17 | 11.times do |number| 18 | puts "#{number}! = #{factorial(number)}" 19 | end 20 | end 21 | 22 | main 23 | -------------------------------------------------------------------------------- /src/ruby/factorial_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def fatorial(number) 4 | aux = 1 5 | (2..number).each do |x| 6 | aux *= x 7 | end 8 | aux 9 | end 10 | 11 | def fatorial_recursiva(number) 12 | return 1 if number <= 1 13 | 14 | n * fatorial_recursiva(number - 1) 15 | end 16 | 17 | puts fatorial(5) 18 | puts fatorial_recursiva(5) 19 | -------------------------------------------------------------------------------- /src/ruby/fibonacci_iterative.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def fibonacci(number) 4 | last = 0 5 | curr = 1 6 | (0..number - 1).each do |_| 7 | swap = curr 8 | curr += last 9 | last = swap 10 | end 11 | last 12 | end 13 | 14 | puts fibonacci(12) 15 | -------------------------------------------------------------------------------- /src/ruby/fibonacci_memoization.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def fibonacci(n, memo = {}) 4 | if n <= 1 5 | return 1 6 | end 7 | 8 | # Check if the result is already memoized 9 | if memo.key?(n) 10 | return memo[n] 11 | end 12 | 13 | # Calculate Fibonacci recursively and store the result in memoization 14 | result = fibonacci(n - 1, memo) + fibonacci(n - 2, memo) 15 | memo[n] = result 16 | 17 | return result 18 | end 19 | 20 | n = 16 21 | puts "Fib(#{n}): #{fibonacci(n)}" 22 | -------------------------------------------------------------------------------- /src/ruby/fibonacci_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def fibonacci(number) 4 | if number <= 0 5 | 0 6 | elsif number == 1 7 | 1 8 | else 9 | fibonacci(number - 1) + fibonacci(number - 2) 10 | end 11 | end 12 | 13 | puts fibonacci(12) 14 | -------------------------------------------------------------------------------- /src/ruby/gnome_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Algoritmo Gnome sort em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def gnome_sort(array) 8 | count = 0 9 | 10 | while count < array.length - 1 11 | if array[count] > array[count + 1] 12 | array[count + 1], array[count] = array[count], array[count + 1] 13 | count -= 2 if count.positive? 14 | end 15 | count += 1 16 | end 17 | 18 | array 19 | end 20 | 21 | def main 22 | array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6] 23 | print(gnome_sort(array)) 24 | end 25 | 26 | main 27 | -------------------------------------------------------------------------------- /src/ruby/hash_table.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class HashTable 4 | attr_reader :hash 5 | 6 | def initialize(size = 500) 7 | @hash = Array.new(size) { [] } 8 | @size = size 9 | end 10 | 11 | def put(key, value) 12 | idx = calculate_hash(key) 13 | @hash[idx] << [key, value] 14 | end 15 | 16 | def get(key) 17 | idx = calculate_hash(key) 18 | 19 | bucket = @hash[idx] 20 | pair = bucket.find { |pair| pair[0] == key } 21 | 22 | pair[1] if pair 23 | end 24 | 25 | def delete(key) 26 | idx = calculate_hash(key) 27 | @hash.delete_at(idx) 28 | end 29 | 30 | private 31 | 32 | def calculate_hash(str) 33 | str.to_s.bytes.reduce(&:*) % @size 34 | end 35 | end 36 | 37 | hash = HashTable.new 38 | hash.put(:code, "ABC123") 39 | hash.put(:mode, "dark") 40 | 41 | puts "Code is #{hash.get(:code)}" # => ABC123 42 | puts "Mode is #{hash.get(:mode)}" # => "dark 43 | 44 | hash.delete(:code) 45 | puts hash.get(:code) # => nil 46 | -------------------------------------------------------------------------------- /src/ruby/heap_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the HeapSort algorithm 4 | class Heapsort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | heap_sort(array) 13 | end 14 | 15 | private 16 | 17 | def heap_sort(array) 18 | n = array.length 19 | a = [nil] + array 20 | 21 | (n / 2).downto(1) do |i| 22 | heapify(a, i, n) 23 | end 24 | while n > 1 25 | a[1], a[n] = a[n], a[1] 26 | n -= 1 27 | heapify(a, 1, n) 28 | end 29 | a.drop(1) 30 | @array_sorted = a 31 | end 32 | 33 | def heapify(array, parent, limit) 34 | root = array[parent] 35 | while (child = 2 * parent) <= limit 36 | child += 1 if child < limit && array[child] < array[child + 1] 37 | break if root >= array[child] 38 | 39 | array[parent] = array[child] 40 | parent = child 41 | array[parent] = root 42 | end 43 | end 44 | end 45 | 46 | # test 47 | h_s = Heapsort.new 48 | h_s.init([1, 4, 10, 2, 3, 32, 0]) 49 | p h_s.array_sorted 50 | -------------------------------------------------------------------------------- /src/ruby/insertion_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the InsertionSort algorithm 4 | class InsertionSort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | insertion_sort(array) 13 | end 14 | 15 | private 16 | 17 | def insertion_sort(array, compare = ->(a, b) { a <=> b }) 18 | return nil if array.empty? 19 | 20 | (1..array.length - 1).each do |i| 21 | item = array[i] 22 | index_hole = i 23 | while index_hole.positive? && compare.call(array[index_hole - 1], item).positive? 24 | array[index_hole] = array[index_hole - 1] 25 | index_hole -= 1 26 | end 27 | array[index_hole] = item 28 | end 29 | @array_sorted = array 30 | end 31 | end 32 | 33 | # test 34 | i_s = InsertionSort.new 35 | i_s.init([1, 4, 10, 2, 3, 32, 0]) 36 | p i_s.array_sorted 37 | -------------------------------------------------------------------------------- /src/ruby/interpolation_search.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Algoritmo de Busca por interpolação em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def interpolation_search(value, data) 8 | low = 0 9 | high = data.length - 1 10 | mid = ((data.length - 1) / 2).floor + low 11 | 12 | while low < mid 13 | if data[mid] == value 14 | return "Elemento encontrado na #{high}° posição do array ordenado." 15 | elsif value > data[mid] 16 | low = mid 17 | mid = ((high - low) / 2).floor + low 18 | else 19 | high = mid 20 | mid = ((high - low) / 2).floor + low 21 | end 22 | end 23 | end 24 | 25 | def main 26 | array1 = [37, 53, 1, 43, 11, 49, 32, 55, 40, 47, 25, 4].sort 27 | puts interpolation_search(43, array1) # 8° posição do array ordenado 28 | 29 | array2 = [23, 9, 5, 78, 123, 5444, 54_535, 64, 3, 12, 14, 15].sort 30 | puts interpolation_search(5444, array2) # 11° posição do array ordenado 31 | end 32 | 33 | main 34 | -------------------------------------------------------------------------------- /src/ruby/linear_search.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def busca_sequencial(valor, vetor) 4 | # Procura o valor no vetor sequencialmente 5 | # Se encontrar retorna o índice, senão -1 6 | vetor.each_with_index do |elemento, indice| 7 | return indice if elemento.equal?(valor) 8 | end 9 | -1 10 | end 11 | 12 | vetor = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] 13 | puts busca_sequencial(98, vetor) 14 | -------------------------------------------------------------------------------- /src/ruby/linear_search_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test/unit/assertions" 4 | include Test::Unit::Assertions 5 | 6 | # Retorna o índice do elemento. Se não existir, retorna -1. 7 | 8 | def busca_sequencial_recursiva(lista, valor, index = 0) 9 | if lista[index] == valor 10 | index 11 | elsif index == lista.size 12 | -1 13 | else 14 | index += 1 15 | busca_sequencial_recursiva(lista, valor, index) 16 | end 17 | end 18 | 19 | assert_equal busca_sequencial_recursiva([1, 2, 3, 4, 5], 1), 0 20 | assert_equal busca_sequencial_recursiva(%w[a b c], 1), -1 21 | assert_equal busca_sequencial_recursiva([10, 9, 7, 2, 4, 5, 6, 99, 11, 4], 7), 2 22 | -------------------------------------------------------------------------------- /src/ruby/linear_search_sentinel.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | def sentinel_search(value, array) 3 | # Create a copy of the array 4 | array_copy = array.dup 5 | 6 | # Add the value to the end of the array copy 7 | array_copy.push(value) 8 | index = 0 9 | 10 | # While it's not the value, increment by 1 11 | index += 1 while array_copy[index] != value 12 | 13 | # Remove the value from the end of the array copy 14 | array_copy.pop 15 | 16 | # If the index variable equals the array size, return -1 17 | return -1 if index == array_copy.length 18 | 19 | # Otherwise, return the position of the value in the array copy 20 | index 21 | end 22 | 23 | array = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] 24 | puts sentinel_search(98, array) 25 | -------------------------------------------------------------------------------- /src/ruby/max_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Algoritmo de Máximo Recursivo em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def max_recursivo(vetor, maximo, indice) 8 | maximo = vetor[indice] if vetor[indice] > maximo 9 | 10 | maximo = max_recursivo(vetor, maximo, indice + 1) if indice < vetor.length - 1 11 | 12 | maximo 13 | end 14 | 15 | lista = [19, 32, 43, 58, 12, 28, 98, 19, 12, 10] 16 | print lista 17 | 18 | puts "\nMaximo recursivo: #{max_recursivo(lista, lista[0], 0)}" 19 | -------------------------------------------------------------------------------- /src/ruby/merge_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the MergeSort algorithm 4 | class MergeSort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | sort(array) 13 | end 14 | 15 | private 16 | 17 | def sort(array) 18 | return array if array.length <= 1 19 | 20 | mid = (array.length / 2).round 21 | 22 | left = array.take(mid) 23 | right = array.drop(mid) 24 | 25 | sorted_left = sort(left) 26 | sorted_right = sort(right) 27 | 28 | @array_sorted = merge(sorted_left, sorted_right) 29 | end 30 | 31 | def merge(left, right) 32 | return left if right.empty? 33 | return right if left.empty? 34 | 35 | small_number = if left.first <= right.first 36 | left.shift 37 | else 38 | right.shift 39 | end 40 | 41 | recursive = merge(left, right) 42 | 43 | [small_number].concat(recursive) 44 | end 45 | end 46 | 47 | # test 48 | m = MergeSort.new 49 | m.init([1, 4, 10, 2, 3, 32, 0]) 50 | p m.array_sorted 51 | -------------------------------------------------------------------------------- /src/ruby/min_max_dc.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test/unit/assertions" 4 | include Test::Unit::Assertions 5 | 6 | def min_max_dc(vector, start_index, end_index) 7 | if start_index == end_index 8 | return [vector[start_index], vector[start_index]] 9 | end 10 | 11 | middle = (start_index + end_index) / 2 12 | left_min, left_max = min_max_dc(vector, start_index, middle) 13 | right_min, right_max = min_max_dc(vector, middle + 1, end_index) 14 | 15 | min = left_min < right_min ? left_min : right_min 16 | max = left_max > right_max ? left_max : right_max 17 | 18 | [min, max] 19 | end 20 | 21 | assert_equal([1, 5], min_max_dc([1, 2, 3, 4, 5], 0, 4)) 22 | assert_equal([14, 55], min_max_dc([13, 55, 42, 14, 15], 1, 3)) 23 | assert_equal([13, 13], min_max_dc([13, 55, 42, 14, 15], 0, 0)) 24 | assert_equal([14, 15], min_max_dc([13, 55, 42, 14, 15], 3, 4)) 25 | -------------------------------------------------------------------------------- /src/ruby/min_max_iterative.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Mínimo e Máximo Interativo em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def min_max_array(vetor) 8 | minimo = vetor[0] 9 | maximo = vetor[0] 10 | 11 | vetor_size = vetor.length - 1 12 | (1..vetor_size).each do |i| 13 | if vetor[i] < minimo 14 | minimo = vetor[i] 15 | elsif vetor[i] > maximo 16 | maximo = vetor[i] 17 | end 18 | end 19 | 20 | puts "Minimo: #{minimo}" 21 | puts "Maximo: #{maximo}" 22 | end 23 | 24 | lista = [2, 94, 83, 10, 0, 2, 48, 1, 24] 25 | min_max_array(lista) 26 | -------------------------------------------------------------------------------- /src/ruby/min_max_recursive.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Mínimo e Máximo recursivo em Ruby 4 | # Carlos Alves 5 | # https://github.com/EuCarlos 6 | 7 | def recursive_min_and_max(arr, min, max, index) 8 | min = arr[index] if arr[index] < min 9 | max = arr[index] if arr[index] > max 10 | 11 | if index < arr.length - 1 12 | recursive_min_and_max(arr, min, max, index + 1) 13 | else 14 | puts "Mínimo: #{min}" 15 | puts "Máximo: #{max}" 16 | end 17 | end 18 | 19 | list = [37, 53, 1, 43, 11, 49, 32, 55, 40, 47, 25, 4] 20 | recursive_min_and_max(list, list[0], list[0], 0) 21 | -------------------------------------------------------------------------------- /src/ruby/palindrome.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test/unit/assertions" 4 | include Test::Unit::Assertions 5 | 6 | # the easiest implementation would be using .reverse method 7 | 8 | def palindrome?(string) 9 | return true if string.size == 1 || string.empty? 10 | 11 | reversed = "" 12 | string = string.gsub(" ", "").downcase 13 | string.chars.reverse_each do |c| 14 | reversed << c 15 | end 16 | 17 | reversed == string 18 | end 19 | 20 | assert_equal palindrome?("abba"), true 21 | assert_equal palindrome?("abbas"), false 22 | assert_equal palindrome?("tattarrattat"), true 23 | assert_equal palindrome?("Was it a palindrome?"), false 24 | assert_equal palindrome?("No lemon, no melon"), true 25 | -------------------------------------------------------------------------------- /src/ruby/queue.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Implements a Queue data structure 4 | class Queue 5 | def initialize 6 | @queue = [] 7 | end 8 | 9 | def enqueue(value) 10 | @queue.push(value) 11 | end 12 | 13 | def dequeue 14 | @queue.delete_at(0) 15 | end 16 | 17 | def display 18 | print "#{@queue}\n" 19 | end 20 | end 21 | 22 | q = Queue.new 23 | 24 | q.enqueue(1) 25 | q.enqueue(2) 26 | q.enqueue(3) 27 | q.enqueue(4) 28 | q.display 29 | 30 | q.dequeue 31 | q.dequeue 32 | q.display 33 | -------------------------------------------------------------------------------- /src/ruby/quick_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the QuickSort algorithm 4 | class Quicksort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | quick_sort(array) 13 | end 14 | 15 | private 16 | 17 | def quick_sort(array, compare = ->(a, b) { a <=> b }) 18 | inner(array, 0, array.length - 1, compare) 19 | end 20 | 21 | def inner(array, left, right, compare) 22 | if left < right 23 | pivot = partition_random(array, left, right, compare) 24 | inner(array, left, pivot - 1, compare) 25 | inner(array, pivot + 1, right, compare) 26 | end 27 | @array_sorted = array 28 | end 29 | 30 | def partition_random(array, left, right, compare) 31 | pivot = left + (rand * (right - left)).floor 32 | array[right], array[pivot] = array[pivot], array[right] if pivot != right 33 | partition_right(array, left, right, compare) 34 | end 35 | 36 | def partition_right(array, left, right, compare) 37 | pivot = array[right] 38 | mid = left 39 | (mid..right - 1).each do |i| 40 | next unless compare.call(array[i], pivot) <= 0 41 | 42 | array[i], array[mid] = array[mid], array[i] if i != mid 43 | mid += 1 44 | end 45 | array[right], array[mid] = array[mid], array[right] if right != mid 46 | mid 47 | end 48 | end 49 | 50 | # test 51 | q_s = Quicksort.new 52 | q_s.init([1, 4, 10, 2, 3, 32, 0]) 53 | p q_s.array_sorted 54 | -------------------------------------------------------------------------------- /src/ruby/radix_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the RadixSort algorithm 4 | class RadixSort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | radix_sort(array) 13 | end 14 | 15 | private 16 | 17 | def radix_sort(array) 18 | max_value = array.max 19 | exp = 0 20 | 21 | until max_value.zero? 22 | exp += 1 23 | max_value = (max_value / 10) 24 | end 25 | 26 | (0...exp).each do |i| 27 | array = radix(array, i) 28 | end 29 | 30 | @array_sorted = array 31 | end 32 | 33 | def radix(array, exp = 0) 34 | array_c = Array.new(10, 0) 35 | result = Array.new(array.length) 36 | m = 10**(exp + 1) 37 | n = 10**exp 38 | 39 | array.each do |value| 40 | num = (value % m) / n 41 | array_c[num] += 1 42 | end 43 | (1...10).each do |i| 44 | array_c[i] = array_c[i - 1] + array_c[i] 45 | end 46 | 47 | i = (array.length - 1) 48 | until i.negative? 49 | value = array[i] 50 | num = (value % m) / n 51 | array_c[num] -= 1 52 | result[array_c[num]] = value 53 | i -= 1 54 | end 55 | result 56 | end 57 | end 58 | 59 | # test 60 | r_s = RadixSort.new 61 | r_s.init([1, 4, 10, 2, 3, 32, 0]) 62 | p r_s.array_sorted 63 | -------------------------------------------------------------------------------- /src/ruby/selection_sort.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Sort an array using the SelectionSort algorithm 4 | class SelectionSort 5 | attr_reader :array_sorted 6 | 7 | def initialize 8 | @array_sorted = [] 9 | end 10 | 11 | def init(array) 12 | selection_sort(array, array.length - 1) 13 | end 14 | 15 | private 16 | 17 | def selection_sort(array, size) 18 | size.times do |i| 19 | index_min = i 20 | 21 | (i + 1).upto(size) do |j| 22 | index_min = j if array[j] < array[index_min] 23 | end 24 | array[i], array[index_min] = array[index_min], array[i] if index_min != i 25 | end 26 | @array_sorted = array 27 | end 28 | end 29 | 30 | # test 31 | s_s = SelectionSort.new 32 | s_s.init([1, 4, 10, 2, 3, 32, 0]) 33 | p s_s.array_sorted 34 | -------------------------------------------------------------------------------- /src/ruby/stack.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Implement the Stack data structure 4 | class Stack 5 | def initialize 6 | @stack = [] 7 | end 8 | 9 | def push(value) 10 | @stack.push(value) 11 | end 12 | 13 | def pop 14 | @stack.pop 15 | end 16 | 17 | def display 18 | print "#{@stack}\n" 19 | end 20 | end 21 | 22 | s = Stack.new 23 | 24 | s.push(1) 25 | s.push(2) 26 | s.push(3) 27 | s.push(4) 28 | s.display 29 | 30 | s.pop 31 | s.pop 32 | s.display 33 | -------------------------------------------------------------------------------- /src/ruby/tower_of_hanoi.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def hanoi(pin0, pin2, pin1, num) 4 | if num == 1 5 | # Show the operations 6 | print "Move from ", pin0, " to ", pin2, "\n" 7 | else 8 | hanoi(pin0, pin1, pin2, num - 1) 9 | hanoi(pin0, pin2, pin1, 1) 10 | hanoi(pin1, pin2, pin0, num - 1) 11 | end 12 | end 13 | 14 | # Move from Pin-0 to Pin-2 using Pin-1 as helper (number of disks = 3) 15 | hanoi(0, 2, 1, 3) 16 | -------------------------------------------------------------------------------- /src/rust/bubble_sort.rs: -------------------------------------------------------------------------------- 1 | fn bubble_sort(mut slice: Vec) -> Vec { 2 | for i in 0..slice.len() { 3 | for j in 0..slice.len() - 1 - i { 4 | if slice[j] > slice[j + 1] { 5 | slice.swap(j, j + 1); 6 | } 7 | } 8 | } 9 | slice 10 | } 11 | fn main() { 12 | println!( 13 | "{:?}", 14 | bubble_sort(vec![4, 65, 2, -31, 0, 99, 2, 83, 782, 1]) 15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /src/rust/calculate_pi.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("{:?}", calculate_pi(vec![10, 1000, 100000, 10000000])); 3 | } 4 | fn calculate_pi(terms: Vec) -> Vec { 5 | let mut denominator: f64; 6 | let mut operation: f64; 7 | let mut pi: Vec = Vec::::new(); 8 | 9 | for i in 0..terms.len() { 10 | denominator = 1.0; 11 | operation = 1.0; 12 | pi.push(0.0); 13 | for _ in 0..terms[i] { 14 | let i: usize = i as usize; 15 | pi[i] += operation * (4.0 / denominator); 16 | denominator += 2.0; 17 | operation *= -1.0; 18 | } 19 | } 20 | pi 21 | } 22 | -------------------------------------------------------------------------------- /src/rust/deque.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Deque { 3 | deque: Vec, 4 | } 5 | 6 | impl Deque { 7 | fn new() -> Self { 8 | Deque { deque: Vec::new() } 9 | } 10 | 11 | fn add_last(&mut self, item: T) { 12 | self.deque.push(item) 13 | } 14 | 15 | fn remove_last(&mut self) -> Option { 16 | self.deque.pop() 17 | } 18 | 19 | fn add_first(&mut self, item: T) { 20 | self.deque.insert(0, item) 21 | } 22 | 23 | fn remove_first(&mut self) -> T { 24 | self.deque.remove(0) 25 | } 26 | 27 | fn length(&self) -> usize { 28 | self.deque.len() 29 | } 30 | 31 | fn is_empty(&self) -> bool { 32 | self.deque.is_empty() 33 | } 34 | 35 | fn peek(&self) -> Option<&T> { 36 | self.deque.first() 37 | } 38 | 39 | fn peek_last(&self) -> Option<&T> { 40 | self.deque.last() 41 | } 42 | } 43 | 44 | fn main() { 45 | let mut deque: Deque = Deque::::new(); 46 | deque.add_first(1); 47 | deque.add_last(2); 48 | deque.add_first(3); 49 | println!("{:?}", deque); 50 | deque.remove_last(); 51 | deque.remove_first(); 52 | println!("{:?}", deque); 53 | println!( 54 | "length: {:?}, is empty? {:?}", 55 | deque.length(), 56 | deque.is_empty() 57 | ); 58 | deque.add_first(1); 59 | deque.add_last(2); 60 | deque.add_first(3); 61 | println!("{:?}, {:?}", deque.peek(), deque.peek_last()); 62 | } 63 | -------------------------------------------------------------------------------- /src/rust/exponentiation_recursive.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println! {"3^3 = {:?}", exponentiation_recursive(3,3)} 3 | println! {"3^4 = {:?}", exponentiation_recursive(3,4)} 4 | println! {"2^3 = {:?}", exponentiation_recursive(2,3)} 5 | println! {"5^2 = {:?}", exponentiation_recursive(5,2)} 6 | } 7 | 8 | fn exponentiation_recursive(base: i32, exponent: i32) -> i32 { 9 | if exponent <= 1 { 10 | return base; 11 | } 12 | base * exponentiation_recursive(base, exponent - 1) 13 | } 14 | -------------------------------------------------------------------------------- /src/rust/factorial.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Contribuidores 3 | - Dromedario de Chapéu 4 | 5 | Fatorial é uma função matematica que consistem em realizar 6 | a multiplicação de todos os antecessores de um numero. 7 | 8 | Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120 9 | */ 10 | 11 | // A diferença desta implementação para a com recursão é 12 | // que nesta versão o retorno, é feito utilizado interadores. 13 | fn fatorial(valor: u128) -> u128 { 14 | let total = match valor { 15 | 0 => 1, 16 | // Product faz a multiplicação de todos os valores em um array 17 | 1.. => (1..valor + 1).product(), 18 | }; 19 | return total; 20 | } 21 | 22 | fn main() { 23 | println!("{}", fatorial(21)); 24 | } 25 | 26 | #[cfg(test)] 27 | mod test { 28 | use super::*; 29 | #[test] 30 | fn teste_fatorial() { 31 | assert_eq!(fatorial(0), 1); 32 | assert_eq!(fatorial(1), 1); 33 | assert_eq!(fatorial(10), 3628800); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/rust/factorial_recursive.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Contribuidores 3 | - Heitor582 4 | - Dromedario de Chapéu 5 | 6 | Fatorial é uma função matematica que consistem em realizar 7 | a multiplicação de todos os antecessores de um numero. 8 | 9 | Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120 10 | */ 11 | 12 | // Para realizar uma fatoração com recursão basta fazer o retorno 13 | // de uma função ser valor * a propia função recebendo valor - 1 14 | fn fatorial(valor: u128) -> u128 { 15 | // Para que não chege a multiplicar por 0 quando chegamos a 1 ou 0 é 16 | // retornado 1 para que o utlimo valor não sejá zerado ao multiplicar por zero 17 | match valor { 18 | 0 | 1 => 1, 19 | 2.. => valor * (fatorial(valor - 1)), 20 | } 21 | } 22 | 23 | fn main() { 24 | println!("{}", fatorial(21)); 25 | } 26 | 27 | #[cfg(test)] 28 | mod test { 29 | use super::*; 30 | #[test] 31 | fn teste_fatorial() { 32 | assert_eq!(fatorial(0), 1); 33 | assert_eq!(fatorial(1), 1); 34 | assert_eq!(fatorial(10), 3628800); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/rust/fibonacci_iterative.rs: -------------------------------------------------------------------------------- 1 | fn fibonacci(n: u32) -> u64 { 2 | if n <= 1 { 3 | return n as u64; 4 | } 5 | 6 | let mut a: u64 = 0; 7 | let mut b: u64 = 1; 8 | 9 | for _ in 2..=n { 10 | let temp = a; 11 | a = b; 12 | b += temp; 13 | } 14 | 15 | b 16 | } 17 | 18 | fn main() { 19 | let index = 15; 20 | println!( 21 | "Fibonacci (iterative) of {} is: {}", 22 | index, 23 | fibonacci(index) 24 | ); 25 | } 26 | -------------------------------------------------------------------------------- /src/rust/fibonacci_memoization.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | fn fibonacci(n: u32, memo: &mut HashMap) -> u64 { 4 | if n <= 1 { 5 | return n as u64; 6 | } 7 | 8 | // Check if the result is already memoized 9 | if let Some(&cached_result) = memo.get(&n) { 10 | return cached_result; 11 | } 12 | 13 | // Calculate Fibonacci recursively and store the result in memoization 14 | let result = fibonacci(n - 1, memo) + fibonacci(n - 2, memo); 15 | memo.insert(n, result); 16 | 17 | result 18 | } 19 | 20 | fn main() { 21 | let index = 15; 22 | let mut memo: HashMap = HashMap::new(); 23 | 24 | println!( 25 | "Fibonacci (memoization) of {} is: {}", 26 | index, 27 | fibonacci(index, &mut memo) 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /src/rust/fibonacci_recursive.rs: -------------------------------------------------------------------------------- 1 | fn fibonacci(number: i32) -> i32 { 2 | if number < 2 { 3 | return number; 4 | } else { 5 | return fibonacci(number - 1) + fibonacci(number - 2); 6 | } 7 | } 8 | fn main() { 9 | println!("{:?}", fibonacci(3)); 10 | println!("{:?}", fibonacci(15)); 11 | println!("{:?}", fibonacci(30)); 12 | } 13 | -------------------------------------------------------------------------------- /src/rust/gnome_sort.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("{:?}", gnomesort(vec![1, 3, 5, 2])); 3 | } 4 | fn gnomesort(mut slice: Vec) -> Vec { 5 | let mut pivot: i32 = 0; 6 | let size: i32 = slice.len() as i32; 7 | 8 | while pivot < size - 1 { 9 | if slice[pivot as usize] > slice[pivot as usize + 1] { 10 | let temp: i32 = slice[pivot as usize]; 11 | slice[pivot as usize] = slice[pivot as usize + 1]; 12 | slice[pivot as usize + 1] = temp; 13 | if pivot > 0 { 14 | pivot -= 2; 15 | } 16 | } 17 | pivot += 1; 18 | } 19 | slice 20 | } 21 | -------------------------------------------------------------------------------- /src/rust/insertion_sort.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println! {"{:?}", insertion_sort(vec![54,42,11,33,24,99,77,80])}; 3 | } 4 | fn insertion_sort(mut vetor: Vec) -> Vec { 5 | for i in 1..vetor.len() { 6 | let mut index: i32 = i as i32; 7 | while index > 0 && vetor[index as usize] < vetor[index as usize - 1] { 8 | vetor.swap(index as usize, index as usize - 1); 9 | index -= 1; 10 | } 11 | } 12 | vetor 13 | } 14 | -------------------------------------------------------------------------------- /src/rust/linear_search.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Contribuidores 3 | - Dromedario de Chapéu 4 | 5 | Busca Sequencial é o mais simples algoritmo de busca possessive, alem de 6 | ser um dos menos eficientes. Ele simplesmente itera por todos os itens 7 | de uma lista até encontrar o valor desejado ou atingir o final da lista 8 | retornando que o elemento não esta presente na lista. 9 | 10 | Esse algoritmo pode ser útil para listas pequenas de algumas poucas centenas 11 | de valores de tipo simples, porem mais que isso ele sera um grande gargalo 12 | durante a execução do programa. 13 | 14 | Uma possível vantagem deste algoritmo, é que ele independe da lista estar 15 | ordenada para funcionar, pois ele não se importa com a ordem dos elementos. 16 | */ 17 | fn busca_sequencial(lista: &[i32], valor: i32) -> (bool, usize) { 18 | for (i, c) in lista.iter().enumerate() { 19 | if *c == valor { 20 | return (true, i); 21 | } 22 | } 23 | return (false, 0); 24 | } 25 | 26 | fn main() { 27 | let lista = vec![1, 2, 3, 4]; 28 | let (existe, indice) = busca_sequencial(&lista, 2); 29 | println!("{}, {}", existe, indice); 30 | } 31 | 32 | #[cfg(test)] 33 | mod test { 34 | use super::*; 35 | 36 | #[test] 37 | fn busca() { 38 | let lista = vec![1, 2, 3, 4]; 39 | assert_eq!(busca_sequencial(&lista, 2), (true, 1)); 40 | assert_eq!(busca_sequencial(&lista, 0), (false, 0)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/rust/min_max_iterative.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | min_max(vec![54, 42, 11, 33, 24, 99, 77, 80]); 3 | } 4 | 5 | fn min_max(vetor: Vec) { 6 | let mut min = vetor[0]; 7 | let mut max = vetor[0]; 8 | 9 | for i in 1..vetor.len() { 10 | if vetor[i] < min { 11 | min = vetor[i]; 12 | } else if vetor[i] > max { 13 | max = vetor[i]; 14 | } 15 | } 16 | 17 | println! {"Data: {:?}", vetor}; 18 | println! {"Min.: {:?}", min}; 19 | println! {"Max.: {:?}", max}; 20 | } 21 | -------------------------------------------------------------------------------- /src/rust/min_max_recursive.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let vetor = vec![54, 42, 11, 33, 24, 99, 77, 80]; 3 | min_max(vetor, i32::MAX, i32::MIN, 0); 4 | } 5 | 6 | fn min_max(vetor: Vec, mut min: i32, mut max: i32, indice: usize) { 7 | if vetor[indice] < min { 8 | min = vetor[indice]; 9 | } 10 | if vetor[indice] > max { 11 | max = vetor[indice]; 12 | } 13 | if indice < vetor.len() - 1 { 14 | min_max(vetor, min, max, indice + 1); 15 | } else { 16 | println! {"Data: {:?}", vetor}; 17 | println! {"Min.: {:?}", min}; 18 | println! {"Max.: {:?}", max}; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/rust/palindrome.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("{:?}", palindromo("".to_string())); 3 | println!("{:?}", palindromo("a".to_string())); 4 | println!("{:?}", palindromo("abba".to_string())); 5 | println!("{:?}", palindromo("abbas".to_string())); 6 | println!("{:?}", palindromo("tattarrattat".to_string())); 7 | println!("{:?}", palindromo("Was it a palindrome?".to_string())); 8 | println!("{:?}", palindromo("No lemon, no melon".to_string())); 9 | } 10 | fn palindromo(mut word: String) -> bool { 11 | word = word.to_lowercase().split_whitespace().collect::(); 12 | let reversed_string: String = word.chars().rev().collect::(); 13 | if word.len() <= 1 { 14 | return true; 15 | } 16 | word == reversed_string 17 | } 18 | -------------------------------------------------------------------------------- /src/rust/queue.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Fila { 3 | fila: Vec, 4 | } 5 | 6 | impl Fila { 7 | fn new() -> Self { 8 | Fila { fila: Vec::new() } 9 | } 10 | 11 | fn length(&self) -> usize { 12 | self.fila.len() 13 | } 14 | 15 | fn enqueue(&mut self, item: T) { 16 | self.fila.push(item) 17 | } 18 | 19 | fn dequeue(&mut self) -> T { 20 | self.fila.remove(0) 21 | } 22 | fn is_empty(&self) -> bool { 23 | self.fila.is_empty() 24 | } 25 | 26 | fn peek(&self) -> Option<&T> { 27 | self.fila.first() 28 | } 29 | } 30 | 31 | fn main() { 32 | let mut fila: Fila = Fila::::new(); 33 | fila.enqueue(1); 34 | println!("{:?}", fila); 35 | fila.dequeue(); 36 | println!( 37 | "length: {:?}, is empty? {:?}", 38 | fila.length(), 39 | fila.is_empty() 40 | ); 41 | fila.enqueue(1); 42 | fila.enqueue(2); 43 | fila.enqueue(3); 44 | println!("{:?}", fila.peek()); 45 | } 46 | -------------------------------------------------------------------------------- /src/rust/singly_linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Node { 3 | data: T, 4 | next: Option>>, 5 | } 6 | 7 | #[derive(Debug)] 8 | struct LinkedList { 9 | head: Option>>, 10 | size: usize, 11 | } 12 | 13 | impl LinkedList { 14 | pub fn new() -> Self { 15 | LinkedList { 16 | head: None, 17 | size: 0, 18 | } 19 | } 20 | 21 | pub fn len(&self) -> usize { 22 | self.size 23 | } 24 | 25 | pub fn push(&mut self, data: T) { 26 | self.head = Some(Box::new(Node { 27 | data: data, 28 | next: self.head.take(), 29 | })); 30 | self.size += 1; 31 | } 32 | 33 | pub fn pop(&mut self) -> Option { 34 | self.head.take().map(|h| { 35 | self.head = h.next; 36 | self.size -= 1; 37 | h.data 38 | }) 39 | } 40 | } 41 | 42 | fn main() { 43 | let mut linked_list: LinkedList = LinkedList::new(); 44 | linked_list.push(1); 45 | linked_list.push(2); 46 | linked_list.push(3); 47 | println!("{:#?}", linked_list); 48 | linked_list.pop(); 49 | println!("{:#?}", linked_list); 50 | println!("Linked List Length: {}", linked_list.len()); 51 | } 52 | -------------------------------------------------------------------------------- /src/rust/stack.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Pilha { 3 | pilha: Vec, 4 | } 5 | 6 | impl Pilha { 7 | fn new() -> Self { 8 | Pilha { pilha: Vec::new() } 9 | } 10 | 11 | fn length(&self) -> usize { 12 | self.pilha.len() 13 | } 14 | 15 | fn push(&mut self, item: T) { 16 | self.pilha.push(item) 17 | } 18 | 19 | fn pop(&mut self) -> Option { 20 | self.pilha.pop() 21 | } 22 | 23 | fn is_empty(&self) -> bool { 24 | self.pilha.is_empty() 25 | } 26 | 27 | fn peek(&self) -> Option<&T> { 28 | self.pilha.first() 29 | } 30 | } 31 | 32 | fn main() { 33 | let mut pilha: Pilha = Pilha::::new(); 34 | pilha.push(1); 35 | pilha.push(2); 36 | println!("{:?}", pilha); 37 | pilha.pop(); 38 | println!("{:?}", pilha); 39 | println!( 40 | "length: {:?}, is empty? {:?}", 41 | pilha.length(), 42 | pilha.is_empty() 43 | ); 44 | pilha.push(3); 45 | println!("{:?}", pilha.peek()); 46 | } 47 | -------------------------------------------------------------------------------- /src/rust/tower_of_hanoi.rs: -------------------------------------------------------------------------------- 1 | fn torre_hanoi(pin0: i32, pin2: i32, pin1: i32, num: i32) { 2 | if num == 1 { 3 | println!("Move from {} to {}", pin0, pin2) 4 | } else { 5 | torre_hanoi(pin0, pin1, pin2, num - 1); 6 | torre_hanoi(pin0, pin2, pin1, 1); 7 | torre_hanoi(pin1, pin2, pin0, num - 1); 8 | } 9 | } 10 | fn main() { 11 | torre_hanoi(0, 2, 1, 3); 12 | } 13 | -------------------------------------------------------------------------------- /src/rust/two_sum.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | fn existe_soma(lista: &[i32], x: i32) -> bool { 3 | let mut valores = HashMap::new(); 4 | for (indice, valor) in lista.iter().enumerate() { 5 | valores.insert(valor, indice); 6 | let diff = x - valor; 7 | if valores.contains_key(&diff) { 8 | if valores[&diff] != indice { 9 | return true; 10 | } 11 | } 12 | } 13 | return false; 14 | } 15 | 16 | fn main() { 17 | let lista = vec![1, 2, 3, 4, 5, 6, 7, 8]; 18 | println!("{}", existe_soma(&lista, 3)); 19 | } 20 | 21 | #[cfg(test)] 22 | mod test { 23 | use super::*; 24 | #[test] 25 | fn t_exite_soma() { 26 | let lista = vec![1, 2, 3, 4, 5, 6, 7, 8]; 27 | 28 | assert_eq!(existe_soma(&lista, 3), true); 29 | assert_eq!(existe_soma(&lista, 5), true); 30 | assert_eq!(existe_soma(&lista, 7), true); 31 | assert_eq!(existe_soma(&lista, 15), true); 32 | 33 | assert_eq!(existe_soma(&lista, 1), false); 34 | assert_eq!(existe_soma(&lista, 2), false); 35 | assert_eq!(existe_soma(&lista, 16), false); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/scala/BinarySearch.scala: -------------------------------------------------------------------------------- 1 | import scala.annotation.tailrec 2 | 3 | def binarySearch(data: Seq[Int], target: Int): Option[Int] = { 4 | 5 | @tailrec 6 | def search(left: Int, right: Int): Option[Int] = { 7 | if (left > right) { 8 | None 9 | } else { 10 | val middle: Int = (left + right) / 2 11 | if (data(middle) == target) Some(middle) 12 | else if (data(middle) < target) search(middle + 1, right) 13 | else search(left, middle - 1) 14 | } 15 | } 16 | 17 | search(0, data.size) 18 | } 19 | 20 | object Main extends App { 21 | val data: Seq[Int] = Seq(0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12) 22 | val value: Int = 11 23 | println( 24 | s"Value '$value' found in position '${binarySearch(data, value).get}'" 25 | ) 26 | } 27 | -------------------------------------------------------------------------------- /src/scala/Bogosort.scala: -------------------------------------------------------------------------------- 1 | import scala.annotation.tailrec 2 | import scala.util.Random 3 | 4 | @tailrec 5 | def isSorted(data: Seq[Int]): Boolean = { 6 | if (data.size < 2) true 7 | else if (data(0) > data(1)) false 8 | else isSorted(data.tail) 9 | } 10 | 11 | @tailrec 12 | def bogosort(data: Seq[Int]): Seq[Int] = { 13 | val result: Seq[Int] = Random.shuffle(data) 14 | if (isSorted(result)) result 15 | else bogosort(data) 16 | } 17 | 18 | object Main extends App { 19 | val data: Seq[Int] = Seq.fill(10)(Random.nextInt(10)) 20 | println(s"Unsorted data: $data") 21 | println(s"Sorted data: ${bogosort(data)}") 22 | } 23 | -------------------------------------------------------------------------------- /src/scala/BubbleSort.scala: -------------------------------------------------------------------------------- 1 | def bubble_sort(data: List[Int]): List[Int] = { 2 | var sortedData: List[Int] = data 3 | var swapped: Boolean = true 4 | 5 | while (swapped == true) { 6 | swapped = false 7 | for (i <- 0 to sortedData.length - 2) { 8 | if (sortedData(i) > sortedData(i + 1)) { 9 | sortedData = 10 | sortedData.updated(i, sortedData(i + 1)).updated(i + 1, sortedData(i)) 11 | swapped = true 12 | } 13 | } 14 | } 15 | sortedData 16 | } 17 | 18 | object Main extends App { 19 | var data: List[Int] = List(9, 2, 8, 1, 5, 7, 3, 6, 4) 20 | println(data) 21 | var sortedData: List[Int] = bubble_sort(data) 22 | println(sortedData) 23 | } 24 | -------------------------------------------------------------------------------- /src/scala/CalculatePi.scala: -------------------------------------------------------------------------------- 1 | def calculatePi(n: Int): Double = { 2 | (0 until n).foldLeft(0.0)((pi, index) => { 3 | val operation: Double = if (index % 2 == 0) 1.0 else -1.0 4 | val denominator: Double = 1.0 + (index * 2.0) 5 | pi + (operation * (4.0 / denominator)) 6 | }) 7 | } 8 | 9 | object Main extends App { 10 | val nTerms: Seq[Int] = Seq(10, 1000, 100000, 10000000) 11 | nTerms.foreach(n => println(s"Pi ($n): ${calculatePi(n)}")) 12 | } 13 | -------------------------------------------------------------------------------- /src/scala/Exponentiation.scala: -------------------------------------------------------------------------------- 1 | def exponentiation(base: Int, exponent: Int): Int = { 2 | (1 to exponent) 3 | .map(_ => base) 4 | .reduce(_ * _) 5 | } 6 | 7 | object Main extends App { 8 | println("5 ^ 3 = " + exponentiation(5, 3)) 9 | } 10 | -------------------------------------------------------------------------------- /src/scala/ExponentiationRecursive.scala: -------------------------------------------------------------------------------- 1 | import scala.annotation.tailrec 2 | 3 | @tailrec 4 | def exponentiationRecursive( 5 | base: Int, 6 | exponent: Int, 7 | accumulator: Int = 1 8 | ): Int = exponent match { 9 | case 0 => accumulator 10 | case _ => exponentiationRecursive(base, exponent - 1, accumulator * base) 11 | } 12 | 13 | object Main extends App { 14 | println("5 ^ 3 = " + exponentiationRecursive(5, 3)) 15 | } 16 | -------------------------------------------------------------------------------- /src/scala/Factorial.scala: -------------------------------------------------------------------------------- 1 | def factorial(n: Long): Long = (1L to n).product 2 | 3 | object Main extends App { 4 | val data: Map[Long, Long] = Map( 5 | 0L -> 1L, 6 | 1L -> 1L, 7 | 5L -> 120L, 8 | 20L -> 2432902008176640000L 9 | ) 10 | data.foreach { (key, value) => 11 | val result: Long = factorial(key) 12 | assert(result == value) 13 | println(s"Factorial($key): $result") 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/scala/FactorialRecursive.scala: -------------------------------------------------------------------------------- 1 | def factorial(n: Long): Long = { 2 | n match { 3 | case 0L | 1L => 1L 4 | case _ => n * factorial(n - 1L) 5 | } 6 | } 7 | 8 | object Main extends App { 9 | val data: Map[Long, Long] = Map( 10 | 0L -> 1L, 11 | 1L -> 1L, 12 | 5L -> 120L, 13 | 20L -> 2432902008176640000L 14 | ) 15 | data.foreach { (key, value) => 16 | val result: Long = factorial(key) 17 | assert(result == value) 18 | println(s"Factorial($key): $result") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/scala/FibonacciIterative.scala: -------------------------------------------------------------------------------- 1 | object FibonacciIterative { 2 | def fibonacci(n: Int): BigInt = { 3 | if (n <= 1) { 4 | return n 5 | } 6 | 7 | var a = BigInt(0) 8 | var b = BigInt(1) 9 | 10 | var result = BigInt(0) 11 | 12 | for (i <- 2 to n) { 13 | result = a + b 14 | a = b 15 | b = result 16 | } 17 | 18 | result 19 | } 20 | 21 | def main(args: Array[String]): Unit = { 22 | val index = 15 23 | println(s"Fibonacci (iterative) of $index is: ${fibonacci(index)}") 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/scala/FibonacciMemoization.scala: -------------------------------------------------------------------------------- 1 | object FibonacciMemoization { 2 | import scala.collection.mutable.Map 3 | 4 | val memo: Map[Int, BigInt] = Map() 5 | 6 | def fibonacci(n: Int): BigInt = { 7 | if (n <= 1) { 8 | return n 9 | } 10 | 11 | memo.getOrElseUpdate(n, fibonacci(n - 1) + fibonacci(n - 2)) 12 | } 13 | 14 | def main(args: Array[String]): Unit = { 15 | val index = 15 16 | println(s"Fibonacci (memoization) of $index is: ${fibonacci(index)}") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/scala/FibonacciRecursive.scala: -------------------------------------------------------------------------------- 1 | object FibonacciRecursive { 2 | def fibonacci(n: Int): BigInt = { 3 | if (n <= 1) { 4 | return n 5 | } 6 | 7 | fibonacci(n - 1) + fibonacci(n - 2) 8 | } 9 | 10 | def main(args: Array[String]): Unit = { 11 | val index = 15 12 | println(s"Fibonacci (recursive) of $index is: ${fibonacci(index)}") 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/scala/LinearSearch.scala: -------------------------------------------------------------------------------- 1 | def search(data: List[Int], value: Int): Int = { 2 | data.zipWithIndex 3 | .find((tupleValue, _) => tupleValue == value) 4 | .map((_, index) => index) 5 | .getOrElse(-1) 6 | } 7 | 8 | object Main extends App { 9 | val data: List[Int] = List(9, 2, 6, 1, 3, 5, 4, 7, 8) 10 | val values: List[Int] = List(9, 3, 8, 246) 11 | val results: List[Int] = values.map(v => search(data, v)) 12 | 13 | values 14 | .zip(results) 15 | .foreach((value, result) => println(s"Value: $value -> Index: $result")) 16 | } 17 | -------------------------------------------------------------------------------- /src/scala/LinearSearchRecursive.scala: -------------------------------------------------------------------------------- 1 | import scala.annotation.tailrec 2 | 3 | @tailrec 4 | def search(data: List[Int], value: Int, index: Int = 0): Int = { 5 | if (index >= data.size) -1 6 | else if (data(index) == value) index 7 | else search(data, value, index + 1) 8 | } 9 | 10 | object Main extends App { 11 | val data: List[Int] = List(9, 2, 6, 1, 3, 5, 4, 7, 8) 12 | val values: List[Int] = List(9, 3, 8, 246) 13 | val results: List[Int] = values.map(v => search(data, v)) 14 | 15 | values 16 | .zip(results) 17 | .foreach((value, result) => println(s"Value: $value -> Index: $result")) 18 | } 19 | -------------------------------------------------------------------------------- /src/scala/MaxRecursive.scala: -------------------------------------------------------------------------------- 1 | def recursiveMax(data: List[Int], max: Int, index: Int): Int = { 2 | var maximum = max 3 | if (data(index) > max) { 4 | maximum = data(index) 5 | } 6 | if (index < data.length - 1) { 7 | maximum = recursiveMax(data, maximum, index + 1) 8 | } 9 | maximum 10 | } 11 | 12 | def recursiveMax(data: List[Int]): Int = recursiveMax(data, data(0), 0) 13 | 14 | object Main extends App { 15 | val data: List[Int] = List(1, 5, 2, 7, 3, 9, 4, 6) 16 | val max: Int = recursiveMax(data) 17 | println(s"$data\nMax: $max") 18 | } 19 | -------------------------------------------------------------------------------- /src/scala/MinMaxIterative.scala: -------------------------------------------------------------------------------- 1 | def minMax(data: List[Int]): (Int, Int) = { 2 | var min: Int = data(0) 3 | var max: Int = data(0) 4 | for (value <- data) { 5 | if (value < min) { 6 | min = value 7 | } 8 | if (value > max) { 9 | max = value 10 | } 11 | } 12 | (min, max) 13 | } 14 | 15 | object Main extends App { 16 | val data: List[Int] = List(4, 6, 2, 9, 3, 8, 1, 7, 5) 17 | val (min, max): (Int, Int) = minMax(data) 18 | println(s"$data\nMin: $min\nMax: $max") 19 | } 20 | -------------------------------------------------------------------------------- /src/scala/MinMaxRecursive.scala: -------------------------------------------------------------------------------- 1 | def minMax( 2 | data: List[Int], 3 | minimum: Int, 4 | maximum: Int, 5 | index: Int 6 | ): (Int, Int) = { 7 | var min: Int = minimum 8 | var max: Int = maximum 9 | 10 | if (data(index) < min) { 11 | min = data(index) 12 | } 13 | if (data(index) > max) { 14 | max = data(index) 15 | } 16 | 17 | if (index < data.length - 1) { 18 | minMax(data, min, max, index + 1) 19 | } else { 20 | (min, max) 21 | } 22 | } 23 | 24 | def minMax(data: List[Int]): (Int, Int) = minMax(data, data(0), data(0), 0) 25 | 26 | object Main extends App { 27 | val data: List[Int] = List(4, 6, 2, 9, 3, 8, 1, 7, 5) 28 | val (min, max): (Int, Int) = minMax(data) 29 | println(s"$data\nMin: $min\nMax: $max") 30 | } 31 | -------------------------------------------------------------------------------- /src/scala/Palindrome.scala: -------------------------------------------------------------------------------- 1 | def isPalindrome(content: String): Boolean = { 2 | val sanitizedContent: String = content.replaceAll("\\W", "").toLowerCase 3 | sanitizedContent == sanitizedContent.reverse 4 | } 5 | 6 | object Main extends App { 7 | val data: Seq[String] = Seq( 8 | "", 9 | "a", 10 | "abba", 11 | "No lemon, no melon", 12 | "Was it a palindrome?" 13 | ) 14 | data.foreach(x => println(s"'$x' is a palindrome? ${isPalindrome(x)}")) 15 | } 16 | -------------------------------------------------------------------------------- /src/scala/Queue.scala: -------------------------------------------------------------------------------- 1 | // Note that this is just for study purposes since Scala provides a built-in Queue collection: 2 | // https://www.scala-lang.org/api/current/scala/collection/mutable/Queue.html 3 | 4 | import scala.collection.mutable.ListBuffer 5 | 6 | class Queue[Any] { 7 | private var queue: ListBuffer[Any] = ListBuffer() 8 | 9 | def enqueue(value: Any): Unit = queue += value 10 | 11 | def dequeue(): Any = queue.remove(0) 12 | 13 | override def toString(): String = queue.mkString(", ") 14 | } 15 | 16 | object Main extends App { 17 | val queue = new Queue[Int] 18 | 19 | println("Queuing 3 values...") 20 | queue.enqueue(1) 21 | queue.enqueue(2) 22 | queue.enqueue(3) 23 | println(queue) 24 | 25 | println("Dequeuing 1 value...") 26 | queue.dequeue() 27 | println(queue) 28 | } 29 | -------------------------------------------------------------------------------- /src/scala/Stack.scala: -------------------------------------------------------------------------------- 1 | // Note that this is just for study purposes since Scala provides a built-in Stack collection: 2 | // https://www.scala-lang.org/api/current/scala/collection/mutable/Stack.html 3 | 4 | import scala.collection.mutable.ListBuffer 5 | 6 | class Stack[Any] { 7 | private var stack: ListBuffer[Any] = ListBuffer() 8 | 9 | def push(value: Any): Unit = stack += value 10 | 11 | def pop(): Any = stack.remove(stack.length - 1) 12 | 13 | override def toString(): String = stack.mkString(", ") 14 | } 15 | 16 | object Main extends App { 17 | val stack = new Stack[Int] 18 | 19 | println("Pushing 3 values...") 20 | stack.push(1) 21 | stack.push(2) 22 | stack.push(3) 23 | println(stack) 24 | 25 | println("Poping 1 value...") 26 | stack.pop() 27 | println(stack) 28 | } 29 | -------------------------------------------------------------------------------- /src/scala/TowerOfHanoi.scala: -------------------------------------------------------------------------------- 1 | def hanoi(pin0: Int, pin2: Int, pin1: Int, disks: Int): Unit = { 2 | if (disks == 1) { 3 | println(s"Move from $pin0 to $pin2") 4 | } else { 5 | hanoi(pin0, pin1, pin2, disks - 1) 6 | hanoi(pin0, pin2, pin1, 1) 7 | hanoi(pin1, pin2, pin0, disks - 1) 8 | } 9 | } 10 | 11 | object Main extends App { 12 | hanoi(0, 2, 1, 3) 13 | } 14 | -------------------------------------------------------------------------------- /src/swift/binarySearch.swift: -------------------------------------------------------------------------------- 1 | func binarySearch(array: [Int], searchedElement: Int) -> Int { 2 | var firstIndex: Int = 0 3 | var lastIndex: Int = array.count - 1 4 | var middleIndex: Int; 5 | while firstIndex <= lastIndex { 6 | middleIndex = (firstIndex + lastIndex) / 2 7 | if (searchedElement == array[middleIndex]) { 8 | return middleIndex 9 | } 10 | searchedElement < array[middleIndex] ? (lastIndex = middleIndex - 1) : (firstIndex = middleIndex + 1) 11 | } 12 | return -1 // If the searched element isn't in the array 13 | } 14 | 15 | func main() { 16 | let sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9] 17 | let elementToSearch = 5 18 | 19 | let result = binarySearch(array: sortedArray, searchedElement: elementToSearch) 20 | 21 | if result != -1 { 22 | print("Element \(elementToSearch) found at index \(result)") 23 | } else { 24 | print("Element \(elementToSearch) not found in the array.") 25 | } 26 | } 27 | 28 | main() 29 | -------------------------------------------------------------------------------- /src/swift/calculatePi.swift: -------------------------------------------------------------------------------- 1 | func calculatePi(_ number: Int) -> Float { 2 | var denominator: Float = 1 3 | var operation: Float = 1 4 | var pi: Float = 0 5 | 6 | for _ in 0..(base: Number, power: Int) -> Number { 2 | var result = base 3 | if power == 0 { 4 | return 1 5 | } 6 | for _ in 0..(base: Number, power: Int) -> Number { 2 | if (power == 0) { 3 | return 1 4 | } 5 | return base * recursiveExponentiation(base: base, power: power - 1) 6 | } 7 | 8 | func main() { 9 | print(recursiveExponentiation(base: 5, power: 3)) 10 | print(recursiveExponentiation(base: 2.5, power: 4)) 11 | print(recursiveExponentiation(base: 50, power: 0)) 12 | } 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /src/swift/factorial.swift: -------------------------------------------------------------------------------- 1 | func factorial(_ number: Int) -> Int { 2 | var result: Int = 1 3 | for index in (1...number).reversed() { 4 | result = result * index 5 | } 6 | return result 7 | } 8 | 9 | print(factorial(5)) 10 | 11 | -------------------------------------------------------------------------------- /src/swift/factorialRecursive.swift: -------------------------------------------------------------------------------- 1 | func factorial(_ number: Int) -> Int { 2 | if number <= 1 { return 1 } 3 | return number * factorial(number - 1) 4 | } 5 | 6 | print(factorial(7)) 7 | -------------------------------------------------------------------------------- /src/swift/fibonacciIterative.swift: -------------------------------------------------------------------------------- 1 | // Function to calculate Fibonacci numbers iteratively 2 | func fibonacci(_ number: Int) -> Int { 3 | if number <= 1 { 4 | return number 5 | } else { 6 | var currentNumber: Int = 1 7 | var nextNumber: Int = 0 8 | 9 | // Iterate from 0 to 'number - 1' 10 | for _ in 0.. Int { 6 | if n <= 1 { 7 | return n 8 | } 9 | 10 | // Check if the result is already memoized 11 | if let cachedResult = memo[n] { 12 | return cachedResult 13 | } 14 | 15 | // Calculate Fibonacci recursively and store the result in memoization 16 | let result = fibonacci(n - 1) + fibonacci(n - 2) 17 | memo[n] = result 18 | 19 | return result 20 | } 21 | 22 | let index: Int = 15 23 | print("Fibonacci (memoization):", fibonacci(index)) 24 | -------------------------------------------------------------------------------- /src/swift/fibonacciRecursive.swift: -------------------------------------------------------------------------------- 1 | // Function to calculate Fibonacci numbers recursively 2 | func fibonacci(_ number: Int) -> Int { 3 | if number <= 1 { 4 | return number 5 | } else { 6 | // Recursively calculate Fibonacci using the formula F(n) = F(n-1) + F(n-2) 7 | return fibonacci(number - 1) + fibonacci(number - 2) 8 | } 9 | } 10 | 11 | let index: Int = 15 12 | print("Fibonacci (recursive):", fibonacci(index)) 13 | -------------------------------------------------------------------------------- /src/swift/insertionSort.swift: -------------------------------------------------------------------------------- 1 | func insertionSort(_ array: [Int]) -> [Int] { 2 | var newArray: [Int] = array 3 | for i in 1..= 0, newArray[supp] > key { 7 | newArray[supp + 1] = newArray[supp] 8 | supp -= 1 9 | } 10 | newArray[supp + 1] = key 11 | } 12 | return newArray 13 | } 14 | 15 | let unsortedArray: [Int] = [92, 23, 42, 12, 54, 65, 1, 2, 8, 9, 31, 99] 16 | print(insertionSort(unsortedArray)) 17 | 18 | -------------------------------------------------------------------------------- /src/swift/linearSearch.swift: -------------------------------------------------------------------------------- 1 | func sequentialSearch(array: [Int], searchedElement: Int) -> Int { 2 | for index in 0.. Bool { 4 | let lowercasedString: String = string.lowercased().replacingOccurrences(of: " ", with: "") 5 | let reversedString = String(lowercasedString.reversed()) 6 | return (lowercasedString == reversedString) 7 | } 8 | 9 | print(isPalindrome("")) 10 | print(isPalindrome("a")) 11 | print(isPalindrome("abba")) 12 | print(isPalindrome("abbas")) 13 | print(isPalindrome("tattarrattat")) 14 | print(isPalindrome("Was it a palindrome?")) 15 | print(isPalindrome("No lemon, no melon")) 16 | 17 | -------------------------------------------------------------------------------- /src/swift/queue.swift: -------------------------------------------------------------------------------- 1 | class Queue { 2 | var queue: [Int] = [] 3 | 4 | func enqueue(_ value: Int) { 5 | self.queue.append(value) 6 | } 7 | 8 | func dequeue() { 9 | self.queue.removeFirst() 10 | } 11 | 12 | func show() { 13 | print(self.queue) 14 | } 15 | 16 | func clear() { 17 | self.queue = [] 18 | } 19 | } 20 | 21 | let queue = Queue() 22 | 23 | for n in 0...10 { queue.enqueue(n) } 24 | queue.show() 25 | queue.dequeue() 26 | queue.show() 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/swift/stack.swift: -------------------------------------------------------------------------------- 1 | class Stack { 2 | var stack: [Int] = [] 3 | 4 | func push(_ value: Int) { 5 | stack.append(value) 6 | } 7 | 8 | func pop() { 9 | stack.removeLast() 10 | } 11 | 12 | func show() { 13 | print(stack) 14 | } 15 | 16 | func clean() { 17 | stack = [] 18 | } 19 | } 20 | 21 | let stack = Stack() 22 | 23 | stack.push(1) 24 | stack.push(2) 25 | stack.push(3) 26 | stack.push(4) 27 | 28 | stack.show() 29 | 30 | stack.pop() 31 | stack.pop() 32 | stack.show() 33 | 34 | -------------------------------------------------------------------------------- /src/swift/towerOfHanoi.swift: -------------------------------------------------------------------------------- 1 | func hanoi(_ p1: Int, _ p2: Int, _ p3: Int, disks: Int) { 2 | if disks == 1 { 3 | print("Move de \(p1) para \(p2)") 4 | } else { 5 | hanoi(p1, p3, p2, disks: disks - 1) 6 | hanoi(p1, p2, p3, disks: 1) 7 | hanoi(p3, p2, p1, disks: disks - 1) 8 | } 9 | } 10 | 11 | hanoi(0, 2, 1, disks: 3) 12 | 13 | --------------------------------------------------------------------------------