├── .github ├── pull_request_template.md └── workflows │ ├── dart_test_analyze_format.yml │ └── update_directory_md.yml ├── .gitignore ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── array ├── car_pool.dart ├── move_zeroes.dart ├── pivot_index.dart ├── sorted_squared_array.dart ├── two_sum.dart └── validate_subsequence.dart ├── backtracking ├── n-queen.dart └── open_knight_tour.dart ├── conversions ├── Decimal_To_Any.dart ├── Decimal_To_Binary.dart ├── Decimal_to_Hexadecimal.dart ├── Decimal_to_Octal.dart ├── Integer_To_Roman.dart ├── binary_to_decimal.dart ├── binary_to_hexadecimal.dart ├── binary_to_octal.dart ├── hexadecimal_to_binary.dart ├── hexadecimal_to_decimal.dart ├── hexadecimal_to_octal.dart ├── octal_to_binary.dart ├── octal_to_decimal.dart ├── octal_to_hexadecimal.dart └── roman_to_integer.dart ├── dart_test.yaml ├── data_structures ├── HashMap │ ├── Hashing.dart │ └── hashmap_implementation ├── Heap │ └── Binary_Heap │ │ ├── Max_heap.dart │ │ ├── Min_Heap.dart │ │ └── min_heap_two.dart ├── Queue │ ├── Circular_Queue.dart │ ├── List_Queue.dart │ └── Priority_Queue.dart ├── Stack │ ├── Array_Stack.dart │ ├── Linked_List_Stack.dart │ └── balanced_brackets.dart ├── binary_tree │ ├── basic_binary_tree.dart │ └── binary_tree_traversal.dart └── linked_list │ ├── cycle_in_linked_list.dart │ ├── linked_list.dart │ └── merge_sorted_list.dart ├── dynamic_programming ├── 01knapsack_recursive.dart ├── coin_change.dart ├── kadanes_algorithm.dart ├── longest_common_subsequence.dart ├── longest_common_substring.dart └── min_number_of_jumps.dart ├── graphs ├── area_of_island.dart ├── breadth_first_search.dart ├── depth_first_search.dart └── nearest_neighbour_algorithm.dart ├── maths ├── Armstrong_number.dart ├── Kynea_numbers.dart ├── LinearDiophantineEqn.dart ├── Ugly_numbers.dart ├── abs.dart ├── abs_max.dart ├── abs_min.dart ├── amicable_numbers.dart ├── average.dart ├── eulers_totient.dart ├── factorial.dart ├── factorial_approximation.dart ├── factorial_recursion.dart ├── factors.dart ├── fermats_little_theorem.dart ├── fibonacci_dynamic_programming.dart ├── fibonacci_recursion.dart ├── find_max.dart ├── find_max_recursion.dart ├── find_min.dart ├── find_min_recursion.dart ├── hamming_distance.dart ├── lu_decomposition.dart ├── newton_method.dart ├── palindrome_number.dart ├── palindrome_string.dart ├── palindrome_string_recursion.dart ├── perfect_number.dart ├── pow.dart ├── power_of_two.dart ├── prime_check.dart ├── relu_function.dart ├── shreedharacharya.dart ├── sieve_of_eratosthenes.dart ├── sigmoid.dart ├── simpson_rule.dart ├── sphenic_number.dart └── symmetric_derivative.dart ├── other ├── FizzBuzz.dart ├── LCM.dart ├── Moore_voting_algorithm.dart ├── N_bonacci.dart ├── ackermann.dart ├── binpow.dart ├── chinese_remainder_theorem.dart ├── collatz.dart ├── fisher_yates_shuffle.dart ├── gcd.dart ├── haversine_formula.dart ├── heaps_algorithm.dart ├── kadaneAlgo.dart ├── magic_number.dart ├── swap_all_odd_and_even_bits.dart └── tower_of_hanoi.dart ├── project_euler ├── problem_1 │ └── sol1.dart ├── problem_10 │ └── sol10.dart ├── problem_12 │ └── sol12.dart ├── problem_13 │ └── sol13.dart ├── problem_17 │ └── sol17.dart ├── problem_2 │ └── sol2.dart ├── problem_20 │ └── sol20.dart ├── problem_3 │ └── sol3.dart ├── problem_4 │ └── sol4.dart ├── problem_5 │ └── sol5.dart ├── problem_6 │ └── sol6.dart ├── problem_7 │ └── sol7.dart ├── problem_8 │ └── sol8.dart └── problem_9 │ └── sol9.dart ├── pubspec.yaml ├── search ├── binary_Search.dart ├── binary_search_recursion.dart ├── fibonacci_Search.dart ├── interpolation_Search.dart ├── jump_Search.dart ├── linear_Search.dart ├── peak_element.dart └── ternary_Search.dart ├── sort ├── bubble_Sort.dart ├── cocktail_sort.dart ├── comb_sort.dart ├── count_sort.dart ├── gnome_Sort.dart ├── heap_Sort.dart ├── insert_Sort.dart ├── merge_sort.dart ├── pigeonhole_sort.dart ├── quick_Sort.dart ├── radix_sort.dart ├── select_Sort.dart ├── shell_Sort.dart └── tim_Sort.dart ├── strings ├── isomorphic_strings.dart ├── knuth_morris_prat.dart ├── remove duplicates.dart ├── reverse_string.dart └── reverse_words_of_string.dart ├── tests └── README.md └── trees └── path_sum.dart /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Welcome to Dart community 2 | 3 | ### **Describe your change:** 4 | 5 | * [ ] Add an algorithm? 6 | * [ ] Fix a bug or typo in an existing algorithm? 7 | * [ ] Documentation change? 8 | * [ ] Add/Update/Fix test cases. 9 | 10 | 11 | ### **Checklist:** 12 | * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Dart/blob/master/CONTRIBUTING.md). 13 | * [ ] This pull request is all my own work -- I have not plagiarized. 14 | * [ ] I know that pull requests will not be merged if they fail the automated tests. 15 | * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. 16 | * [ ] All new Dart files are placed inside an existing directory. 17 | * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. 18 | * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. 19 | -------------------------------------------------------------------------------- /.github/workflows/dart_test_analyze_format.yml: -------------------------------------------------------------------------------- 1 | name: dart_test_analyze_format 2 | on: [push, pull_request] 3 | jobs: 4 | dart_test_analyze_format: 5 | runs-on: ubuntu-latest 6 | container: 7 | image: google/dart 8 | steps: 9 | - uses: actions/checkout@v2 10 | # - run: (echo 'deb http://deb.debian.org/debian buster main contrib non-free') > /etc/apt/sources.list.d/buster.list 11 | - run: dart pub get 12 | - run: dart format --set-exit-if-changed . 13 | - run: dart test --coverage . 14 | - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov 15 | - run: dart analyze 16 | -------------------------------------------------------------------------------- /.github/workflows/update_directory_md.yml: -------------------------------------------------------------------------------- 1 | name: update_directory_md 2 | on: [push] 3 | jobs: 4 | update_directory_md: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v1 # v1, NOT v2 8 | - uses: actions/setup-python@v2 9 | - name: update_directory_md 10 | shell: python 11 | run: | 12 | import os 13 | from typing import Iterator 14 | URL_BASE = "https://github.com/TheAlgorithms/Dart/blob/master" 15 | g_output = [] 16 | 17 | def good_filepaths(top_dir: str = ".") -> Iterator[str]: 18 | for dirpath, dirnames, filenames in os.walk(top_dir): 19 | dirnames[:] = [d for d in dirnames if d[0] not in "._"] 20 | for filename in filenames: 21 | if os.path.splitext(filename)[1].lower() == ".dart": 22 | yield os.path.join(dirpath, filename).lstrip("./") 23 | 24 | def md_prefix(i): 25 | return f"{i * ' '}*" if i else "\n##" 26 | 27 | def print_path(old_path: str, new_path: str) -> str: 28 | global g_output 29 | old_parts = old_path.split(os.sep) 30 | for i, new_part in enumerate(new_path.split(os.sep)): 31 | if i + 1 > len(old_parts) or old_parts[i] != new_part: 32 | if new_part: 33 | g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") 34 | return new_path 35 | 36 | def build_directory_md(top_dir: str = ".") -> str: 37 | global g_output 38 | old_path = "" 39 | for filepath in sorted(good_filepaths(), key=str.lower): 40 | filepath, filename = os.path.split(filepath) 41 | if filepath != old_path: 42 | old_path = print_path(old_path, filepath) 43 | indent = (filepath.count(os.sep) + 1) if filepath else 0 44 | url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") 45 | filename = os.path.splitext(filename.replace("_", " ").title())[0] 46 | g_output.append(f"{md_prefix(indent)} [{filename}]({url})") 47 | return "\n".join(g_output) 48 | with open("DIRECTORY.md", "w") as out_file: 49 | out_file.write(build_directory_md(".") + "\n") 50 | - name: Update DIRECTORY.md 51 | run: | 52 | cat DIRECTORY.md 53 | git config --global user.name github-actions 54 | git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' 55 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 56 | git add DIRECTORY.md 57 | git commit -am "updating DIRECTORY.md" || true 58 | git push --force origin HEAD:$GITHUB_REF || true 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://www.dartlang.org/guides/libraries/private-files 2 | 3 | # Files and directories created by pub 4 | .dart_tool/ 5 | .packages 6 | build/ 7 | # If you're building an application, you may want to check-in your pubspec.lock 8 | pubspec.lock 9 | 10 | # Directory created by dartdoc 11 | # If you don't generate documentation locally you can remove this line. 12 | doc/api/ 13 | 14 | # Avoid committing generated Javascript files: 15 | *.dart.js 16 | *.info.json # Produced by the --dump-info flag. 17 | *.js # When generated by dart2js. Don't specify *.js if your 18 | # project includes source files written in JavaScript. 19 | *.js_ 20 | *.js.deps 21 | *.js.map 22 | *.json 23 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing guidelines 2 | 3 | Welcome to [TheAlgorithms/Dart](https://github.com/TheAlgorithms/Dart)! 4 | 5 | ## Contributing 6 | * Fork this [repo](https://github.com/TheAlgorithms/Dart). 7 | * If Already Forked, Then make sure to sync your fork. 8 | * Make some changes and pull a request 9 | * [Automated tests are run](https://github.com/TheAlgorithms/Dart/actions) on all pull requests 10 | * `dart analyze` is mandatory 11 | * `dart format` is mandatory 12 | * `dart test` is recommended 13 | 14 | ## New File Name guidelines 15 | * Use lowercase words with "_" as separator 16 | * For example: 17 | ``` 18 | MyNewAlgorithm.dart is incorrect 19 | my_new_algorithm.dart is correct format 20 | ``` 21 | 22 | Writer [@StepfenShawn](https://github.com/StepfenShawn), Feb 2020. 23 | Updated [@akashgk](https://github.com/akashgk), Oct 2022. 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 The Algorithms 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 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | analyzer: 2 | exclude: 3 | - maths/fermats_little_theorem.dart 4 | -------------------------------------------------------------------------------- /array/car_pool.dart: -------------------------------------------------------------------------------- 1 | // Leetcode problem: https://leetcode.com/problems/car-pooling/ 2 | // Solution Explanation: https://leetcode.com/problems/car-pooling/solutions/3252690/dart-time-o-n-o-1-space-solution/ 3 | 4 | import 'dart:math'; 5 | import "package:test/test.dart"; 6 | 7 | bool carPooling(List> trips, int capacity) { 8 | List passengerTimelineCount = List.filled(1001, 0); 9 | int lastPoint = 0; 10 | 11 | for (List trip in trips) { 12 | int count = trip[0]; 13 | int from = trip[1]; 14 | int to = trip[2]; 15 | if (count > capacity) { 16 | return false; 17 | } 18 | 19 | lastPoint = max(lastPoint, to); 20 | passengerTimelineCount[from] += count; 21 | passengerTimelineCount[to] -= count; 22 | } 23 | 24 | for (int i = 1; i < lastPoint; ++i) { 25 | passengerTimelineCount[i] += passengerTimelineCount[i - 1]; 26 | if (passengerTimelineCount[i] > capacity) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | 33 | void main() { 34 | List> trips = [ 35 | [2, 1, 5], 36 | [3, 3, 7] 37 | ]; 38 | 39 | List> trips1 = [ 40 | [2, 1, 5], 41 | [3, 5, 7] 42 | ]; 43 | 44 | List> trips2 = [ 45 | [2, 2, 6], 46 | [2, 4, 7], 47 | [8, 6, 7] 48 | ]; 49 | 50 | List> trips3 = [ 51 | [7, 5, 6], 52 | [6, 7, 8], 53 | [10, 1, 6] 54 | ]; 55 | 56 | test('test case 1', () => expect(carPooling(trips, 4), false)); 57 | test('test case 2', () => expect(carPooling(trips, 5), true)); 58 | test('test case 3', () => expect(carPooling(trips1, 3), true)); 59 | test('test case 4', () => expect(carPooling(trips2, 11), true)); 60 | test('test case 5', () => expect(carPooling(trips3, 16), false)); 61 | } 62 | -------------------------------------------------------------------------------- /array/move_zeroes.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | List moveZeroes(List nums) { 4 | int lastNonZeroFoundAt = 0; 5 | 6 | for (int i = 0; i < nums.length; ++i) { 7 | if (nums[i] != 0) { 8 | nums[lastNonZeroFoundAt] = nums[i]; 9 | lastNonZeroFoundAt += 1; 10 | } 11 | } 12 | 13 | for (int i = lastNonZeroFoundAt; i < nums.length; ++i) { 14 | nums[i] = 0; 15 | } 16 | return nums; 17 | } 18 | 19 | void main() { 20 | test('test case 1', () { 21 | return expect(moveZeroes([1, 0, 2, 0, 0]), [1, 2, 0, 0, 0]); 22 | }); 23 | test('test case 2', () { 24 | return expect(moveZeroes([1, 2, 2, 3, 5]), [1, 2, 2, 3, 5]); 25 | }); 26 | test('test case 3', () { 27 | return expect(moveZeroes([0, 0, 0, 0, 0]), [0, 0, 0, 0, 0]); 28 | }); 29 | test('test case 4', () { 30 | return expect(moveZeroes([]), []); 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /array/pivot_index.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // Leetcode problem URL: https://leetcode.com/problems/find-pivot-index/ 4 | int sum(List numbers) { 5 | int sum = 0; 6 | for (int i = 0; i < numbers.length; i++) { 7 | sum += numbers[i]; 8 | } 9 | return sum; 10 | } 11 | 12 | int pivotIndex(List nums) { 13 | int leftSum = 0; 14 | int arraySum = sum(nums); 15 | 16 | for (int i = 0; i < nums.length; ++i) { 17 | if (leftSum == arraySum - leftSum - nums[i]) { 18 | return i; 19 | } 20 | leftSum += nums[i]; 21 | } 22 | 23 | return -1; 24 | } 25 | 26 | void main() { 27 | test('test case 1', () => expect(pivotIndex([1, 7, 3, 6, 5, 6]), 3)); 28 | test('test case 2', () => expect(pivotIndex([2, 1, -1]), 0)); 29 | test('test case 3', () => expect(pivotIndex([1, 2, 3]), -1)); 30 | } 31 | -------------------------------------------------------------------------------- /array/sorted_squared_array.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | List sortedSquaredArray(List array) { 4 | int start = 0; 5 | int end = array.length - 1; 6 | int sortedIndex = array.length - 1; 7 | List answer = List.filled(array.length, 0); 8 | 9 | while (end >= start) { 10 | if (array[start].abs() > array[end].abs()) { 11 | answer[sortedIndex] = array[start] * array[start]; 12 | start += 1; 13 | } else { 14 | answer[sortedIndex] = array[end] * array[end]; 15 | end -= 1; 16 | } 17 | sortedIndex -= 1; 18 | } 19 | 20 | return answer; 21 | } 22 | 23 | void main() { 24 | test('test case 1', () { 25 | expect(sortedSquaredArray([-1, -1, 2, 3, 3, 3, 4]), [1, 1, 4, 9, 9, 9, 16]); 26 | }); 27 | 28 | test('test case 2', () { 29 | expect(sortedSquaredArray([0]), [0]); 30 | }); 31 | 32 | test('test case 2', () { 33 | expect(sortedSquaredArray([-7, -6, -5, -4, -3, -2, -1]), 34 | [1, 4, 9, 16, 25, 36, 49]); 35 | }); 36 | 37 | test('test case 4', () { 38 | expect( 39 | sortedSquaredArray([1, 2, 3, 4, 5, 6, 7]), [1, 4, 9, 16, 25, 36, 49]); 40 | }); 41 | } 42 | -------------------------------------------------------------------------------- /array/two_sum.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | bool twoSum(List nums, int target) { 4 | Map seen = {}; 5 | for (int index = 0; index < nums.length; ++index) { 6 | int number = nums[index]; 7 | 8 | int complement = target - number; 9 | if (seen.containsKey(complement)) { 10 | return true; 11 | } else { 12 | seen[number] = index; 13 | } 14 | } 15 | return false; 16 | } 17 | 18 | void main() { 19 | test('test 1', () { 20 | expect(twoSum([1, 2, 3, 4], 7), isTrue); 21 | }); 22 | 23 | test('test 2', () { 24 | expect(twoSum([1, 2, 3, 4], 12), isFalse); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /array/validate_subsequence.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | bool checkIsSubSequence(List array, List sequence) { 4 | if (array.isEmpty) { 5 | return false; 6 | } 7 | 8 | if (sequence.isEmpty) { 9 | return true; 10 | } 11 | int arrayIndex = 0; 12 | int sequenceIndex = 0; 13 | 14 | while (sequenceIndex < sequence.length && arrayIndex < array.length) { 15 | if (sequence[sequenceIndex] == array[arrayIndex]) { 16 | sequenceIndex += 1; 17 | } 18 | arrayIndex += 1; 19 | } 20 | return sequenceIndex == sequence.length; 21 | } 22 | 23 | void main() { 24 | List array; 25 | List sequence; 26 | 27 | test('test 1', () { 28 | array = [5, 1, 22, 25, 6, -1, 8, 10]; 29 | sequence = [1, 6, -1, 10]; 30 | expect(checkIsSubSequence(array, sequence), isTrue); 31 | }); 32 | 33 | test('test 2', () { 34 | array = [5, 1, 22, 25, 6, -1, 8, 10]; 35 | sequence = [5, -1, 8, 10]; 36 | expect(checkIsSubSequence(array, sequence), isTrue); 37 | }); 38 | 39 | test('test 3', () { 40 | array = [1, 1, 1, 1, 1]; 41 | sequence = [0, 0, 0, 0]; 42 | expect(checkIsSubSequence(array, sequence), isFalse); 43 | }); 44 | 45 | test('test 4', () { 46 | array = [1, 6, -1, 10]; 47 | sequence = [1, 6, -1, 10]; 48 | expect(checkIsSubSequence(array, sequence), isTrue); 49 | }); 50 | 51 | test('test 5', () { 52 | array = [1, 1, 6, 1]; 53 | sequence = [0]; 54 | expect(checkIsSubSequence(array, sequence), isFalse); 55 | }); 56 | 57 | test('test 6', () { 58 | array = []; 59 | sequence = [0]; 60 | expect(checkIsSubSequence(array, sequence), isFalse); 61 | }); 62 | 63 | test('test 7', () { 64 | array = [1, 1, 6, 1]; 65 | sequence = []; 66 | expect(checkIsSubSequence(array, sequence), isTrue); 67 | }); 68 | } 69 | -------------------------------------------------------------------------------- /backtracking/n-queen.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | /*N-Queens Problem 4 | 5 | N - Queens problem is to place n - queens in such a manner 6 | on an n x n chessboard that no queens attack each other by being in the same row, column or diagonal 7 | We have to find maximum no of solutions that are possible. 8 | You can learn more about from the following link :https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/ 9 | .*/ 10 | 11 | // Chess board, A 2d List of integers 12 | 13 | List> board = []; 14 | 15 | // checking is it safe place for a queen ? 16 | 17 | /*size : no of rows or columns of the given chess board 18 | for e.g if there is a 3*3 chessboard then size = 3*/ 19 | 20 | bool isSafe(int size, int row, int col) { 21 | //checking column safe 22 | for (int k = 0; k < row; k++) { 23 | if (board[k][col] == 1) { 24 | return false; 25 | } 26 | } 27 | int i = row; 28 | int j = col; 29 | 30 | //checking left diagonal safe 31 | while (i >= 0 && j >= 0) { 32 | if (board[i][j] == 1) { 33 | return false; 34 | } 35 | j--; 36 | i--; 37 | } 38 | //checking right diagonal safe 39 | i = row; 40 | j = col; 41 | while (i >= 0 && j < size) { 42 | if (board[i][j] == 1) { 43 | return false; 44 | } 45 | j++; 46 | i--; 47 | } 48 | return true; 49 | } 50 | 51 | int solveNQueen(int row, int size) { 52 | //base case 53 | if (size == row) { 54 | return 1; 55 | } 56 | //recursive case 57 | int ways = 0; 58 | for (int col = 0; col < size; col++) { 59 | //whether the current i,j is safe or not 60 | if (isSafe(size, row, col)) { 61 | board[row][col] = 1; 62 | ways += solveNQueen(row + 1, size); 63 | 64 | //backtrack 65 | board[row][col] = 0; 66 | } 67 | } 68 | return ways; 69 | } 70 | 71 | //This Function is used to refilled board with default value for testing purpose only. 72 | // You can remove it, if you are using single test case. 73 | void resetBoard(int boardSize) { 74 | board = List.generate(boardSize, (i) => List.generate(boardSize, (j) => 0)); 75 | } 76 | 77 | void main() { 78 | /* 79 | Test Cases 80 | Size Expected Values 81 | 1 : 1 82 | 2 : 0 83 | 3 : 0 84 | 4 : 2 85 | 5 : 10 86 | 6 : 4 87 | 7 : 40 88 | 8 : 92 89 | 9 : 352 90 | 10 : 724 91 | 92 | */ 93 | test("N Queen #testcase 1", () { 94 | resetBoard(1); 95 | expect(solveNQueen(0, 1), equals(1)); 96 | }); 97 | 98 | test("N Queen #testcase 2", () { 99 | resetBoard(2); 100 | expect(solveNQueen(0, 2), equals(0)); 101 | }); 102 | 103 | test("N Queen #testcase 3", () { 104 | resetBoard(3); 105 | expect(solveNQueen(0, 3), equals(0)); 106 | }); 107 | 108 | test("N Queen #testcase 4", () { 109 | resetBoard(4); 110 | expect(solveNQueen(0, 4), equals(2)); 111 | }); 112 | 113 | test("N Queen #testcase 5", () { 114 | resetBoard(5); 115 | expect(solveNQueen(0, 5), equals(10)); 116 | }); 117 | 118 | test("N Queen #testcase 6", () { 119 | resetBoard(6); 120 | expect(solveNQueen(0, 6), equals(4)); 121 | }); 122 | 123 | test("N Queen #testcase 7", () { 124 | resetBoard(7); 125 | expect(solveNQueen(0, 7), equals(40)); 126 | }); 127 | 128 | test("N Queen #testcase 8", () { 129 | resetBoard(8); 130 | expect(solveNQueen(0, 8), equals(92)); 131 | }); 132 | test("N Queen #testcase 9", () { 133 | resetBoard(9); 134 | expect(solveNQueen(0, 9), equals(352)); 135 | }); 136 | test("N Queen #testcase 10", () { 137 | resetBoard(10); 138 | expect(solveNQueen(0, 10), equals(724)); 139 | }); 140 | } 141 | -------------------------------------------------------------------------------- /backtracking/open_knight_tour.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:test/test.dart'; 4 | 5 | List> getValidPos(List position, int n) { 6 | final i = position[0]; 7 | final j = position[1]; 8 | final positions = [ 9 | [i + 1, j + 2], 10 | [i - 1, j + 2], 11 | [i + 1, j - 2], 12 | [i - 1, j - 2], 13 | [i + 2, j + 1], 14 | [i + 2, j - 1], 15 | [i - 2, j + 1], 16 | [i - 2, j - 1], 17 | ]; 18 | 19 | final List> permissiblePositions = []; 20 | for (final currPosition in positions) { 21 | final iTest = currPosition[0]; 22 | final jTest = currPosition[1]; 23 | if (0 <= iTest && iTest < n && 0 <= jTest && jTest < n) { 24 | permissiblePositions.add(currPosition); 25 | } 26 | } 27 | return permissiblePositions; 28 | } 29 | 30 | bool isComplete(List> board) { 31 | for (final row in board) { 32 | for (final elem in row) { 33 | if (elem == 0) { 34 | return false; 35 | } 36 | } 37 | } 38 | return true; 39 | } 40 | 41 | bool openKnightTourHelper(List> board, List pos, int curr) { 42 | if (isComplete(board)) { 43 | return true; 44 | } 45 | 46 | for (final position in getValidPos(pos, board.length)) { 47 | final i = position[0]; 48 | final j = position[1]; 49 | 50 | if (board[i][j] == 0) { 51 | board[i][j] = curr + 1; 52 | if (openKnightTourHelper(board, position, curr + 1)) { 53 | return true; 54 | } 55 | board[i][j] = 0; 56 | } 57 | } 58 | return false; 59 | } 60 | 61 | List> openKnightTour(int n) { 62 | // board creation 63 | final List> board = []; 64 | for (var i = 0; i < n; i++) { 65 | final List row = []; 66 | for (var j = 0; j < n; j++) { 67 | row.add(0); 68 | } 69 | board.add(row); 70 | } 71 | // open knight tour with backtracking 72 | for (var i = 0; i < n; i++) { 73 | for (var j = 0; j < n; j++) { 74 | board[i][j] = 1; 75 | if (openKnightTourHelper(board, [i, j], 1)) { 76 | return board; 77 | } 78 | board[i][j] = 0; 79 | } 80 | } 81 | return board; 82 | } 83 | 84 | void printBoard(List> board) { 85 | for (final row in board) { 86 | for (final elem in row) { 87 | stdout.write(elem); 88 | } 89 | stdout.write("\n"); 90 | } 91 | stdout.write("\n"); 92 | } 93 | 94 | void main() { 95 | test(('getValidPos: testCase #1'), () { 96 | expect( 97 | getValidPos([1, 3], 4), 98 | equals([ 99 | [2, 1], 100 | [0, 1], 101 | [3, 2] 102 | ])); 103 | }); 104 | 105 | test(('getValidPos: testCase #3'), () { 106 | expect( 107 | getValidPos([1, 2], 5), 108 | equals([ 109 | [2, 4], 110 | [0, 4], 111 | [2, 0], 112 | [0, 0], 113 | [3, 3], 114 | [3, 1] 115 | ])); 116 | }); 117 | 118 | test(('isComplete: testCase #1'), () { 119 | expect( 120 | isComplete([ 121 | [1] 122 | ]), 123 | equals(true)); 124 | }); 125 | 126 | test(('isComplete: testCase #2'), () { 127 | expect( 128 | isComplete([ 129 | [1, 2], 130 | [3, 0] 131 | ]), 132 | equals(false)); 133 | }); 134 | 135 | test(('openKnightTour: testCase #1'), () { 136 | expect( 137 | openKnightTour(1), 138 | equals([ 139 | [1] 140 | ])); 141 | }); 142 | 143 | test(('openKnightTour: testCase #2'), () { 144 | expect( 145 | openKnightTour(2), 146 | equals([ 147 | [0, 0], 148 | [0, 0] 149 | ])); 150 | }); 151 | 152 | test(('openKnightTour: testCase #3'), () { 153 | expect( 154 | openKnightTour(5), 155 | equals([ 156 | [1, 14, 19, 8, 25], 157 | [6, 9, 2, 13, 18], 158 | [15, 20, 7, 24, 3], 159 | [10, 5, 22, 17, 12], 160 | [21, 16, 11, 4, 23] 161 | ])); 162 | }); 163 | } 164 | -------------------------------------------------------------------------------- /conversions/Decimal_To_Any.dart: -------------------------------------------------------------------------------- 1 | //Convert a Decimal Number to Any Other Representation 2 | //https://en.wikipedia.org/wiki/Positional_notation#Base_conversion 3 | 4 | import 'package:test/expect.dart'; 5 | import 'package:test/scaffolding.dart'; 6 | 7 | String decimalToAny(int value, int base) { 8 | var ALPHABET_VALUES = { 9 | 10: 'A', 10 | 11: 'B', 11 | 12: 'C', 12 | 13: 'D', 13 | 14: 'E', 14 | 15: 'F', 15 | 16: 'G', 16 | 17: 'H', 17 | 18: 'I', 18 | 19: 'J', 19 | 20: 'K', 20 | 21: 'L', 21 | 22: 'M', 22 | 23: 'N', 23 | 24: 'O', 24 | 25: 'P', 25 | 26: 'Q', 26 | 27: 'R', 27 | 28: 'S', 28 | 29: 'T', 29 | 30: 'U', 30 | 31: 'V', 31 | 32: 'W', 32 | 33: 'X', 33 | 34: 'Y', 34 | 35: 'Z' 35 | }; 36 | 37 | if (value == 0) return "0"; 38 | 39 | if (base < 2 || base > 36) throw FormatException("Base not supported!"); 40 | 41 | bool negative = false; 42 | if (value < 0) { 43 | negative = true; 44 | value *= -1; 45 | } 46 | 47 | String output = ""; 48 | while (value > 0) { 49 | int remainder = value % base; 50 | value = value ~/ base; 51 | output = (remainder < 10 52 | ? remainder.toString() 53 | : ALPHABET_VALUES[remainder] ?? '0') + 54 | output; 55 | } 56 | 57 | return negative ? '-' + output : output; 58 | } 59 | 60 | void main() { 61 | test('test case 1', () => expect(decimalToAny(0, 2), '0')); 62 | test('test case 2', () => expect(decimalToAny(5, 4), '11')); 63 | test('test case 3', () => expect(decimalToAny(20, 3), '202')); 64 | test('test case 4', () => expect(decimalToAny(-58, 16), '-3A')); 65 | test('test case 5', () => expect(decimalToAny(243, 17), 'E5')); 66 | test('test case 6', () => expect(decimalToAny(34923, 36), 'QY3')); 67 | test('test case 7', () => expect(decimalToAny(10, 11), 'A')); 68 | test('test case 8', () => expect(decimalToAny(-16, 16), '-10')); 69 | test('test case 9', () => expect(decimalToAny(36, 36), '10')); 70 | } 71 | -------------------------------------------------------------------------------- /conversions/Decimal_To_Binary.dart: -------------------------------------------------------------------------------- 1 | //Author:Shawn 2 | //Email:stepfencurryxiao@gmail.com 3 | 4 | import "dart:math" show pow; 5 | 6 | /* 7 | * This method converts a decimal number 8 | * to a binary number using a bitwise 9 | * algorithm 10 | */ 11 | void bitwiseConversion(var n) { 12 | int b = 0, c = 0, d; 13 | print("Bitwise conversion.\n"); 14 | while (n != 0) { 15 | d = (n & 1); 16 | b += d * (pow(10, c++).toInt()); 17 | n >>= 1; 18 | } 19 | print("\tBinary number: $b"); 20 | } 21 | 22 | //Main method 23 | void main() { 24 | bitwiseConversion(8); 25 | } 26 | -------------------------------------------------------------------------------- /conversions/Decimal_to_Hexadecimal.dart: -------------------------------------------------------------------------------- 1 | Map hex_table = { 2 | "10": "A", 3 | "11": "B", 4 | "12": "C", 5 | "13": "D", 6 | "14": "E", 7 | "15": "F", 8 | }; 9 | void main() { 10 | print(decimal_to_hexadecimal(-123)); 11 | print(decimal_to_hexadecimal(0)); 12 | print(decimal_to_hexadecimal(404)); 13 | } 14 | 15 | String decimal_to_hexadecimal(int decimal_val) { 16 | if (decimal_val == 0) { 17 | return "0"; 18 | } 19 | bool negative = false; 20 | if (decimal_val < 0) { 21 | negative = true; 22 | decimal_val *= -1; 23 | } 24 | String hex_string = ""; 25 | while (decimal_val > 0) { 26 | String hex_val = ""; 27 | int remainder = decimal_val % 16; 28 | decimal_val = decimal_val ~/ 16; 29 | if (hex_table.containsKey(remainder.toString())) { 30 | hex_val = hex_table[remainder.toString()] ?? ''; 31 | } else { 32 | hex_val = remainder.toString(); 33 | } 34 | hex_string = hex_val + hex_string; 35 | } 36 | return negative ? "-" + hex_string : hex_string; 37 | } 38 | -------------------------------------------------------------------------------- /conversions/Decimal_to_Octal.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | print(decimal_to_octal(-123)); 3 | print(decimal_to_octal(0)); 4 | print(decimal_to_octal(404)); 5 | } 6 | 7 | String decimal_to_octal(int decimal_val) { 8 | if (decimal_val == 0) { 9 | return "0"; 10 | } 11 | bool negative = false; 12 | if (decimal_val < 0) { 13 | negative = true; 14 | decimal_val *= -1; 15 | } 16 | String oct_string = ""; 17 | while (decimal_val > 0) { 18 | int remainder = decimal_val % 8; 19 | decimal_val = decimal_val ~/ 8; 20 | oct_string = remainder.toString() + oct_string; 21 | } 22 | return negative ? "-" + oct_string : oct_string; 23 | } 24 | -------------------------------------------------------------------------------- /conversions/Integer_To_Roman.dart: -------------------------------------------------------------------------------- 1 | ///Author: Shawn 2 | ///Email: stepfencurryxiao@gmail.com 3 | 4 | /* 5 | * 6 | * Concerting Integers into Roman Numerals 7 | * 8 | */ 9 | 10 | List ArabianRomanNumbers = [ 11 | 1000, 12 | 900, 13 | 500, 14 | 400, 15 | 100, 16 | 90, 17 | 50, 18 | 40, 19 | 10, 20 | 9, 21 | 5, 22 | 4, 23 | 1 24 | ]; 25 | 26 | List RomanNumbers = [ 27 | "M", 28 | "CM", 29 | "D", 30 | "CD", 31 | "C", 32 | "XC", 33 | "L", 34 | "XL", 35 | "X", 36 | "IX", 37 | "V", 38 | "IV", 39 | "I" 40 | ]; 41 | 42 | List integer_to_roman(int num) { 43 | if (num < 0) { 44 | return []; 45 | } 46 | 47 | List result = []; 48 | for (int i = 0; i < ArabianRomanNumbers.length; i++) { 49 | int times = num ~/ ArabianRomanNumbers[i]; 50 | for (int j = 0; j < times; j++) { 51 | print(RomanNumbers[i]); 52 | } 53 | num -= times * ArabianRomanNumbers[i]; 54 | } 55 | 56 | return result; 57 | } 58 | 59 | int main() { 60 | /* IV */ 61 | integer_to_roman(4); 62 | /* II */ 63 | integer_to_roman(2); 64 | /* M */ 65 | integer_to_roman(1000); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /conversions/binary_to_decimal.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | 3 | import 'package:test/test.dart'; 4 | 5 | int binaryToDecimal(String binaryString) { 6 | binaryString = binaryString.trim(); 7 | if (binaryString == "") { 8 | throw FormatException("An empty value was passed to the function"); 9 | } 10 | bool isNegative = binaryString[0] == "-"; 11 | if (isNegative) binaryString = binaryString.substring(1); 12 | int decimalValue = 0; 13 | for (int i = 0; i < binaryString.length; i++) { 14 | if ("01".contains(binaryString[i]) == false) { 15 | throw FormatException("Non-binary value was passed to the function"); 16 | } else { 17 | decimalValue += (pow(2, binaryString.length - i - 1).toInt() * 18 | (int.tryParse(binaryString[i]) ?? 0)); 19 | } 20 | } 21 | return isNegative ? -1 * decimalValue : decimalValue; 22 | } 23 | 24 | void main() { 25 | test('test case 1', () { 26 | expect(binaryToDecimal("-111"), -7); 27 | }); 28 | test('test case 2', () { 29 | expect(binaryToDecimal("101011"), 43); 30 | }); 31 | 32 | test('test case 3', () { 33 | expect(() => binaryToDecimal("1a1"), throwsFormatException); 34 | }); 35 | } 36 | -------------------------------------------------------------------------------- /conversions/binary_to_hexadecimal.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | //Binary number to hexadecimal number conversion 4 | Map hexTable = { 5 | "0000": '0', 6 | "0001": '1', 7 | "0010": '2', 8 | "0011": '3', 9 | "0100": '4', 10 | "0101": '5', 11 | "0110": '6', 12 | "0111": '7', 13 | "1000": '8', 14 | "1001": '9', 15 | "1010": 'A', 16 | "1011": 'B', 17 | "1100": 'C', 18 | "1101": 'D', 19 | "1110": 'E', 20 | "1111": 'F', 21 | }; 22 | 23 | // function to take a binary string and to return hex value 24 | String binaryToHexadecimal(String binaryString) { 25 | // checking for unexpected values 26 | binaryString = binaryString.trim(); 27 | if (binaryString.isEmpty) { 28 | throw new FormatException("An empty value was passed to the function"); 29 | } 30 | try { 31 | int.parse(binaryString); 32 | } catch (e) { 33 | throw new FormatException("An invalid value was passed to the function"); 34 | } 35 | 36 | // negative number check 37 | bool isNegative = binaryString[0] == "-"; 38 | if (isNegative) binaryString = binaryString.substring(1); 39 | 40 | // add min 0's in the end to make right substring length divisible by 4 41 | var binaryStringLength = binaryString.length; 42 | for (int i = 1; i <= (4 - binaryStringLength % 4) % 4; i++) 43 | binaryString = '0' + binaryString; 44 | 45 | // coverting the binary values to hex by diving into substring 46 | String hexValue = ""; 47 | int i = 0; 48 | while (i != binaryString.length) { 49 | String bin_curr = binaryString.substring(i, i + 4); 50 | hexValue += hexTable[bin_curr] ?? ''; 51 | i += 4; 52 | } 53 | 54 | // returning the value 55 | if (isNegative) { 56 | return "-" + hexValue; 57 | } 58 | return hexValue; 59 | } 60 | 61 | // driver function 62 | void main() { 63 | test("binary_to_hexadecimal -1111", () { 64 | expect(binaryToHexadecimal("-1111"), equals("-F")); 65 | }); 66 | 67 | test("binary_to_hexadecimal 101011", () { 68 | expect(binaryToHexadecimal("101011"), equals("2B")); 69 | }); 70 | 71 | test("binary_to_hexadecimal rasies error when number is invalid", () { 72 | expect(() => binaryToHexadecimal("-1011a01"), throwsFormatException); 73 | }); 74 | 75 | test("binary_to_hexadecimal of empty string raises error", () { 76 | expect(() => binaryToHexadecimal(""), throwsFormatException); 77 | }); 78 | } 79 | -------------------------------------------------------------------------------- /conversions/binary_to_octal.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | //Binary number to octal number conversion 4 | void main() { 5 | test("binary_to_octal -1111", () { 6 | expect(binaryToOctal("-1111"), equals("-17")); 7 | }); 8 | 9 | test("binary_to_octal 101011", () { 10 | expect(binaryToOctal("101011"), equals("53")); 11 | }); 12 | 13 | test("binary_to_octal rasies error when number is invalid", () { 14 | expect(() => binaryToOctal("-1011a01"), throwsFormatException); 15 | }); 16 | 17 | test("binary_to_octal of empty string raises error", () { 18 | expect(() => binaryToOctal(""), throwsFormatException); 19 | }); 20 | } 21 | 22 | String binaryToOctal(String binaryString) { 23 | binaryString = binaryString.trim(); 24 | if (binaryString.isEmpty) { 25 | throw new FormatException("An empty value was passed to the function"); 26 | } 27 | bool isNegative = binaryString[0] == "-"; 28 | if (isNegative) binaryString = binaryString.substring(1); 29 | 30 | String octalValue = ""; 31 | int binary; 32 | try { 33 | binary = int.parse(binaryString); 34 | } catch (e) { 35 | throw new FormatException("An invalid value was passed to the function"); 36 | } 37 | int currentBit; 38 | int j = 1; 39 | while (binary > 0) { 40 | int code3 = 0; 41 | for (int i = 0; i < 3; i++) { 42 | currentBit = binary % 10; 43 | binary = binary ~/ 10; 44 | code3 += currentBit * j; 45 | j *= 2; 46 | } 47 | octalValue = code3.toString() + octalValue; 48 | j = 1; 49 | } 50 | if (isNegative) { 51 | return "-" + octalValue; 52 | } 53 | return octalValue; 54 | } 55 | -------------------------------------------------------------------------------- /conversions/hexadecimal_to_binary.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // hexadecimal number to binary number conversion 4 | Map bin_table = { 5 | "0": "0", 6 | "1": "1", 7 | "2": "10", 8 | "3": "11", 9 | "4": "100", 10 | "5": "101", 11 | "6": "110", 12 | "7": "111", 13 | "8": "1000", 14 | "9": "1001", 15 | "A": "1010", 16 | "B": "1011", 17 | "C": "1100", 18 | "D": "1101", 19 | "E": "1110", 20 | "F": "1111", 21 | }; 22 | 23 | // function to take hex value as string and return binary value as string 24 | String hexadecimal_to_binary(String hex_value) { 25 | // checking for unexpected values 26 | hex_value = hex_value.trim(); 27 | if (hex_value.isEmpty) { 28 | throw new FormatException("An empty value was passed to the function"); 29 | } 30 | 31 | // negative number check 32 | bool is_negative = hex_value[0] == "-"; 33 | if (is_negative) hex_value = hex_value.substring(1); 34 | 35 | // coverting the hex to binary values by diving into substring 36 | String bin_val = ""; 37 | int i = 0; 38 | while (i != hex_value.length) { 39 | String hex_cur = hex_value.substring(i, i + 1); 40 | if (!bin_table.containsKey(hex_cur)) { 41 | throw new FormatException("An invalid value was passed to the function"); 42 | } 43 | bin_val += bin_table[hex_cur] ?? ''; 44 | i++; 45 | } 46 | 47 | // returning the value 48 | if (is_negative) { 49 | return "-" + bin_val; 50 | } 51 | return bin_val; 52 | } 53 | 54 | void main() { 55 | test("hexadecimal_to_binary -F", () { 56 | expect(hexadecimal_to_binary("-F"), equals("-1111")); 57 | }); 58 | 59 | test("hexadecimal_to_binaryl 2B", () { 60 | expect(hexadecimal_to_binary("2B"), equals("101011")); 61 | }); 62 | 63 | test("hexadecimal_to_binary rasies error when number is invalid", () { 64 | expect(() => hexadecimal_to_binary("AIO"), throwsFormatException); 65 | }); 66 | 67 | test("hexadecimal_to_binary of empty string raises error", () { 68 | expect(() => hexadecimal_to_binary(""), throwsFormatException); 69 | }); 70 | } 71 | -------------------------------------------------------------------------------- /conversions/hexadecimal_to_decimal.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | 3 | Map hex_table = { 4 | "A": 10, 5 | "B": 11, 6 | "C": 12, 7 | "D": 13, 8 | "E": 14, 9 | "F": 15, 10 | }; 11 | void main() { 12 | print(hexadecimal_to_decimal("1abc")); // 6844 13 | 14 | print(hexadecimal_to_decimal(" -123 ")); // -291 15 | try { 16 | print(hexadecimal_to_decimal("1x")); //error 17 | } catch (ex) { 18 | print(ex); 19 | } 20 | } 21 | 22 | int hexadecimal_to_decimal(String hex_string) { 23 | hex_string = hex_string.trim().toUpperCase(); 24 | if (hex_string == "") { 25 | throw Exception("An empty value was passed to the function"); 26 | } 27 | bool is_negative = hex_string[0] == "-"; 28 | if (is_negative) hex_string = hex_string.substring(1); 29 | int decimal_val = 0; 30 | for (int i = 0; i < hex_string.length; i++) { 31 | if (int.tryParse(hex_string[i]) == null && 32 | hex_table.containsKey(hex_string[i]) == false) { 33 | throw Exception("Non-hex value was passed to the function"); 34 | } else { 35 | decimal_val += pow(16, hex_string.length - i - 1).toInt() * 36 | (int.tryParse(hex_string[i]) ?? hex_table[hex_string[i]] ?? 0); 37 | } 38 | } 39 | return is_negative ? -1 * decimal_val : decimal_val; 40 | } 41 | -------------------------------------------------------------------------------- /conversions/hexadecimal_to_octal.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | import 'package:test/test.dart'; 3 | 4 | // Hexadecimal number to octal number conversion program 5 | String hexadecimal_to_octal(String hex_val) { 6 | int dec = 0; 7 | 8 | // checking for null string passed to function 9 | if (hex_val == "") { 10 | throw new FormatException("An empty value was passed to the function"); 11 | } 12 | 13 | // negative number check 14 | bool is_negative = hex_val[0] == "-"; 15 | if (is_negative) hex_val = hex_val.substring(1); 16 | int c = hex_val.length - 1; 17 | 18 | // finding the decimal equivalent of the hexa decimal number 19 | for (int i = 0; i < hex_val.length; i++) { 20 | var ch = hex_val.substring(i, i + 1); 21 | switch (ch) { 22 | case '0': 23 | case '1': 24 | case '2': 25 | case '3': 26 | case '4': 27 | case '5': 28 | case '6': 29 | case '7': 30 | case '8': 31 | case '9': 32 | dec = dec + (int.tryParse(ch) ?? 0) * pow(16, c).toInt(); 33 | c--; 34 | break; 35 | case 'a': 36 | case 'A': 37 | dec = dec + 10 * pow(16, c).toInt(); 38 | c--; 39 | break; 40 | case 'b': 41 | case 'B': 42 | dec = dec + 11 * pow(16, c).toInt(); 43 | c--; 44 | break; 45 | case 'c': 46 | case 'C': 47 | dec = dec + 12 * pow(16, c).toInt(); 48 | c--; 49 | break; 50 | case 'd': 51 | case 'D': 52 | dec = dec + 13 * pow(16, c).toInt(); 53 | c--; 54 | break; 55 | case 'e': 56 | case 'E': 57 | dec = dec + 14 * pow(16, c).toInt(); 58 | c--; 59 | break; 60 | case 'f': 61 | case 'F': 62 | dec = dec + 15 * pow(16, c).toInt(); 63 | c--; 64 | break; 65 | default: 66 | throw new FormatException( 67 | "An invalid value was passed to the function"); 68 | } 69 | } 70 | 71 | // String oct to store the octal equivalent of a hexadecimal number. 72 | String oct_val = ""; 73 | 74 | // Converting decimal to octal number. 75 | while (dec > 0) { 76 | oct_val = (dec % 8).toString() + oct_val; 77 | dec = dec ~/ 8; 78 | } 79 | 80 | // Returning the value 81 | if (is_negative) { 82 | return "-" + oct_val; 83 | } 84 | return oct_val; 85 | } 86 | 87 | void main() { 88 | // Test cases with various input 89 | test("hexadecimal_to_octal 43DF", () { 90 | expect(hexadecimal_to_octal("43DF"), equals("41737")); 91 | }); 92 | 93 | test("hexadecimal_to_octal -2CB", () { 94 | expect(hexadecimal_to_octal("-2CB"), equals("-1313")); 95 | }); 96 | 97 | test("hexadecimal_to_octal rasies error when number is invalid", () { 98 | expect(() => hexadecimal_to_octal("AIO"), throwsFormatException); 99 | }); 100 | 101 | test("hexadecimal_to_octal of empty string raises error", () { 102 | expect(() => hexadecimal_to_octal(""), throwsFormatException); 103 | }); 104 | } 105 | -------------------------------------------------------------------------------- /conversions/octal_to_binary.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | import 'package:test/test.dart'; 3 | 4 | // octal number to binary number conversion 5 | String ocatal_to_binary(String oct_val) { 6 | // checking for unexpected values 7 | oct_val = oct_val.trim(); 8 | if (oct_val.isEmpty) { 9 | throw new FormatException("An empty value was passed to the function"); 10 | } 11 | 12 | // negative number check 13 | bool is_negative = oct_val[0] == "-"; 14 | if (is_negative) oct_val = oct_val.substring(1); 15 | 16 | int oct; 17 | try { 18 | oct = int.parse(oct_val); 19 | } catch (e) { 20 | throw new FormatException("An invalid value was passed to the function"); 21 | } 22 | 23 | // checking number not valid for octal is passed(0-7) 24 | for (int i = 0; i < oct_val.length; i++) { 25 | if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { 26 | throw new FormatException("An invalid value was passed to the function"); 27 | } 28 | ; 29 | } 30 | 31 | // converting octal to decimal 32 | int dec_val = 0, i = 0, bin_val = 0; 33 | while (oct != 0) { 34 | dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); 35 | i++; 36 | oct = oct ~/ 10; 37 | } 38 | 39 | // converting to decimal to binary 40 | i = 1; 41 | while (dec_val != 0) { 42 | bin_val = bin_val + (dec_val % 2) * i; 43 | dec_val = dec_val ~/ 2; 44 | i = i * 10; 45 | } 46 | 47 | // returning the value 48 | if (is_negative) { 49 | return "-" + bin_val.toString(); 50 | } 51 | return bin_val.toString(); 52 | } 53 | 54 | void main() { 55 | test("ocatal_to_binary 75", () { 56 | expect(ocatal_to_binary("75"), equals("111101")); 57 | }); 58 | 59 | test("ocatal_to_binary -62", () { 60 | expect(ocatal_to_binary("-62"), equals("-110010")); 61 | }); 62 | 63 | test("ocatal_to_binary rasies error when number is invalid", () { 64 | expect(() => ocatal_to_binary("84"), throwsFormatException); 65 | }); 66 | 67 | test("ocatal_to_binary rasies error when number is invalid", () { 68 | expect(() => ocatal_to_binary("as23"), throwsFormatException); 69 | }); 70 | 71 | test("ocatal_to_binary of empty string raises error", () { 72 | expect(() => ocatal_to_binary(""), throwsFormatException); 73 | }); 74 | } 75 | -------------------------------------------------------------------------------- /conversions/octal_to_decimal.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | import 'package:test/test.dart'; 3 | 4 | // octal number to decimal number conversion 5 | // 6 | // function to take oct string value and return decmal string value 7 | String ocatal_to_decimal(String oct_val) { 8 | // checking for unexpected values 9 | oct_val = oct_val.trim(); 10 | if (oct_val.isEmpty) { 11 | throw new FormatException("An empty value was passed to the function"); 12 | } 13 | 14 | // negative number check 15 | bool is_negative = oct_val[0] == "-"; 16 | if (is_negative) oct_val = oct_val.substring(1); 17 | 18 | int oct; 19 | try { 20 | oct = int.parse(oct_val); 21 | } catch (e) { 22 | throw new FormatException("An invalid value was passed to the function"); 23 | } 24 | 25 | // checking number not valid for octal is passed(0-7) 26 | for (int i = 0; i < oct_val.length; i++) { 27 | if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { 28 | throw new FormatException("An invalid value was passed to the function"); 29 | } 30 | ; 31 | } 32 | 33 | // converting octal to decimal 34 | int dec_val = 0, i = 0; 35 | while (oct != 0) { 36 | dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); 37 | i++; 38 | oct = oct ~/ 10; 39 | } 40 | 41 | // returning the value 42 | if (is_negative) { 43 | return "-" + dec_val.toString(); 44 | } 45 | return dec_val.toString(); 46 | } 47 | 48 | // driver function 49 | void main() { 50 | // test cases for different input 51 | test("ocatal_to_decimal 75", () { 52 | expect(ocatal_to_decimal("75"), equals("61")); 53 | }); 54 | 55 | test("ocatal_to_decimal -62", () { 56 | expect(ocatal_to_decimal("-62"), equals("-50")); 57 | }); 58 | 59 | test("ocatal_to_decimal rasies error when number is invalid", () { 60 | expect(() => ocatal_to_decimal("84"), throwsFormatException); 61 | }); 62 | 63 | test("ocatal_to_decimal rasies error when number is invalid", () { 64 | expect(() => ocatal_to_decimal("as23"), throwsFormatException); 65 | }); 66 | 67 | test("ocatal_to_decimal of empty string raises error", () { 68 | expect(() => ocatal_to_decimal(""), throwsFormatException); 69 | }); 70 | } 71 | -------------------------------------------------------------------------------- /conversions/octal_to_hexadecimal.dart: -------------------------------------------------------------------------------- 1 | import "dart:math" show pow; 2 | import 'package:test/test.dart'; 3 | 4 | // octal number to hex number 5 | Map hex_table = { 6 | "10": "A", 7 | "11": "B", 8 | "12": "C", 9 | "13": "D", 10 | "14": "E", 11 | "15": "F", 12 | }; 13 | // 14 | // function take octal string value and return hexadecimal string value 15 | String ocatal_to_hex(String oct_val) { 16 | // checking for unexpected values 17 | oct_val = oct_val.trim(); 18 | if (oct_val == "") { 19 | throw new FormatException("An empty value was passed to the function"); 20 | } 21 | 22 | // negative number check 23 | bool is_negative = oct_val[0] == "-"; 24 | if (is_negative) oct_val = oct_val.substring(1); 25 | 26 | int oct; 27 | try { 28 | oct = int.parse(oct_val); 29 | } catch (e) { 30 | throw new FormatException("An invalid value was passed to the function"); 31 | } 32 | 33 | // checking number not valid for octal is passed(0-7) 34 | for (int i = 0; i < oct_val.length; i++) { 35 | if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { 36 | throw new FormatException("An invalid value was passed to the function"); 37 | } 38 | ; 39 | } 40 | 41 | // converting octal to decimal 42 | int dec_val = 0, i = 0; 43 | while (oct != 0) { 44 | dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); 45 | i++; 46 | oct = oct ~/ 10; 47 | } 48 | 49 | // converting to decimal to hex 50 | if (dec_val == 0) { 51 | return "0"; 52 | } 53 | String hex_string = ""; 54 | while (dec_val > 0) { 55 | String hex_val = ""; 56 | int remainder = dec_val % 16; 57 | dec_val = dec_val ~/ 16; 58 | if (hex_table.containsKey(remainder.toString())) { 59 | hex_val = hex_table[remainder.toString()] ?? ''; 60 | } else { 61 | hex_val = remainder.toString(); 62 | } 63 | hex_string = hex_val + hex_string; 64 | } 65 | 66 | // returning the value 67 | if (is_negative) { 68 | return "-" + hex_string; 69 | } 70 | return hex_string; 71 | } 72 | 73 | // driver function 74 | void main() { 75 | // test input 76 | test("ocatal_to_hex 75", () { 77 | expect(ocatal_to_hex("75"), equals("3D")); 78 | }); 79 | 80 | test("ocatal_to_hex -62", () { 81 | expect(ocatal_to_hex("-62"), equals("-32")); 82 | }); 83 | 84 | test("ocatal_to_hex rasies error when number is invalid", () { 85 | expect(() => ocatal_to_hex("84"), throwsFormatException); 86 | }); 87 | 88 | test("ocatal_to_hex rasies error when number is invalid", () { 89 | expect(() => ocatal_to_hex("as23"), throwsFormatException); 90 | }); 91 | 92 | test("ocatal_to_hex of empty string raises error", () { 93 | expect(() => ocatal_to_hex(""), throwsFormatException); 94 | }); 95 | } 96 | -------------------------------------------------------------------------------- /conversions/roman_to_integer.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | int romanToInteger(var s) { 4 | int ans = 0; 5 | for (int i = 0; i < s.length; i++) { 6 | int num1 = value(s[i]); 7 | if (i + 1 < s.length) { 8 | int num2 = value(s[i + 1]); 9 | if (num1 < num2) { 10 | ans = ans + num2 - num1; 11 | i++; 12 | } else { 13 | ans = ans + num1; 14 | } 15 | } else { 16 | ans = ans + num1; 17 | } 18 | } 19 | return ans; 20 | } 21 | 22 | int value(var r) { 23 | if (r == 'I') 24 | return 1; 25 | else if (r == 'V') 26 | return 5; 27 | else if (r == 'X') 28 | return 10; 29 | else if (r == 'L') 30 | return 50; 31 | else if (r == 'C') 32 | return 100; 33 | else if (r == 'D') 34 | return 500; 35 | else if (r == 'M') return 1000; 36 | return 0; 37 | } 38 | 39 | void main() { 40 | test("romanToInteger XII returns 12", () { 41 | expect(romanToInteger('XII'), equals(12)); 42 | }); 43 | 44 | test("romanToInteger LII returns 52", () { 45 | expect(romanToInteger('LII'), equals(52)); 46 | }); 47 | 48 | test("romanToInteger DLVII returns 557", () { 49 | expect(romanToInteger('LII'), equals(52)); 50 | }); 51 | 52 | test("romanToInteger VI returns 6", () { 53 | expect(romanToInteger('VI'), equals(6)); 54 | }); 55 | 56 | test("romanToInteger CLXV returns 165", () { 57 | expect(romanToInteger('CLXV'), equals(165)); 58 | }); 59 | 60 | test("romanToInteger MDCI returns 1601", () { 61 | expect(romanToInteger('MDCI'), equals(1601)); 62 | }); 63 | 64 | test("romanToInteger LVII returns 57", () { 65 | expect(romanToInteger('LVII'), equals(57)); 66 | }); 67 | } 68 | -------------------------------------------------------------------------------- /dart_test.yaml: -------------------------------------------------------------------------------- 1 | paths: [.] 2 | 3 | filename: "*.dart" 4 | -------------------------------------------------------------------------------- /data_structures/HashMap/Hashing.dart: -------------------------------------------------------------------------------- 1 | //Author:Shawn 2 | //Email:stepfencurryxiao@gmail.com 3 | 4 | class Node { 5 | int? data; 6 | Node? next; 7 | 8 | Node(int data) { 9 | this.data = data; 10 | this.next = null; 11 | } 12 | } 13 | 14 | class LinkedList { 15 | Node? head; 16 | int size; 17 | 18 | LinkedList({this.size = 0}) { 19 | head = null; 20 | } 21 | 22 | void insert(int data) { 23 | Node newnode = new Node(data); 24 | 25 | size++; 26 | 27 | if (head == null) { 28 | head = newnode; 29 | } else { 30 | newnode.next = head; 31 | head = newnode; 32 | } 33 | } 34 | 35 | void delete(int data) { 36 | if (size == 0) { 37 | print("underFlow!"); 38 | return; 39 | } else { 40 | Node? curr = head; 41 | if (curr?.data == data) { 42 | head = curr?.next; 43 | size--; 44 | return; 45 | } else { 46 | while (curr?.next?.next != null) { 47 | if (curr?.next?.data == data) { 48 | curr?.next = curr.next?.next; 49 | return; 50 | } 51 | } 52 | print("Key not found"); 53 | } 54 | } 55 | } 56 | 57 | void display() { 58 | Node? temp = head; 59 | while (temp != null) { 60 | print(temp.data.toString()); 61 | temp = temp.next; 62 | } 63 | print("\n"); 64 | } 65 | } 66 | 67 | class HashMap { 68 | int hsize; 69 | List buckets; 70 | 71 | HashMap({this.hsize = 0, this.buckets = const []}) { 72 | buckets = new List.generate(hsize, (a) => LinkedList()); 73 | for (int i = 0; i < hsize; i++) { 74 | buckets[i] = new LinkedList(); 75 | } 76 | this.hsize = hsize; 77 | } 78 | 79 | int hashing(int key) { 80 | int hash = key % hsize; 81 | if (hash < 0) { 82 | hash += hsize; 83 | } 84 | return hash; 85 | } 86 | 87 | void insertHash(int key) { 88 | int hash = hashing(key); 89 | buckets[hash].insert(key); 90 | } 91 | 92 | void deleteHash(int key) { 93 | int hash = hashing(key); 94 | buckets[hash].delete(key); 95 | } 96 | 97 | void displayHashtable() { 98 | for (int i = 0; i < hsize; i++) { 99 | print("Bucket $i:"); 100 | buckets[i].display(); 101 | } 102 | } 103 | } 104 | 105 | void main() { 106 | HashMap h = new HashMap(hsize: 7); 107 | 108 | print("Add key 5"); 109 | h.insertHash(5); 110 | 111 | print("Add key 28"); 112 | h.insertHash(28); 113 | 114 | print("Add key 1"); 115 | h.insertHash(1); 116 | 117 | print("Delete Key 28"); 118 | h.deleteHash(28); 119 | 120 | print("Print Table:\n"); 121 | h.displayHashtable(); 122 | 123 | print("Delete Key 1"); 124 | h.deleteHash(1); 125 | 126 | print("Print Table:\n"); 127 | h.displayHashtable(); 128 | } 129 | -------------------------------------------------------------------------------- /data_structures/HashMap/hashmap_implementation: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // Internal class to store each key-value pair and its next node 4 | class Entry { 5 | final K key; 6 | V value; 7 | Entry next; 8 | 9 | Entry(this.key, this.value, [this.next]); 10 | } 11 | 12 | class HashMap { 13 | // Internal list to store the keys and values 14 | List> _table; 15 | 16 | HashMap() { 17 | _table = List>.filled(256, null); 18 | } 19 | 20 | // Helper function to generate a hash code for a key 21 | int _hashCode(K key) { 22 | return key.hashCode % _table.length; 23 | } 24 | 25 | // Insert a new key-value pair into the hash map 26 | void insert(K key, V value) { 27 | final int index = _hashCode(key); 28 | if (_table[index] == null) { 29 | _table[index] = Entry(key, value); 30 | } else { 31 | Entry entry = _table[index]; 32 | while (entry.next != null && entry.key != key) { 33 | entry = entry.next; 34 | } 35 | if (entry.key == key) { 36 | entry.value = value; 37 | } else { 38 | entry.next = Entry(key, value); 39 | } 40 | } 41 | } 42 | 43 | // Get the value associated with a key in the hash map 44 | V get(K key) { 45 | final int index = _hashCode(key); 46 | if (_table[index] == null) { 47 | return null; 48 | } else { 49 | Entry entry = _table[index]; 50 | while (entry != null && entry.key != key) { 51 | entry = entry.next; 52 | } 53 | return entry?.value; 54 | } 55 | } 56 | } 57 | 58 | void main() { 59 | test('adding a key to a map', () { 60 | HashMap map = HashMap(); 61 | expect(map.get(1), null); 62 | map.insert(1, 'Akash'); 63 | expect(map.get(1), 'Akash'); 64 | }); 65 | 66 | test('updating a key in a map', () { 67 | HashMap map = HashMap(); 68 | map.insert(1, 'Akash'); 69 | expect(map.get(1), 'Akash'); 70 | map.insert(1, 'IronMan'); 71 | expect(map.get(1), 'IronMan'); 72 | }); 73 | } 74 | -------------------------------------------------------------------------------- /data_structures/Heap/Binary_Heap/Max_heap.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | class MaxHeap { 4 | List heap = []; 5 | 6 | void buildHeap(List array) { 7 | this.heap = _heapify(array); 8 | } 9 | 10 | List _heapify(List array) { 11 | int firstParent = (array.length - 2) ~/ 2; 12 | for (int i = firstParent; i >= 0; i--) { 13 | _siftDown(i, array.length - 1, array); 14 | } 15 | return array; 16 | } 17 | 18 | int? peek() { 19 | if (!isEmpty()) { 20 | return this.heap[0]; 21 | } 22 | return null; 23 | } 24 | 25 | bool isEmpty() { 26 | return this.heap.length == 0; 27 | } 28 | 29 | void _siftUp(int currentIndex) { 30 | int parentIndex = (currentIndex - 1) ~/ 2; 31 | while ( 32 | parentIndex >= 0 && this.heap[parentIndex] < this.heap[currentIndex]) { 33 | _swap(parentIndex, currentIndex, this.heap); 34 | currentIndex = parentIndex; 35 | parentIndex = (currentIndex - 1) ~/ 2; 36 | } 37 | } 38 | 39 | void _siftDown(int currentIndex, int endIndex, List heap) { 40 | int childOneIndex = (2 * currentIndex) + 1; 41 | int childTwoIndex; 42 | 43 | while (childOneIndex <= endIndex) { 44 | childTwoIndex = 45 | 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; 46 | int indexToSwap; 47 | if (childTwoIndex != -1 && heap[childTwoIndex] > heap[childOneIndex]) { 48 | indexToSwap = childTwoIndex; 49 | } else { 50 | indexToSwap = childOneIndex; 51 | } 52 | 53 | if (heap[currentIndex] < heap[indexToSwap]) { 54 | _swap(currentIndex, indexToSwap, heap); 55 | currentIndex = indexToSwap; 56 | childOneIndex = (2 * currentIndex) + 1; 57 | } else { 58 | break; 59 | } 60 | } 61 | } 62 | 63 | void insert(int value) { 64 | this.heap.add(value); 65 | _siftUp(this.heap.length - 1); 66 | } 67 | 68 | int? remove() { 69 | if (!isEmpty()) { 70 | _swap(0, this.heap.length - 1, this.heap); 71 | int maxElement = this.heap.removeLast(); 72 | _siftDown(0, this.heap.length - 1, this.heap); 73 | return maxElement; 74 | } 75 | return null; 76 | } 77 | 78 | void _swap(int left, int right, List array) { 79 | int temp; 80 | temp = array[left]; 81 | array[left] = array[right]; 82 | array[right] = temp; 83 | } 84 | } 85 | 86 | void main() { 87 | MaxHeap maxHeap = new MaxHeap(); 88 | List array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]; 89 | maxHeap.buildHeap(array); 90 | test(('Test case 1'), () { 91 | expect(maxHeap.remove(), equals(391)); 92 | maxHeap.insert(-100); 93 | expect(maxHeap.isEmpty(), isFalse); 94 | expect(maxHeap.peek(), equals(56)); 95 | maxHeap.insert(1000); 96 | expect(maxHeap.peek(), equals(1000)); 97 | expect(maxHeap.remove(), equals(1000)); 98 | expect(maxHeap.remove(), equals(56)); 99 | }); 100 | 101 | test(('Test case 2'), () { 102 | array = [-7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8]; 103 | maxHeap = new MaxHeap(); 104 | maxHeap.buildHeap(array); 105 | expect(maxHeap.remove(), equals(10)); 106 | expect(maxHeap.peek(), equals(9)); 107 | maxHeap.insert(890); 108 | expect(maxHeap.peek(), equals(890)); 109 | expect(maxHeap.remove(), equals(890)); 110 | expect(maxHeap.peek(), equals(9)); 111 | expect(maxHeap.isEmpty(), isFalse); 112 | maxHeap.insert(1); 113 | expect(maxHeap.peek(), equals(9)); 114 | }); 115 | } 116 | -------------------------------------------------------------------------------- /data_structures/Heap/Binary_Heap/Min_Heap.dart: -------------------------------------------------------------------------------- 1 | //Author:Shawn 2 | //Email:stepfencurryxiao@gmail.com 3 | 4 | /* 5 | * 1 6 | * / \ 7 | * 2 3 8 | * / \ / \ 9 | * 5 4 6 7 10 | * / \ 11 | * 8 9 12 | * 13 | * Array:[1,2,3,5,4,6,7,8,9] 14 | * 15 | * rightchild : 2n + 2 16 | * leftcgild : 2n + 1 17 | */ 18 | 19 | List upAdjust(List arr, int length) { 20 | //Mark inserted nodes 21 | var child = length - 1; 22 | //Father nodes 23 | int parent = (child - 1) ~/ 2; 24 | //Save the inserted node temporarily 25 | int temp = arr[child]; 26 | 27 | while (child > 0 && temp < arr[parent]) { 28 | //When temp finds the correct location, we will assign the value of temp to this node 29 | arr[child] = arr[parent]; 30 | child = parent; 31 | parent = (child - 1) ~/ 2; 32 | } 33 | arr[child] = temp; 34 | return arr; 35 | } 36 | 37 | /* * 38 | ** Sink operation, delete operation is equivalent to 39 | ** after an element is assigned to the root element, the sink operation is performed on the root element 40 | * @param arr 41 | *@ param parent subscript of element to sink 42 | *@ param length array length 43 | */ 44 | List downAdjust(List arr, int parent, int length) { 45 | //Save elements to sink 46 | int temp = arr[parent]; 47 | //Locate left child node location 48 | int child = 2 * parent + 1; 49 | //Begin to sink 50 | while (child < length) { 51 | //If the right child node is smaller than the left child, locate the right child 52 | if (child + 1 < length && arr[child] > arr[child + 1]) { 53 | child++; 54 | } 55 | //Sink ends if parent is smaller or equal to child 56 | if (temp <= arr[child]) break; 57 | 58 | arr[parent] = arr[child]; 59 | parent = child; 60 | child = 2 * parent + 1; 61 | } 62 | arr[parent] = temp; 63 | return arr; 64 | } 65 | 66 | List buildHead(List arr, int length) { 67 | //Sink from the last non leaf node 68 | for (int i = (length - 2) ~/ 2; i >= 0; i--) { 69 | arr = downAdjust(arr, i, length); 70 | } 71 | return arr; 72 | } 73 | 74 | void main() { 75 | List arr = [1, 3, 0, 5, 4, 6, 7, 8, 9]; 76 | List BinaryHeap = buildHead(arr, arr.length); 77 | print(BinaryHeap); 78 | } 79 | -------------------------------------------------------------------------------- /data_structures/Heap/Binary_Heap/min_heap_two.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | class MinHeap { 4 | List heap = []; 5 | 6 | void buildHeap(List array) { 7 | this.heap = _heapify(array); 8 | } 9 | 10 | List _heapify(List array) { 11 | int firstParent = (array.length - 2) ~/ 2; 12 | for (int i = firstParent; i >= 0; i--) { 13 | _siftDown(i, array.length - 1, array); 14 | } 15 | return array; 16 | } 17 | 18 | int? peek() { 19 | if (!isEmpty()) { 20 | return this.heap[0]; 21 | } 22 | return null; 23 | } 24 | 25 | bool isEmpty() { 26 | return this.heap.length == 0; 27 | } 28 | 29 | void _siftUp(int currentIndex) { 30 | int parentIndex = (currentIndex - 1) ~/ 2; 31 | while ( 32 | parentIndex >= 0 && this.heap[parentIndex] > this.heap[currentIndex]) { 33 | _swap(parentIndex, currentIndex, this.heap); 34 | currentIndex = parentIndex; 35 | parentIndex = (currentIndex - 1) ~/ 2; 36 | } 37 | } 38 | 39 | void _siftDown(int currentIndex, int endIndex, List heap) { 40 | int childOneIndex = (2 * currentIndex) + 1; 41 | int childTwoIndex; 42 | 43 | while (childOneIndex <= endIndex) { 44 | childTwoIndex = 45 | 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; 46 | int indexToSwap; 47 | if (childTwoIndex != -1 && heap[childTwoIndex] < heap[childOneIndex]) { 48 | indexToSwap = childTwoIndex; 49 | } else { 50 | indexToSwap = childOneIndex; 51 | } 52 | 53 | if (heap[currentIndex] > heap[indexToSwap]) { 54 | _swap(currentIndex, indexToSwap, heap); 55 | currentIndex = indexToSwap; 56 | childOneIndex = (2 * currentIndex) + 1; 57 | } else { 58 | break; 59 | } 60 | } 61 | } 62 | 63 | void insert(int value) { 64 | this.heap.add(value); 65 | _siftUp(this.heap.length - 1); 66 | } 67 | 68 | int? remove() { 69 | if (!isEmpty()) { 70 | _swap(0, this.heap.length - 1, this.heap); 71 | int minElement = this.heap.removeLast(); 72 | _siftDown(0, this.heap.length - 1, this.heap); 73 | return minElement; 74 | } 75 | return null; 76 | } 77 | 78 | void _swap(int left, int right, List array) { 79 | int temp; 80 | temp = array[left]; 81 | array[left] = array[right]; 82 | array[right] = temp; 83 | } 84 | } 85 | 86 | void main() { 87 | MinHeap minheap = new MinHeap(); 88 | List array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]; 89 | minheap.buildHeap(array); 90 | test(('Test case 1'), () { 91 | expect(minheap.remove(), equals(-5)); 92 | expect(minheap.isEmpty(), isFalse); 93 | minheap.insert(-100); 94 | expect(minheap.peek(), equals(-100)); 95 | minheap.insert(-100); 96 | expect(minheap.remove(), equals(-100)); 97 | expect(minheap.remove(), equals(-100)); 98 | }); 99 | 100 | test(('Test case 2'), () { 101 | array = [-7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8]; 102 | minheap = new MinHeap(); 103 | minheap.buildHeap(array); 104 | expect(minheap.remove(), equals(-10)); 105 | expect(minheap.peek(), equals(-10)); 106 | minheap.insert(-8); 107 | expect(minheap.peek(), equals(-10)); 108 | expect(minheap.remove(), equals(-10)); 109 | expect(minheap.peek(), equals(-9)); 110 | expect(minheap.isEmpty(), isFalse); 111 | minheap.insert(-8); 112 | expect(minheap.peek(), equals(-9)); 113 | }); 114 | } 115 | -------------------------------------------------------------------------------- /data_structures/Queue/Circular_Queue.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // author: kjain1810 4 | // reference: https://en.wikipedia.org/wiki/Circular_buffer 5 | const int MAX_SIZE = 10; 6 | 7 | class CircularQueue { 8 | int start = -1, end = -1; 9 | List queue = List.filled(MAX_SIZE, null); 10 | 11 | // insert elements into the queue 12 | void enque(T element) { 13 | if (start == -1) { 14 | start = 0; 15 | end = 0; 16 | queue[0] = element; 17 | return; 18 | } 19 | if (end == MAX_SIZE - 1 && start == 0) { 20 | print("The queue is full!!!"); 21 | return; 22 | } 23 | if (end == start - 1) { 24 | print("The queue is full!!!"); 25 | return; 26 | } 27 | end++; 28 | end %= MAX_SIZE; 29 | queue[end] = element; 30 | } 31 | 32 | // remove elements from the queue 33 | T? deque() { 34 | if (start == -1) { 35 | print("The queue is empty!!!"); 36 | return null; 37 | } 38 | T? here = queue[start]; 39 | if (start == end) { 40 | start = -1; 41 | end = -1; 42 | return here; 43 | } 44 | start++; 45 | start %= MAX_SIZE; 46 | return here; 47 | } 48 | 49 | // get the size of the queue 50 | int size() { 51 | if (start == -1) return 0; 52 | if (start < end) return end - start + 1; 53 | return (MAX_SIZE - (start - end)); 54 | } 55 | 56 | // print all the elements of the queue 57 | void printAll() { 58 | if (start == -1) { 59 | print("The queue is empty!!!"); 60 | return; 61 | } 62 | int i = start; 63 | while (i != end) { 64 | i++; 65 | i %= MAX_SIZE; 66 | print(queue[i]); 67 | } 68 | } 69 | } 70 | 71 | void main() { 72 | test("Initial CircularQueue is empty", () { 73 | CircularQueue queue = new CircularQueue(); 74 | 75 | expect(queue.deque(), isNull); 76 | }); 77 | 78 | test("deque return first item put to CircularQueue", () { 79 | CircularQueue queue = new CircularQueue(); 80 | queue.enque(1); 81 | 82 | expect(queue.deque(), equals(1)); 83 | }); 84 | 85 | test("CircularQueue act as fifo", () { 86 | CircularQueue queue = new CircularQueue(); 87 | queue.enque(1); 88 | queue.enque(2); 89 | queue.enque(3); 90 | 91 | expect(queue.deque(), equals(1)); 92 | expect(queue.deque(), equals(2)); 93 | expect(queue.deque(), equals(3)); 94 | }); 95 | 96 | test("deque returns null after removing all items", () { 97 | CircularQueue queue = new CircularQueue(); 98 | queue.enque(1); 99 | queue.enque(2); 100 | queue.enque(3); 101 | 102 | queue.deque(); 103 | queue.deque(); 104 | queue.deque(); 105 | 106 | expect(queue.deque(), isNull); 107 | }); 108 | } 109 | -------------------------------------------------------------------------------- /data_structures/Queue/List_Queue.dart: -------------------------------------------------------------------------------- 1 | //Author:Shawn 2 | //Email:stepfencurryxiao@gmail.com 3 | 4 | const int MAX_SIZE = 10; 5 | 6 | class ListQueue { 7 | int count = 0; 8 | List queue = List.filled(MAX_SIZE, null); 9 | 10 | //Checks if the queue has elements (not empty) 11 | bool hasElements() { 12 | if (queue.length == 0) { 13 | return false; 14 | } else { 15 | return true; 16 | } 17 | } 18 | 19 | //Add an element to the queue 20 | void enque(T element) { 21 | if (count == MAX_SIZE) { 22 | print("The queue is full!!!"); 23 | } else { 24 | queue[count] = element; 25 | count++; 26 | } 27 | } 28 | 29 | //Takes the next element from the queue 30 | T? deque() { 31 | T? result = null; 32 | if (count == 0) { 33 | print("The queue is empty!!!"); 34 | } else { 35 | result = queue[0]; 36 | for (int i = 0; i < queue.length - 1; i++) { 37 | queue[i] = queue[i + 1]; 38 | } 39 | } 40 | return result; 41 | } 42 | } 43 | 44 | void main() { 45 | ListQueue Queue = new ListQueue(); 46 | Queue.enque(12); 47 | Queue.enque(2); 48 | Queue.enque(7); 49 | print(Queue.queue); 50 | print("Enqueue:"); 51 | var returnData = Queue.deque(); 52 | print("$returnData\n"); 53 | print("Enqueue:"); 54 | returnData = Queue.deque(); 55 | print("$returnData\n"); 56 | print("Enqueue:"); 57 | returnData = Queue.deque(); 58 | print("$returnData\n"); 59 | print("Now the queue is: " + (Queue.queue).toString()); 60 | } 61 | -------------------------------------------------------------------------------- /data_structures/Queue/Priority_Queue.dart: -------------------------------------------------------------------------------- 1 | class PriorityQueue { 2 | List> _dataStore = >[]; 3 | 4 | int get size => _dataStore.length; 5 | 6 | bool get isEmpty => _dataStore.isEmpty; 7 | 8 | enqueue(T item, int priority) { 9 | QueueItem queueItem = new QueueItem(item, priority); 10 | bool added = false; 11 | for (int i = 0; i < _dataStore.length; i++) { 12 | if (priority < _dataStore[i].priority) { 13 | added = true; 14 | _dataStore.insert(i, queueItem); 15 | break; 16 | } 17 | } 18 | if (!added) { 19 | _dataStore.add(queueItem); 20 | } 21 | } 22 | 23 | T? dequeue() { 24 | if (_dataStore.isNotEmpty) { 25 | return _dataStore.removeAt(0).item; 26 | } 27 | return null; 28 | } 29 | 30 | T? get front { 31 | if (_dataStore.isNotEmpty) { 32 | return _dataStore.first.item; 33 | } 34 | return null; 35 | } 36 | 37 | T? get end { 38 | if (_dataStore.isNotEmpty) { 39 | return _dataStore.last.item; 40 | } 41 | return null; 42 | } 43 | 44 | clear() { 45 | _dataStore.clear(); 46 | } 47 | 48 | String toString() { 49 | return _dataStore.toString(); 50 | } 51 | } 52 | 53 | class QueueItem { 54 | T item; 55 | int priority; 56 | 57 | QueueItem(this.item, this.priority); 58 | 59 | String toString() { 60 | return '$item - $priority'; 61 | } 62 | } 63 | 64 | void main() { 65 | PriorityQueue queue = new PriorityQueue(); 66 | queue.enqueue(1, 2); 67 | queue.enqueue(2, 1); 68 | queue.enqueue(3, 3); 69 | queue.enqueue(4, 2); 70 | 71 | print(queue.dequeue()); 72 | print(queue.dequeue()); 73 | print(queue.dequeue()); 74 | print(queue.dequeue()); 75 | } 76 | -------------------------------------------------------------------------------- /data_structures/Stack/Array_Stack.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/expect.dart'; 2 | import 'package:test/scaffolding.dart'; 3 | 4 | class ArrayStack { 5 | /// [stack] 6 | List _stack = []; 7 | 8 | /// [_count] is the number of element in the stack 9 | int _count = 0; 10 | 11 | /// [_size] of stack 12 | int _size = 0; 13 | 14 | //Init the array stack 15 | ArrayStack(int size) { 16 | this._size = size; 17 | this._stack = List.filled(_size, null); 18 | this._count = 0; 19 | } 20 | 21 | /// Push a item to the stack of type [T] to the [_stack] 22 | /// if the size is exceeded the element wont be added. 23 | void push(T item) { 24 | if (_count == _size) { 25 | return null; 26 | } 27 | _stack[_count] = item; 28 | _count++; 29 | } 30 | 31 | /// Pop the last element inserted from the [_stack]. 32 | T? pop() { 33 | if (_count == 0) { 34 | return null; 35 | } 36 | T? pop_data = _stack[_count - 1]; 37 | _stack[_count - 1] = null; 38 | _count--; 39 | return pop_data; 40 | } 41 | 42 | List get stack { 43 | return _stack; 44 | } 45 | } 46 | 47 | void main() { 48 | ArrayStack arrayStack = new ArrayStack(6); 49 | 50 | arrayStack.push('1'); 51 | arrayStack.push("2"); 52 | arrayStack.push('3'); 53 | arrayStack.push("4"); 54 | arrayStack.push('5'); 55 | arrayStack.push("6"); 56 | 57 | test('test case 1', () { 58 | expect(arrayStack.stack, ['1', '2', '3', '4', '5', '6']); 59 | }); 60 | 61 | test('test case 2: pop stack', () { 62 | expect('6', arrayStack.pop()); 63 | }); 64 | 65 | test('test case 3: pop stack', () { 66 | expect('5', arrayStack.pop()); 67 | }); 68 | 69 | test('test case 4: pop stack', () { 70 | expect('4', arrayStack.pop()); 71 | }); 72 | 73 | test('test case 5: pop stack', () { 74 | expect('3', arrayStack.pop()); 75 | }); 76 | 77 | test('test case 6: pop stack', () { 78 | expect('2', arrayStack.pop()); 79 | }); 80 | 81 | test('test case 7: pop stack', () { 82 | expect('1', arrayStack.pop()); 83 | }); 84 | 85 | test('test case 8: pop stack', () { 86 | expect(null, arrayStack.pop()); 87 | }); 88 | 89 | ArrayStack arrayStack2 = new ArrayStack(3); 90 | 91 | test('test case 9', () { 92 | expect(arrayStack2.stack, [null, null, null]); 93 | }); 94 | } 95 | -------------------------------------------------------------------------------- /data_structures/Stack/Linked_List_Stack.dart: -------------------------------------------------------------------------------- 1 | //Author: Shawn 2 | //Email: stepfencurryxiao@gmail.com 3 | 4 | class Node { 5 | //the data of the Node 6 | T? data; 7 | Node? next; 8 | 9 | Node(T? data) { 10 | this.data = data; 11 | this.next = null; 12 | } 13 | } 14 | 15 | class LinkedListStack { 16 | //Top of stack 17 | Node? head; 18 | 19 | //Size of stack 20 | int size = 0; 21 | 22 | LinkedListStack() { 23 | this.head = null; 24 | this.size = 0; 25 | } 26 | 27 | //Add element at top of the stack 28 | 29 | void push(T element) { 30 | Node newNode = new Node(element); 31 | newNode.next = this.head; 32 | this.head = newNode; 33 | this.size++; 34 | } 35 | 36 | //Pop element from top at the stack 37 | 38 | T? pop() { 39 | T? returnData = null; 40 | if (size == 0) { 41 | print("The stack is empty!!!"); 42 | } else { 43 | Node? destroy = this.head; 44 | this.head = this.head?.next; 45 | returnData = destroy?.data; 46 | this.size--; 47 | } 48 | return returnData; 49 | } 50 | 51 | bool isEmpty() { 52 | return this.size == 0; 53 | } 54 | 55 | int getSize() { 56 | return this.size; 57 | } 58 | } 59 | 60 | int main() { 61 | LinkedListStack Stack = new LinkedListStack(); 62 | var returnData; 63 | print("Push 2 5 9 7 to the stack\n"); 64 | Stack.push("2"); 65 | Stack.push("5"); 66 | Stack.push("9"); 67 | Stack.push("7"); 68 | print("Successful push!\n"); 69 | returnData = Stack.pop(); 70 | print("Pop a data: $returnData\n"); 71 | returnData = Stack.pop(); 72 | print("Pop a data: $returnData\n"); 73 | returnData = Stack.pop(); 74 | print("Pop a data: $returnData\n"); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /data_structures/Stack/balanced_brackets.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | import 'package:stack/stack.dart'; 3 | 4 | bool isBalancedBrackets(String string) { 5 | Stack stack = Stack(); 6 | 7 | List openingBrackets = ['(', '{', '[']; 8 | final Map matchingBracket = {'}': '{', ')': '(', ']': '['}; 9 | 10 | for (int i = 0; i < string.length; i++) { 11 | var currentChar = string[i]; 12 | 13 | if (openingBrackets.contains(currentChar)) { 14 | stack.push(currentChar); 15 | } else { 16 | if (stack.isNotEmpty) { 17 | if (stack.top() == matchingBracket[currentChar]) { 18 | stack.pop(); 19 | } else { 20 | return false; 21 | } 22 | } else { 23 | return false; 24 | } 25 | } 26 | } 27 | return stack.isEmpty; 28 | } 29 | 30 | void main() { 31 | test(('Balanced Bracket'), () { 32 | expect(isBalancedBrackets('([])(){}(())()()'), isTrue); 33 | }); 34 | 35 | test(('Balanced Bracket'), () { 36 | expect(isBalancedBrackets('()[]{}{'), isFalse); 37 | }); 38 | 39 | test(('Balanced Bracket'), () { 40 | expect(isBalancedBrackets('()()[{()})]'), isFalse); 41 | }); 42 | 43 | test(('Balanced Bracket'), () { 44 | expect(isBalancedBrackets('()([])'), isTrue); 45 | }); 46 | 47 | test(('Balanced Bracket'), () { 48 | expect( 49 | isBalancedBrackets( 50 | '(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), 51 | isTrue); 52 | }); 53 | } 54 | -------------------------------------------------------------------------------- /data_structures/binary_tree/basic_binary_tree.dart: -------------------------------------------------------------------------------- 1 | //Author:Shawn 2 | //Email:stepfencurryxiao@gmail.com 3 | 4 | /*This is Class Node with constructor that contains 5 | * data variable to type data and left,right pointers 6 | */ 7 | class Node { 8 | var data; 9 | var left; 10 | var right; 11 | 12 | Node(var data) { 13 | this.data = data; 14 | this.left = null; 15 | this.right = null; 16 | } 17 | } 18 | 19 | /*In order traversal of the tree*/ 20 | void display(var tree) { 21 | if (tree == null) { 22 | return; 23 | } 24 | 25 | if (tree.left != null) { 26 | display(tree.left); 27 | } 28 | 29 | print(tree.data); 30 | 31 | if (tree.right != null) { 32 | display(tree.right); 33 | } 34 | 35 | return; 36 | } 37 | 38 | /* 39 | *This is the recursive function to find the depth of 40 | * binary tree. 41 | */ 42 | double depth_of_tree(var tree) { 43 | if (tree == null) { 44 | return 0; 45 | } else { 46 | var depth_l_tree = depth_of_tree(tree.left); 47 | var depth_r_tree = depth_of_tree(tree.right); 48 | 49 | if (depth_l_tree > depth_r_tree) { 50 | return (1 + depth_l_tree); 51 | } else { 52 | return (1 + depth_r_tree); 53 | } 54 | } 55 | } 56 | 57 | /*This function returns that is it full binary tree or not*/ 58 | bool is_full_binary_tree(var tree) { 59 | if (tree == null) { 60 | return true; 61 | } 62 | if (tree.left == null && tree.right == null) { 63 | return true; 64 | } 65 | if (tree.left != null && tree.right != null) { 66 | return (is_full_binary_tree(tree.left) && is_full_binary_tree(tree.right)); 67 | } else { 68 | return false; 69 | } 70 | } 71 | 72 | //Main function for testing 73 | void main() { 74 | var tree = Node(1); 75 | tree.left = Node(2); 76 | tree.right = Node(3); 77 | tree.left.left = Node(4); 78 | tree.left.right = Node(5); 79 | tree.left.right.left = Node(6); 80 | tree.right.left = Node(7); 81 | tree.right.left.left = Node(8); 82 | tree.right.left.left.right = Node(9); 83 | 84 | print(is_full_binary_tree(tree)); 85 | print(depth_of_tree(tree)); 86 | print("Tree is:\n"); 87 | display(tree); 88 | } 89 | -------------------------------------------------------------------------------- /data_structures/binary_tree/binary_tree_traversal.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | import 'package:test/test.dart'; 4 | 5 | class TreeNode { 6 | int? data; 7 | TreeNode? leftNode = null; 8 | TreeNode? rightNode = null; 9 | 10 | int? get value { 11 | return this.data; 12 | } 13 | 14 | TreeNode? get left { 15 | return this.leftNode; 16 | } 17 | 18 | void set left(TreeNode? value) { 19 | this.leftNode = value; 20 | } 21 | 22 | void set right(TreeNode? value) { 23 | this.rightNode = value; 24 | } 25 | 26 | TreeNode? get right { 27 | return this.rightNode; 28 | } 29 | 30 | TreeNode(this.data); 31 | } 32 | 33 | List inOrder(TreeNode? root, List result) { 34 | if (root != null) { 35 | inOrder(root.left, result); 36 | result.add(root.value); 37 | inOrder(root.right, result); 38 | } 39 | return result; 40 | } 41 | 42 | List preOrder(TreeNode? root, List result) { 43 | if (root != null) { 44 | result.add(root.value); 45 | preOrder(root.left, result); 46 | preOrder(root.right, result); 47 | } 48 | return result; 49 | } 50 | 51 | List postOrder(TreeNode? root, List result) { 52 | if (root != null) { 53 | postOrder(root.left, result); 54 | postOrder(root.right, result); 55 | result.add(root.value); 56 | } 57 | return result; 58 | } 59 | 60 | List levelOrder(TreeNode? root, List result) { 61 | Queue q = Queue(); 62 | if (root != null) { 63 | q.add(root); 64 | } 65 | 66 | while (!q.isEmpty) { 67 | TreeNode? curr = q.first; 68 | q.removeFirst(); 69 | result.add(curr?.data); 70 | if (curr?.left != null) { 71 | q.addLast(curr?.left); 72 | } 73 | if (curr?.right != null) { 74 | q.addLast(curr?.right); 75 | } 76 | } 77 | 78 | return result; 79 | } 80 | 81 | void main() { 82 | TreeNode? root = TreeNode(1); 83 | root.left = TreeNode(2); 84 | root.right = TreeNode(3); 85 | root.left?.left = TreeNode(4); 86 | root.left?.right = TreeNode(5); 87 | root.left?.right?.left = TreeNode(6); 88 | root.right?.left = TreeNode(7); 89 | root.right?.left?.left = TreeNode(8); 90 | root.right?.left?.left?.right = TreeNode(9); 91 | 92 | List result; 93 | result = List.empty(growable: true); 94 | 95 | test(('inOrder traversal'), () { 96 | result = List.empty(growable: true); 97 | expect(inOrder(root, result), equals([4, 2, 6, 5, 1, 8, 9, 7, 3])); 98 | }); 99 | 100 | test(('preOrder traversal'), () { 101 | result = List.empty(growable: true); 102 | expect(preOrder(root, result), equals([1, 2, 4, 5, 6, 3, 7, 8, 9])); 103 | }); 104 | 105 | test(('postOrder traversal'), () { 106 | result = List.empty(growable: true); 107 | expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); 108 | }); 109 | 110 | test(('levelOrder traversal'), () { 111 | // https://www.geeksforgeeks.org/level-order-tree-traversal/ 112 | result = List.empty(growable: true); 113 | expect(levelOrder(root, result), equals([1, 2, 3, 4, 5, 7, 6, 8, 9])); 114 | }); 115 | 116 | test(('postOrder traversal'), () { 117 | result = List.empty(growable: true); 118 | root = null; 119 | expect(postOrder(root, result), equals([])); 120 | }); 121 | 122 | test(('inOrder traversal'), () { 123 | result = List.empty(growable: true); 124 | root = null; 125 | expect(inOrder(root, result), equals([])); 126 | }); 127 | 128 | test(('preOrder traversal'), () { 129 | result = List.empty(growable: true); 130 | root = null; 131 | expect(preOrder(root, result), equals([])); 132 | }); 133 | 134 | test(('levelOrder traversal'), () { 135 | result = List.empty(growable: true); 136 | root = null; 137 | expect(levelOrder(root, result), equals([])); 138 | }); 139 | } 140 | -------------------------------------------------------------------------------- /data_structures/linked_list/cycle_in_linked_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'package:test/test.dart'; 3 | 4 | class Node { 5 | int value; 6 | Node? next = null; 7 | Node(this.value); 8 | 9 | int get nodeValue { 10 | return this.value; 11 | } 12 | 13 | Node? get nextNode { 14 | return this.next; 15 | } 16 | } 17 | 18 | class LinkedList { 19 | Node? _headNode; 20 | Node? _tailNode; 21 | 22 | Node? get head { 23 | return this._headNode; 24 | } 25 | 26 | Node? get tail { 27 | return this._tailNode; 28 | } 29 | 30 | void insert(Node? newNode) { 31 | if (head == null) { 32 | this._headNode = newNode; 33 | this._tailNode = newNode; 34 | } else { 35 | this._tailNode?.next = newNode; 36 | this._tailNode = this._tailNode?.next; 37 | } 38 | } 39 | } 40 | 41 | Node createNode(int value) { 42 | return Node(value); 43 | } 44 | 45 | Node? findCyclicNode(Node? headNode) { 46 | /// Check : https://en.wikipedia.org/wiki/Cycle_detection 47 | /// we maintain a fast and slow pointer 48 | /// The fast pointer jumps 2 nodes at a time 49 | /// and the slow pointer jumps one node at a time 50 | /// eventually the fast and slow will coincide on a node 51 | /// 52 | /// Then we place one of the node back to the head. 53 | /// The node where these two nodes coincide again will be the 54 | /// origin of the loop node. 55 | /// and move in tandem. check algorith for proof 56 | Node? fastNode = headNode; 57 | Node? slowNode = headNode; 58 | 59 | while (fastNode != null && fastNode.next != null) { 60 | slowNode = slowNode?.next; 61 | fastNode = fastNode.next?.next; 62 | 63 | if (slowNode == fastNode) { 64 | break; 65 | } 66 | } 67 | 68 | if (slowNode == fastNode) { 69 | slowNode = headNode; 70 | while (slowNode != fastNode) { 71 | slowNode = slowNode?.next; 72 | fastNode = fastNode?.next; 73 | } 74 | return slowNode; 75 | } else { 76 | return null; 77 | } 78 | } 79 | 80 | void main() { 81 | LinkedList linkedList = LinkedList(); 82 | List allNodes = []; 83 | for (var i = 0; i <= 10; i++) { 84 | Node newNode = createNode(i); 85 | linkedList.insert(newNode); 86 | allNodes.add(newNode); 87 | } 88 | Node? tail = linkedList.tail; 89 | Random random = new Random(); 90 | 91 | test(('test 1'), () { 92 | int randomIndex = random.nextInt(9); 93 | tail?.next = allNodes[randomIndex]; 94 | Node? cycleNode = findCyclicNode(linkedList.head); 95 | expect(cycleNode, equals(allNodes[randomIndex])); 96 | }); 97 | test(('test 2'), () { 98 | int randomIndex = random.nextInt(9); 99 | tail?.next = allNodes[randomIndex]; 100 | Node? cycleNode = findCyclicNode(linkedList.head); 101 | expect(cycleNode, equals(allNodes[randomIndex])); 102 | }); 103 | 104 | test(('test 3'), () { 105 | int randomIndex = random.nextInt(9); 106 | tail?.next = allNodes[randomIndex]; 107 | Node? cycleNode = findCyclicNode(linkedList.head); 108 | expect(cycleNode, equals(allNodes[randomIndex])); 109 | }); 110 | 111 | test(('test 4'), () { 112 | int randomIndex = random.nextInt(9); 113 | tail?.next = allNodes[randomIndex]; 114 | Node? cycleNode = findCyclicNode(linkedList.head); 115 | expect(cycleNode, equals(allNodes[randomIndex])); 116 | }); 117 | 118 | test(('test 5'), () { 119 | int randomIndex = random.nextInt(9); 120 | tail?.next = allNodes[randomIndex]; 121 | Node? cycleNode = findCyclicNode(linkedList.head); 122 | expect(cycleNode, equals(allNodes[randomIndex])); 123 | }); 124 | 125 | test(('test 6'), () { 126 | int randomIndex = random.nextInt(9); 127 | tail?.next = allNodes[randomIndex]; 128 | Node? cycleNode = findCyclicNode(linkedList.head); 129 | expect(cycleNode, equals(allNodes[randomIndex])); 130 | }); 131 | 132 | test(('test 7'), () { 133 | int randomIndex = random.nextInt(9); 134 | tail?.next = allNodes[randomIndex]; 135 | Node? cycleNode = findCyclicNode(linkedList.head); 136 | expect(cycleNode, equals(allNodes[randomIndex])); 137 | }); 138 | } 139 | -------------------------------------------------------------------------------- /data_structures/linked_list/linked_list.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | class Node { 4 | Node? next; 5 | T? value; 6 | 7 | Node(this.value); 8 | Node.before(this.next, this.value); 9 | } 10 | 11 | class LinkedListIterator extends Iterator { 12 | Node? _current; 13 | 14 | @override 15 | bool moveNext() => _current != null; 16 | 17 | @override 18 | T? get current { 19 | T? currentValue = this._current?.value; 20 | 21 | this._current = this._current?.next; 22 | 23 | return currentValue; 24 | } 25 | 26 | LinkedListIterator(this._current); 27 | } 28 | 29 | class LinkedList extends Iterable { 30 | int _length = 0; 31 | int get length => this._length; 32 | 33 | Node? _head; 34 | 35 | @override 36 | Iterator get iterator => new LinkedListIterator(this._head); 37 | 38 | void remove(T? item) { 39 | if (this._head?.value == item) { 40 | this._head = this._head?.next; 41 | this._length--; 42 | } 43 | 44 | if (this._head != null) { 45 | Node? current = this._head; 46 | while (current?.next != null) { 47 | if (current?.next?.value == item) { 48 | current?.next = current.next?.next; 49 | this._length--; 50 | } 51 | 52 | current = current?.next; 53 | } 54 | } 55 | } 56 | 57 | T? pop() { 58 | if (this._head != null) { 59 | T? value = this._head?.value; 60 | this._head = this._head?.next; 61 | this._length--; 62 | 63 | return value; 64 | } 65 | 66 | return null; 67 | } 68 | 69 | void push(T item) { 70 | this._head = new Node.before(this._head, item); 71 | this._length++; 72 | } 73 | 74 | void add(T? item) { 75 | if (this._head == null) { 76 | this._head = new Node(item); 77 | } else { 78 | Node? current = this._head; 79 | while (current?.next != null) { 80 | current = current?.next; 81 | } 82 | 83 | current?.next = Node(item); 84 | } 85 | this._length++; 86 | } 87 | } 88 | 89 | main() { 90 | test(".add is adding elements in order", () { 91 | LinkedList linkedList = new LinkedList(); 92 | linkedList.add(1); 93 | linkedList.add(2); 94 | linkedList.add(3); 95 | 96 | expect(linkedList, equals([1, 2, 3])); 97 | }); 98 | 99 | test(".remove is removing all elements with given value", () { 100 | LinkedList linkedList = new LinkedList(); 101 | linkedList.add(1); 102 | linkedList.add(2); 103 | linkedList.add(3); 104 | linkedList.add(2); 105 | 106 | linkedList.remove(2); 107 | 108 | expect(linkedList, equals([1, 3])); 109 | }); 110 | 111 | test(".remove on empty list do nothing", () { 112 | LinkedList linkedList = new LinkedList(); 113 | 114 | linkedList.remove(2); 115 | 116 | expect(linkedList, isEmpty); 117 | }); 118 | 119 | test(".push is appending first element", () { 120 | LinkedList linkedList = new LinkedList(); 121 | 122 | linkedList.push(1); 123 | expect(linkedList, equals([1])); 124 | 125 | linkedList.push(2); 126 | expect(linkedList, equals([2, 1])); 127 | 128 | linkedList.push(3); 129 | expect(linkedList, equals([3, 2, 1])); 130 | }); 131 | 132 | test(".pop is returning and removing first element", () { 133 | LinkedList linkedList = new LinkedList(); 134 | 135 | linkedList.add(1); 136 | linkedList.add(2); 137 | linkedList.add(3); 138 | 139 | expect(linkedList.pop(), equals(1)); 140 | expect(linkedList, equals([2, 3])); 141 | 142 | expect(linkedList.pop(), equals(2)); 143 | expect(linkedList, equals([3])); 144 | 145 | expect(linkedList.pop(), equals(3)); 146 | expect(linkedList, equals([])); 147 | }); 148 | 149 | test(".pop is returning null when list is empty", () { 150 | LinkedList linkedList = new LinkedList(); 151 | 152 | expect(linkedList.pop(), isNull); 153 | }); 154 | } 155 | -------------------------------------------------------------------------------- /data_structures/linked_list/merge_sorted_list.dart: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-sorted-lists/ 2 | import 'package:test/test.dart'; 3 | 4 | class ListNode { 5 | int? val; 6 | ListNode? next; 7 | ListNode({this.val = 0, this.next}); 8 | } 9 | 10 | extension PrintLinkedList on ListNode? { 11 | void printLinkedList() { 12 | ListNode? node = this; 13 | while (node != null) { 14 | print(node.val); 15 | node = node.next; 16 | } 17 | } 18 | 19 | List listValues() { 20 | List values = []; 21 | ListNode? node = this; 22 | while (node != null) { 23 | values.add(node.val); 24 | node = node.next; 25 | } 26 | return values; 27 | } 28 | } 29 | 30 | ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { 31 | if (list1 == null) { 32 | return list2; 33 | } else if (list2 == null) { 34 | return list1; 35 | } 36 | ListNode head = list1; 37 | 38 | if ((list1.val ?? 0) < (list2.val ?? 0)) { 39 | head = list1; 40 | list1 = list1.next; 41 | } else { 42 | head = list2; 43 | list2 = list2.next; 44 | } 45 | 46 | ListNode? node = head; 47 | 48 | while (list1 != null || list2 != null) { 49 | if (list1 != null && list2 != null) { 50 | if ((list1.val ?? 0) < (list2.val ?? 0)) { 51 | node?.next = list1; 52 | list1 = list1.next; 53 | } else { 54 | node?.next = list2; 55 | list2 = list2.next; 56 | } 57 | } else if (list1 != null) { 58 | node?.next = list1; 59 | list1 = list1.next; 60 | } else { 61 | node?.next = list2; 62 | list2 = list2?.next; 63 | } 64 | 65 | node = node?.next; 66 | } 67 | return head; 68 | } 69 | 70 | void main() { 71 | test('test case 1', () { 72 | ListNode head1 = 73 | ListNode(val: 1, next: ListNode(val: 2, next: ListNode(val: 4))); 74 | ListNode head2 = 75 | ListNode(val: 1, next: ListNode(val: 3, next: ListNode(val: 4))); 76 | expect(mergeTwoLists(head1, head2).listValues(), [1, 1, 2, 3, 4, 4]); 77 | }); 78 | 79 | test('test case 2', () { 80 | ListNode head1 = 81 | ListNode(val: 1, next: ListNode(val: 2, next: ListNode(val: 3))); 82 | ListNode head2 = 83 | ListNode(val: 4, next: ListNode(val: 5, next: ListNode(val: 6))); 84 | expect(mergeTwoLists(head1, head2).listValues(), [1, 2, 3, 4, 5, 6]); 85 | }); 86 | } 87 | -------------------------------------------------------------------------------- /dynamic_programming/01knapsack_recursive.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'package:test/test.dart'; 3 | 4 | int knapSackProblem(int capacity, List values, List weights, 5 | [int? numberOfItems]) { 6 | numberOfItems ??= values.length; 7 | if (numberOfItems == 0 || capacity == 0) { 8 | return 0; 9 | } 10 | int currentValue = values[numberOfItems - 1]; 11 | int currentWeight = weights[numberOfItems - 1]; 12 | 13 | if (weights[numberOfItems - 1] <= capacity) { 14 | return max( 15 | currentValue + 16 | knapSackProblem( 17 | capacity - currentWeight, values, weights, numberOfItems - 1), 18 | knapSackProblem(capacity, values, weights, numberOfItems - 1)); 19 | } else { 20 | return knapSackProblem(capacity, values, weights, numberOfItems - 1); 21 | } 22 | } 23 | 24 | void main() { 25 | int ans = knapSackProblem(10, [1, 4, 5, 6], [2, 3, 6, 7]); 26 | print(ans); 27 | 28 | test('TC: 1', () { 29 | expect(knapSackProblem(10, [1, 4, 5, 6], [2, 3, 6, 7]), 10); 30 | }); 31 | 32 | ans = knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]); 33 | print(ans); 34 | 35 | test('TC: 2', () { 36 | expect( 37 | knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), 101); 38 | }); 39 | } 40 | -------------------------------------------------------------------------------- /dynamic_programming/coin_change.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'package:test/test.dart'; 3 | 4 | /// we build an array which calculates the min coins for all amounts upto n 5 | /// 6 | /// bottom up approach where we calculate the number of coins used for each 7 | /// amount from 1 to n for each coin. 8 | /// time complexity O(targetAmount * coinDenoms) 9 | /// space complexity O(targetAmount) 10 | int minNumberOfCoins(int targetAmount, List coinDenoms) { 11 | List amounts = 12 | new List.generate(targetAmount + 1, (int index) => 1000000000000); 13 | 14 | amounts[0] = 0; 15 | 16 | for (int currentCoin in coinDenoms) { 17 | for (int amount = currentCoin; amount <= targetAmount; amount++) { 18 | amounts[amount] = min(amounts[amount], amounts[amount - currentCoin] + 1); 19 | } 20 | } 21 | if (amounts[targetAmount] != 1000000000000) { 22 | return amounts[targetAmount]; 23 | } 24 | return -1; 25 | } 26 | 27 | void main() { 28 | test(('testCase #1'), () { 29 | expect(minNumberOfCoins(7, [1, 5, 10]), equals(3)); 30 | }); 31 | 32 | test(('testCase #2'), () { 33 | expect(minNumberOfCoins(7, [3, 5]), equals(-1)); 34 | }); 35 | 36 | test(('testCase #3'), () { 37 | expect(minNumberOfCoins(9, [3, 4, 5]), equals(2)); 38 | }); 39 | } 40 | -------------------------------------------------------------------------------- /dynamic_programming/kadanes_algorithm.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | import 'dart:math'; 3 | 4 | int kadanesAlgorithm(List array) { 5 | int maxEndingHere = array[0]; 6 | int maxSoFar = array[0]; 7 | 8 | for (int num in array.sublist(1, array.length)) { 9 | maxEndingHere = max(maxEndingHere + num, num); 10 | maxSoFar = max(maxSoFar, maxEndingHere); 11 | } 12 | return maxSoFar; 13 | } 14 | 15 | void main() { 16 | List array; 17 | int maxContiniousSubarraySum; 18 | 19 | test(('.Check the response for each test case'), () { 20 | array = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]; 21 | 22 | maxContiniousSubarraySum = kadanesAlgorithm(array); 23 | expect(maxContiniousSubarraySum, equals(19)); 24 | }); 25 | 26 | test(('.Check the response for each test case'), () { 27 | array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 28 | maxContiniousSubarraySum = kadanesAlgorithm(array); 29 | expect(maxContiniousSubarraySum, equals(55)); 30 | }); 31 | 32 | test(('.Check the response for each test case'), () { 33 | array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; 34 | maxContiniousSubarraySum = kadanesAlgorithm(array); 35 | expect(maxContiniousSubarraySum, equals(-1)); 36 | }); 37 | 38 | test(('.Check the response for each test case'), () { 39 | array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; 40 | maxContiniousSubarraySum = kadanesAlgorithm(array); 41 | expect(maxContiniousSubarraySum, equals(34)); 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /dynamic_programming/longest_common_subsequence.dart: -------------------------------------------------------------------------------- 1 | // Longest Common Subsequence Editorial: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ 2 | //Longest Common Subsequence Wiki: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem 3 | import 'dart:math'; 4 | import 'package:test/test.dart'; 5 | 6 | int longestCommonSubsequence(String text1, String text2) { 7 | int m = text1.length; 8 | int n = text2.length; 9 | 10 | // BottomUp Tabulation 11 | List> dp = List.generate(m + 1, (_) => List.filled(n + 1, 0)); 12 | for (int i = 1; i <= m; i++) { 13 | for (int j = 1; j <= n; j++) { 14 | if (text1[i - 1] == text2[j - 1]) { 15 | dp[i][j] = 1 + dp[i - 1][j - 1]; 16 | continue; 17 | } 18 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 19 | } 20 | } 21 | return dp[m][n]; 22 | } 23 | 24 | void main() { 25 | test(('testCase #1'), () { 26 | expect(longestCommonSubsequence("", ""), equals(0)); 27 | }); 28 | 29 | test(('testCase #2'), () { 30 | expect(longestCommonSubsequence("", "abcd"), equals(0)); 31 | }); 32 | test(('testCase #3'), () { 33 | expect(longestCommonSubsequence("abcd", ""), equals(0)); 34 | }); 35 | test(('testCase #4'), () { 36 | expect(longestCommonSubsequence("abcd", "c"), equals(1)); 37 | }); 38 | test(('testCase #5'), () { 39 | expect(longestCommonSubsequence("abcd", "d"), equals(1)); 40 | }); 41 | test(('testCase #6'), () { 42 | expect(longestCommonSubsequence("abcd", "e"), equals(0)); 43 | }); 44 | test(('testCase #7'), () { 45 | expect(longestCommonSubsequence("abcdefghi", "acegi"), equals(5)); 46 | }); 47 | test(('testCase #8'), () { 48 | expect(longestCommonSubsequence("abcdgh", "aedfhr"), equals(3)); 49 | }); 50 | test(('testCase #9'), () { 51 | expect(longestCommonSubsequence("aggtab", "gxtxayb"), equals(4)); 52 | }); 53 | test(('testCase #10'), () { 54 | expect(longestCommonSubsequence("ggg", "g"), equals(1)); 55 | }); 56 | } 57 | -------------------------------------------------------------------------------- /dynamic_programming/longest_common_substring.dart: -------------------------------------------------------------------------------- 1 | // Longest Common Substring Editorial: https://www.geeksforgeeks.org/longest-common-substring-dp-29/ 2 | //Longest Common Substring Wiki: https://en.wikipedia.org/wiki/Longest_common_substring_problem 3 | 4 | import 'dart:math'; 5 | import 'package:test/test.dart'; 6 | 7 | int longestCommonSubstring(String text1, String text2) { 8 | int m = text1.length; 9 | int n = text2.length; 10 | 11 | // BottomUp Tabulation 12 | List> dp = List.generate(m + 1, (_) => List.filled(n + 1, 0)); 13 | int ans = 0; 14 | for (int i = 1; i <= m; i++) { 15 | for (int j = 1; j <= n; j++) { 16 | if (text1[i - 1] == text2[j - 1]) { 17 | dp[i][j] = 1 + dp[i - 1][j - 1]; 18 | ans = max(ans, dp[i][j]); 19 | } 20 | } 21 | } 22 | return ans; 23 | } 24 | 25 | void main() { 26 | test(('testCase #1'), () { 27 | expect(longestCommonSubstring("", ""), equals(0)); 28 | }); 29 | 30 | test(('testCase #2'), () { 31 | expect(longestCommonSubstring("a", ""), equals(0)); 32 | }); 33 | test(('testCase #3'), () { 34 | expect(longestCommonSubstring("", "a"), equals(0)); 35 | }); 36 | test(('testCase #4'), () { 37 | expect(longestCommonSubstring("c", "c"), equals(1)); 38 | }); 39 | test(('testCase #5'), () { 40 | expect(longestCommonSubstring("abcdef", "bcd"), equals(3)); 41 | }); 42 | test(('testCase #6'), () { 43 | expect(longestCommonSubstring("abcdef", "xabded"), equals(2)); 44 | }); 45 | test(('testCase #7'), () { 46 | expect(longestCommonSubstring("GeeksforGeeks", "GeeksQuiz"), equals(5)); 47 | }); 48 | test(('testCase #8'), () { 49 | expect(longestCommonSubstring("abcdxyz", "xyzabcd"), equals(4)); 50 | }); 51 | test(('testCase #9'), () { 52 | expect(longestCommonSubstring("zxabcdezy", "yzabcdezx"), equals(6)); 53 | }); 54 | test(('testCase #10'), () { 55 | expect( 56 | longestCommonSubstring( 57 | "OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com"), 58 | equals(10)); 59 | }); 60 | } 61 | -------------------------------------------------------------------------------- /dynamic_programming/min_number_of_jumps.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'package:test/test.dart'; 3 | 4 | int minimumNumberOfJumps(List array) { 5 | List jumps = List.generate((array.length), (index) => 1000000000000); 6 | jumps[0] = 0; 7 | int length = array.length; 8 | for (int i = 1; i < length; i++) { 9 | for (int j = 0; j < i; j++) { 10 | if (array[j] + j >= i) { 11 | jumps[i] = min(jumps[j] + 1, jumps[i]); 12 | } 13 | } 14 | } 15 | return jumps[length - 1]; 16 | } 17 | 18 | void main() { 19 | List array; 20 | test('test 1', () { 21 | array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]; 22 | expect(minimumNumberOfJumps(array), 4); 23 | }); 24 | test('test 2', () { 25 | array = [1]; 26 | expect(minimumNumberOfJumps(array), 0); 27 | }); 28 | test('test 3', () { 29 | array = [1, 1]; 30 | expect(minimumNumberOfJumps(array), 1); 31 | }); 32 | test('test 4', () { 33 | array = [1, 1, 1]; 34 | expect(minimumNumberOfJumps(array), 2); 35 | }); 36 | test('test 5', () { 37 | array = [2, 1, 2, 3, 1, 1, 1]; 38 | expect(minimumNumberOfJumps(array), 3); 39 | }); 40 | test('test 6', () { 41 | array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3, 2, 3, 2, 1, 1, 1, 1]; 42 | expect(minimumNumberOfJumps(array), 7); 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /graphs/area_of_island.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | extension MinMax on List { 4 | int get max { 5 | num maxNumber = double.negativeInfinity; 6 | for (int i = 0; i < length; ++i) { 7 | if (maxNumber < this[i]) { 8 | maxNumber = this[i]; 9 | } 10 | } 11 | if (maxNumber != double.negativeInfinity) { 12 | return maxNumber.toInt(); 13 | } 14 | return 0; 15 | } 16 | } 17 | 18 | const List> deltas = [ 19 | [-1, 0], // top neighbour 20 | [0, 1], // right neighbour 21 | [1, 0], // bottom neighbour 22 | [0, -1] // left neighbour. 23 | ]; 24 | 25 | int maxAreaOfIsland(List> grid) { 26 | int numRows = grid.length; 27 | int numCols = grid[0].length; 28 | List> visited = 29 | List.generate(numRows, (int index) => List.filled(numCols, false)); 30 | 31 | List areas = []; 32 | for (int i = 0; i < numRows; ++i) { 33 | for (int j = 0; j < numCols; ++j) { 34 | if (visited[i][j] || grid[i][j] == 0) continue; 35 | traverseNode(i, j, grid, visited, areas); 36 | } 37 | } 38 | return areas.max; 39 | } 40 | 41 | bool isInvalidIndex(int i, int j, int rowCount, int colCount) { 42 | return (i < 0 || i >= rowCount || j >= colCount || j < 0); 43 | } 44 | 45 | List> adjacentNodes( 46 | List> grid, List> visited, int x, int y) { 47 | List> nodes = []; 48 | for (int i = 0; i < deltas.length; ++i) { 49 | int dx = x + deltas[i][0]; 50 | int dy = y + deltas[i][1]; 51 | 52 | if (isInvalidIndex(dx, dy, grid.length, grid[0].length)) continue; 53 | if (visited[dx][dy] || grid[dx][dy] == 0) continue; 54 | 55 | nodes.add([dx, dy]); 56 | } 57 | return nodes; 58 | } 59 | 60 | void traverseNode(int i, int j, List> grid, List> visited, 61 | List areas) { 62 | int area = 0; 63 | List> nodesToExplore = [ 64 | [i, j] 65 | ]; 66 | while (nodesToExplore.isNotEmpty) { 67 | List node = nodesToExplore.removeLast(); 68 | 69 | int x = node[0]; 70 | int y = node[1]; 71 | 72 | if (visited[x][y]) continue; 73 | visited[x][y] = true; 74 | if (grid[x][y] == 0) continue; 75 | 76 | area += 1; 77 | nodesToExplore.addAll(adjacentNodes(grid, visited, x, y)); 78 | } 79 | if (area > 0) { 80 | areas.add(area); 81 | } 82 | } 83 | 84 | void main() { 85 | test('test case 1', () { 86 | List> island = [ 87 | [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], 88 | [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 89 | [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 90 | [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], 91 | [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], 92 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 93 | [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 94 | [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0] 95 | ]; 96 | expect(maxAreaOfIsland(island), 6); 97 | }); 98 | 99 | test('test case 2', () { 100 | List> island = [ 101 | [0, 0, 1], 102 | [0, 0, 0], 103 | [0, 1, 1], 104 | ]; 105 | expect(maxAreaOfIsland(island), 2); 106 | }); 107 | 108 | test('test case 3', () { 109 | List> island = [ 110 | [0, 0, 0], 111 | [0, 0, 0], 112 | [0, 0, 0], 113 | ]; 114 | expect(maxAreaOfIsland(island), 0); 115 | }); 116 | } 117 | -------------------------------------------------------------------------------- /graphs/breadth_first_search.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | import 'package:test/test.dart'; 3 | 4 | /// Implementation of Breadth First Search 5 | /// https://en.wikipedia.org/wiki/Breadth-first_search 6 | 7 | class Graph { 8 | /// Adjacency List representation using dynamic list and HashMap 9 | HashMap graph = new HashMap>(); 10 | List nodes; 11 | 12 | void makeGraph() { 13 | /// initialise all nodes with empty lists. 14 | /// each node will have a list as value which stores 15 | /// the nodes to which it is connected to 16 | for (int i = 0; i < this.nodes.length; i++) { 17 | this.graph[nodes[i]] = []; 18 | } 19 | } 20 | 21 | Graph(this.nodes) { 22 | this.makeGraph(); 23 | } 24 | 25 | int get numberOfNodesInGraph { 26 | return this.nodes.length; 27 | } 28 | 29 | HashMap get graphDataStructure { 30 | return this.graph; 31 | } 32 | 33 | void addNodes(int newNode) { 34 | this.nodes.add(newNode); 35 | this.graph[newNode] = []; 36 | } 37 | 38 | void addEdges(int start, int end) { 39 | this.graph[start].add(end); 40 | } 41 | } 42 | 43 | List breadthFirstSearch(Graph graph, int numberOfNodes, int startNode) { 44 | Queue queue = new Queue(); 45 | List answer = []; 46 | queue.add(startNode); 47 | while (queue.isNotEmpty) { 48 | int node = queue.removeFirst(); 49 | answer.add(node); 50 | for (int child in graph.graph[node]) { 51 | queue.add(child); 52 | } 53 | } 54 | return answer; 55 | } 56 | 57 | void main() { 58 | test(('Test case 1:'), () { 59 | List nodes = [0, 1, 2]; 60 | int numberOfEdges = 2; 61 | 62 | List> edges = [ 63 | [0, 1], 64 | [0, 2] 65 | ]; 66 | Graph graph = Graph(nodes); 67 | 68 | for (int i = 0; i < numberOfEdges; i++) { 69 | int start = edges[i][0]; 70 | int end = edges[i][1]; 71 | graph.addEdges(start, end); 72 | } 73 | int startNode = 0; 74 | List answer = 75 | breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); 76 | expect(answer, equals([0, 1, 2])); 77 | }); 78 | 79 | test(('Test case 2:'), () { 80 | List nodes = [0, 1, 2, 3, 4]; 81 | int numberOfEdges = 4; 82 | 83 | List> edges = [ 84 | [0, 1], 85 | [0, 2], 86 | [0, 3], 87 | [2, 4] 88 | ]; 89 | Graph graph = Graph(nodes); 90 | 91 | for (int i = 0; i < numberOfEdges; i++) { 92 | int start = edges[i][0]; 93 | int end = edges[i][1]; 94 | graph.addEdges(start, end); 95 | } 96 | int startNode = 0; 97 | List answer = 98 | breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); 99 | expect(answer, equals([0, 1, 2, 3, 4])); 100 | }); 101 | } 102 | -------------------------------------------------------------------------------- /graphs/depth_first_search.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | import 'package:test/test.dart'; 3 | 4 | /// Implementation of Depth First Search 5 | /// https://en.wikipedia.org/wiki/Depth-first_search 6 | 7 | class Graph { 8 | /// Adjacency List representation using dynamic list and HashMap 9 | HashMap graph = new HashMap>(); 10 | List nodes; 11 | 12 | void makeGraph() { 13 | /// initialise all nodes with empty lists. 14 | /// each node will have a list as value which stores 15 | /// the nodes to which it is connected to 16 | for (int i = 0; i < this.nodes.length; i++) { 17 | this.graph[nodes[i]] = []; 18 | } 19 | } 20 | 21 | Graph(this.nodes) { 22 | this.makeGraph(); 23 | } 24 | 25 | int get numberOfNodesInGraph { 26 | return this.nodes.length; 27 | } 28 | 29 | HashMap get graphDataStructure { 30 | return this.graph; 31 | } 32 | 33 | void addNodes(int newNode) { 34 | this.nodes.add(newNode); 35 | this.graph[newNode] = []; 36 | } 37 | 38 | void addEdges(int start, int end) { 39 | this.graph[start].add(end); 40 | } 41 | } 42 | 43 | void depthFirstSearchHelper(graph, visitedNodes, node, answer) { 44 | if (visitedNodes[node]) { 45 | return null; 46 | } 47 | visitedNodes[node] = true; 48 | answer.add(node); 49 | if (graph.containsKey(node)) { 50 | for (int child in graph[node]) { 51 | if (!visitedNodes[child]) { 52 | depthFirstSearchHelper(graph, visitedNodes, child, answer); 53 | } 54 | } 55 | } 56 | } 57 | 58 | List depthFirstSearch(Graph graph, int numberOfNodes, int startNode) { 59 | List visitedNodes = 60 | new List.generate(numberOfNodes, (index) => false); 61 | 62 | List answer = []; 63 | depthFirstSearchHelper(graph.graph, visitedNodes, startNode, answer); 64 | return answer; 65 | } 66 | 67 | void main() { 68 | test(('Test case 1:'), () { 69 | List nodes = [0, 1, 2, 3]; 70 | int numberOfEdges = 3; 71 | 72 | List> edges = [ 73 | [0, 1], 74 | [1, 2], 75 | [0, 3] 76 | ]; 77 | Graph graph = Graph(nodes); 78 | 79 | for (int i = 0; i < numberOfEdges; i++) { 80 | int start = edges[i][0]; 81 | int end = edges[i][1]; 82 | graph.addEdges(start, end); 83 | } 84 | int startNode = 0; 85 | List answer = 86 | depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); 87 | expect(answer, equals([0, 1, 2, 3])); 88 | }); 89 | 90 | test(('Test case 2:'), () { 91 | List nodes = [0, 1, 2, 3, 4]; 92 | int numberOfEdges = 4; 93 | 94 | List> edges = [ 95 | [0, 1], 96 | [0, 2], 97 | [0, 3], 98 | [2, 4] 99 | ]; 100 | Graph graph = Graph(nodes); 101 | 102 | for (int i = 0; i < numberOfEdges; i++) { 103 | int start = edges[i][0]; 104 | int end = edges[i][1]; 105 | graph.addEdges(start, end); 106 | } 107 | int startNode = 0; 108 | List answer = 109 | depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); 110 | expect(answer, equals([0, 1, 2, 4, 3])); 111 | }); 112 | } 113 | -------------------------------------------------------------------------------- /graphs/nearest_neighbour_algorithm.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | /// Graph represented as adjacency matrix 4 | /// [nodes] - node names preserved in order 5 | /// [adjacencyMatrix] edge weights, distances between nodes 6 | class Graph { 7 | List nodes; 8 | List> adjacencyMatrix; 9 | 10 | Graph(this.nodes, this.adjacencyMatrix); 11 | } 12 | 13 | /// Find path visiting all nodes in given [graph] using greedy approach 14 | List nearestNeighbourSearch(Graph graph) { 15 | List path = []; 16 | Set unvisitedNodes = Set.from(Iterable.generate(graph.nodes.length)); 17 | 18 | int currentNode = 0; 19 | while (unvisitedNodes.isNotEmpty) { 20 | unvisitedNodes.remove(currentNode); 21 | int? nearestNeighbour; 22 | double nearestNeighbourDistance = 0; 23 | 24 | for (int neighbour in unvisitedNodes) { 25 | double neighbourDistance = graph.adjacencyMatrix[currentNode][neighbour]; 26 | if (nearestNeighbour == null || 27 | neighbourDistance < nearestNeighbourDistance) { 28 | nearestNeighbour = neighbour; 29 | nearestNeighbourDistance = neighbourDistance; 30 | } 31 | } 32 | 33 | path.add(graph.nodes[currentNode]); 34 | currentNode = nearestNeighbour ?? 0; 35 | } 36 | 37 | return path; 38 | } 39 | 40 | class Point { 41 | double x; 42 | double y; 43 | 44 | @override 45 | String toString() => "P($x, $y)"; 46 | 47 | Point(this.x, this.y); 48 | } 49 | 50 | /// Euclidean distance between [p1] and [p2] 51 | double distance(Point p1, Point p2) { 52 | return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)); 53 | } 54 | 55 | /// Form graph using given [points]. 56 | /// Edge weights will correspond to distances 57 | Graph fromPoints(List points) { 58 | List nodes = []; 59 | List> adjacencyMatrix = []; 60 | 61 | for (Point p1 in points) { 62 | List neigbourDistances = []; 63 | for (Point p2 in points) { 64 | neigbourDistances.add(distance(p1, p2)); 65 | } 66 | nodes.add(p1.toString()); 67 | adjacencyMatrix.add(neigbourDistances); 68 | } 69 | 70 | return Graph(nodes, adjacencyMatrix); 71 | } 72 | 73 | void main() { 74 | Graph graph = Graph([ 75 | "A", 76 | "B", 77 | "C", 78 | "D", 79 | "E" 80 | ], [ 81 | [0, 12, 4, 54, 100], 82 | [3, 0, 5, 1, 1], 83 | [300, 20, 0, 433, 123], 84 | [32, 31, 54, 0, 3], 85 | [2, 65, 12, 32, 0] 86 | ]); 87 | 88 | print(nearestNeighbourSearch(graph)); 89 | 90 | List points = [ 91 | new Point(0, 0), 92 | new Point(0, 10), 93 | new Point(-10, 10), 94 | new Point(3.33, 8.11), 95 | new Point(12, 11), 96 | new Point(-1, 1), 97 | new Point(-2, 2) 98 | ]; 99 | 100 | print(nearestNeighbourSearch(fromPoints(points))); 101 | } 102 | -------------------------------------------------------------------------------- /maths/Armstrong_number.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | bool Armstrong_no(var x) { 4 | var n = x; 5 | var s = n.toString(); 6 | var d = s.length; 7 | var sum = 0; 8 | while (n != 0) { 9 | var r = n % 10; 10 | sum = sum + pow(r, d).toInt(); 11 | n = n ~/ 10; 12 | } 13 | return sum == x; 14 | } 15 | 16 | void main() { 17 | for (var x in [0, 10, 370, 371]) { 18 | if (Armstrong_no(x)) { 19 | print("${x} is armstrong number"); 20 | } else { 21 | print("${x} is not Armstrong number"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /maths/Kynea_numbers.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // Function to calculate nth kynea number 4 | int nthKyneaNumber(int n) { 5 | // Calculate nth kynea number 6 | // using formula ((2^n + 1)^2 ) -2 7 | 8 | // Firstly calculate 2^n + 1 9 | n = (1 << n) + 1; 10 | 11 | // Now calculate (2^n + 1)^2 12 | n = n * n; 13 | 14 | // Now calculate ((2^n + 1)^2 ) - 2 15 | n = n - 2; 16 | 17 | // return nth Kynea number 18 | return n; 19 | } 20 | 21 | // Driver Program 22 | 23 | void main() { 24 | test("1th Kynea number equals to 7", () { 25 | expect(nthKyneaNumber(1), equals(7)); 26 | }); 27 | 28 | test("4th Kynea number equals to 287", () { 29 | expect(nthKyneaNumber(4), equals(287)); 30 | }); 31 | 32 | test("6th Kynea number equals to 4223", () { 33 | expect(nthKyneaNumber(6), equals(4223)); 34 | }); 35 | 36 | test("10th Kynea number equals to 1050623", () { 37 | expect(nthKyneaNumber(10), equals(1050623)); 38 | }); 39 | } 40 | -------------------------------------------------------------------------------- /maths/LinearDiophantineEqn.dart: -------------------------------------------------------------------------------- 1 | // Program Linear Diophantine equation 2 | 3 | //Find the GCD of two numbers 4 | int gcd(int a, int b) { 5 | return (a % b == 0) ? b.abs() : gcd(b, a % b); 6 | } 7 | 8 | // This function checks if integral solutions are possible 9 | bool Isposs(int a, int b, int c) { 10 | return (c % gcd(a, b) == 0); 11 | } 12 | 13 | //Driver function for Linear Diophantine Equations 14 | int main() { 15 | int a = 3, b = 6, c = 9; 16 | if (Isposs(a, b, c) == true) { 17 | print("Possible"); 18 | } else { 19 | print("Not Possible"); 20 | } 21 | int x = 3, y = 6, z = 8; 22 | if (Isposs(x, y, z) == true) { 23 | print("Possible"); 24 | } else { 25 | print("Not Possible"); 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /maths/Ugly_numbers.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | int maxDivide(int a, int b) { 4 | var n; 5 | while (a % b == 0) { 6 | n = a / b; 7 | a = n.toInt(); 8 | } 9 | return a; 10 | } 11 | 12 | /* Function to check if a number is ugly or not */ 13 | bool isUgly(int no) { 14 | no = maxDivide(no, 2); 15 | no = maxDivide(no, 3); 16 | no = maxDivide(no, 5); 17 | 18 | return no == 1; 19 | } 20 | 21 | /* Function to get the nth ugly number*/ 22 | int getNthUglyNo(int n) { 23 | int i = 1; 24 | int count = 1; /* ugly number count */ 25 | 26 | /*Check for all integers untill ugly count 27 | becomes n*/ 28 | while (n > count) { 29 | i++; 30 | if (isUgly(i)) count++; 31 | } 32 | return i; 33 | } 34 | 35 | /* Driver program to test above functions */ 36 | void main() { 37 | test("getNthUglyNo(150) returns 5832", () { 38 | expect(getNthUglyNo(150), equals(5832)); 39 | }); 40 | 41 | test("isUgly returns true for 6", () { 42 | expect(isUgly(6), isTrue); 43 | }); 44 | 45 | test("isUgly returns true for 5832", () { 46 | expect(isUgly(5832), isTrue); 47 | }); 48 | 49 | test("isUgly returns false for 5833", () { 50 | expect(isUgly(5833), isFalse); 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /maths/abs.dart: -------------------------------------------------------------------------------- 1 | abs_value(number) { 2 | return number < 0 ? -number : number; 3 | } 4 | 5 | void main() { 6 | print(abs_value(-34)); 7 | } 8 | -------------------------------------------------------------------------------- /maths/abs_max.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(absMax([0, 5, 1, 11]) == 11); 4 | assert(absMax([3, -10, -2]) == -10); 5 | } 6 | 7 | /** 8 | * get the value in [list], it's absolute value is max 9 | * Examples: 10 | * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10 11 | */ 12 | int absMax(List list) { 13 | int max = list[0]; 14 | for (int i = 1, length = list.length; i < length; ++i) { 15 | if (list[i].abs() > max.abs()) { 16 | max = list[i]; 17 | } 18 | } 19 | return max; 20 | } 21 | -------------------------------------------------------------------------------- /maths/abs_min.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(absMin([0, 5, 1, 11]) == 0); 4 | assert(absMin([3, -10, -2]) == -2); 5 | } 6 | 7 | /** 8 | * get the value in [list], it's absolute value is min 9 | * Examples: 10 | * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2 11 | */ 12 | int absMin(List list) { 13 | int min = list[0]; 14 | for (int i = 1, length = list.length; i < length; ++i) { 15 | if (list[i].abs() < min.abs()) { 16 | min = list[i]; 17 | } 18 | } 19 | return min; 20 | } 21 | -------------------------------------------------------------------------------- /maths/amicable_numbers.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * https://en.wikipedia.org/wiki/Amicable_numbers 3 | * 4 | *Amicable numbers are two different numbers related in such a way that the sum of the proper divisors of each is equal to the other number. 5 | * 6 | * */ 7 | 8 | //this function returns true if numbers are amicable and false otherwise 9 | bool amicable_number(int first_number, int second_number) { 10 | if (first_number <= 1 || second_number <= 1) return false; 11 | List first_number_proper_divisors = []; 12 | List second_number_proper_divisors = []; 13 | for (int i = 1; i < first_number; i++) { 14 | if (first_number % i == 0) first_number_proper_divisors.add(i); 15 | } 16 | for (int i = 1; i < second_number; i++) { 17 | if (second_number % i == 0) second_number_proper_divisors.add(i); 18 | } 19 | return first_number == 20 | second_number_proper_divisors.reduce((a, b) => a + b) && 21 | second_number == first_number_proper_divisors.reduce((a, b) => a + b); 22 | } 23 | 24 | void main() { 25 | print(amicable_number(12, 14)); // false 26 | print(amicable_number(220, 284)); // true 27 | print(amicable_number(60, 84)); // true 28 | print(amicable_number(1184, 1210)); //true 29 | print(amicable_number(-14, 10)); //false 30 | } 31 | -------------------------------------------------------------------------------- /maths/average.dart: -------------------------------------------------------------------------------- 1 | //Find mean of a list of numbers. 2 | 3 | average(List numbers) { 4 | int sum = 0; 5 | for (var x in numbers) { 6 | sum += x; 7 | } 8 | var avg = sum / numbers.length; 9 | print(avg); 10 | return avg; 11 | } 12 | 13 | void main() { 14 | average([2, 8, 6, 90, 60]); 15 | } 16 | -------------------------------------------------------------------------------- /maths/eulers_totient.dart: -------------------------------------------------------------------------------- 1 | /* Source: 2 | * https://en.wikipedia.org/wiki/Euler%27s_totient_function 3 | * 4 | * Description: 5 | * eulers_totient(n) = n * product(1 - 1/p for all prime p dividing n) 6 | * 7 | * Time Complexity: 8 | * O(sqrt(n)) 9 | */ 10 | 11 | int eulers_totient(int n) { 12 | // Input: n: int 13 | // Output: phi(n): count of numbers b/w 1 and n that are coprime to n 14 | int res = n; 15 | for (int i = 2; i * i <= n; i++) { 16 | if (n % i == 0) { 17 | while (n % i == 0) { 18 | n = n ~/ i; 19 | } 20 | // i is a prime dividing n, multiply res bu 1 - 1/i 21 | // res = res * (1 - 1/i) = res - (res/i) 22 | res = res - (res ~/ i); 23 | } 24 | } 25 | if (n > 1) { 26 | res = res - (res ~/ n); 27 | } 28 | return res; 29 | } 30 | 31 | main() { 32 | // eulers_totient(9) = 6 as 1, 2, 4, 5, 6, 7, 8 are coprime to 9 33 | // > 6 34 | print(eulers_totient(9)); 35 | // eulers_totient(10) = 4 as 1, 3, 7, 9 are coprime to 10 36 | // > 4 37 | print(eulers_totient(10)); 38 | } 39 | -------------------------------------------------------------------------------- /maths/factorial.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | var n = 5; 3 | var fac = factorial(n); 4 | print("$n! = $fac"); /* output: 5! = 120 */ 5 | } 6 | 7 | /* calculate factorial of n*/ 8 | int factorial(var n) { 9 | var fac = 1; 10 | for (int i = 2; i <= n; ++i) { 11 | fac *= i; 12 | } 13 | return fac; 14 | } 15 | -------------------------------------------------------------------------------- /maths/factorial_approximation.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | /// Approximation for gamma(x + 1) discovered by Srinivasa Ramanujanea 4 | double factorial(double x) { 5 | return sqrt(pi) * 6 | pow(x / e, x) * 7 | pow(8 * pow(x, 3) + 4 * pow(x, 2) + x + 1 / 30, 1 / 6); 8 | } 9 | 10 | main() { 11 | for (int i = 0; i < 10; i++) { 12 | print("$i! ~= ${factorial(i.toDouble())}"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /maths/factorial_recursion.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | var n = 5; 3 | var fac = factorial(n); 4 | print("$n! = $fac"); /* output: 5! = 120 */ 5 | } 6 | 7 | /* calculate factorial of n*/ 8 | int factorial(var n) => n == 0 || n == 1 ? 1 : n * factorial(n - 1); 9 | -------------------------------------------------------------------------------- /maths/factors.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] 3 | 4 | try { 5 | print(factorsOf(-1) 6 | .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function 7 | } catch (ex) { 8 | print(ex); 9 | } 10 | } 11 | 12 | List factorsOf(int num) { 13 | if (num <= 0) 14 | throw Exception("A non-positive value was passed to the function"); 15 | List factors = [1]; 16 | for (int i = 2; i <= num; i++) { 17 | if (num % i == 0) factors.add(i); 18 | } 19 | return factors; 20 | } 21 | -------------------------------------------------------------------------------- /maths/fermats_little_theorem.dart: -------------------------------------------------------------------------------- 1 | @Skip('currently failing (see issue #86)') 2 | 3 | import 'package:test/test.dart'; 4 | 5 | /* 6 | Fermat's little Theorem 7 | Translated from TheAlgorithms/Python 8 | */ 9 | binary_exponentiation(a, n, mod) { 10 | if (n == 0) { 11 | return 1; 12 | } else if (n % 2 == 1) { 13 | return (binary_exponentiation(a, n - 1, mod) * a) % mod; 14 | } 15 | int b = binary_exponentiation(a, n / 2, mod); 16 | 17 | return (b * b) % mod; 18 | } 19 | 20 | void main() { 21 | // a prime number 22 | int p = 701; 23 | 24 | double a = 1000000000; 25 | int b = 10; 26 | 27 | // using binary exponentiation function, O(log(p)): 28 | print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p); 29 | 30 | // using Python operators: 31 | print((a / b) % p == (a * b ^ (p - 2)) % p); 32 | } 33 | -------------------------------------------------------------------------------- /maths/fibonacci_dynamic_programming.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | //Title: Nth Fibonacci Number using Dynamic Programming 4 | //Author: Richik Chanda 5 | //Email: richikchanda1999@gmail.com 6 | List dp = []; 7 | int mod = (1e9 + 7).toInt(); 8 | 9 | //Get the nth Fibonacci number modulo 10^9 + 7 since it can be a very large number 10 | int getFib(int n) { 11 | if (dp[n] == -1) dp[n] = (getFib(n - 1) % mod) + (getFib(n - 2) % mod); 12 | return dp[n] % mod; 13 | } 14 | 15 | //Driver 16 | void main() { 17 | dp = List.generate((1e6 + 1).toInt(), (e) => -1); 18 | dp[0] = 0; 19 | dp[1] = 1; 20 | 21 | test("getFib 0 equals 0", () { 22 | expect(getFib(0), equals(0)); 23 | }); 24 | 25 | test("getFib 1 equals 1", () { 26 | expect(getFib(1), equals(1)); 27 | }); 28 | 29 | test("getFib 5 equals 5", () { 30 | expect(getFib(5), equals(5)); 31 | }); 32 | 33 | test("getFib(n) equals getFib(n - 1) + getFib(n - 2)", () { 34 | expect(getFib(7), equals(getFib(6) + getFib(5))); 35 | expect(getFib(14), equals(getFib(13) + getFib(12))); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /maths/fibonacci_recursion.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(fibonacci(1) == 1); 4 | assert(fibonacci(2) == 1); 5 | assert(fibonacci(3) == 2); 6 | assert(fibonacci(4) == 3); 7 | assert(fibonacci(5) == 5); 8 | assert(fibonacci(8) == 21); 9 | } 10 | 11 | /** 12 | * get Nth item of fibonacci 13 | * fibonacci: 1 1 2 3 5 8 13 21 ... 14 | */ 15 | int fibonacci(int n) => 16 | n == 1 || n == 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2); 17 | -------------------------------------------------------------------------------- /maths/find_max.dart: -------------------------------------------------------------------------------- 1 | //find the max number 2 | find_max(List numbers) { 3 | var max = numbers[0]; 4 | for (var x in numbers) { 5 | if (x > max) { 6 | max = x; 7 | } 8 | } 9 | print(max); 10 | } 11 | 12 | void main() { 13 | find_max([2, 9, 18, 8, 76, -3]); 14 | } 15 | -------------------------------------------------------------------------------- /maths/find_max_recursion.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List numbers = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]; 3 | int max = find_max_recursion(numbers, 0, numbers.length - 1); 4 | print("max = $max"); 5 | } 6 | 7 | /** 8 | * find min using divide-and-conquer algorithm 9 | */ 10 | int find_max_recursion(List numbers, int low, int high) { 11 | if (low == high) { 12 | return numbers[low]; // or numbers[high] 13 | } 14 | int mid = (low + high) >> 1; 15 | int leftMax = 16 | find_max_recursion(numbers, low, mid); /* max in range [low mid] */ 17 | int rightMax = find_max_recursion( 18 | numbers, mid + 1, high); /* max in range [mid + 1, high] */ 19 | return leftMax >= rightMax ? leftMax : rightMax; 20 | } 21 | -------------------------------------------------------------------------------- /maths/find_min.dart: -------------------------------------------------------------------------------- 1 | //find the min number 2 | find_min(List numbers) { 3 | var min = numbers[0]; 4 | for (var x in numbers) { 5 | if (min > x) { 6 | min = x; 7 | } 8 | } 9 | print(min); 10 | } 11 | 12 | void main() { 13 | find_min([2, 9, 18, 8, 76, -3]); 14 | } 15 | -------------------------------------------------------------------------------- /maths/find_min_recursion.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List numbers = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]; 3 | int min = find_min_recursion(numbers, 0, numbers.length - 1); 4 | print("min = $min"); 5 | } 6 | 7 | /** 8 | * find max using divide-and-conquer algorithm 9 | */ 10 | int find_min_recursion(List numbers, int low, int high) { 11 | if (low == high) { 12 | return numbers[low]; // or numbers[high] 13 | } 14 | int mid = (low + high) >> 1; 15 | int leftMin = 16 | find_min_recursion(numbers, low, mid); /* min in range [low mid] */ 17 | int rightMin = find_min_recursion( 18 | numbers, mid + 1, high); /* min in range [mid + 1, high] */ 19 | return leftMin <= rightMin ? leftMin : rightMin; 20 | } 21 | -------------------------------------------------------------------------------- /maths/hamming_distance.dart: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two strings of equal length is 2 | // the number of positions at which the corresponding symbols are different. 3 | // https://en.wikipedia.org/wiki/Hamming_distance 4 | 5 | int hamming_distance(String stringA, String stringB) { 6 | //Calculates Hamming Distance 7 | int distance; 8 | 9 | //strings must be of equal length 10 | if (stringA.length != stringB.length) { 11 | print('String lengths must be same!'); 12 | return 0; 13 | } else { 14 | distance = 0; 15 | for (var i = 0; i < stringA.length; i++) { 16 | if (stringA[i] != stringB[i]) { 17 | distance += 1; 18 | } 19 | } 20 | } 21 | return distance; 22 | } 23 | 24 | void main() { 25 | String stringA; 26 | String stringB; 27 | int dist; 28 | 29 | stringA = 'karolin'; 30 | stringB = 'kathrin'; 31 | dist = hamming_distance(stringA, stringB); 32 | print('Hamming Distance between $stringA and $stringB is $dist'); 33 | 34 | stringA = '1011101'; 35 | stringB = '1001001'; 36 | dist = hamming_distance(stringA, stringB); 37 | print('Hamming Distance between $stringA and $stringB is $dist'); 38 | } 39 | -------------------------------------------------------------------------------- /maths/newton_method.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | /// Approximate derivative of [f] at [x] 4 | double derivative(double Function(double) f, double x, [double h = 1e-10]) { 5 | return (f(x + h) - f(x - h)) / (2 * h); 6 | } 7 | 8 | /// Find root of given [f] (x where [f(x)] == 0) 9 | double findRoot(double Function(double) f, 10 | [double initialValue = 0, int iterations = 10, double h = 1e-10]) { 11 | double currentValue = initialValue; 12 | for (int i = 0; i < iterations; i++) { 13 | currentValue -= f(currentValue) / derivative(f, currentValue); 14 | } 15 | 16 | return currentValue; 17 | } 18 | 19 | double f(x) { 20 | return 2 * x + 4; 21 | } 22 | 23 | double g(x) { 24 | return 2 * pow(x, 2) + 7 * x + 1; 25 | } 26 | 27 | main() { 28 | double fRoot = findRoot(f); 29 | double gRoot = findRoot(g); 30 | double sinRoot = findRoot(sin, 10); 31 | 32 | print("f(x) = 2x + 4, f($fRoot) = ${f(fRoot)}"); 33 | print("g(x) = 2x^2 + 7x + 1, g($gRoot) = ${g(gRoot)}"); 34 | print("sin(${sinRoot / pi} * pi) = ${sin(sinRoot)}"); 35 | } 36 | -------------------------------------------------------------------------------- /maths/palindrome_number.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(isPalindrome(12321) == true); 4 | assert(isPalindrome(0) == true); 5 | assert(isPalindrome(1) == true); 6 | assert(isPalindrome(123322) == false); 7 | } 8 | 9 | /** 10 | * Return true if [n] is palindrome number, otherwise false 11 | * Throws [ArgumentError] if [n] is negative 12 | */ 13 | bool isPalindrome(int n) { 14 | if (n < 0) { 15 | throw new ArgumentError("$n is negative"); 16 | } 17 | var copy = n; 18 | var reverseNumber = 0; 19 | while (n != 0) { 20 | reverseNumber = reverseNumber * 10 + n % 10; 21 | n = n ~/ 10; 22 | } 23 | 24 | return copy == reverseNumber; 25 | } 26 | -------------------------------------------------------------------------------- /maths/palindrome_string.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(isPalindrome("abcba")); 4 | assert(isPalindrome("a")); 5 | assert(isPalindrome("")); 6 | assert(isPalindrome("abbcba") == false); 7 | } 8 | 9 | /** 10 | * Return true if [string] is palindrome string, otherwise false 11 | */ 12 | bool isPalindrome(String string) { 13 | if (string.length <= 1) { 14 | return true; 15 | } 16 | 17 | for (int i = 0, limit = string.length ~/ 2; i <= limit; ++i) { 18 | if (string[i] != string[string.length - 1 - i]) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | -------------------------------------------------------------------------------- /maths/palindrome_string_recursion.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | assert(isPalindrome("abcba", 0, 4)); 4 | assert(isPalindrome("a", 0, 0)); 5 | assert(isPalindrome("abbcba", 0, 5) == false); 6 | } 7 | 8 | /** 9 | * Return true if [string] is palindrome string, otherwise false 10 | */ 11 | bool isPalindrome(String string, int low, int high) { 12 | if (low == high) { 13 | return true; 14 | } else if (string[low] != string[high]) { 15 | return false; 16 | } else { 17 | return isPalindrome(string, low + 1, high - 1); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /maths/perfect_number.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * From: https://www.britannica.com/science/perfect-number 3 | * 4 | * A positive integer that is equal to the sum of its proper divisors. 5 | * The smallest perfect number is 6, which is the sum of 1, 2, and 3. 6 | * Other perfect numbers are 28, 496, and 8,128. 7 | * 8 | * */ 9 | 10 | //this function returns true if number is perfect and false otherwise 11 | bool perfect_number(int number) { 12 | if (number <= 1) return false; 13 | List divisors = []; 14 | for (int i = 1; i < number; i++) { 15 | if (number % i == 0) divisors.add(i); 16 | } 17 | return divisors.reduce((a, b) => a + b) == number; 18 | } 19 | 20 | void main() { 21 | print(perfect_number(-1)); // false 22 | print(perfect_number(6)); // true 23 | print(perfect_number(12)); // false 24 | print(perfect_number(16)); // false 25 | print(perfect_number(26)); // false 26 | print(perfect_number(27)); // false 27 | print(perfect_number(28)); // true 28 | } 29 | -------------------------------------------------------------------------------- /maths/pow.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | print(pow(10, 2)); // 100 3 | print(pow(2, 0)); // 1 4 | print(pow(2, 10)); // 1024 5 | } 6 | 7 | double pow(int a, int b) { 8 | double result = 1; 9 | for (int i = 1; i <= b; i++) { 10 | result *= a; 11 | } 12 | return result; 13 | } 14 | -------------------------------------------------------------------------------- /maths/power_of_two.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | bool power_of_two(int n) { 4 | if (n == 0) return false; 5 | 6 | return (n & (n - 1)) == 0; 7 | } 8 | 9 | void main() { 10 | test("Test power_of_two 0 returns false", () { 11 | expect(power_of_two(0), isFalse); 12 | }); 13 | 14 | test("Test power_of_two 1 returns true", () { 15 | expect(power_of_two(1), isTrue); 16 | }); 17 | 18 | test("Test power_of_two 10 returns false", () { 19 | expect(power_of_two(10), isFalse); 20 | }); 21 | 22 | test("Test power_of_two 10 returns false", () { 23 | expect(power_of_two(10), isFalse); 24 | }); 25 | 26 | test("Test power_of_two 23 returns false", () { 27 | expect(power_of_two(23), isFalse); 28 | }); 29 | 30 | test("Test power_of_two 32 returns true", () { 31 | expect(power_of_two(32), isTrue); 32 | }); 33 | 34 | test("Test power_of_two 2234 returns false", () { 35 | expect(power_of_two(2234), isFalse); 36 | }); 37 | 38 | test("Test power_of_two 2048 returns true", () { 39 | expect(power_of_two(2048), isTrue); 40 | }); 41 | } 42 | -------------------------------------------------------------------------------- /maths/prime_check.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | List numbers = [1, 2, 3, 4, 5, 9, 13]; 5 | for (int number in numbers) { 6 | if (isPrime(number)) { 7 | print("$number is prime."); 8 | } else { 9 | print("$number is not prime."); 10 | } 11 | } 12 | } 13 | 14 | /** 15 | *check out whether number is prime number or not. 16 | */ 17 | bool isPrime(int number) { 18 | if (number == 2) { 19 | return true; 20 | } 21 | if (number <= 1 || number % 2 == 0) { 22 | return false; 23 | } 24 | 25 | for (int i = 3, limit = sqrt(number).toInt(); i <= limit; i += 2) { 26 | if (number % i == 0) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | -------------------------------------------------------------------------------- /maths/relu_function.dart: -------------------------------------------------------------------------------- 1 | // Program to Implement RELU function 2 | // RELU function is commonly used in Machine learning as an activation function 3 | 4 | int relu_func(var x) { 5 | // here x passed is value passed in the function relu 6 | if (x > 0) 7 | return x; 8 | else 9 | return 0; 10 | } 11 | 12 | //Driver function for RELU function 13 | int main() { 14 | var a = 5; 15 | print(relu_func(a)); 16 | var b = -1; 17 | print(relu_func(b)); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /maths/shreedharacharya.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | //this function return a list of roots of a quadratic equation 4 | // [x1, x2] where x1 and x2 are roots of 5 | // aX^2 + bX + c = 0 6 | List shreedharacharya(double a, double b, double c) { 7 | double d = b * b - 4 * a * c; 8 | List A = []; 9 | if (d < 0) { 10 | print('Imaginary roots'); 11 | } else if (d == 0) { 12 | A.add(-b / (2 * a)); 13 | } else { 14 | A.add((-b + sqrt(d)) / (2 * a)); 15 | A.add((-b - sqrt(d)) / (2 * a)); 16 | } 17 | return A; 18 | } 19 | 20 | void main() { 21 | double a = 1.00, b = -4.00, c = 4.00; 22 | List p = shreedharacharya(a, b, c); 23 | print(p); 24 | } 25 | -------------------------------------------------------------------------------- /maths/sieve_of_eratosthenes.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Source: 3 | * https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 4 | * 5 | * Description: 6 | * Calculates prime numbers till a number n 7 | * 8 | * Time Complexity: 9 | * O(n log(log(n))) 10 | */ 11 | 12 | List sieve_of_eratosthenes(int n) { 13 | // Input: n: int 14 | // Output: is_prime: List denoting whether ith element is prime or not 15 | List is_prime = new List.filled(n + 1, true); 16 | is_prime[0] = false; 17 | is_prime[1] = false; 18 | for (int i = 2; i * i <= n; i++) { 19 | if (is_prime[i]) { 20 | for (int j = i * i; j <= n; j += i) { 21 | // mark all multiples of i as false 22 | is_prime[j] = false; 23 | } 24 | } 25 | } 26 | return is_prime; 27 | } 28 | 29 | main() { 30 | // Prints all the primes under 50 31 | List primes = sieve_of_eratosthenes(50); 32 | for (int i = 2; i <= 50; i++) { 33 | if (primes[i]) { 34 | print(i); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /maths/sigmoid.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | double sigmoid( 4 | double x, double a) //x is the function variable and a is the gain 5 | { 6 | double p = exp(-a * x); 7 | return 1 / (1 + p); 8 | } 9 | 10 | void main() { 11 | double gain = 1.00, x = 0.5; 12 | double p = sigmoid(x, gain); 13 | print(p); 14 | } 15 | -------------------------------------------------------------------------------- /maths/simpson_rule.dart: -------------------------------------------------------------------------------- 1 | /// Approximate definite integral of f in [a, b] interval 2 | double simpson(double Function(double) f, double a, double b, int n) { 3 | if (n <= 0) { 4 | throw ArgumentError("n have to be greater than 0"); 5 | } 6 | 7 | double step = (b - a) / n; 8 | double sum = f(a) + f(b); 9 | 10 | for (int i = 1; i < n; i++) { 11 | if (i % 2 == 0) { 12 | sum += 2 * f(a + i * step); 13 | } else { 14 | sum += 4 * f(a + i * step); 15 | } 16 | } 17 | 18 | return (step / 3) * sum; 19 | } 20 | 21 | double f(double x) { 22 | return x * x + 2 * x + 7; 23 | } 24 | 25 | void main() { 26 | print(simpson(f, 0, 10, 10)); 27 | } 28 | -------------------------------------------------------------------------------- /maths/sphenic_number.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | var arr = new List.filled(1001, true, growable: false); 4 | void simple_seive() { 5 | for (int p = 2; p * p < 1001; p++) { 6 | if (arr[p]) { 7 | for (int i = p * 2; i < 1001; i = i + p) arr[i] = false; 8 | } 9 | } 10 | } 11 | 12 | bool sphenic_number(int N) { 13 | var arr1 = new List.filled(9, 0, growable: false); 14 | 15 | var count = 0; 16 | var j = 0; 17 | 18 | for (int i = 1; i <= N; i++) { 19 | if (N % i == 0 && count < 9) { 20 | count++; 21 | arr1[j] = i; 22 | j++; 23 | } 24 | } 25 | 26 | return (count == 8 && arr[arr1[0]] && arr[arr1[1]] && arr[arr1[2]]); 27 | } 28 | 29 | void main() { 30 | simple_seive(); 31 | test("Test Sphenic_no returns false for non-sphenic numbers", () { 32 | expect(sphenic_number(0), isFalse); 33 | expect(sphenic_number(371), isFalse); 34 | expect(sphenic_number(509), isFalse); 35 | expect(sphenic_number(501), isFalse); 36 | }); 37 | test("Test sphenic_no returns true for sphenic numbers", () { 38 | expect(sphenic_number(370), isTrue); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /maths/symmetric_derivative.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | /// Approximate derivative of [f] at [x] 4 | double derivative(double Function(double) f, double x, [double h = 1e-10]) { 5 | return (f(x + h) - f(x - h)) / (2 * h); 6 | } 7 | 8 | void main() { 9 | print("derivative(sin, pi) = ${derivative(sin, pi)}, cos(pi) = ${cos(pi)}"); 10 | print( 11 | "derivative(sin, 2 * pi) = ${derivative(sin, 2 * pi)}, cos(2 * pi) = ${cos(2 * pi)}"); 12 | print("derivative(exp, 3) = ${derivative(exp, 3)}, exp(3) = ${exp(3)}"); 13 | } 14 | -------------------------------------------------------------------------------- /other/FizzBuzz.dart: -------------------------------------------------------------------------------- 1 | //Title:FizzBuzz 2 | // Author:ShivamVerma 3 | // Email:shivamthegreat.sv@gmail.com 4 | 5 | // Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". 6 | 7 | void main() { 8 | fizzBuzz(); 9 | } 10 | 11 | void fizzBuzz() { 12 | for (int i = 1; i <= 100; i++) { 13 | if (i % 3 == 0 && i % 5 == 0) { 14 | print("FizzBuzz"); 15 | } else if (i % 3 == 0) { 16 | print("Fizz"); 17 | } else if (i % 5 == 0) { 18 | print("Buzz"); 19 | } else { 20 | print(i); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /other/LCM.dart: -------------------------------------------------------------------------------- 1 | //Title:Find LCM of two numbers. 2 | //Author:Shawn 3 | //Email:stepfencurryxiao@gmail.com 4 | 5 | /*suppose we have two numbers a and b. 6 | * Property: Since product of LCM and GCD of two numbers are 7 | * equal to product of that number itself. 8 | * i.e, LCM(a,b)*GCD(a,b)=a*b 9 | * So,here we first find GCD of two numbers and using above 10 | * property we find LCM of that two numbers. 11 | */ 12 | 13 | //Recursive function to return gcd of a and b 14 | int gcd(int a, int b) { 15 | if (a == 0) { 16 | return b; 17 | } 18 | return gcd(b % a, a); 19 | } 20 | 21 | //Function to return LCM of two numbers 22 | double lcm(int a, int b) { 23 | return (a * b) / gcd(a, b); 24 | } 25 | 26 | //Driver program 27 | void main() { 28 | var a, b; 29 | //Test case1: 30 | a = 15; 31 | b = 20; 32 | //print the result 33 | print("LCM of " + 34 | a.toString() + 35 | " and " + 36 | b.toString() + 37 | " is " + 38 | lcm(a, b).toString()); 39 | //Test case2: 40 | a = 12; 41 | b = 18; 42 | //print the result 43 | print("LCM of " + 44 | a.toString() + 45 | " and " + 46 | b.toString() + 47 | " is " + 48 | lcm(a, b).toString()); 49 | } 50 | -------------------------------------------------------------------------------- /other/Moore_voting_algorithm.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | int majorityElement(List arr, int n) { 4 | arr.sort(); 5 | 6 | var count = 1, max_ele = -1, temp = arr[0], ele = 0, f = 0; 7 | 8 | for (int i = 1; i < n; i++) { 9 | if (temp == arr[i]) { 10 | count++; 11 | } else { 12 | count = 1; 13 | temp = arr[i]; 14 | } 15 | if (max_ele < count) { 16 | max_ele = count; 17 | ele = arr[i]; 18 | 19 | if (max_ele > (n / 2)) { 20 | f = 1; 21 | break; 22 | } 23 | } 24 | } 25 | return (f == 1 ? ele : -1); 26 | } 27 | 28 | // Driver code 29 | void main() { 30 | test("majorityElement", () { 31 | List a1 = [1, 2, 2, 2, 2, 5, 1]; 32 | expect(majorityElement(a1, a1.length), equals(2)); 33 | 34 | List a2 = [30, 30, 40, 30, 40, 30, 40]; 35 | expect(majorityElement(a2, a2.length), equals(30)); 36 | }); 37 | 38 | test("majorityElement returns -1 when there is no dominant element", () { 39 | List a1 = [3, 3, 22, 21, 21, 5, 21]; 40 | expect(majorityElement(a1, a1.length), equals(-1)); 41 | 42 | List a2 = [100, 4000, 220, 220, 220, 100, 4000]; 43 | expect(majorityElement(a2, a2.length), equals(-1)); 44 | }); 45 | } 46 | -------------------------------------------------------------------------------- /other/N_bonacci.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | List N_bonacci(int n, int m) { 4 | List v = List.generate(m, (index) => 0); 5 | var i; 6 | for (i = 0; i < m; i++) { 7 | v[i] = 0; 8 | } 9 | v[n - 1] = 1; 10 | v[n] = 1; 11 | for (i = n + 1; i < m; i++) { 12 | v[i] = 2 * v[i - 1] - v[i - 1 - n]; 13 | } 14 | 15 | return v; 16 | } 17 | 18 | void main() { 19 | test("For n=2 N_bonacci is same as fibbonaci", () { 20 | expect(N_bonacci(2, 6), equals([0, 1, 1, 2, 3, 5])); 21 | }); 22 | 23 | test("For n=3 N_bonacci is same as tribbonaci", () { 24 | expect(N_bonacci(3, 7), equals([0, 0, 1, 1, 2, 4, 7])); 25 | }); 26 | 27 | test("n=4 N_bonacci", () { 28 | expect(N_bonacci(4, 10), equals([0, 0, 0, 1, 1, 2, 4, 8, 15, 29])); 29 | }); 30 | 31 | test("n=6 N_bonacci", () { 32 | expect(N_bonacci(6, 10), equals([0, 0, 0, 0, 0, 1, 1, 2, 4, 8])); 33 | }); 34 | 35 | test("n=8 N_bonacci", () { 36 | expect(N_bonacci(8, 10), equals([0, 0, 0, 0, 0, 0, 0, 1, 1, 2])); 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /other/ackermann.dart: -------------------------------------------------------------------------------- 1 | /// Here be dragons 2 | int ackermann(int m, int n) { 3 | if (m == 0) 4 | return n + 1; 5 | else if (m > 0 && n == 0) 6 | return ackermann(m - 1, 1); 7 | else 8 | return ackermann(m - 1, ackermann(m, n - 1)); 9 | } 10 | 11 | void main() { 12 | print("A(2, 2) = ${ackermann(2, 2)}"); 13 | print("A(3, 3) = ${ackermann(3, 3)}"); 14 | print("A(3, 4) = ${ackermann(3, 4)}"); 15 | print("A(3, 5) = ${ackermann(3, 5)}"); 16 | //print("A(4, 4)=${ackermann(4, 4)}"); /// too much recursionError raised right there 17 | } 18 | -------------------------------------------------------------------------------- /other/binpow.dart: -------------------------------------------------------------------------------- 1 | // Effective computation of large exponents modulo a number 2 | // Function binpow to calculate (x^n mod m) 3 | int binPow(int a, int b, int m) { 4 | int result = 1; 5 | a %= m; 6 | if (a == 0) return 0; 7 | while (b > 0) { 8 | if (b % 2 == 1) { 9 | result = (result * a) % m; 10 | } 11 | b >>= 1; 12 | a = (a * a) % m; 13 | } 14 | return result; 15 | } 16 | 17 | void main() { 18 | print('binary power of (2,5,13) = ' + binPow(2, 5, 13).toString()); 19 | print('binary power of (5, 3,13) = ' + binPow(5, 3, 13).toString()); 20 | } 21 | -------------------------------------------------------------------------------- /other/chinese_remainder_theorem.dart: -------------------------------------------------------------------------------- 1 | // Function to calculate modulo inverse. 2 | int modular_inverse(int a, int m) { 3 | // Temporary variable to store m to use later. 4 | int temp = m; 5 | 6 | if (m == 1) { 7 | return 0; 8 | } 9 | 10 | int y = 0, x = 1, temp2, quotient, remainder; 11 | 12 | // Calculating x and y based on Euclid's algorithm 13 | while (a > 1) { 14 | quotient = (a / m).floor(); 15 | remainder = a % m; 16 | a = m; 17 | m = remainder; 18 | temp2 = y; 19 | y = x - quotient * y; 20 | x = temp2; 21 | } 22 | 23 | // Making x positive if found negative 24 | if (x < 0) { 25 | x += temp; 26 | } 27 | 28 | return x; 29 | } 30 | 31 | // Driver function of the program 32 | void main() { 33 | // Taking input of the number array (num[i]). 34 | print("Enter array of pairwise co-prime numbers:"); 35 | 36 | List numbers = [9, 8, 5, 7, 1]; 37 | 38 | // Taking input of remainder array (rem[i]). 39 | print("Enter remainders:"); 40 | 41 | List remainders = [1, 2, 3, 4, 5]; 42 | 43 | num product = 1; 44 | 45 | // Length of the 'numbers' list. 46 | int length = numbers.length; 47 | 48 | // Finding product of all the numbers. 49 | for (int i = 0; i < length; i++) { 50 | product *= numbers[i]; 51 | } 52 | 53 | int temp; 54 | num result = 0; 55 | 56 | // Summing the required values for all i according to the formula. 57 | for (int i = 0; i < length; i++) { 58 | temp = (product / numbers[i]).floor(); 59 | result += temp * (remainders[i]) * modular_inverse(temp, numbers[i]); 60 | } 61 | 62 | result = result % product; 63 | 64 | // Printing result 65 | print("The value of 'x' by Chinese Remainder Theorem is $result."); 66 | } 67 | -------------------------------------------------------------------------------- /other/collatz.dart: -------------------------------------------------------------------------------- 1 | //collatz conjecture: 2 | //A series for a number n in which if n 3 | //even then the next number is n/2, 4 | //but if n is odd then the next number is 3n + 1. 5 | //This series continues till it reaches 1 6 | 7 | //Author:Shawn 8 | //Email:stepfencurryxiao@gmail.com 9 | //Reference the C repo 10 | 11 | void main() { 12 | //The number 13 | double n = 20; 14 | //curr_no stores number n 15 | double curr_no = n; 16 | //Loop till series reaches 1 17 | while (curr_no != 1) { 18 | //condition for even number 19 | if (curr_no % 2 == 0) { 20 | curr_no = curr_no / 2; 21 | print(curr_no.toString() + "->"); 22 | } 23 | //condition for odd number 24 | else { 25 | curr_no = (curr_no * 3) + 1; 26 | print(curr_no.toString() + "->"); 27 | } 28 | } 29 | print("1"); 30 | } 31 | -------------------------------------------------------------------------------- /other/fisher_yates_shuffle.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random rng = new Random(); 4 | 5 | /// Swap given [index1] and [index2] in given [collection] 6 | void swap(List collection, int index1, int index2) { 7 | T temp = collection[index1]; 8 | collection[index1] = collection[index2]; 9 | collection[index2] = temp; 10 | } 11 | 12 | /// Randomly shuffle given [collection] (inplace) 13 | void shuffle(List collection) { 14 | for (int i = collection.length - 1; i > 1; i--) { 15 | swap(collection, i, rng.nextInt(i - 1)); 16 | } 17 | } 18 | 19 | main() { 20 | List someList = [1, 2, 3, 4, 5]; 21 | print(someList); 22 | shuffle(someList); 23 | print(someList); 24 | shuffle(someList); 25 | print(someList); 26 | shuffle(someList); 27 | print(someList); 28 | } 29 | -------------------------------------------------------------------------------- /other/gcd.dart: -------------------------------------------------------------------------------- 1 | //This is the Euclidean algorithm. 2 | euclidean_gcd(var a, var b) { 3 | while (b != 0) { 4 | var t = b; 5 | b = a % b; 6 | a = t; 7 | } 8 | return a; 9 | } 10 | 11 | void main() { 12 | print('GCD(1, 4) = ' + euclidean_gcd(1, 4).toString()); 13 | print('GCD(5, 3) = ' + euclidean_gcd(5, 3).toString()); 14 | print('GCD(3, 6) = ' + euclidean_gcd(3, 6).toString()); 15 | print('GCD(8, 4) = ' + euclidean_gcd(8, 4).toString()); 16 | } 17 | -------------------------------------------------------------------------------- /other/haversine_formula.dart: -------------------------------------------------------------------------------- 1 | /// Based on https://www.movable-type.co.uk/scripts/latlong.html 2 | import "dart:math"; 3 | 4 | const double earthRadius = 6371; 5 | 6 | /// Earth radius in kilometers 7 | 8 | class Coordinates { 9 | double latitude; 10 | double longitude; 11 | 12 | Coordinates(this.latitude, this.longitude); 13 | } 14 | 15 | double haversine(fi) => pow(sin(fi / 2), 2).toDouble(); 16 | 17 | /// Convert [angle] to radians 18 | double radians(double angle) => (angle * pi) / 180; 19 | 20 | /// Calculate distance from [p1] to [p2] in kilometers 21 | /// We assume that earth is perfect sphere (which is not true) 22 | /// In practice you might expect ~1% errors 23 | double distance(Coordinates p1, Coordinates p2) { 24 | double latitudeChange = radians(p2.latitude - p1.latitude); 25 | double latitude1 = radians(p1.latitude); 26 | double latitude2 = radians(p2.latitude); 27 | double longitudeChange = radians(p2.longitude - p1.longitude); 28 | 29 | double a = haversine(latitudeChange) + 30 | cos(latitude1) * cos(latitude2) * haversine(longitudeChange); 31 | double c = 2 * atan2(sqrt(a), sqrt(1 - a)); 32 | 33 | return earthRadius * c; 34 | } 35 | 36 | void main() { 37 | Coordinates newYork = new Coordinates(40.730610, -73.935242); 38 | Coordinates moskov = new Coordinates(55.751244, 37.618423); 39 | Coordinates toronto = new Coordinates(43.651070, -79.347015); 40 | Coordinates seoul = new Coordinates(37.532600, 127.024612); 41 | 42 | print("distance(newYork, moskov) = ${distance(newYork, moskov)}km"); 43 | print("distance(newYork, toronto) = ${distance(newYork, toronto)}km"); 44 | print("distance(seoul, moskov) = ${distance(seoul, moskov)}km"); 45 | print("distance(moskov, seoul) = ${distance(moskov, seoul)}km"); 46 | } 47 | -------------------------------------------------------------------------------- /other/heaps_algorithm.dart: -------------------------------------------------------------------------------- 1 | /// Swap given [index1] and [index2] in given [collection] 2 | void swap(List collection, int index1, int index2) { 3 | T temp = collection[index1]; 4 | collection[index1] = collection[index2]; 5 | collection[index2] = temp; 6 | } 7 | 8 | /// Returns all permutations of given [collection] 9 | List> permutations(List collection) { 10 | List stack = List.generate(collection.length, (x) => 0); 11 | 12 | List currentPermutation = List.from(collection); 13 | List> output = [collection]; 14 | 15 | int i = 0; 16 | while (i < collection.length) { 17 | if (stack[i] < i) { 18 | if (i % 2 == 0) { 19 | swap(currentPermutation, 0, i); 20 | } else { 21 | swap(currentPermutation, stack[i], i); 22 | } 23 | output.add(List.from(currentPermutation)); 24 | stack[i]++; 25 | i = 0; 26 | } else { 27 | stack[i] = 0; 28 | i++; 29 | } 30 | } 31 | return output; 32 | } 33 | 34 | main() { 35 | print(permutations([])); 36 | print(permutations([1, 2])); 37 | print(permutations([1, 2, 3])); 38 | 39 | print("3! = ${permutations([1, 2, 3]).length}"); 40 | print("4! = ${permutations([1, 2, 3, 4]).length}"); 41 | print("5! = ${permutations([1, 2, 3, 4, 5]).length}"); 42 | print("6! = ${permutations([1, 2, 3, 4, 5, 6]).length}"); 43 | } 44 | -------------------------------------------------------------------------------- /other/kadaneAlgo.dart: -------------------------------------------------------------------------------- 1 | // Program to find the Maximum contiguous sum (Kadane's Algorithm) 2 | // Function to Calculate Maximum of Two Number 3 | int max(int a, int b) { 4 | if (a > b) 5 | return a; 6 | else 7 | return b; 8 | } 9 | 10 | // Function to find the Maximum contiguous Sum in the array 11 | int maxSubArraySum(List a, int size) { 12 | int max_so_far = a[0]; 13 | int curr_max = a[0]; 14 | 15 | for (int i = 1; i < size; i++) { 16 | curr_max = max(a[i], curr_max + a[i]); 17 | max_so_far = max(max_so_far, curr_max); 18 | } 19 | return max_so_far; 20 | } 21 | 22 | // main function for validation of the above 23 | int main() { 24 | List a = [-2, -3, 4, -1, -2, 1, 5, -3]; 25 | int n = a.length; 26 | int max_sum = maxSubArraySum(a, n); 27 | print("Maximum contiguous sum is " + max_sum.toString()); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /other/magic_number.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | bool Magic_no(var x) { 4 | var result = x % 9; 5 | return result == 1; 6 | } 7 | 8 | void main() { 9 | test("Test Magic_no returns false for non-magic numbers", () { 10 | expect(Magic_no(0), isFalse); 11 | expect(Magic_no(371), isFalse); 12 | expect(Magic_no(509), isFalse); 13 | expect(Magic_no(501), isFalse); 14 | }); 15 | 16 | test("Test Magic_no returns true for magic numbers", () { 17 | expect(Magic_no(10), isTrue); 18 | expect(Magic_no(370), isTrue); 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /other/swap_all_odd_and_even_bits.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | //we are given an integer,the tast is to get its binary representation,swap all odd and even bits and print the new number 4 | int swapbits(int n) { 5 | return (((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)); 6 | } 7 | 8 | void main() { 9 | test("swapbits returns 1 for 2", () { 10 | expect(swapbits(2), equals(1)); 11 | }); 12 | 13 | test("swapbits returns 23 for 43", () { 14 | expect(swapbits(43), equals(23)); 15 | }); 16 | 17 | test("swapbits returns 43 for 23", () { 18 | expect(swapbits(23), equals(43)); 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /other/tower_of_hanoi.dart: -------------------------------------------------------------------------------- 1 | moveDisk(String fp, String tp) { 2 | print('moving disk from ' + fp + ' to ' + tp); 3 | } 4 | 5 | moveTower(int height, var fromPole, var toPole, var withPole) { 6 | if (height >= 1) { 7 | moveTower(height - 1, fromPole, withPole, fromPole); 8 | moveDisk(fromPole, toPole); 9 | moveTower(height - 1, withPole, toPole, fromPole); 10 | } 11 | } 12 | 13 | void main() { 14 | int height = 3; 15 | moveTower(height, 'A', 'B', 'C'); 16 | /* 17 | moving disk from A to A 18 | moving disk from A to C 19 | moving disk from A to C 20 | moving disk from A to B 21 | moving disk from C to A 22 | moving disk from C to B 23 | moving disk from A to B 24 | */ 25 | } 26 | -------------------------------------------------------------------------------- /project_euler/problem_1/sol1.dart: -------------------------------------------------------------------------------- 1 | ///Author: Shawn 2 | ///Email: stepfencurryxiao@gmail.com 3 | 4 | /* 5 | * [Problem 1](https://projecteuler.net/problem=1) solution 6 | * Problem Statement: 7 | * If we list all the natural numbers below 10 that are multiples of 3 8 | * or 5, 9 | * we get 3,5,6 and 9. The sum of these multiples is 23. 10 | * Find the sum of all the multiples of 3 or 5 below N. 11 | */ 12 | 13 | int sol(int t) { 14 | int sum = 0; 15 | int terms = (t - 1) ~/ 3; 16 | sum += ((terms) * (6 + (terms - 1) * 3)) ~/ 2; // sum of an A.P. 17 | terms = (t - 1) ~/ 5; 18 | sum += ((terms) * (10 + (terms - 1) * 5)) ~/ 2; 19 | terms = (t - 1) ~/ 15; 20 | sum -= ((terms) * (30 + (terms - 1) * 15)) ~/ 2; 21 | 22 | return sum; 23 | } 24 | 25 | int main() { 26 | int value = sol(4); 27 | print("solution(4): $value"); 28 | value = sol(3); 29 | print("solution(3): $value"); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /project_euler/problem_10/sol10.dart: -------------------------------------------------------------------------------- 1 | /** 2 | * Project Euler Problem 10: https://projecteuler.net/problem=10 3 | * Summation of primes 4 | * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 5 | * Find the sum of all the primes below two million. 6 | */ 7 | 8 | import 'dart:math'; 9 | import 'package:test/test.dart'; 10 | 11 | void main() { 12 | print("Solution 1 => ${solution1(2000000)}"); 13 | print("Solution 2 => ${solution2(2000000)}"); 14 | 15 | test("Test isPrime", () { 16 | expect(isPrime(-2), false); 17 | expect(isPrime(0), false); 18 | expect(isPrime(1), false); 19 | expect(isPrime(2), true); 20 | }); 21 | 22 | test("Test solution1", () { 23 | expect(solution1(10), 17); 24 | expect(solution1(20), 77); 25 | }); 26 | 27 | test("Test solution2", () { 28 | expect(solution2(10), 17); 29 | expect(solution2(20), 77); 30 | }); 31 | } 32 | 33 | int solution1(int n) { 34 | var sum = 0; 35 | 36 | for (int i = 2; i < n; i++) { 37 | if (isPrime(i)) sum += i; 38 | } 39 | return sum; 40 | } 41 | 42 | int solution2(int n) { 43 | if (n <= 2) return 0; 44 | if (n <= 3) return 2; 45 | 46 | var sum = 5; 47 | var i = 5; 48 | 49 | while (i < n) { 50 | if (isPrime(i)) sum += i; 51 | i += 2; 52 | if (i < n && isPrime(i)) sum += i; 53 | i += 4; 54 | } 55 | return sum; 56 | } 57 | 58 | bool isPrime(int number) { 59 | if (number <= 1) return false; 60 | 61 | var root = sqrt(number).floor(); 62 | 63 | for (int div = 2; div <= root; div++) { 64 | if (number % div == 0) return false; 65 | } 66 | 67 | return true; 68 | } 69 | -------------------------------------------------------------------------------- /project_euler/problem_12/sol12.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | List prime_sieve(int limit) { 4 | int sieve_bound = (limit - 1) ~/ 2; 5 | int upper_sqrt = (sqrt(limit).toInt() - 1) ~/ 2; 6 | List prime_bits = List.generate(sieve_bound + 1, (_) => true); 7 | 8 | for (int i = 1; i <= upper_sqrt; ++i) 9 | if (prime_bits[i]) 10 | for (int j = i * (i + 1) * 2; j <= sieve_bound; j += 2 * i + 1) 11 | prime_bits[j] = false; 12 | 13 | List primes = [2]; 14 | for (int i = 1; i <= sieve_bound; ++i) 15 | if (prime_bits[i]) primes.add(2 * i + 1); 16 | 17 | return primes; 18 | } 19 | 20 | int prime_factorisation_number_of_divisors(int n, List primes) { 21 | int nod = 1; 22 | int remain = n; 23 | for (int i = 0; i < primes.length; ++i) { 24 | if (primes[i] * primes[i] > n) return nod * 2; 25 | int power = 1; 26 | while (remain % primes[i] == 0) { 27 | power += 1; 28 | remain ~/= primes[i]; 29 | } 30 | nod *= power; 31 | if (remain == 1) break; 32 | } 33 | return nod; 34 | } 35 | 36 | void main() { 37 | int i = 2; 38 | int count = 0; 39 | int odd = 2; 40 | int even = 2; 41 | List primes = prime_sieve(500); 42 | while (count < 500) { 43 | even = i % 2 == 0 44 | ? prime_factorisation_number_of_divisors(i + 1, primes) 45 | : even; 46 | odd = i % 2 != 0 47 | ? prime_factorisation_number_of_divisors((i + 1) ~/ 2, primes) 48 | : odd; 49 | count = even * odd; 50 | ++i; 51 | } 52 | int ans = (i * (i - 1) * 0.5).toInt(); 53 | print("First Triangle Number with more than 500 divisors: $ans"); 54 | } 55 | -------------------------------------------------------------------------------- /project_euler/problem_17/sol17.dart: -------------------------------------------------------------------------------- 1 | /// Author: Pasan Godamune 2 | /// Email: pasanjg@gmail.com 3 | 4 | /** 5 | * [Problem 17](https://projecteuler.net/problem=17) solution 6 | * Problem Statement: 7 | * If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. 8 | * If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? 9 | * 10 | * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. 11 | * The use of "and" when writing out numbers is in compliance with British usage. 12 | */ 13 | 14 | import 'dart:math'; 15 | 16 | const ONES = [ 17 | 'One', 18 | 'Two', 19 | 'Three', 20 | 'Four', 21 | 'Five', 22 | 'Six', 23 | 'Seven', 24 | 'Eight', 25 | 'Nine', 26 | 'Ten' 27 | ]; 28 | 29 | const TEN_TWENTY = [ 30 | 'Eleven', 31 | 'Twelve', 32 | 'Thirteen', 33 | 'Fourteen', 34 | 'Fifteen', 35 | 'Sixteen', 36 | 'Seventeen', 37 | 'Eighteen', 38 | 'Nineteen' 39 | ]; 40 | 41 | const TENS = [ 42 | 'Ten', 43 | 'Twenty', 44 | 'Thirty', 45 | 'Forty', // [It's 'Forty' NOT 'Fourty'](https://www.grammarly.com/blog/forty-fourty/) 46 | 'Fifty', 47 | 'Sixty', 48 | 'Seventy', 49 | 'Eighty', 50 | 'Ninety' 51 | ]; 52 | 53 | const HUNDRED = 'Hundred'; 54 | const THOUSDAND = 'Thousand'; 55 | const AND = 'And'; 56 | 57 | String inWords = ""; 58 | 59 | String convertToWords(int number) { 60 | String numString = number.toString(); 61 | int length = numString.length; 62 | int place = pow(10, length - 1).toInt(); 63 | 64 | if (number == 0) return inWords = "Zero"; 65 | 66 | if (length == 1) { 67 | inWords = ONES[number - 1]; 68 | } 69 | 70 | if (length == 2) { 71 | inWords = TENS[(number / place).floor() - 1]; 72 | 73 | if (number % place != 0) { 74 | if (number < 20) { 75 | return inWords = TEN_TWENTY[(number % place) - 1]; 76 | } 77 | 78 | inWords += convertToWords(number % place); 79 | } 80 | } 81 | 82 | if (length == 3) { 83 | inWords = convertToWords((number / place).floor()) + HUNDRED; 84 | 85 | if (number % place != 0) { 86 | inWords += AND + convertToWords(number % place); 87 | } 88 | } 89 | 90 | if (length == 4) { 91 | inWords = convertToWords((number / place).floor()) + THOUSDAND; 92 | 93 | if (number % place != 0) { 94 | inWords += AND + convertToWords(number % place); 95 | } 96 | } 97 | 98 | return inWords; 99 | } 100 | 101 | calculateWithRange({int start = 1, end = 1000}) { 102 | int count = 0; 103 | 104 | if (end > 1000) { 105 | print("Max safe range is 0 - 1000 inclusive"); 106 | return; 107 | } 108 | 109 | for (int i = start; i <= end; i++) { 110 | count += convertToWords(i).length; 111 | } 112 | 113 | print(count); 114 | } 115 | 116 | void main() { 117 | calculateWithRange(start: 1, end: 1000); // 21124 118 | } 119 | -------------------------------------------------------------------------------- /project_euler/problem_2/sol2.dart: -------------------------------------------------------------------------------- 1 | //Title:Project Euler Prob 2 - Even Fibonacci numbers 2 | // Author:ShivamVerma 3 | // Email:shivamthegreat.sv@gmail.com 4 | 5 | // Each new term in the Fibonacci sequence is generated by adding the previous two terms. 6 | // By starting with 1 and 2, the first 10 terms will be: 7 | 8 | // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 9 | 10 | // By considering the terms in the Fibonacci sequence whose values do not exceed four million, 11 | // find the sum of the even-valued terms. 12 | 13 | int evenFibSum(int limit) { 14 | if (limit < 2) return 0; 15 | 16 | // Initialize first two even prime numbers 17 | // and their sum 18 | int ef1 = 0, ef2 = 2; 19 | int sum = ef1 + ef2; 20 | 21 | // calculating sum of even Fibonacci value 22 | while (ef2 <= limit) { 23 | // get next even value of Fibonacci sequence 24 | int ef3 = 4 * ef2 + ef1; 25 | 26 | // If we go beyond limit, we break loop 27 | if (ef3 > limit) break; 28 | 29 | // Move to next even number and update sum 30 | ef1 = ef2; 31 | ef2 = ef3; 32 | sum += ef2; 33 | } 34 | 35 | return sum; 36 | } 37 | 38 | //driver code 39 | void main() { 40 | int limit = 4000000; 41 | print(evenFibSum(limit)); 42 | } 43 | -------------------------------------------------------------------------------- /project_euler/problem_20/sol20.dart: -------------------------------------------------------------------------------- 1 | /* 2 | Problem 20: Factorial digit sum 3 | 4 | n! means n × (n − 1) × ... × 3 × 2 × 1 5 | For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, 6 | and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. 7 | Find the sum of the digits in the number 100! 8 | */ 9 | 10 | import 'package:test/test.dart'; 11 | 12 | // To Calculate Factorial 13 | int factorial(int number) { 14 | int factorial = 1; 15 | for (int i = number; i >= 1; i--) { 16 | factorial *= i; 17 | } 18 | return factorial; 19 | } 20 | 21 | // To Calculate Sum 22 | int sum(int number) { 23 | int sum = 0; 24 | for (int i = factorial(number); i > 0; i = (i / 10).floor()) { 25 | sum += (i % 10); 26 | } 27 | return sum; 28 | } 29 | 30 | // Driver Code 31 | void main() { 32 | group("Solution 20", () { 33 | test("Test 1", () { 34 | expect(1, sum(1)); 35 | }); 36 | 37 | test("Test 2", () { 38 | expect(3, sum(5)); 39 | }); 40 | 41 | test("Test 3", () { 42 | expect(27, sum(10)); 43 | }); 44 | }); 45 | } 46 | -------------------------------------------------------------------------------- /project_euler/problem_3/sol3.dart: -------------------------------------------------------------------------------- 1 | //Title:Project Euler Prob 3 2 | // Author:Shivam Verma 3 | // Email:shivamthegreat.sv@gmail.com 4 | 5 | // The prime factors of 13195 are 5, 7, 13 and 29. 6 | 7 | // What is the largest prime factor of the number 600851475143 ? 8 | 9 | void main() { 10 | double i, n = 600851475143; 11 | 12 | for (i = 3; n > 1; i += 2) while (n % i == 0) n /= i; 13 | 14 | print(i - 2); 15 | } 16 | -------------------------------------------------------------------------------- /project_euler/problem_4/sol4.dart: -------------------------------------------------------------------------------- 1 | // Author : Devmaufh 2 | // Email : mau1361317@gmail.com 3 | 4 | /** 5 | * [Problem 4](https://projecteuler.net/problem=4) solution 6 | * Problem Statement: 7 | * A palindromic number reads the same both ways. 8 | * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. 9 | * Find the largest palindrome made from the product of two 3-digit numbers. 10 | */ 11 | 12 | void main() { 13 | int max = 0; 14 | for (int i = 100; i < 1000; i++) { 15 | for (int j = 100; j < 1000; j++) { 16 | int result = i * j; 17 | if (isPanlindrome("$result")) { 18 | if (result > max) { 19 | max = result; 20 | } 21 | } 22 | } 23 | } 24 | print("MAX $max"); 25 | } 26 | 27 | bool isPanlindrome(String word) { 28 | for (int i = 0; i < word.length ~/ 2; i++) { 29 | if (word[i] != word[word.length - i - 1]) return false; 30 | } 31 | return true; 32 | } 33 | -------------------------------------------------------------------------------- /project_euler/problem_5/sol5.dart: -------------------------------------------------------------------------------- 1 | // Author : Devmaufh 2 | // Email : mau1361317@gmail.com 3 | 4 | /** 5 | * [Problem 5](https://projecteuler.net/problem=5) solution 6 | * Problem Statement: 7 | * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. 8 | * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? 9 | */ 10 | 11 | void main() { 12 | int number = 21; 13 | LOOP: 14 | while (true) { 15 | bool isSolution = true; 16 | for (int i = 1; i <= 21; i++) { 17 | if (number % i != 0) { 18 | isSolution = false; 19 | break; // Break if have a remainder 20 | } 21 | } 22 | if (isSolution) 23 | break LOOP; //If any number hasn't a remainder, break main loop because we found the solution 24 | number++; 25 | } 26 | print("Solution problem 5 = $number"); 27 | } 28 | -------------------------------------------------------------------------------- /project_euler/problem_6/sol6.dart: -------------------------------------------------------------------------------- 1 | /// Author: Pasan Godamune 2 | /// Email: pasanjg@gmail.com 3 | 4 | /** 5 | * [Problem 6](https://projecteuler.net/problem=6) solution 6 | * Problem Statement: 7 | * The sum of the squares of the first ten natural numbers is, 8 | * 1^2 + 2^2 + … + 10^2 = 385 9 | * The square of the sum of the first ten natural numbers is, 10 | * (1 + 2 + … + 10)^2 = 552 = 3025 11 | * Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. 12 | * Find the difference between the sum of the squares of the first one hundred natural numbers natural numbers and the square of the sum. 13 | */ 14 | 15 | import 'dart:math'; 16 | 17 | squareDifference(n) { 18 | return squareSumOfFirst(n) - sumOfSquare(n); 19 | } 20 | 21 | sumOfSquare(n) { 22 | return (((n * (n + 1)) * (n + (n + 1))) / 6); 23 | } 24 | 25 | squareSumOfFirst(n) { 26 | return pow((n + 1) * (n / 2), 2); 27 | } 28 | 29 | void main() { 30 | int n = 100; 31 | print(squareDifference(n)); 32 | 33 | /// 25164150 34 | } 35 | -------------------------------------------------------------------------------- /project_euler/problem_7/sol7.dart: -------------------------------------------------------------------------------- 1 | // Author : Devmaufh 2 | // Email : mau1361317@gmail.com 3 | 4 | /** 5 | * [Problem 7](https://projecteuler.net/problem=7) solution 6 | * Problem Statement: 7 | * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. 8 | * What is the 10 001st prime number? 9 | */ 10 | 11 | void main() { 12 | int numberOfPrimes = 0; 13 | int number = 1; 14 | while (numberOfPrimes < 10001) { 15 | number++; 16 | if (isPrime(number)) { 17 | numberOfPrimes++; 18 | } 19 | } 20 | print(" 10 001st prime number is => $number "); 21 | } 22 | 23 | bool isPrime(int number) { 24 | if (number < 2) return false; 25 | for (int i = 2; i < number; i++) if (number % i == 0) return false; 26 | return true; 27 | } 28 | -------------------------------------------------------------------------------- /project_euler/problem_8/sol8.dart: -------------------------------------------------------------------------------- 1 | /// Author: Pasan Godamune 2 | /// Email: pasanjg@gmail.com 3 | 4 | /** 5 | * [Problem 8](https://projecteuler.net/problem=8) solution 6 | * Problem Statement: 7 | * The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 8 | 9 | 73167176531330624919225119674426574742355349194934 10 | 96983520312774506326239578318016984801869478851843 11 | 85861560789112949495459501737958331952853208805511 12 | 12540698747158523863050715693290963295227443043557 13 | 66896648950445244523161731856403098711121722383113 14 | 62229893423380308135336276614282806444486645238749 15 | 30358907296290491560440772390713810515859307960866 16 | 70172427121883998797908792274921901699720888093776 17 | 65727333001053367881220235421809751254540594752243 18 | 52584907711670556013604839586446706324415722155397 19 | 53697817977846174064955149290862569321978468622482 20 | 83972241375657056057490261407972968652414535100474 21 | 82166370484403199890008895243450658541227588666881 22 | 16427171479924442928230863465674813919123162824586 23 | 17866458359124566529476545682848912883142607690042 24 | 24219022671055626321111109370544217506941658960408 25 | 07198403850962455444362981230987879927244284909188 26 | 84580156166097919133875499200524063689912560717606 27 | 05886116467109405077541002256983155200055935729725 28 | 71636269561882670428252483600823257530420752963450 29 | 30 | * Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. 31 | * What is the value of this product? 32 | */ 33 | 34 | void main() { 35 | String series = "73167176531330624919225119674426574742355349194934" 36 | "96983520312774506326239578318016984801869478851843" 37 | "85861560789112949495459501737958331952853208805511" 38 | "12540698747158523863050715693290963295227443043557" 39 | "66896648950445244523161731856403098711121722383113" 40 | "62229893423380308135336276614282806444486645238749" 41 | "30358907296290491560440772390713810515859307960866" 42 | "70172427121883998797908792274921901699720888093776" 43 | "65727333001053367881220235421809751254540594752243" 44 | "52584907711670556013604839586446706324415722155397" 45 | "53697817977846174064955149290862569321978468622482" 46 | "83972241375657056057490261407972968652414535100474" 47 | "82166370484403199890008895243450658541227588666881" 48 | "16427171479924442928230863465674813919123162824586" 49 | "17866458359124566529476545682848912883142607690042" 50 | "24219022671055626321111109370544217506941658960408" 51 | "07198403850962455444362981230987879927244284909188" 52 | "84580156166097919133875499200524063689912560717606" 53 | "05886116467109405077541002256983155200055935729725" 54 | "71636269561882670428252483600823257530420752963450"; 55 | 56 | largestAdjacentNumbers(series, {adjacentLength = 4}) { 57 | var largestProduct = 0; 58 | 59 | for (int i = 0; i < series.length - adjacentLength + 1; i++) { 60 | var subset = series.substring(i, adjacentLength + i); 61 | 62 | var numList = subset.split('').map((x) => int.parse(x)); 63 | var product = numList.reduce((a, b) => a * b); 64 | 65 | if (product > largestProduct) largestProduct = product; 66 | } 67 | return largestProduct; 68 | } 69 | 70 | print(largestAdjacentNumbers(series, adjacentLength: 13)); // 23514624000 71 | } 72 | -------------------------------------------------------------------------------- /project_euler/problem_9/sol9.dart: -------------------------------------------------------------------------------- 1 | // Author : Devmaufh 2 | // Email : mau1361317@gmail.com 3 | 4 | /** 5 | * [Problem 9](https://projecteuler.net/problem=8) solution 6 | * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, 7 | * a^2 + b^2 = c^2 8 | * For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. 9 | * There exists exactly one Pythagorean triplet for which a + b + c = 1000. 10 | * Find the product abc. 11 | */ 12 | 13 | void main() { 14 | for (int i = 0; i <= 300; ++i) { 15 | for (int j = 0; j <= 400; ++j) { 16 | int k = 1000 - i - j; 17 | if (i * i + j * j == k * k) { 18 | var sol = i * j * k; 19 | print("Solution : $sol"); 20 | break; 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: the_algorithms_dart 2 | 3 | repository: https://github.com/TheAlgorithms/Dart 4 | 5 | dependencies: 6 | test: ^1.15.4 7 | coverage: ^1.6.0 8 | 9 | dev_dependencies: 10 | stack: ^0.2.1 11 | 12 | environment: 13 | sdk: ">=2.12.0 <3.0.0" 14 | -------------------------------------------------------------------------------- /search/binary_Search.dart: -------------------------------------------------------------------------------- 1 | int binary_search(List a, int l, int r, int x) { 2 | if (r >= l) { 3 | int middle = (l + (r - l) / 2).toInt(); 4 | 5 | //If the element is present at middle 6 | if (a[middle] == x) { 7 | return middle; 8 | } 9 | 10 | //If the element is smaller than middle 11 | if (a[middle] > x) { 12 | return binary_search(a, l, middle - 1, x); 13 | } 14 | 15 | return binary_search(a, middle + 1, r, x); 16 | } 17 | return -1; 18 | } 19 | 20 | void main() { 21 | List list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; 22 | int x = 55; 23 | int n = list.length; 24 | int index = binary_search(list, 0, n - 1, x); 25 | print('list:'); 26 | print(list); 27 | if (index != -1) { 28 | print('$x found at positions: $index'); 29 | } else { 30 | print('$x Not found'); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /search/binary_search_recursion.dart: -------------------------------------------------------------------------------- 1 | /* Driver */ 2 | void main() { 3 | List list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 4 | 5 | int low = 0; 6 | int high = list.length - 1; 7 | 8 | assert(binarySearch(list, low, high, 5) == 5); 9 | assert(binarySearch(list, low, high, 9) == 9); 10 | assert(binarySearch(list, low, high, 66) == -1); 11 | } 12 | 13 | /** 14 | * Return the index of [key] value in [list] 15 | */ 16 | int binarySearch(List list, int low, int high, int key) { 17 | if (low > high) { 18 | return -1; /* not found */ 19 | } 20 | int mid = (low + high) >> 1; 21 | if (key == list[mid]) { 22 | return mid; /* found */ 23 | } else if (key > list[mid]) { 24 | return binarySearch( 25 | list, mid + 1, high, key); /* search in range[mid + 1, high] */ 26 | } else { 27 | return binarySearch( 28 | list, low, mid - 1, key); /* search in range[low, mid - 1] */ 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /search/fibonacci_Search.dart: -------------------------------------------------------------------------------- 1 | //Title:Fibonacci Search 2 | //Author:Shawn 3 | //Email:stepfencurryxiao@gmail.com 4 | 5 | int fibMaonaccianSearch(List arr, int x, int n) { 6 | //Initialize fibonacci numbers 7 | //(m - 2)'th Fibonacci No 8 | int fibMMm2 = 0; 9 | //(m - 2)'th Fibonacci No 10 | int fibMMm1 = 1; 11 | //m'th Fibonacci 12 | int fibM = fibMMm2 + fibMMm1; 13 | 14 | //fibM is going to store the smallest Fibonacci 15 | //Number greater than or equal to n 16 | while (fibM < n) { 17 | fibMMm2 = fibMMm1; 18 | fibMMm1 = fibM; 19 | fibM = fibMMm2 + fibMMm1; 20 | } 21 | 22 | // Marks the eliminated range from front 23 | int offset = -1; 24 | 25 | /*While three are elements to be inspected. 26 | * Note that we compare arr[fibMMm2] with x. 27 | * When fibM becomes 1, 28 | * fibMm2 becomes 0 */ 29 | while (fibM > 1) { 30 | //Check if fibMMm2 is a valid location 31 | 32 | //sets i to the min. of (offset + fibMMm2) and (n - 1) 33 | int i = ((offset + fibMMm2) < (n - 1)) ? (offset + fibMMm2) : (n - 1); 34 | 35 | /* If x is greater than the value at index fibMmm2 36 | * cut the subarray array from offset to i 37 | */ 38 | 39 | if (arr[i] < x) { 40 | fibM = fibMMm1; 41 | fibMMm1 = fibMMm2; 42 | fibMMm2 = fibM - fibMMm1; 43 | offset = i; 44 | } 45 | 46 | /* If x is greater than the value at index fibMmm2 47 | * cut the subarray array after i + 1. 48 | */ 49 | else if (arr[i] > x) { 50 | fibM = fibMMm2; 51 | fibMMm1 = fibMMm1 - fibMMm2; 52 | fibMMm2 = fibM - fibMMm1; 53 | } 54 | 55 | //elwment found.Return index 56 | else { 57 | return i; 58 | } 59 | } 60 | 61 | //Comparing the last element with x 62 | if (arr[offset + 1] == x) { 63 | return offset + 1; 64 | } 65 | 66 | //element not found :( 67 | return -1; 68 | } 69 | 70 | void main() { 71 | //Get the array 72 | var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 73 | 74 | var result; 75 | 76 | //Print the array 77 | print(arr); 78 | 79 | //The size of the array 80 | var n = arr.length; 81 | 82 | //Key to be searched in the array 83 | var key = 7; 84 | 85 | //Search the key using ternarySearch 86 | result = fibMaonaccianSearch(arr, key, n); 87 | 88 | //Print the result 89 | print("Index of " + key.toString() + " is " + result.toString()); 90 | } 91 | -------------------------------------------------------------------------------- /search/interpolation_Search.dart: -------------------------------------------------------------------------------- 1 | /* By comparison, binary search always chooses the middle of the remaining 2 | * search space, discarding one half or the other, depending on the comparison 3 | * between the key found at the estimated position and the key sought. The remaining 4 | * search space is reduced to the part before or after the estimated position. 5 | * The linear search uses equality only as it compares elements one-by-one from the start, ignoring any sorting. 6 | * On average the interpolation search makes about log(log(n)) comparisons (if the elements 7 | * are uniformly distributed), where n is the number of elements to be searched. In the worst case 8 | * (for instance where the numerical values of the keys increase exponentially) it can make up to O(n) comparisons. 9 | * In interpolation-sequential search, interpolation is used to find an item near the one being searched for, 10 | * then linear search is used to find the exact item. */ 11 | 12 | //Author:Shawn 13 | //Email:stepfencurryxiao@gmail.com 14 | 15 | int interpolationSearch(List arr, int n, int key) { 16 | int low = 0, high = n - 1; 17 | while (low <= high && key >= arr[low] && key <= arr[high]) { 18 | /* Calculate the nearest possible position of key */ 19 | int pos = low + 20 | (((key - arr[low]) * (high - low)) / (arr[high] - arr[low])).round(); 21 | if (key > arr[pos]) 22 | low = pos + 1; 23 | else if (key < arr[pos]) 24 | high = pos - 1; 25 | else /* Found */ 26 | return pos; 27 | } 28 | /* Not found */ 29 | return -1; 30 | } 31 | 32 | int main() { 33 | //Get the arr 34 | List arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 35 | //The size of the arr 36 | var n = arr.length; 37 | //The Key 38 | var key = 5; 39 | print("I want to found $key at $arr"); 40 | //Get the index 41 | var index = interpolationSearch(arr, n, key); 42 | //print the result 43 | print("Element found at position: $index"); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /search/jump_Search.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show sqrt; 2 | 3 | min(X, Y) { 4 | if (X < Y) { 5 | return X; 6 | } else { 7 | return Y; 8 | } 9 | } 10 | 11 | int jump_search(List a, int x) { 12 | int n = a.length; 13 | int step = sqrt(n).floor().toInt(); 14 | int prev = 0; 15 | while (a[min(step, n) - 1] < x) { 16 | prev = step; 17 | step += sqrt(n).floor().toInt(); 18 | if (prev >= n) { 19 | return -1; 20 | } 21 | } 22 | while (a[prev] < x) { 23 | prev = prev + 1; 24 | if (prev == min(step, n)) { 25 | return -1; 26 | } 27 | } 28 | if (a[prev] == x) { 29 | return prev; 30 | } 31 | return -1; 32 | } 33 | 34 | void main() { 35 | var list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; 36 | var x = 55; 37 | var index = jump_search(list, x); 38 | print('list:'); 39 | print(list); 40 | print('Number ' + x.toString() + ' is at index ' + index.toString()); 41 | } 42 | -------------------------------------------------------------------------------- /search/linear_Search.dart: -------------------------------------------------------------------------------- 1 | int linear_search(List a, number) { 2 | for (int i = 0; i < a.length; i++) { 3 | if (a[i] == number) { 4 | return i; 5 | } 6 | } 7 | return -1; 8 | } 9 | 10 | void main() { 11 | List list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; 12 | int x = 15; 13 | int index = linear_search(list, x); 14 | print('list:'); 15 | print(list); 16 | if (index != -1) { 17 | print('$x found at positions: $index'); 18 | } else { 19 | print('$x Not found'); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /search/peak_element.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | int findPeakUtil(List arr, int low, int high, int n) { 4 | var x = (low + high) / 2; 5 | int mid = x.toInt(); 6 | if ((mid == 0 || arr[mid - 1] <= arr[mid]) && 7 | (mid == n - 1 || arr[mid + 1] <= arr[mid])) 8 | return mid; 9 | else if (mid > 0 && arr[mid - 1] > arr[mid]) 10 | return findPeakUtil(arr, low, (mid - 1), n); 11 | else 12 | return findPeakUtil(arr, (mid + 1), high, n); 13 | } 14 | 15 | int findPeak(List arr, int n) { 16 | return findPeakUtil(arr, 0, n - 1, n); 17 | } 18 | 19 | void main() { 20 | test("findPeak returns 2 for [1, 3, 20, 6, 1, 2]", () { 21 | List lst = [1, 3, 20, 6, 1, 2]; 22 | expect(findPeak(lst, lst.length), equals(2)); 23 | }); 24 | 25 | test("findPeak returns 3 for [1, 3, 20, 32, 1, 2]", () { 26 | List lst = [1, 3, 20, 32, 1, 2]; 27 | expect(findPeak(lst, lst.length), equals(3)); 28 | }); 29 | 30 | test("findPeak returns 2 for [321, 4353, 22320, 232, 23, 223]", () { 31 | List lst = [321, 4353, 22320, 232, 23, 223]; 32 | expect(findPeak(lst, lst.length), equals(2)); 33 | }); 34 | 35 | test("findPeak returns 2 for [121, 54, 2100, 36, 155, 90]", () { 36 | List lst = [121, 54, 2100, 36, 155, 90]; 37 | expect(findPeak(lst, lst.length), equals(2)); 38 | }); 39 | 40 | test("findPeak returns 2 for [5, 10, 20, 15]", () { 41 | List lst = [5, 10, 20, 15]; 42 | expect(findPeak(lst, lst.length), equals(2)); 43 | }); 44 | 45 | test("findPeak returns 1 for [10, 20, 15, 2, 23, 90, 67]", () { 46 | List lst = [10, 20, 15, 2, 23, 90, 67]; 47 | expect(findPeak(lst, lst.length), equals(1)); 48 | }); 49 | } 50 | -------------------------------------------------------------------------------- /search/ternary_Search.dart: -------------------------------------------------------------------------------- 1 | //Title:Ternary Search 2 | //Author:Shawn 3 | //Email:stepfencurryxiao@gmail.com 4 | 5 | int ternarySearch(var l, var r, var key, var arr) { 6 | if (r >= 1) { 7 | //Find the mid1 and mid2 8 | var mid1 = (l + (r - l) / 3).toInt(); 9 | var mid2 = (r - (r - 1) / 3).toInt(); 10 | 11 | //Check if key is present at any mid 12 | if (arr[mid1] == key) return mid1; 13 | 14 | if (arr[mid2] == key) return mid2; 15 | 16 | /*Since Key is not present at mid 17 | * check in which region it is present 18 | * then repeat the Search operation 19 | * in that region 20 | */ 21 | 22 | if (key < arr[mid1]) { 23 | //The Key lies in between 1 and mid1 24 | return ternarySearch(l, mid1 - 1, key, arr); 25 | } else if (key > arr[mid2]) { 26 | //The key lies in between mid2 and r 27 | return ternarySearch(mid2 + 1, r, key, arr); 28 | } else { 29 | //The key lies in between mid1 and mid2 30 | return ternarySearch(mid1 + 1, mid2 - 1, key, arr); 31 | } 32 | } 33 | 34 | //Key not found 35 | return -1; 36 | } 37 | 38 | //Driver code 39 | void main() { 40 | var l, r, p, key; 41 | 42 | //Get the array 43 | var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 44 | 45 | //Print the array 46 | print(arr); 47 | 48 | //Starting index 49 | l = 0; 50 | 51 | // length of array 52 | r = arr.length; 53 | 54 | //Checking for 5 55 | //Key to be searched in the array 56 | key = 5; 57 | 58 | //Search the key using ternarySearch 59 | p = ternarySearch(l, r, key, arr); 60 | 61 | //Print the result 62 | print("Index of " + key.toString() + " is " + p.toString()); 63 | } 64 | -------------------------------------------------------------------------------- /sort/bubble_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show Random; 2 | 3 | //main function,the program start 4 | void main() { 5 | final seed = 100, rnd = Random(), length = 100; 6 | var list = 7 | List.generate(length, (i) => rnd.nextInt(seed), growable: false); 8 | print('before sorting:'); 9 | print(list); 10 | print('---------------------------------------------'); 11 | print('After sorting:'); 12 | bubbleSort(list); 13 | print(list); 14 | } 15 | 16 | void bubbleSort(List a) { 17 | for (var i = 0, length = a.length; i < length - 1; ++i) { 18 | bool swapped = false; 19 | for (var j = 0; j < length - 1 - i; ++j) { 20 | if (a[j] > a[j + 1]) { 21 | /* swap */ 22 | var temp = a[j]; 23 | a[j] = a[j + 1]; 24 | a[j + 1] = temp; 25 | swapped = true; 26 | } 27 | } 28 | if (!swapped) { 29 | break; /* array has been sorted */ 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /sort/cocktail_sort.dart: -------------------------------------------------------------------------------- 1 | void cocktailSort(List lst) //function to sort a list 2 | { 3 | bool swap_done = true; 4 | do { 5 | swap_done = false; 6 | for (int i = 0; i < lst.length - 2; i++) { 7 | swap_done = swapItemCocktail(lst, i, swap_done); 8 | } 9 | 10 | if (swap_done) { 11 | swap_done = false; 12 | for (int i = lst.length - 2; i >= 0; i--) { 13 | swap_done = swapItemCocktail(lst, i, swap_done); 14 | } 15 | } 16 | } while (swap_done); 17 | } 18 | 19 | bool swapItemCocktail(List lst, int i, bool swap_done) { 20 | if (lst[i] > lst[i + 1]) { 21 | swap(lst, i); 22 | swap_done = true; 23 | } 24 | return swap_done; 25 | } 26 | 27 | void swap(List lst, int i) { 28 | int tmp = lst[i]; 29 | lst[i] = lst[i + 1]; 30 | lst[i + 1] = tmp; 31 | } 32 | 33 | void main() //driver function 34 | { 35 | var lst = [5, 3, 6, 7, 3, 378, 3, 1, -1]; 36 | print(lst); 37 | cocktailSort(lst); 38 | print(lst); 39 | } 40 | -------------------------------------------------------------------------------- /sort/comb_sort.dart: -------------------------------------------------------------------------------- 1 | // function for combsort 2 | void combSort(List list) { 3 | int gpVal = list.length; 4 | double shrink = 1.3; 5 | bool sortedBool = false; 6 | 7 | while (!sortedBool) { 8 | gpVal = (gpVal / shrink).floor(); 9 | if (gpVal > 1) { 10 | sortedBool = false; 11 | } else { 12 | gpVal = 1; 13 | sortedBool = true; 14 | } 15 | 16 | int i = 0; 17 | while (i + gpVal < list.length) { 18 | if (list[i] > list[i + gpVal]) { 19 | swap(list, i, gpVal); 20 | sortedBool = false; 21 | } 22 | i++; 23 | } 24 | } 25 | } 26 | 27 | // function to swap the values 28 | void swap(List list, int i, int gpVal) { 29 | int temp = list[i]; 30 | list[i] = list[i + gpVal]; 31 | list[i + gpVal] = temp; 32 | } 33 | 34 | void main() { 35 | //Get the dummy array 36 | List arr = [1, 451, 562, 2, 99, 78, 5]; 37 | // for printing the array before sorting 38 | print("Before sorting the array: $arr\n"); 39 | // applying combSort function 40 | combSort(arr); 41 | // printing the sortedBool value 42 | print("After sorting the array: $arr"); 43 | } 44 | -------------------------------------------------------------------------------- /sort/count_sort.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | List countSort(List arr) { 4 | // In case the list is empty, return an empty list 5 | if (arr.length == 0) return []; 6 | 7 | int min = arr[0], max = arr[0], i; 8 | List outputArr = [], countArr = []; 9 | for (int i in arr) { 10 | if (i > max) max = i; 11 | if (i < min) min = i; 12 | } 13 | 14 | int range = max - min + 1; 15 | 16 | // INITIALISING countArr with 0's 17 | for (i = 0; i < range; i++) { 18 | countArr.add(0); 19 | } 20 | for (i = 0; i < arr.length; i++) { 21 | outputArr.add(0); 22 | } 23 | 24 | for (i in arr) { 25 | countArr[i - min] += 1; 26 | } 27 | 28 | // PREFIX SUM OF countArr 29 | for (i = 1; i < countArr.length; i++) { 30 | countArr[i] += countArr[i - 1]; 31 | } 32 | 33 | // PUTING VALUES IN SORTED ARRAY 34 | for (i in arr) { 35 | int index = countArr[i - min]; 36 | outputArr[index - 1] = i; 37 | countArr[i - min] -= 1; 38 | } 39 | 40 | // COPYING VALUES OF SORTED ARRAY INTO ORIGINAL ARRAY 41 | for (i = 0; i < outputArr.length; i++) { 42 | arr[i] = outputArr[i]; 43 | } 44 | 45 | return arr; 46 | } 47 | 48 | int main() { 49 | test("Sorting of empty list returns empty list", () { 50 | expect(countSort([]), equals([])); 51 | }); 52 | test("Sorting one element list return same list", () { 53 | expect(countSort([1]), equals([1])); 54 | }); 55 | test("Sorting two times doesnt change input", () { 56 | List lst = [5, 7, 1, 10, 54, -1]; 57 | expect(countSort(lst), equals(countSort(countSort(lst)))); 58 | }); 59 | test("Sorting already sorted list returns same list", () { 60 | List lst = [1, 2, 3, 4, 10]; 61 | expect(countSort(lst), equals(lst)); 62 | }); 63 | test("count sort", () { 64 | expect(countSort([34, -2, 122, 24435, 23, 434, 232, 1323]), 65 | equals([-2, 23, 34, 122, 232, 434, 1323, 24435])); 66 | }); 67 | 68 | print(countSort([-10, -4, 1, 5, 2, -2])); 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /sort/gnome_Sort.dart: -------------------------------------------------------------------------------- 1 | // Sorting of array using gnome sort 2 | //Author:Shawn 3 | //Email:stepfencurryxiao@gmail.com 4 | 5 | //Function sort the array using gnome sort 6 | void gnomeSort(List arr, var n) { 7 | if (arr.isEmpty || n == 0) return; 8 | int first = 1; 9 | int second = 2; 10 | 11 | while (first < n) { 12 | if (arr[first - 1] <= arr[first]) { 13 | first = second; 14 | second++; 15 | } else { 16 | int temp = arr[first - 1]; 17 | arr[first - 1] = arr[first]; 18 | arr[first] = temp; 19 | first -= 1; 20 | if (first == 0) { 21 | first = 1; 22 | second = 2; 23 | } 24 | } 25 | } 26 | } 27 | 28 | void main() { 29 | //Get the array 30 | List arr = [10, 34, 6, 323, 7]; 31 | 32 | //Get size of the array 33 | int n = arr.length; 34 | 35 | //print the array 36 | print(arr); 37 | 38 | //Sorting of array using gnome sort 39 | gnomeSort(arr, n); 40 | 41 | //print the result 42 | print("Sorted:\n" + arr.toString()); 43 | } 44 | -------------------------------------------------------------------------------- /sort/heap_Sort.dart: -------------------------------------------------------------------------------- 1 | void sort(List arr) { 2 | //The length of the list 3 | int n = arr.length; 4 | 5 | //Build heap (rearrange array) 6 | for (int i = (n / 2 - 1).round(); i >= 0; i--) { 7 | heapify(arr, n, i); 8 | } 9 | 10 | // One by one extract an element from heap 11 | for (int i = n - 1; i >= 0; i--) { 12 | //Move current root to end 13 | var temp = arr[0]; 14 | arr[0] = arr[i]; 15 | arr[i] = temp; 16 | 17 | //call max heapify on the reduce heap 18 | heapify(arr, i, 0); 19 | } 20 | } 21 | 22 | void heapify(List arr, var n, int i) { 23 | //Init largest as root 24 | var largest = i; 25 | //left = 2*i + 1 26 | int l = 2 * i + 1; 27 | //right = 2*i + 2 28 | var r = 2 * i + 2; 29 | 30 | // If left child is lager than root 31 | if (l < n && arr[l] > arr[largest]) largest = l; 32 | 33 | // If right child is larger than largest so far 34 | if (r < n && arr[r] > arr[largest]) largest = r; 35 | 36 | // If largest is not root 37 | if (largest != i) { 38 | var swap = arr[i]; 39 | arr[i] = arr[largest]; 40 | arr[largest] = swap; 41 | 42 | //Recursively heapify the affected sub-tree 43 | heapify(arr, n, largest); 44 | } 45 | } 46 | 47 | void main() { 48 | List list = [19, 48, 5, 7, 99, 10]; 49 | sort(list); 50 | print(list); 51 | } 52 | -------------------------------------------------------------------------------- /sort/insert_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show Random; 2 | 3 | void main() { 4 | final seed = 100, rnd = Random(), length = 100; 5 | var list = 6 | List.generate(length, (i) => rnd.nextInt(seed), growable: false); 7 | print('before sorting:'); 8 | print(list); 9 | print('----------------------------------------------'); 10 | print('After sorting:'); 11 | insertSort(list); 12 | print(list); 13 | } 14 | 15 | void insertSort(List a) { 16 | for (var i = 1; i < a.length; i++) { 17 | int j, t = a[i]; 18 | for (j = i - 1; j >= 0 && t < a[j]; j--) { 19 | a[j + 1] = a[j]; 20 | } 21 | if (j < i - 1) a[j + 1] = t; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sort/merge_sort.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | void merge(List list, int lIndex, int mIndex, int rIndex) { 4 | int lSize = mIndex - lIndex + 1; 5 | int rSize = rIndex - mIndex; 6 | 7 | List lList = new List.filled(lSize, () => 0); 8 | List rList = new List.filled(rSize, () => 0); 9 | 10 | for (int i = 0; i < lSize; i++) lList[i] = list[lIndex + i]; 11 | for (int j = 0; j < rSize; j++) rList[j] = list[mIndex + j + 1]; 12 | 13 | int i = 0, j = 0; 14 | int k = lIndex; 15 | 16 | while (i < lSize && j < rSize) { 17 | if (lList[i] <= rList[j]) { 18 | list[k] = lList[i]; 19 | i++; 20 | } else { 21 | list[k] = rList[j]; 22 | j++; 23 | } 24 | k++; 25 | } 26 | 27 | while (i < lSize) { 28 | list[k] = lList[i]; 29 | i++; 30 | k++; 31 | } 32 | 33 | while (j < rSize) { 34 | list[k] = rList[j]; 35 | j++; 36 | k++; 37 | } 38 | } 39 | 40 | List mergeSort(List list, int lIndex, int rIndex) { 41 | if (lIndex < rIndex) { 42 | int mIndex = (rIndex + lIndex) ~/ 2; // finds the middle index 43 | 44 | mergeSort(list, lIndex, mIndex); // sorts the first half of the list 45 | mergeSort(list, mIndex + 1, rIndex); // sorts the second half of the list 46 | 47 | merge(list, lIndex, mIndex, rIndex); 48 | } 49 | return list; 50 | } 51 | 52 | void main() { 53 | List list = [5, 4, 3, 2, 1]; 54 | test('test case 1', 55 | () => expect(mergeSort(list, 0, list.length - 1), [1, 2, 3, 4, 5])); 56 | 57 | List list1 = []; 58 | test('test case 2', () => expect(mergeSort(list1, 0, list1.length - 1), [])); 59 | 60 | List list2 = [1, 1, 1, 1, 1]; 61 | test('test case 3', 62 | () => expect(mergeSort(list2, 0, list2.length - 1), [1, 1, 1, 1, 1])); 63 | 64 | List list3 = [-1, -11, -1221, -123121, -1111111]; 65 | test( 66 | 'test case 4', 67 | () => expect(mergeSort(list3, 0, list3.length - 1), 68 | [-1111111, -123121, -1221, -11, -1])); 69 | 70 | List list4 = [11, 1, 1200, -1, 5]; 71 | test( 72 | 'test case 1', 73 | () => 74 | expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200])); 75 | } 76 | -------------------------------------------------------------------------------- /sort/pigeonhole_sort.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | void pigeonholeSort(List arr) { 4 | //The length of the list 5 | int n = arr.length; 6 | 7 | //checking the size 8 | if (n <= 0) { 9 | return; 10 | } 11 | 12 | //Find minimum and maximum values in arr 13 | int min = arr[0]; 14 | int max = arr[0]; 15 | 16 | for (int i = 1; i < n; i++) { 17 | if (arr[i] < min) min = arr[i]; 18 | if (arr[i] > max) max = arr[i]; 19 | } 20 | 21 | int range = max - min; 22 | range++; 23 | 24 | List phole = List.generate(range, (i) => 0); 25 | 26 | //Populate the pigeonholes. 27 | for (int i = 0; i < n; i++) { 28 | phole[arr[i] - min]; 29 | phole[arr[i] - min] = phole[arr[i] - min] + 1; 30 | } 31 | 32 | //Put the elements back into the array in order 33 | int index = 0; 34 | 35 | for (int j = 0; j < range; j++) while (phole[j]-- > 0) arr[index++] = j + min; 36 | } 37 | 38 | void main() { 39 | test("Sort empty list returns empty list", () { 40 | List list = []; 41 | pigeonholeSort(list); 42 | expect(list, isEmpty); 43 | }); 44 | 45 | test("Already sorted list remain sorted", () { 46 | List list = [1, 2, 3, 4, 5]; 47 | pigeonholeSort(list); 48 | expect(list, equals([1, 2, 3, 4, 5])); 49 | }); 50 | 51 | test("Sort", () { 52 | List list = [87, 48, 5, 7, 135, 85]; 53 | pigeonholeSort(list); 54 | expect(list, equals([5, 7, 48, 85, 87, 135])); 55 | }); 56 | 57 | test("Sorted list size doesnt change", () { 58 | List list = [1, 1, 4, 1, -12, -12, 77]; 59 | pigeonholeSort(list); 60 | expect(list.length, equals(7)); 61 | expect(list, [-12, -12, 1, 1, 1, 4, 77]); 62 | }); 63 | } 64 | -------------------------------------------------------------------------------- /sort/quick_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show Random; 2 | 3 | // quickSort 4 | // O(n*log n) 5 | void main() { 6 | var list = []; 7 | Random random = new Random(); 8 | for (var i = 0; i < 100; i++) { 9 | list.add(random.nextInt(100)); 10 | } 11 | print('before sorting:'); 12 | print(list); 13 | print('---------------------------------------------'); 14 | print('After sorting:'); 15 | print(quickSort(list)); 16 | } 17 | 18 | List quickSort(List a) { 19 | if (a.length < 2) { 20 | return a; 21 | } else { 22 | var pivot = a[0]; 23 | var less = []; 24 | var greater = []; 25 | a.removeAt(0); 26 | for (var i in a) { 27 | if (i <= pivot) { 28 | less.add(i); 29 | } else { 30 | greater.add(i); 31 | } 32 | } 33 | return quickSort(less) + [pivot] + quickSort(greater); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /sort/radix_sort.dart: -------------------------------------------------------------------------------- 1 | //radix sort 2 | /* 3 | radix sort is a non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. 4 | For elements with more than one significant digit, this bucketing process is repeated for each digit, 5 | while preserving the ordering of the prior step, until all digits have been considered. For this reason, 6 | radix sort has also been called bucket sort and digital sort. 7 | */ 8 | import 'dart:math' as Math; 9 | import 'dart:math' show Random; 10 | import 'package:test/test.dart'; 11 | 12 | main() { 13 | test("Sorting of empty list returns empty list", () { 14 | expect(radixSort([]), equals([])); 15 | }); 16 | test("Sorting one element list return same list", () { 17 | expect(radixSort([1]), equals([1])); 18 | }); 19 | test("Sorting two times doesnt change input", () { 20 | List lst = [5, 7, 1, 10, 54, -1]; 21 | expect(radixSort(lst), equals(radixSort(radixSort(lst)))); 22 | }); 23 | test("Sorting already sorted list returns same list", () { 24 | List lst = [1, 2, 3, 4, 10]; 25 | expect(radixSort(lst), equals(lst)); 26 | }); 27 | test("radix sort", () { 28 | expect(radixSort([34, -2, 122, 24435, 23, 434, 232, 1323]), 29 | equals([-2, 23, 34, 122, 232, 434, 1323, 24435])); 30 | }); 31 | 32 | final seed = 10, rnd = Random(), length = 10; 33 | var list = 34 | List.generate(length, (i) => rnd.nextInt(seed), growable: false); 35 | print('before sorting:'); 36 | print(list); 37 | print('----------------------------------------------'); 38 | print('After sorting:'); 39 | print(radixSort(list)); 40 | } 41 | 42 | getDigitNum(int n, int i) { 43 | var cal = (n.round().abs() / Math.pow(10, i)) % 10; 44 | 45 | return cal.round(); 46 | } 47 | 48 | digitCount(int number) { 49 | if (number == 0) { 50 | return 1; 51 | } 52 | return (number.abs().toString().length); 53 | } 54 | 55 | mostDigits(List number) { 56 | var maxDigits = 0; 57 | for (var i = 0; i < number.length; i++) { 58 | maxDigits = Math.max(maxDigits, digitCount(number[i])); 59 | } 60 | return maxDigits; 61 | } 62 | 63 | radixSort(List nums) { 64 | var maxDightCount = mostDigits(nums); 65 | for (var k = 0; k < maxDightCount; k++) { 66 | var digitBuckets = List.generate(10, (_) => []); 67 | for (var i = 0; i < nums.length; i++) { 68 | var digit = getDigitNum(nums[i], k); 69 | digitBuckets[digit].add(nums[i]); 70 | } 71 | 72 | nums = digitBuckets.expand((lst) => lst).toList(); 73 | } 74 | return nums; 75 | } 76 | -------------------------------------------------------------------------------- /sort/select_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show Random; 2 | 3 | //main function,the program start 4 | void main() { 5 | final seed = 100, rnd = Random(), length = 100; 6 | var list = 7 | List.generate(length, (i) => rnd.nextInt(seed), growable: false); 8 | print('before sorting:'); 9 | print(list); 10 | print('--------------------------------------'); 11 | print('After sorting:'); 12 | selectSort(list); 13 | print(list); 14 | } 15 | 16 | void selectSort(List a) { 17 | for (var i = 0; i < a.length - 1; i++) { 18 | var mi = i; 19 | for (var j = i + 1; j < a.length; j++) { 20 | if (a[j] < a[mi]) mi = j; 21 | } 22 | if (i != mi) { 23 | var t = a[i]; 24 | a[i] = a[mi]; 25 | a[mi] = t; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /sort/shell_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math' show Random; 2 | 3 | void main() { 4 | final seed = 100, rnd = Random(), length = 100; 5 | var list = 6 | List.generate(length, (i) => rnd.nextInt(seed), growable: false); 7 | print('before sorting:'); 8 | print(list); 9 | print('----------------------------------------------'); 10 | print('After sorting:'); 11 | shellSort(list); 12 | print(list); 13 | } 14 | 15 | void shellSort(List a) { 16 | for (var i = _initInterval(a); i > 0; i = (i - 1) ~/ 3) { 17 | for (var g = 0; g < i; g++) { 18 | for (var j = i + g; j < a.length; j += i) { 19 | var k = j - i, t = a[j]; 20 | while (k >= 0 && t.compareTo(a[k]) < 0) { 21 | a[k + i] = a[k]; 22 | k -= i; 23 | } 24 | if (k < j - i) a[k + i] = t; 25 | } 26 | } 27 | } 28 | } 29 | 30 | int _initInterval(List a) { 31 | var interval = 1; 32 | while (interval < a.length ~/ 3) interval = interval * 3 + 1; 33 | return interval; 34 | } 35 | -------------------------------------------------------------------------------- /sort/tim_Sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'package:test/expect.dart'; 4 | import 'package:test/scaffolding.dart'; 5 | 6 | const int RUN = 32; 7 | void insertionSort(List list, int left, int right) { 8 | for (int i = left + 1; i <= right; i++) { 9 | int temp = list[i]; 10 | int j = i - 1; 11 | while (j >= left && list[j] > temp) { 12 | list[j + 1] = list[j]; 13 | j--; 14 | } 15 | list[j + 1] = temp; 16 | } 17 | } 18 | 19 | void merge(List list, int left, int middle, int right) { 20 | int length1 = middle - left + 1, length2 = right - middle; 21 | List leftList = List.filled(length1, null), 22 | rightList = new List.filled(length2, null); 23 | 24 | for (int i = 0; i < length1; i++) { 25 | leftList[i] = list[left + i]; 26 | } 27 | 28 | for (int i = 0; i < length2; i++) { 29 | rightList[i] = list[middle + 1 + i]; 30 | } 31 | 32 | int i = 0, j = 0, k = 0; 33 | while (i < length1 && j < length2) { 34 | if (leftList[i] <= rightList[j]) { 35 | list[k] = leftList[i]; 36 | i++; 37 | } else { 38 | list[k] = rightList[j]; 39 | j++; 40 | } 41 | k++; 42 | } 43 | 44 | while (i < length1) { 45 | list[k] = leftList[i]; 46 | i++; 47 | k++; 48 | } 49 | 50 | while (j < length2) { 51 | list[k] = rightList[j]; 52 | k++; 53 | j++; 54 | } 55 | } 56 | 57 | void timSort(List list, int n) { 58 | for (int i = 0; i < n; i += RUN) { 59 | insertionSort(list, i, min((i + 31), n - 1)); 60 | } 61 | 62 | for (int size = RUN; size < n; size = 2 * size) { 63 | for (int left = 0; left < n; left += 2 * size) { 64 | int middle = left + size - 1; 65 | int right = min((left + 2 * size - 1), (n - 1)); 66 | merge(list, left, middle, right); 67 | } 68 | } 69 | } 70 | 71 | void main() { 72 | test('test case 1', () { 73 | List arr = [12, 213, 45, 9, 107]; 74 | timSort(arr, arr.length); 75 | expect(arr, [9, 12, 45, 107, 213]); 76 | }); 77 | 78 | test('test case 2', () { 79 | List arr = []; 80 | timSort(arr, arr.length); 81 | expect(arr, []); 82 | }); 83 | 84 | test('test case 3', () { 85 | List arr = [-1, 0, 1]; 86 | timSort(arr, arr.length); 87 | expect(arr, [-1, 0, 1]); 88 | }); 89 | } 90 | -------------------------------------------------------------------------------- /strings/isomorphic_strings.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // Leetcode problem url: https://leetcode.com/problems/isomorphic-strings/ 4 | bool isIsomorphic(String string1, String string2) { 5 | Map sMap = {}; 6 | Map tMap = {}; 7 | 8 | for (int i = 0; i < string1.length; ++i) { 9 | String s = string1[i]; 10 | String c = string2[i]; 11 | 12 | // Both characters are not mapped so far. 13 | if (!sMap.containsKey(s) && !tMap.containsKey(c)) { 14 | sMap[s] = c; 15 | tMap[c] = s; 16 | } 17 | // One of the characters is mapped. 18 | else if (!sMap.containsKey(s) || !tMap.containsKey(c)) { 19 | return false; 20 | } 21 | // Both characters are mapped 22 | else if (sMap[s] != c || tMap[c] != s) { 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | void main() { 30 | test('test case 1', () => expect(isIsomorphic('egg', 'add'), true)); 31 | test('test case 2', () => expect(isIsomorphic('foo', 'bar'), false)); 32 | test('test case 3', () => expect(isIsomorphic('paper', 'title'), true)); 33 | } 34 | -------------------------------------------------------------------------------- /strings/knuth_morris_prat.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | /// Preprocess pattern to identify any suffixes that are identical to prefixes 4 | /// in the given string. 5 | /// 6 | /// Build a pattern which tells us where to continue iteration from if we 7 | /// get a mismatch between the character 8 | /// 9 | /// Step through the text one character at a time and compare it to a character in 10 | /// the pattern updating our location within the pattern if necessary 11 | bool stringCompare(String string, String subString) { 12 | if (subString.isEmpty) { 13 | return false; 14 | } 15 | 16 | List pattern = 17 | new List.generate(subString.length, (int index) => -1); 18 | 19 | int i = 1; 20 | int j = 0; 21 | 22 | while (i < subString.length) { 23 | if (subString[i] == subString[j]) { 24 | pattern[i] = j; 25 | i++; 26 | j++; 27 | } else if (j > 0) { 28 | j = pattern[j - 1] + 1; 29 | } else { 30 | i++; 31 | } 32 | } 33 | 34 | return stringCompareHelper(string, subString, pattern); 35 | } 36 | 37 | bool stringCompareHelper(String string, String subString, List pattern) { 38 | int i = 0; 39 | int j = 0; 40 | 41 | while (i + subString.length - j <= string.length) { 42 | if (string[i] == subString[j]) { 43 | if (j == subString.length - 1) { 44 | return true; 45 | } 46 | i++; 47 | j++; 48 | } else if (j > 0) { 49 | j = pattern[j - 1] + 1; 50 | } else { 51 | i++; 52 | } 53 | } 54 | return false; 55 | } 56 | 57 | void main() { 58 | String string; 59 | String subString; 60 | 61 | test(('KMP: '), () { 62 | string = 'aefoaefcdaefcdaed'; 63 | subString = 'aefcdaed'; 64 | expect(stringCompare(string, subString), isTrue); 65 | }); 66 | 67 | test(('KMP: '), () { 68 | string = 'testwafwafawfawfawfawfawfawfawfa'; 69 | subString = 'fawfawfawfawfa'; 70 | expect(stringCompare(string, subString), isTrue); 71 | }); 72 | 73 | test(('KMP: '), () { 74 | string = 'aabc'; 75 | subString = 'abc'; 76 | expect(stringCompare(string, subString), isTrue); 77 | }); 78 | 79 | test(('KMP: '), () { 80 | string = 'adafccfefbbbfeeccbcfd'; 81 | subString = 'ecb'; 82 | expect(stringCompare(string, subString), isFalse); 83 | }); 84 | 85 | test(('KMP: '), () { 86 | string = 'akash'; 87 | subString = 'christy'; 88 | expect(stringCompare(string, subString), isFalse); 89 | }); 90 | test(('KMP: '), () { 91 | string = ''; 92 | subString = 'asd'; 93 | expect(stringCompare(string, subString), isFalse); 94 | }); 95 | 96 | test(('KMP: '), () { 97 | string = 'asd'; 98 | subString = ''; 99 | expect(stringCompare(string, subString), isFalse); 100 | }); 101 | } 102 | -------------------------------------------------------------------------------- /strings/remove duplicates.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // function to remove duplicate in string 4 | String removeDups(String s) { 5 | var arr = new List.filled(256, 0); 6 | String l = ''; 7 | int i = 0; 8 | for (i = 0; i < s.length; i++) { 9 | if (arr[s.codeUnitAt(i)] == 0) { 10 | l += s[i]; 11 | arr[s.codeUnitAt(i)]++; 12 | } 13 | } 14 | return l; 15 | } 16 | 17 | void main() { 18 | test("removeDups from string without duplicates returns same string", () { 19 | expect(removeDups("1234"), equals("1234")); 20 | }); 21 | 22 | test("removeDups from empty list returns empty list", () { 23 | expect(removeDups(""), equals("")); 24 | }); 25 | 26 | test("removeDups from 12341234 returns 1234", () { 27 | expect(removeDups("12341234"), equals("1234")); 28 | }); 29 | 30 | test("removeDups from aaaab returns ab", () { 31 | expect(removeDups("aaaab"), equals("ab")); 32 | }); 33 | } 34 | -------------------------------------------------------------------------------- /strings/reverse_string.dart: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse String 3 | */ 4 | 5 | void main() { 6 | String stringToReverse = "The Algorithms:Dart"; 7 | print('Method 1 => $stringToReverse\t ${reverseString(stringToReverse)}'); 8 | print('Method 2 => $stringToReverse\t ${reverseString2(stringToReverse)}'); 9 | } 10 | 11 | /** 12 | * * easiest way to reverses the string 13 | */ 14 | String reverseString(String str) { 15 | return str.split('').reversed.join(); 16 | } 17 | 18 | /** 19 | * Second way to reverses the string 20 | */ 21 | String reverseString2(String str) { 22 | String reversed = ""; 23 | for (int i = str.length - 1; i >= 0; i--) reversed += str[i]; 24 | return reversed; 25 | } 26 | -------------------------------------------------------------------------------- /strings/reverse_words_of_string.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | String reverseStringWords(String s) { 4 | String res = ""; 5 | int m = s.length; 6 | int j = m - 1; 7 | for (int i = m - 1; i >= 0; i--) { 8 | if (s[i] == '.') { 9 | for (int j1 = i + 1; j1 <= j; j1++) { 10 | res += s[j1]; 11 | } 12 | res += s[i]; 13 | j = i - 1; 14 | } else if (i == 0) { 15 | for (int j1 = i; j1 <= j; j1++) { 16 | res += s[j1]; 17 | } 18 | } 19 | } 20 | return res; 21 | } 22 | 23 | void main() { 24 | test("reverseStringWords single word returns same word", () { 25 | expect(reverseStringWords("word"), equals("word")); 26 | }); 27 | 28 | test("reverseStringWords w1.w2 returns w2.w1", () { 29 | expect(reverseStringWords("w1.w2"), equals("w2.w1")); 30 | }); 31 | 32 | test("reverseStringWords on empty string returns empty string", () { 33 | expect(reverseStringWords(""), equals("")); 34 | }); 35 | 36 | test("reverseStringWords", () { 37 | expect(reverseStringWords("abhishek.is.a.good.boy"), 38 | equals("boy.good.a.is.abhishek")); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | # Put dart test files here... 2 | -------------------------------------------------------------------------------- /trees/path_sum.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | // Question URL: https://leetcode.com/problems/path-sum/description/ 4 | class TreeNode { 5 | int val; 6 | TreeNode? left; 7 | TreeNode? right; 8 | TreeNode([this.val = 0, this.left, this.right]); 9 | } 10 | 11 | bool isLeaf(TreeNode node) { 12 | if (node.left == null && node.right == null) { 13 | return true; 14 | } 15 | return false; 16 | } 17 | 18 | bool traverse(TreeNode? node, int targetSum, int runningSum) { 19 | if (node == null) { 20 | return false; 21 | } 22 | runningSum += node.val; 23 | if (isLeaf(node) && runningSum == targetSum) { 24 | return true; 25 | } 26 | 27 | bool hasPathSumInLeftTree = traverse(node.left, targetSum, runningSum); 28 | bool hasPathSumInRightTree = traverse(node.right, targetSum, runningSum); 29 | return hasPathSumInLeftTree || hasPathSumInRightTree; 30 | } 31 | 32 | bool hasPathSum(TreeNode root, int targetSum) { 33 | return traverse(root, targetSum, 0); 34 | } 35 | 36 | void main() { 37 | TreeNode root = TreeNode( 38 | 5, 39 | TreeNode( 40 | 4, 41 | TreeNode( 42 | 11, 43 | TreeNode(7), 44 | TreeNode(2), 45 | ), 46 | ), 47 | TreeNode( 48 | 8, 49 | TreeNode(13), 50 | TreeNode( 51 | 4, 52 | null, 53 | TreeNode(1), 54 | ), 55 | ), 56 | ); 57 | 58 | test('Test Case 1: true case', () { 59 | expect(hasPathSum(root, 22), true); 60 | }); 61 | test('Test Case 2: false case', () { 62 | expect(hasPathSum(root, 222), false); 63 | }); 64 | } 65 | --------------------------------------------------------------------------------