diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 4ea76c5e..a0911f2e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -3,15 +3,13 @@ on: [push, pull_request] jobs: dart_test_analyze_format: runs-on: ubuntu-latest - container: google/dart + container: + image: dart:stable steps: - - uses: actions/checkout@v2 - - run: (echo 'deb http://deb.debian.org/debian buster main contrib non-free') > /etc/apt/sources.list.d/buster.list - - run: apt-get update - - run: apt-get install --no-install-recommends -y -q lcov + - uses: actions/checkout@v4 + # - run: (echo 'deb http://deb.debian.org/debian buster main contrib non-free') > /etc/apt/sources.list.d/buster.list - run: dart pub get + - run: dart format --set-exit-if-changed . - run: dart test --coverage . - - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov - - run: lcov -l coverage.lcov + - run: dart run coverage:format_coverage -i . -l > coverage.lcov - run: dart analyze - - run: dart format --set-exit-if-changed . diff --git a/.gitignore b/.gitignore index dbef116d..d66e1b9e 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ doc/api/ *.js_ *.js.deps *.js.map +*.json diff --git a/DIRECTORY.md b/DIRECTORY.md index 4eb63e92..48986dc4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -2,6 +2,7 @@ ## Array * [Car Pool](https://github.com/TheAlgorithms/Dart/blob/master/array/car_pool.dart) * [Move Zeroes](https://github.com/TheAlgorithms/Dart/blob/master/array/move_zeroes.dart) + * [Pivot Index](https://github.com/TheAlgorithms/Dart/blob/master/array/pivot_index.dart) * [Sorted Squared Array](https://github.com/TheAlgorithms/Dart/blob/master/array/sorted_squared_array.dart) * [Two Sum](https://github.com/TheAlgorithms/Dart/blob/master/array/two_sum.dart) * [Validate Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/array/validate_subsequence.dart) @@ -41,8 +42,7 @@ * Linked List * [Cycle In Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/cycle_in_linked_list.dart) * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/linked_list.dart) - * Quad Tree - * [Quad Tree](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/quad_tree/quad_tree.dart) + * [Merge Sorted List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/merge_sorted_list.dart) * Queue * [Circular Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Circular_Queue.dart) * [List Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/List_Queue.dart) @@ -61,6 +61,7 @@ * [Min Number Of Jumps](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/min_number_of_jumps.dart) ## Graphs + * [Area Of Island](https://github.com/TheAlgorithms/Dart/blob/master/graphs/area_of_island.dart) * [Breadth First Search](https://github.com/TheAlgorithms/Dart/blob/master/graphs/breadth_first_search.dart) * [Depth First Search](https://github.com/TheAlgorithms/Dart/blob/master/graphs/depth_first_search.dart) * [Nearest Neighbour Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/graphs/nearest_neighbour_algorithm.dart) @@ -180,6 +181,7 @@ * [Tim Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/tim_Sort.dart) ## Strings + * [Isomorphic Strings](https://github.com/TheAlgorithms/Dart/blob/master/strings/isomorphic_strings.dart) * [Knuth Morris Prat](https://github.com/TheAlgorithms/Dart/blob/master/strings/knuth_morris_prat.dart) * [Remove Duplicates](https://github.com/TheAlgorithms/Dart/blob/master/strings/remove%20duplicates.dart) * [Reverse String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_string.dart) diff --git a/LICENSE b/LICENSE index 6d7f310d..3b57d694 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 The Algorithms +Copyright (c) 2025 The Algorithms Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index c49f19f2..079f7631 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ [![Build Status](https://travis-ci.com/TheAlgorithms/Dart.svg?branch=master)](https://travis-ci.com/TheAlgorithms/Dart) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100)   -[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/TheAlgorithms)   +[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=5865F2)](https://the-algorithms.com/discord/)   +[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/#TheAlgorithms_community:gitter.im) ### All algorithms implemented in Dart (for education) diff --git a/array/car_pool.dart b/array/car_pool.dart index 2d5adc64..b5cbb401 100644 --- a/array/car_pool.dart +++ b/array/car_pool.dart @@ -2,7 +2,7 @@ // Solution Explanation: https://leetcode.com/problems/car-pooling/solutions/3252690/dart-time-o-n-o-1-space-solution/ import 'dart:math'; -import 'package:test/test.dart'; +import "package:test/test.dart"; bool carPooling(List> trips, int capacity) { List passengerTimelineCount = List.filled(1001, 0); @@ -33,24 +33,24 @@ bool carPooling(List> trips, int capacity) { void main() { List> trips = [ [2, 1, 5], - [3, 3, 7] + [3, 3, 7], ]; List> trips1 = [ [2, 1, 5], - [3, 5, 7] + [3, 5, 7], ]; List> trips2 = [ [2, 2, 6], [2, 4, 7], - [8, 6, 7] + [8, 6, 7], ]; List> trips3 = [ [7, 5, 6], [6, 7, 8], - [10, 1, 6] + [10, 1, 6], ]; test('test case 1', () => expect(carPooling(trips, 4), false)); diff --git a/array/pivot_index.dart b/array/pivot_index.dart new file mode 100644 index 00000000..b73e74ef --- /dev/null +++ b/array/pivot_index.dart @@ -0,0 +1,30 @@ +import 'package:test/test.dart'; + +// Leetcode problem URL: https://leetcode.com/problems/find-pivot-index/ +int sum(List numbers) { + int sum = 0; + for (int i = 0; i < numbers.length; i++) { + sum += numbers[i]; + } + return sum; +} + +int pivotIndex(List nums) { + int leftSum = 0; + int arraySum = sum(nums); + + for (int i = 0; i < nums.length; ++i) { + if (leftSum == arraySum - leftSum - nums[i]) { + return i; + } + leftSum += nums[i]; + } + + return -1; +} + +void main() { + test('test case 1', () => expect(pivotIndex([1, 7, 3, 6, 5, 6]), 3)); + test('test case 2', () => expect(pivotIndex([2, 1, -1]), 0)); + test('test case 3', () => expect(pivotIndex([1, 2, 3]), -1)); +} diff --git a/array/sorted_squared_array.dart b/array/sorted_squared_array.dart index cc0c0407..791474fc 100644 --- a/array/sorted_squared_array.dart +++ b/array/sorted_squared_array.dart @@ -30,12 +30,26 @@ void main() { }); test('test case 2', () { - expect(sortedSquaredArray([-7, -6, -5, -4, -3, -2, -1]), - [1, 4, 9, 16, 25, 36, 49]); + expect(sortedSquaredArray([-7, -6, -5, -4, -3, -2, -1]), [ + 1, + 4, + 9, + 16, + 25, + 36, + 49, + ]); }); test('test case 4', () { - expect( - sortedSquaredArray([1, 2, 3, 4, 5, 6, 7]), [1, 4, 9, 16, 25, 36, 49]); + expect(sortedSquaredArray([1, 2, 3, 4, 5, 6, 7]), [ + 1, + 4, + 9, + 16, + 25, + 36, + 49, + ]); }); } diff --git a/backtracking/open_knight_tour.dart b/backtracking/open_knight_tour.dart index 9f74c601..6825fe80 100644 --- a/backtracking/open_knight_tour.dart +++ b/backtracking/open_knight_tour.dart @@ -94,70 +94,77 @@ void printBoard(List> board) { void main() { test(('getValidPos: testCase #1'), () { expect( - getValidPos([1, 3], 4), - equals([ - [2, 1], - [0, 1], - [3, 2] - ])); + getValidPos([1, 3], 4), + equals([ + [2, 1], + [0, 1], + [3, 2], + ]), + ); }); test(('getValidPos: testCase #3'), () { expect( - getValidPos([1, 2], 5), - equals([ - [2, 4], - [0, 4], - [2, 0], - [0, 0], - [3, 3], - [3, 1] - ])); + getValidPos([1, 2], 5), + equals([ + [2, 4], + [0, 4], + [2, 0], + [0, 0], + [3, 3], + [3, 1], + ]), + ); }); test(('isComplete: testCase #1'), () { expect( - isComplete([ - [1] - ]), - equals(true)); + isComplete([ + [1], + ]), + equals(true), + ); }); test(('isComplete: testCase #2'), () { expect( - isComplete([ - [1, 2], - [3, 0] - ]), - equals(false)); + isComplete([ + [1, 2], + [3, 0], + ]), + equals(false), + ); }); test(('openKnightTour: testCase #1'), () { expect( - openKnightTour(1), - equals([ - [1] - ])); + openKnightTour(1), + equals([ + [1], + ]), + ); }); test(('openKnightTour: testCase #2'), () { expect( - openKnightTour(2), - equals([ - [0, 0], - [0, 0] - ])); + openKnightTour(2), + equals([ + [0, 0], + [0, 0], + ]), + ); }); test(('openKnightTour: testCase #3'), () { expect( - openKnightTour(5), - equals([ - [1, 14, 19, 8, 25], - [6, 9, 2, 13, 18], - [15, 20, 7, 24, 3], - [10, 5, 22, 17, 12], - [21, 16, 11, 4, 23] - ])); + openKnightTour(5), + equals([ + [1, 14, 19, 8, 25], + [6, 9, 2, 13, 18], + [15, 20, 7, 24, 3], + [10, 5, 22, 17, 12], + [21, 16, 11, 4, 23], + ]), + ); }); } diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index 8d44bd55..4dfdaed7 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -31,7 +31,7 @@ String decimalToAny(int value, int base) { 32: 'W', 33: 'X', 34: 'Y', - 35: 'Z' + 35: 'Z', }; if (value == 0) return "0"; @@ -49,8 +49,10 @@ String decimalToAny(int value, int base) { int remainder = value % base; value = value ~/ base; output = - (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder]) + - output; + (remainder < 10 + ? remainder.toString() + : ALPHABET_VALUES[remainder] ?? '0') + + output; } return negative ? '-' + output : output; diff --git a/conversions/Decimal_to_Hexadecimal.dart b/conversions/Decimal_to_Hexadecimal.dart index 3a95ab38..b6f4ab83 100644 --- a/conversions/Decimal_to_Hexadecimal.dart +++ b/conversions/Decimal_to_Hexadecimal.dart @@ -27,7 +27,7 @@ String decimal_to_hexadecimal(int decimal_val) { int remainder = decimal_val % 16; decimal_val = decimal_val ~/ 16; if (hex_table.containsKey(remainder.toString())) { - hex_val = hex_table[remainder.toString()]; + hex_val = hex_table[remainder.toString()] ?? ''; } else { hex_val = remainder.toString(); } diff --git a/conversions/Integer_To_Roman.dart b/conversions/Integer_To_Roman.dart index a2e9db54..f15d37ff 100644 --- a/conversions/Integer_To_Roman.dart +++ b/conversions/Integer_To_Roman.dart @@ -20,7 +20,7 @@ List ArabianRomanNumbers = [ 9, 5, 4, - 1 + 1, ]; List RomanNumbers = [ @@ -36,12 +36,12 @@ List RomanNumbers = [ "IX", "V", "IV", - "I" + "I", ]; List integer_to_roman(int num) { if (num < 0) { - return null; + return []; } List result = []; diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 1ee739c4..e39bcaf9 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -4,7 +4,7 @@ import 'package:test/test.dart'; int binaryToDecimal(String binaryString) { binaryString = binaryString.trim(); - if (binaryString == null || binaryString == "") { + if (binaryString == "") { throw FormatException("An empty value was passed to the function"); } bool isNegative = binaryString[0] == "-"; @@ -15,7 +15,8 @@ int binaryToDecimal(String binaryString) { throw FormatException("Non-binary value was passed to the function"); } else { decimalValue += - pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); + (pow(2, binaryString.length - i - 1).toInt() * + (int.tryParse(binaryString[i]) ?? 0)); } } return isNegative ? -1 * decimalValue : decimalValue; diff --git a/conversions/binary_to_hexadecimal.dart b/conversions/binary_to_hexadecimal.dart index bbdd5227..849acd4c 100644 --- a/conversions/binary_to_hexadecimal.dart +++ b/conversions/binary_to_hexadecimal.dart @@ -24,7 +24,7 @@ Map hexTable = { String binaryToHexadecimal(String binaryString) { // checking for unexpected values binaryString = binaryString.trim(); - if (binaryString == null || binaryString == "") { + if (binaryString.isEmpty) { throw new FormatException("An empty value was passed to the function"); } try { @@ -47,7 +47,7 @@ String binaryToHexadecimal(String binaryString) { int i = 0; while (i != binaryString.length) { String bin_curr = binaryString.substring(i, i + 4); - hexValue += hexTable[bin_curr]; + hexValue += hexTable[bin_curr] ?? ''; i += 4; } diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 7553a4d5..4a68ab2d 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -21,7 +21,7 @@ void main() { String binaryToOctal(String binaryString) { binaryString = binaryString.trim(); - if (binaryString == null || binaryString == "") { + if (binaryString.isEmpty) { throw new FormatException("An empty value was passed to the function"); } bool isNegative = binaryString[0] == "-"; diff --git a/conversions/hexadecimal_to_binary.dart b/conversions/hexadecimal_to_binary.dart index af6b8431..5e1f5ed9 100644 --- a/conversions/hexadecimal_to_binary.dart +++ b/conversions/hexadecimal_to_binary.dart @@ -24,7 +24,7 @@ Map bin_table = { String hexadecimal_to_binary(String hex_value) { // checking for unexpected values hex_value = hex_value.trim(); - if (hex_value == null || hex_value == "") { + if (hex_value.isEmpty) { throw new FormatException("An empty value was passed to the function"); } @@ -40,7 +40,7 @@ String hexadecimal_to_binary(String hex_value) { if (!bin_table.containsKey(hex_cur)) { throw new FormatException("An invalid value was passed to the function"); } - bin_val += bin_table[hex_cur]; + bin_val += bin_table[hex_cur] ?? ''; i++; } diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index 9d12772c..416a8585 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -21,19 +21,20 @@ void main() { int hexadecimal_to_decimal(String hex_string) { hex_string = hex_string.trim().toUpperCase(); - if (hex_string == null || hex_string == "") { + if (hex_string == "") { throw Exception("An empty value was passed to the function"); } bool is_negative = hex_string[0] == "-"; if (is_negative) hex_string = hex_string.substring(1); int decimal_val = 0; for (int i = 0; i < hex_string.length; i++) { - if (int.parse(hex_string[i], onError: (e) => null) == null && + if (int.tryParse(hex_string[i]) == null && hex_table.containsKey(hex_string[i]) == false) { throw Exception("Non-hex value was passed to the function"); } else { - decimal_val += pow(16, hex_string.length - i - 1) * - int.parse((hex_string[i]), onError: (e) => hex_table[hex_string[i]]); + decimal_val += + pow(16, hex_string.length - i - 1).toInt() * + (int.tryParse(hex_string[i]) ?? hex_table[hex_string[i]] ?? 0); } } return is_negative ? -1 * decimal_val : decimal_val; diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart index ffed7b58..c72e29c2 100644 --- a/conversions/hexadecimal_to_octal.dart +++ b/conversions/hexadecimal_to_octal.dart @@ -6,7 +6,7 @@ String hexadecimal_to_octal(String hex_val) { int dec = 0; // checking for null string passed to function - if (hex_val == null || hex_val == "") { + if (hex_val == "") { throw new FormatException("An empty value was passed to the function"); } @@ -29,43 +29,43 @@ String hexadecimal_to_octal(String hex_val) { case '7': case '8': case '9': - dec = dec + int.parse(ch) * pow(16, c); + dec = dec + (int.tryParse(ch) ?? 0) * pow(16, c).toInt(); c--; break; case 'a': case 'A': - dec = dec + 10 * pow(16, c); + dec = dec + 10 * pow(16, c).toInt(); c--; break; case 'b': case 'B': - dec = dec + 11 * pow(16, c); + dec = dec + 11 * pow(16, c).toInt(); c--; break; case 'c': case 'C': - dec = dec + 12 * pow(16, c); + dec = dec + 12 * pow(16, c).toInt(); c--; break; case 'd': case 'D': - dec = dec + 13 * pow(16, c); + dec = dec + 13 * pow(16, c).toInt(); c--; break; case 'e': case 'E': - dec = dec + 14 * pow(16, c); + dec = dec + 14 * pow(16, c).toInt(); c--; break; case 'f': case 'F': - dec = dec + 15 * pow(16, c); + dec = dec + 15 * pow(16, c).toInt(); c--; break; default: throw new FormatException( - "An invalid value was passed to the function"); - break; + "An invalid value was passed to the function", + ); } } diff --git a/conversions/octal_to_binary.dart b/conversions/octal_to_binary.dart index ccb1fb42..d791e173 100644 --- a/conversions/octal_to_binary.dart +++ b/conversions/octal_to_binary.dart @@ -5,7 +5,7 @@ import 'package:test/test.dart'; String ocatal_to_binary(String oct_val) { // checking for unexpected values oct_val = oct_val.trim(); - if (oct_val == null || oct_val == "") { + if (oct_val.isEmpty) { throw new FormatException("An empty value was passed to the function"); } @@ -31,7 +31,7 @@ String ocatal_to_binary(String oct_val) { // converting octal to decimal int dec_val = 0, i = 0, bin_val = 0; while (oct != 0) { - dec_val = dec_val + ((oct % 10) * pow(8, i)); + dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); i++; oct = oct ~/ 10; } diff --git a/conversions/octal_to_decimal.dart b/conversions/octal_to_decimal.dart index c9038706..fca99245 100644 --- a/conversions/octal_to_decimal.dart +++ b/conversions/octal_to_decimal.dart @@ -7,7 +7,7 @@ import 'package:test/test.dart'; String ocatal_to_decimal(String oct_val) { // checking for unexpected values oct_val = oct_val.trim(); - if (oct_val == null || oct_val == "") { + if (oct_val.isEmpty) { throw new FormatException("An empty value was passed to the function"); } @@ -33,7 +33,7 @@ String ocatal_to_decimal(String oct_val) { // converting octal to decimal int dec_val = 0, i = 0; while (oct != 0) { - dec_val = dec_val + ((oct % 10) * pow(8, i)); + dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); i++; oct = oct ~/ 10; } diff --git a/conversions/octal_to_hexadecimal.dart b/conversions/octal_to_hexadecimal.dart index a7171c73..5b1b3885 100644 --- a/conversions/octal_to_hexadecimal.dart +++ b/conversions/octal_to_hexadecimal.dart @@ -15,7 +15,7 @@ Map hex_table = { String ocatal_to_hex(String oct_val) { // checking for unexpected values oct_val = oct_val.trim(); - if (oct_val == null || oct_val == "") { + if (oct_val == "") { throw new FormatException("An empty value was passed to the function"); } @@ -41,7 +41,7 @@ String ocatal_to_hex(String oct_val) { // converting octal to decimal int dec_val = 0, i = 0; while (oct != 0) { - dec_val = dec_val + ((oct % 10) * pow(8, i)); + dec_val = dec_val + ((oct % 10) * pow(8, i).toInt()); i++; oct = oct ~/ 10; } @@ -56,7 +56,7 @@ String ocatal_to_hex(String oct_val) { int remainder = dec_val % 16; dec_val = dec_val ~/ 16; if (hex_table.containsKey(remainder.toString())) { - hex_val = hex_table[remainder.toString()]; + hex_val = hex_table[remainder.toString()] ?? ''; } else { hex_val = remainder.toString(); } diff --git a/conversions/roman_to_integer.dart b/conversions/roman_to_integer.dart index 27f8df7a..95d21b86 100644 --- a/conversions/roman_to_integer.dart +++ b/conversions/roman_to_integer.dart @@ -32,7 +32,8 @@ int value(var r) { return 100; else if (r == 'D') return 500; - else if (r == 'M') return 1000; + else if (r == 'M') + return 1000; return 0; } diff --git a/data_structures/HashMap/Hashing.dart b/data_structures/HashMap/Hashing.dart index 3aaeb852..3a6ad40a 100644 --- a/data_structures/HashMap/Hashing.dart +++ b/data_structures/HashMap/Hashing.dart @@ -2,8 +2,8 @@ //Email:stepfencurryxiao@gmail.com class Node { - int data; - Node next; + int? data; + Node? next; Node(int data) { this.data = data; @@ -12,12 +12,11 @@ class Node { } class LinkedList { - Node head; + Node? head; int size; - LinkedList() { + LinkedList({this.size = 0}) { head = null; - size = 0; } void insert(int data) { @@ -38,15 +37,15 @@ class LinkedList { print("underFlow!"); return; } else { - Node curr = head; - if (curr.data == data) { - head = curr.next; + Node? curr = head; + if (curr?.data == data) { + head = curr?.next; size--; return; } else { - while (curr.next.next != null) { - if (curr.next.data == data) { - curr.next = curr.next.next; + while (curr?.next?.next != null) { + if (curr?.next?.data == data) { + curr?.next = curr.next?.next; return; } } @@ -56,7 +55,7 @@ class LinkedList { } void display() { - Node temp = head; + Node? temp = head; while (temp != null) { print(temp.data.toString()); temp = temp.next; @@ -69,8 +68,8 @@ class HashMap { int hsize; List buckets; - HashMap(int hsize) { - buckets = new List(hsize); + HashMap({this.hsize = 0, this.buckets = const []}) { + buckets = new List.generate(hsize, (a) => LinkedList()); for (int i = 0; i < hsize; i++) { buckets[i] = new LinkedList(); } @@ -104,7 +103,7 @@ class HashMap { } void main() { - HashMap h = new HashMap(7); + HashMap h = new HashMap(hsize: 7); print("Add key 5"); h.insertHash(5); diff --git a/data_structures/Heap/Binary_Heap/Max_heap.dart b/data_structures/Heap/Binary_Heap/Max_heap.dart index f7b4b4de..752d399a 100644 --- a/data_structures/Heap/Binary_Heap/Max_heap.dart +++ b/data_structures/Heap/Binary_Heap/Max_heap.dart @@ -1,7 +1,7 @@ import 'package:test/test.dart'; class MaxHeap { - List heap; + List heap = []; void buildHeap(List array) { this.heap = _heapify(array); @@ -15,7 +15,7 @@ class MaxHeap { return array; } - int peek() { + int? peek() { if (!isEmpty()) { return this.heap[0]; } @@ -28,8 +28,8 @@ class MaxHeap { void _siftUp(int currentIndex) { int parentIndex = (currentIndex - 1) ~/ 2; - while ( - parentIndex >= 0 && this.heap[parentIndex] < this.heap[currentIndex]) { + while (parentIndex >= 0 && + this.heap[parentIndex] < this.heap[currentIndex]) { _swap(parentIndex, currentIndex, this.heap); currentIndex = parentIndex; parentIndex = (currentIndex - 1) ~/ 2; @@ -41,8 +41,9 @@ class MaxHeap { int childTwoIndex; while (childOneIndex <= endIndex) { - childTwoIndex = - 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; + childTwoIndex = 2 * currentIndex + 2 <= endIndex + ? 2 * currentIndex + 2 + : -1; int indexToSwap; if (childTwoIndex != -1 && heap[childTwoIndex] > heap[childOneIndex]) { indexToSwap = childTwoIndex; @@ -65,7 +66,7 @@ class MaxHeap { _siftUp(this.heap.length - 1); } - int remove() { + int? remove() { if (!isEmpty()) { _swap(0, this.heap.length - 1, this.heap); int maxElement = this.heap.removeLast(); diff --git a/data_structures/Heap/Binary_Heap/min_heap_two.dart b/data_structures/Heap/Binary_Heap/min_heap_two.dart index 35493280..6627b3c1 100644 --- a/data_structures/Heap/Binary_Heap/min_heap_two.dart +++ b/data_structures/Heap/Binary_Heap/min_heap_two.dart @@ -1,7 +1,7 @@ import 'package:test/test.dart'; class MinHeap { - List heap; + List heap = []; void buildHeap(List array) { this.heap = _heapify(array); @@ -15,7 +15,7 @@ class MinHeap { return array; } - int peek() { + int? peek() { if (!isEmpty()) { return this.heap[0]; } @@ -28,8 +28,8 @@ class MinHeap { void _siftUp(int currentIndex) { int parentIndex = (currentIndex - 1) ~/ 2; - while ( - parentIndex >= 0 && this.heap[parentIndex] > this.heap[currentIndex]) { + while (parentIndex >= 0 && + this.heap[parentIndex] > this.heap[currentIndex]) { _swap(parentIndex, currentIndex, this.heap); currentIndex = parentIndex; parentIndex = (currentIndex - 1) ~/ 2; @@ -41,8 +41,9 @@ class MinHeap { int childTwoIndex; while (childOneIndex <= endIndex) { - childTwoIndex = - 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; + childTwoIndex = 2 * currentIndex + 2 <= endIndex + ? 2 * currentIndex + 2 + : -1; int indexToSwap; if (childTwoIndex != -1 && heap[childTwoIndex] < heap[childOneIndex]) { indexToSwap = childTwoIndex; @@ -65,7 +66,7 @@ class MinHeap { _siftUp(this.heap.length - 1); } - int remove() { + int? remove() { if (!isEmpty()) { _swap(0, this.heap.length - 1, this.heap); int minElement = this.heap.removeLast(); diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart index 6d870555..84e6bd3b 100644 --- a/data_structures/Queue/Circular_Queue.dart +++ b/data_structures/Queue/Circular_Queue.dart @@ -6,7 +6,7 @@ const int MAX_SIZE = 10; class CircularQueue { int start = -1, end = -1; - List queue = new List(MAX_SIZE); + List queue = List.filled(MAX_SIZE, null); // insert elements into the queue void enque(T element) { @@ -30,12 +30,12 @@ class CircularQueue { } // remove elements from the queue - T deque() { + T? deque() { if (start == -1) { print("The queue is empty!!!"); return null; } - T here = queue[start]; + T? here = queue[start]; if (start == end) { start = -1; end = -1; diff --git a/data_structures/Queue/List_Queue.dart b/data_structures/Queue/List_Queue.dart index 6fb61bfb..ca7d8d50 100644 --- a/data_structures/Queue/List_Queue.dart +++ b/data_structures/Queue/List_Queue.dart @@ -5,7 +5,7 @@ const int MAX_SIZE = 10; class ListQueue { int count = 0; - List queue = new List(MAX_SIZE); + List queue = List.filled(MAX_SIZE, null); //Checks if the queue has elements (not empty) bool hasElements() { @@ -27,8 +27,8 @@ class ListQueue { } //Takes the next element from the queue - T deque() { - T result = null; + T? deque() { + T? result = null; if (count == 0) { print("The queue is empty!!!"); } else { diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart index 970eee82..94ceffe2 100644 --- a/data_structures/Queue/Priority_Queue.dart +++ b/data_structures/Queue/Priority_Queue.dart @@ -6,7 +6,7 @@ class PriorityQueue { bool get isEmpty => _dataStore.isEmpty; enqueue(T item, int priority) { - QueueItem queueItem = new QueueItem(item, priority); + QueueItem queueItem = new QueueItem(item, priority); bool added = false; for (int i = 0; i < _dataStore.length; i++) { if (priority < _dataStore[i].priority) { @@ -20,21 +20,21 @@ class PriorityQueue { } } - T dequeue() { + T? dequeue() { if (_dataStore.isNotEmpty) { return _dataStore.removeAt(0).item; } return null; } - T get front { + T? get front { if (_dataStore.isNotEmpty) { return _dataStore.first.item; } return null; } - T get end { + T? get end { if (_dataStore.isNotEmpty) { return _dataStore.last.item; } diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index ddcdba28..09d218e0 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -3,18 +3,18 @@ import 'package:test/scaffolding.dart'; class ArrayStack { /// [stack] - List _stack; + List _stack = []; /// [_count] is the number of element in the stack - int _count; + int _count = 0; /// [_size] of stack - int _size; + int _size = 0; //Init the array stack ArrayStack(int size) { this._size = size; - this._stack = List.filled(_size, null); + this._stack = List.filled(_size, null); this._count = 0; } @@ -29,17 +29,17 @@ class ArrayStack { } /// Pop the last element inserted from the [_stack]. - T pop() { + T? pop() { if (_count == 0) { return null; } - T pop_data = _stack[_count - 1]; + T? pop_data = _stack[_count - 1]; _stack[_count - 1] = null; _count--; return pop_data; } - List get stack { + List get stack { return _stack; } } diff --git a/data_structures/Stack/Linked_List_Stack.dart b/data_structures/Stack/Linked_List_Stack.dart index db9f15f0..1ce58440 100644 --- a/data_structures/Stack/Linked_List_Stack.dart +++ b/data_structures/Stack/Linked_List_Stack.dart @@ -3,10 +3,10 @@ class Node { //the data of the Node - T data; - Node next; + T? data; + Node? next; - Node(T data) { + Node(T? data) { this.data = data; this.next = null; } @@ -14,10 +14,10 @@ class Node { class LinkedListStack { //Top of stack - Node head; + Node? head; //Size of stack - int size; + int size = 0; LinkedListStack() { this.head = null; @@ -35,14 +35,14 @@ class LinkedListStack { //Pop element from top at the stack - T pop() { - T returnData = null; + T? pop() { + T? returnData = null; if (size == 0) { print("The stack is empty!!!"); } else { - Node destroy = this.head; - this.head = this.head.next; - returnData = destroy.data; + Node? destroy = this.head; + this.head = this.head?.next; + returnData = destroy?.data; this.size--; } return returnData; diff --git a/data_structures/Stack/balanced_brackets.dart b/data_structures/Stack/balanced_brackets.dart index b10abba9..f32fb303 100644 --- a/data_structures/Stack/balanced_brackets.dart +++ b/data_structures/Stack/balanced_brackets.dart @@ -46,8 +46,10 @@ void main() { test(('Balanced Bracket'), () { expect( - isBalancedBrackets( - '(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), - isTrue); + isBalancedBrackets( + '(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())', + ), + isTrue, + ); }); } diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index 0576aa77..2498a86f 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -3,34 +3,34 @@ import 'dart:collection'; import 'package:test/test.dart'; class TreeNode { - int data; - var leftNode = null; - var rightNode = null; + int? data; + TreeNode? leftNode = null; + TreeNode? rightNode = null; - int get value { + int? get value { return this.data; } - TreeNode get left { + TreeNode? get left { return this.leftNode; } - void set left(TreeNode value) { + void set left(TreeNode? value) { this.leftNode = value; } - void set right(TreeNode value) { + void set right(TreeNode? value) { this.rightNode = value; } - TreeNode get right { + TreeNode? get right { return this.rightNode; } TreeNode(this.data); } -List inOrder(TreeNode root, List result) { +List inOrder(TreeNode? root, List result) { if (root != null) { inOrder(root.left, result); result.add(root.value); @@ -39,7 +39,7 @@ List inOrder(TreeNode root, List result) { return result; } -List preOrder(TreeNode root, List result) { +List preOrder(TreeNode? root, List result) { if (root != null) { result.add(root.value); preOrder(root.left, result); @@ -48,7 +48,7 @@ List preOrder(TreeNode root, List result) { return result; } -List postOrder(TreeNode root, List result) { +List postOrder(TreeNode? root, List result) { if (root != null) { postOrder(root.left, result); postOrder(root.right, result); @@ -57,21 +57,21 @@ List postOrder(TreeNode root, List result) { return result; } -List levelOrder(TreeNode root, List result) { - Queue q = Queue(); +List levelOrder(TreeNode? root, List result) { + Queue q = Queue(); if (root != null) { q.add(root); } while (!q.isEmpty) { - TreeNode curr = q.first; + TreeNode? curr = q.first; q.removeFirst(); - result.add(curr.data); - if (curr.left != null) { - q.addLast(curr.left); + result.add(curr?.data); + if (curr?.left != null) { + q.addLast(curr?.left); } - if (curr.right != null) { - q.addLast(curr.right); + if (curr?.right != null) { + q.addLast(curr?.right); } } @@ -79,15 +79,15 @@ List levelOrder(TreeNode root, List result) { } void main() { - var root = TreeNode(1); + TreeNode? root = TreeNode(1); root.left = TreeNode(2); root.right = TreeNode(3); - root.left.left = TreeNode(4); - root.left.right = TreeNode(5); - root.left.right.left = TreeNode(6); - root.right.left = TreeNode(7); - root.right.left.left = TreeNode(8); - root.right.left.left.right = TreeNode(9); + root.left?.left = TreeNode(4); + root.left?.right = TreeNode(5); + root.left?.right?.left = TreeNode(6); + root.right?.left = TreeNode(7); + root.right?.left?.left = TreeNode(8); + root.right?.left?.left?.right = TreeNode(9); List result; result = List.empty(growable: true); diff --git a/data_structures/linked_list/cycle_in_linked_list.dart b/data_structures/linked_list/cycle_in_linked_list.dart index 5582046c..4d0d24ec 100644 --- a/data_structures/linked_list/cycle_in_linked_list.dart +++ b/data_structures/linked_list/cycle_in_linked_list.dart @@ -3,37 +3,37 @@ import 'package:test/test.dart'; class Node { int value; - Node next = null; + Node? next = null; Node(this.value); int get nodeValue { return this.value; } - Node get nextNode { + Node? get nextNode { return this.next; } } class LinkedList { - Node _headNode; - Node _tailNode; + Node? _headNode; + Node? _tailNode; - Node get head { + Node? get head { return this._headNode; } - Node get tail { + Node? get tail { return this._tailNode; } - void insert(Node newNode) { + void insert(Node? newNode) { if (head == null) { this._headNode = newNode; this._tailNode = newNode; } else { - this._tailNode.next = newNode; - this._tailNode = this._tailNode.next; + this._tailNode?.next = newNode; + this._tailNode = this._tailNode?.next; } } } @@ -42,7 +42,7 @@ Node createNode(int value) { return Node(value); } -Node findCyclicNode(Node headNode) { +Node? findCyclicNode(Node? headNode) { /// Check : https://en.wikipedia.org/wiki/Cycle_detection /// we maintain a fast and slow pointer /// The fast pointer jumps 2 nodes at a time @@ -53,12 +53,12 @@ Node findCyclicNode(Node headNode) { /// The node where these two nodes coincide again will be the /// origin of the loop node. /// and move in tandem. check algorith for proof - Node fastNode = headNode; - Node slowNode = headNode; + Node? fastNode = headNode; + Node? slowNode = headNode; while (fastNode != null && fastNode.next != null) { - slowNode = slowNode.next; - fastNode = fastNode.next.next; + slowNode = slowNode?.next; + fastNode = fastNode.next?.next; if (slowNode == fastNode) { break; @@ -68,8 +68,8 @@ Node findCyclicNode(Node headNode) { if (slowNode == fastNode) { slowNode = headNode; while (slowNode != fastNode) { - slowNode = slowNode.next; - fastNode = fastNode.next; + slowNode = slowNode?.next; + fastNode = fastNode?.next; } return slowNode; } else { @@ -79,60 +79,60 @@ Node findCyclicNode(Node headNode) { void main() { LinkedList linkedList = LinkedList(); - List allNodes = List(); + List allNodes = []; for (var i = 0; i <= 10; i++) { Node newNode = createNode(i); linkedList.insert(newNode); allNodes.add(newNode); } - Node tail = linkedList.tail; + Node? tail = linkedList.tail; Random random = new Random(); test(('test 1'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 2'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 3'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 4'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 5'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 6'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); test(('test 7'), () { int randomIndex = random.nextInt(9); - tail.next = allNodes[randomIndex]; - Node cycleNode = findCyclicNode(linkedList.head); + tail?.next = allNodes[randomIndex]; + Node? cycleNode = findCyclicNode(linkedList.head); expect(cycleNode, equals(allNodes[randomIndex])); }); } diff --git a/data_structures/linked_list/linked_list.dart b/data_structures/linked_list/linked_list.dart index e3e805b5..a0eda717 100644 --- a/data_structures/linked_list/linked_list.dart +++ b/data_structures/linked_list/linked_list.dart @@ -1,24 +1,24 @@ import 'package:test/test.dart'; class Node { - Node next; - T value; + Node? next; + T? value; Node(this.value); Node.before(this.next, this.value); } -class LinkedListIterator extends Iterator { - Node _current; +class LinkedListIterator implements Iterator { + Node? _current; @override bool moveNext() => _current != null; @override - T get current { - T currentValue = this._current.value; + T? get current { + T? currentValue = this._current?.value; - this._current = this._current.next; + this._current = this._current?.next; return currentValue; } @@ -26,38 +26,38 @@ class LinkedListIterator extends Iterator { LinkedListIterator(this._current); } -class LinkedList extends Iterable { +class LinkedList extends Iterable { int _length = 0; int get length => this._length; - Node _head; + Node? _head; @override - Iterator get iterator => new LinkedListIterator(this._head); + Iterator get iterator => new LinkedListIterator(this._head); - void remove(T item) { + void remove(T? item) { if (this._head?.value == item) { this._head = this._head?.next; this._length--; } if (this._head != null) { - Node current = this._head; + Node? current = this._head; while (current?.next != null) { - if (current.next.value == item) { - current.next = current.next.next; + if (current?.next?.value == item) { + current?.next = current.next?.next; this._length--; } - current = current.next; + current = current?.next; } } } - T pop() { + T? pop() { if (this._head != null) { - T value = this._head.value; - this._head = this._head.next; + T? value = this._head?.value; + this._head = this._head?.next; this._length--; return value; @@ -71,16 +71,16 @@ class LinkedList extends Iterable { this._length++; } - void add(T item) { + void add(T? item) { if (this._head == null) { this._head = new Node(item); } else { - Node current = this._head; + Node? current = this._head; while (current?.next != null) { - current = current.next; + current = current?.next; } - current.next = Node(item); + current?.next = Node(item); } this._length++; } diff --git a/data_structures/linked_list/merge_sorted_list.dart b/data_structures/linked_list/merge_sorted_list.dart new file mode 100644 index 00000000..c31c26c7 --- /dev/null +++ b/data_structures/linked_list/merge_sorted_list.dart @@ -0,0 +1,94 @@ +// https://leetcode.com/problems/merge-two-sorted-lists/ +import 'package:test/test.dart'; + +class ListNode { + int? val; + ListNode? next; + ListNode({this.val = 0, this.next}); +} + +extension PrintLinkedList on ListNode? { + void printLinkedList() { + ListNode? node = this; + while (node != null) { + print(node.val); + node = node.next; + } + } + + List listValues() { + List values = []; + ListNode? node = this; + while (node != null) { + values.add(node.val); + node = node.next; + } + return values; + } +} + +ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { + if (list1 == null) { + return list2; + } else if (list2 == null) { + return list1; + } + ListNode head = list1; + + if ((list1.val ?? 0) < (list2.val ?? 0)) { + head = list1; + list1 = list1.next; + } else { + head = list2; + list2 = list2.next; + } + + ListNode? node = head; + + while (list1 != null || list2 != null) { + if (list1 != null && list2 != null) { + if ((list1.val ?? 0) < (list2.val ?? 0)) { + node?.next = list1; + list1 = list1.next; + } else { + node?.next = list2; + list2 = list2.next; + } + } else if (list1 != null) { + node?.next = list1; + list1 = list1.next; + } else { + node?.next = list2; + list2 = list2?.next; + } + + node = node?.next; + } + return head; +} + +void main() { + test('test case 1', () { + ListNode head1 = ListNode( + val: 1, + next: ListNode(val: 2, next: ListNode(val: 4)), + ); + ListNode head2 = ListNode( + val: 1, + next: ListNode(val: 3, next: ListNode(val: 4)), + ); + expect(mergeTwoLists(head1, head2).listValues(), [1, 1, 2, 3, 4, 4]); + }); + + test('test case 2', () { + ListNode head1 = ListNode( + val: 1, + next: ListNode(val: 2, next: ListNode(val: 3)), + ); + ListNode head2 = ListNode( + val: 4, + next: ListNode(val: 5, next: ListNode(val: 6)), + ); + expect(mergeTwoLists(head1, head2).listValues(), [1, 2, 3, 4, 5, 6]); + }); +} diff --git a/data_structures/quad_tree/quad_tree.dart b/data_structures/quad_tree/quad_tree.dart deleted file mode 100644 index b3628318..00000000 --- a/data_structures/quad_tree/quad_tree.dart +++ /dev/null @@ -1,219 +0,0 @@ -// Author: Jerold Albertson -// Profile: https://github.com/jerold -// Algorithm: https://en.wikipedia.org/wiki/Quadtree - -import 'dart:math'; -import 'package:test/test.dart'; - -// defaults should almost never be used, tune the quad tree to fit your problem -int default_max_depth = 1000; -int default_max_items = 100; - -// names reflect a coordinate system where values increase as one goes left or down -const _upperLeftIndex = 0; -const _upperRightIndex = 1; -const _lowerLeftIndex = 2; -const _lowerRightIndex = 3; - -class Node extends Rectangle { - final int maxDepth; - final int maxItems; - - final int _depth; - final Point _center; - final List<_ItemAtPoint> _items = <_ItemAtPoint>[]; - final List> _children = >[]; - - factory Node(num left, num top, num width, num height, - {int maxDepth, int maxItems}) => - Node._(left, top, width, height, maxDepth, maxItems, 0); - - Node._(num left, num top, num width, num height, int maxDepth, int maxItems, - int depth) - : maxDepth = maxDepth ?? default_max_depth, - maxItems = maxItems ?? default_max_items, - _depth = depth, - _center = Point(left + width / 2.0, top + height / 2.0), - super(left, top, width, height); - - bool insert(T item, Point atPoint) { - if (!containsPoint(atPoint)) return false; - - if (_children.isEmpty) { - if (_items.length + 1 <= maxItems || _depth + 1 > maxDepth) { - _items.add(_ItemAtPoint(item, atPoint)); - return true; - } - _splitItemsBetweenChildren(); - } - return _insertItemIntoChildren(item, atPoint); - } - - List query(Rectangle range) { - if (_children.isEmpty) { - return _items - .where((item) => range.containsPoint(item.point)) - .map((item) => item.item) - .toList(); - } - return _children - .where((child) => child.intersects(range)) - .expand((child) => child.query(range)) - .toList(); - } - - String toString() { - return '[$_depth](${_items.map((item) => item.item).toList()}:$_children)'; - } - - bool _insertItemIntoChildren(T item, Point atPoint) { - if (atPoint.x > _center.x) { - if (atPoint.y > _center.y) { - return _children[_lowerRightIndex].insert(item, atPoint); - } - return _children[_upperRightIndex].insert(item, atPoint); - } else { - if (atPoint.y > _center.y) { - return _children[_lowerLeftIndex].insert(item, atPoint); - } else { - return _children[_upperLeftIndex].insert(item, atPoint); - } - } - } - - void _splitItemsBetweenChildren() { - _children.addAll([ - _newUpperLeft, // _upperLeftIndex = 0 - _newUpperRight, // _upperRightIndex = 1 - _newLowerLeft, // _lowerLeftIndex = 2 - _newLowerRight // _lowerRightIndex = 3 - ]); - for (final item in _items) { - _insertItemIntoChildren(item.item, item.point); - } - _items.clear(); - } - - Node get _newUpperLeft => Node._( - left, top, width / 2.0, height / 2.0, maxDepth, maxItems, _depth + 1); - - Node get _newUpperRight => Node._(_center.x, top, width / 2.0, - height / 2.0, maxDepth, maxItems, _depth + 1); - - Node get _newLowerLeft => Node._(left, _center.y, width / 2.0, - height / 2.0, maxDepth, maxItems, _depth + 1); - - Node get _newLowerRight => Node._(_center.x, _center.y, width / 2.0, - height / 2.0, maxDepth, maxItems, _depth + 1); -} - -class _ItemAtPoint { - final T item; - final Point point; - - _ItemAtPoint(this.item, this.point); -} - -void main() { - group('QuadTree', () { - test('items will not insert at points outside the tree\'s bounds', () { - final tree = Node(-50, -50, 100, 100); - expect(tree.insert("a", Point(-75, 0)), isFalse); - expect(tree.insert("b", Point(75, 0)), isFalse); - expect(tree.insert("c", Point(0, -75)), isFalse); - expect(tree.insert("d", Point(0, 75)), isFalse); - expect(tree.toString(), equals("[0]([]:[])")); - }); - - test('maxItems is honored until maxDepth is hit', () { - final tree = Node(0, 0, 100, 100, maxItems: 2, maxDepth: 2); - - expect(tree.insert("a", Point(0, 0)), isTrue); - expect(tree.toString(), equals("[0]([a]:[])")); - - expect(tree.insert("b", Point(100, 0)), isTrue); - expect(tree.toString(), equals("[0]([a, b]:[])")); - - expect(tree.insert("c", Point(0, 100)), isTrue); - expect( - tree.toString(), - equals( - "[0]([]:[[1]([a]:[]), [1]([b]:[]), [1]([c]:[]), [1]([]:[])])")); - - expect(tree.insert("d", Point(100, 100)), isTrue); - expect( - tree.toString(), - equals( - "[0]([]:[[1]([a]:[]), [1]([b]:[]), [1]([c]:[]), [1]([d]:[])])")); - - expect(tree.insert("e", Point(99, 99)), isTrue); - expect(tree.insert("f", Point(99, 99)), isTrue); - expect(tree.insert("g", Point(99, 99)), isTrue); - expect(tree.insert("h", Point(99, 99)), isTrue); - expect( - tree.toString(), - equals( - "[0]([]:[[1]([a]:[]), [1]([b]:[]), [1]([c]:[]), [1]([]:[[2]([]:[]), [2]([]:[]), [2]([]:[]), [2]([d, e, f, g, h]:[])])])")); - }); - - test( - 'better at finding local points within a large space than simple iteration', - () { - final rand = Random.secure(); - final items = {}; - - final width = 1000; - final height = 1000; - - var timesBetter = 0; - final numberOfRuns = 100; - // run the same test x number of times - for (int j = 0; j < numberOfRuns; j++) { - // test consists of setting up x items, distributing them randomly - // within a space, and then searching for a small subset of those - // using simple rect comparison on all items, or a quad tree query - final tree = Node(0, 0, width, height); - final numberOfItems = 50000; - for (int i = 0; i < numberOfItems; i++) { - items[i] = - Point(rand.nextDouble() * width, rand.nextDouble() * height); - expect(tree.insert(i, items[i]), isTrue); - } - - // set up a box that is 1/10th the size of the total space - final rangeSizePercentage = .1; - final rangeWidth = width * rangeSizePercentage; - final rangeHeight = height * rangeSizePercentage; - final rangeLeft = rand.nextDouble() * (width - rangeWidth); - final rangeTop = rand.nextDouble() * (height - rangeHeight); - - final range = Rectangle(rangeLeft, rangeTop, rangeWidth, rangeHeight); - - // simple iteration over all items, comparing each to the given range - var startTime = DateTime.now(); - final foundA = - items.keys.where((key) => range.containsPoint(items[key])).toList(); - var iterationTime = DateTime.now().difference(startTime); - - // quad tree query rules out whole quadrants full of points when possible - startTime = DateTime.now(); - final foundB = tree.query(range); - var quadTreeTime = DateTime.now().difference(startTime); - - if (iterationTime.compareTo(quadTreeTime) > 0) { - timesBetter++; - } - - // every time, quad tree query results should equal brute force results - expect(foundA.toSet().containsAll(foundB), isTrue, - reason: "not all items were found"); - expect(foundB.toSet().containsAll(foundA), isTrue, - reason: "not all items were found"); - } - - expect(timesBetter / numberOfRuns > 0.5, isTrue, - reason: - "tree query was only better ${timesBetter / numberOfRuns * 100}% of the time"); - }); - }); -} diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index bd28bfa7..55924098 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -1,8 +1,12 @@ import 'dart:math'; import 'package:test/test.dart'; -int knapSackProblem(int capacity, List values, List weights, - [int numberOfItems]) { +int knapSackProblem( + int capacity, + List values, + List weights, [ + int? numberOfItems, +]) { numberOfItems ??= values.length; if (numberOfItems == 0 || capacity == 0) { return 0; @@ -12,10 +16,15 @@ int knapSackProblem(int capacity, List values, List weights, if (weights[numberOfItems - 1] <= capacity) { return max( - currentValue + - knapSackProblem( - capacity - currentWeight, values, weights, numberOfItems - 1), - knapSackProblem(capacity, values, weights, numberOfItems - 1)); + currentValue + + knapSackProblem( + capacity - currentWeight, + values, + weights, + numberOfItems - 1, + ), + knapSackProblem(capacity, values, weights, numberOfItems - 1), + ); } else { return knapSackProblem(capacity, values, weights, numberOfItems - 1); } @@ -34,6 +43,8 @@ void main() { test('TC: 2', () { expect( - knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), 101); + knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), + 101, + ); }); } diff --git a/dynamic_programming/coin_change.dart b/dynamic_programming/coin_change.dart index 4f3367be..f03c64f9 100644 --- a/dynamic_programming/coin_change.dart +++ b/dynamic_programming/coin_change.dart @@ -8,8 +8,10 @@ import 'package:test/test.dart'; /// time complexity O(targetAmount * coinDenoms) /// space complexity O(targetAmount) int minNumberOfCoins(int targetAmount, List coinDenoms) { - List amounts = - new List.generate(targetAmount + 1, (int index) => 1000000000000); + List amounts = new List.generate( + targetAmount + 1, + (int index) => 1000000000000, + ); amounts[0] = 0; diff --git a/dynamic_programming/longest_common_substring.dart b/dynamic_programming/longest_common_substring.dart index 3662c60d..46918727 100644 --- a/dynamic_programming/longest_common_substring.dart +++ b/dynamic_programming/longest_common_substring.dart @@ -53,8 +53,11 @@ void main() { }); test(('testCase #10'), () { expect( - longestCommonSubstring( - "OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com"), - equals(10)); + longestCommonSubstring( + "OldSite:GeeksforGeeks.org", + "NewSite:GeeksQuiz.com", + ), + equals(10), + ); }); } diff --git a/graphs/area_of_island.dart b/graphs/area_of_island.dart new file mode 100644 index 00000000..688dc037 --- /dev/null +++ b/graphs/area_of_island.dart @@ -0,0 +1,127 @@ +import 'package:test/test.dart'; + +extension MinMax on List { + int get max { + num maxNumber = double.negativeInfinity; + for (int i = 0; i < length; ++i) { + if (maxNumber < this[i]) { + maxNumber = this[i]; + } + } + if (maxNumber != double.negativeInfinity) { + return maxNumber.toInt(); + } + return 0; + } +} + +const List> deltas = [ + [-1, 0], // top neighbour + [0, 1], // right neighbour + [1, 0], // bottom neighbour + [0, -1], // left neighbour. +]; + +int maxAreaOfIsland(List> grid) { + int numRows = grid.length; + int numCols = grid[0].length; + List> visited = List.generate( + numRows, + (int index) => List.filled(numCols, false), + ); + + List areas = []; + for (int i = 0; i < numRows; ++i) { + for (int j = 0; j < numCols; ++j) { + if (visited[i][j] || grid[i][j] == 0) continue; + traverseNode(i, j, grid, visited, areas); + } + } + return areas.max; +} + +bool isInvalidIndex(int i, int j, int rowCount, int colCount) { + return (i < 0 || i >= rowCount || j >= colCount || j < 0); +} + +List> adjacentNodes( + List> grid, + List> visited, + int x, + int y, +) { + List> nodes = []; + for (int i = 0; i < deltas.length; ++i) { + int dx = x + deltas[i][0]; + int dy = y + deltas[i][1]; + + if (isInvalidIndex(dx, dy, grid.length, grid[0].length)) continue; + if (visited[dx][dy] || grid[dx][dy] == 0) continue; + + nodes.add([dx, dy]); + } + return nodes; +} + +void traverseNode( + int i, + int j, + List> grid, + List> visited, + List areas, +) { + int area = 0; + List> nodesToExplore = [ + [i, j], + ]; + while (nodesToExplore.isNotEmpty) { + List node = nodesToExplore.removeLast(); + + int x = node[0]; + int y = node[1]; + + if (visited[x][y]) continue; + visited[x][y] = true; + if (grid[x][y] == 0) continue; + + area += 1; + nodesToExplore.addAll(adjacentNodes(grid, visited, x, y)); + } + if (area > 0) { + areas.add(area); + } +} + +void main() { + test('test case 1', () { + List> island = [ + [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], + [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], + ]; + expect(maxAreaOfIsland(island), 6); + }); + + test('test case 2', () { + List> island = [ + [0, 0, 1], + [0, 0, 0], + [0, 1, 1], + ]; + expect(maxAreaOfIsland(island), 2); + }); + + test('test case 3', () { + List> island = [ + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ]; + expect(maxAreaOfIsland(island), 0); + }); +} diff --git a/graphs/breadth_first_search.dart b/graphs/breadth_first_search.dart index 4a7406f7..ff504d0d 100644 --- a/graphs/breadth_first_search.dart +++ b/graphs/breadth_first_search.dart @@ -61,7 +61,7 @@ void main() { List> edges = [ [0, 1], - [0, 2] + [0, 2], ]; Graph graph = Graph(nodes); @@ -71,8 +71,11 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = - breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + List answer = breadthFirstSearch( + graph, + graph.numberOfNodesInGraph, + startNode, + ); expect(answer, equals([0, 1, 2])); }); @@ -84,7 +87,7 @@ void main() { [0, 1], [0, 2], [0, 3], - [2, 4] + [2, 4], ]; Graph graph = Graph(nodes); @@ -94,8 +97,11 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = - breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + List answer = breadthFirstSearch( + graph, + graph.numberOfNodesInGraph, + startNode, + ); expect(answer, equals([0, 1, 2, 3, 4])); }); } diff --git a/graphs/depth_first_search.dart b/graphs/depth_first_search.dart index c60ca4fc..4903e584 100644 --- a/graphs/depth_first_search.dart +++ b/graphs/depth_first_search.dart @@ -14,7 +14,7 @@ class Graph { /// each node will have a list as value which stores /// the nodes to which it is connected to for (int i = 0; i < this.nodes.length; i++) { - this.graph[nodes[i]] = List(); + this.graph[nodes[i]] = []; } } @@ -32,7 +32,7 @@ class Graph { void addNodes(int newNode) { this.nodes.add(newNode); - this.graph[newNode] = List(); + this.graph[newNode] = []; } void addEdges(int start, int end) { @@ -56,10 +56,12 @@ void depthFirstSearchHelper(graph, visitedNodes, node, answer) { } List depthFirstSearch(Graph graph, int numberOfNodes, int startNode) { - List visitedNodes = - new List.generate(numberOfNodes, (index) => false); + List visitedNodes = new List.generate( + numberOfNodes, + (index) => false, + ); - List answer = List(); + List answer = []; depthFirstSearchHelper(graph.graph, visitedNodes, startNode, answer); return answer; } @@ -72,7 +74,7 @@ void main() { List> edges = [ [0, 1], [1, 2], - [0, 3] + [0, 3], ]; Graph graph = Graph(nodes); @@ -82,8 +84,11 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = - depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + List answer = depthFirstSearch( + graph, + graph.numberOfNodesInGraph, + startNode, + ); expect(answer, equals([0, 1, 2, 3])); }); @@ -95,7 +100,7 @@ void main() { [0, 1], [0, 2], [0, 3], - [2, 4] + [2, 4], ]; Graph graph = Graph(nodes); @@ -105,8 +110,11 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = - depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + List answer = depthFirstSearch( + graph, + graph.numberOfNodesInGraph, + startNode, + ); expect(answer, equals([0, 1, 2, 4, 3])); }); } diff --git a/graphs/nearest_neighbour_algorithm.dart b/graphs/nearest_neighbour_algorithm.dart index c4675f73..50dc2dcd 100644 --- a/graphs/nearest_neighbour_algorithm.dart +++ b/graphs/nearest_neighbour_algorithm.dart @@ -18,8 +18,8 @@ List nearestNeighbourSearch(Graph graph) { int currentNode = 0; while (unvisitedNodes.isNotEmpty) { unvisitedNodes.remove(currentNode); - int nearestNeighbour; - double nearestNeighbourDistance; + int? nearestNeighbour; + double nearestNeighbourDistance = 0; for (int neighbour in unvisitedNodes) { double neighbourDistance = graph.adjacencyMatrix[currentNode][neighbour]; @@ -31,7 +31,7 @@ List nearestNeighbourSearch(Graph graph) { } path.add(graph.nodes[currentNode]); - currentNode = nearestNeighbour; + currentNode = nearestNeighbour ?? 0; } return path; @@ -71,19 +71,16 @@ Graph fromPoints(List points) { } void main() { - Graph graph = Graph([ - "A", - "B", - "C", - "D", - "E" - ], [ - [0, 12, 4, 54, 100], - [3, 0, 5, 1, 1], - [300, 20, 0, 433, 123], - [32, 31, 54, 0, 3], - [2, 65, 12, 32, 0] - ]); + Graph graph = Graph( + ["A", "B", "C", "D", "E"], + [ + [0, 12, 4, 54, 100], + [3, 0, 5, 1, 1], + [300, 20, 0, 433, 123], + [32, 31, 54, 0, 3], + [2, 65, 12, 32, 0], + ], + ); print(nearestNeighbourSearch(graph)); @@ -94,7 +91,7 @@ void main() { new Point(3.33, 8.11), new Point(12, 11), new Point(-1, 1), - new Point(-2, 2) + new Point(-2, 2), ]; print(nearestNeighbourSearch(fromPoints(points))); diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart index 0c42469d..b53c4bdf 100644 --- a/maths/Armstrong_number.dart +++ b/maths/Armstrong_number.dart @@ -7,7 +7,7 @@ bool Armstrong_no(var x) { var sum = 0; while (n != 0) { var r = n % 10; - sum = sum + pow(r, d); + sum = sum + pow(r, d).toInt(); n = n ~/ 10; } return sum == x; diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index d09dc210..03f17ab8 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -23,7 +23,7 @@ int getNthUglyNo(int n) { int i = 1; int count = 1; /* ugly number count */ -/*Check for all integers untill ugly count + /*Check for all integers untill ugly count becomes n*/ while (n > count) { i++; diff --git a/maths/average.dart b/maths/average.dart index d195e39a..32cee4f0 100644 --- a/maths/average.dart +++ b/maths/average.dart @@ -1,7 +1,7 @@ //Find mean of a list of numbers. -average(List numbers) { - var sum = 0; +average(List numbers) { + int sum = 0; for (var x in numbers) { sum += x; } diff --git a/maths/factors.dart b/maths/factors.dart index 8f624505..5538449d 100644 --- a/maths/factors.dart +++ b/maths/factors.dart @@ -2,8 +2,9 @@ void main() { print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] try { - print(factorsOf(-1) - .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function + print( + factorsOf(-1).toString(), + ); //Unhandled exception: Exception: A non-positive value was passed to the function } catch (ex) { print(ex); } diff --git a/maths/fermats_little_theorem.dart b/maths/fermats_little_theorem.dart index 56073fe7..4d3847eb 100644 --- a/maths/fermats_little_theorem.dart +++ b/maths/fermats_little_theorem.dart @@ -1,5 +1,4 @@ @Skip('currently failing (see issue #86)') - import 'package:test/test.dart'; /* diff --git a/maths/fibonacci_dynamic_programming.dart b/maths/fibonacci_dynamic_programming.dart index 570e3016..973ab618 100644 --- a/maths/fibonacci_dynamic_programming.dart +++ b/maths/fibonacci_dynamic_programming.dart @@ -3,7 +3,7 @@ import 'package:test/test.dart'; //Title: Nth Fibonacci Number using Dynamic Programming //Author: Richik Chanda //Email: richikchanda1999@gmail.com -List dp; +List dp = []; int mod = (1e9 + 7).toInt(); //Get the nth Fibonacci number modulo 10^9 + 7 since it can be a very large number diff --git a/maths/find_max_recursion.dart b/maths/find_max_recursion.dart index d9565953..5a20f6e0 100644 --- a/maths/find_max_recursion.dart +++ b/maths/find_max_recursion.dart @@ -12,9 +12,15 @@ int find_max_recursion(List numbers, int low, int high) { return numbers[low]; // or numbers[high] } int mid = (low + high) >> 1; - int leftMax = - find_max_recursion(numbers, low, mid); /* max in range [low mid] */ + int leftMax = find_max_recursion( + numbers, + low, + mid, + ); /* max in range [low mid] */ int rightMax = find_max_recursion( - numbers, mid + 1, high); /* max in range [mid + 1, high] */ + numbers, + mid + 1, + high, + ); /* max in range [mid + 1, high] */ return leftMax >= rightMax ? leftMax : rightMax; } diff --git a/maths/find_min_recursion.dart b/maths/find_min_recursion.dart index b53ca13e..0c4b7be1 100644 --- a/maths/find_min_recursion.dart +++ b/maths/find_min_recursion.dart @@ -12,9 +12,15 @@ int find_min_recursion(List numbers, int low, int high) { return numbers[low]; // or numbers[high] } int mid = (low + high) >> 1; - int leftMin = - find_min_recursion(numbers, low, mid); /* min in range [low mid] */ + int leftMin = find_min_recursion( + numbers, + low, + mid, + ); /* min in range [low mid] */ int rightMin = find_min_recursion( - numbers, mid + 1, high); /* min in range [mid + 1, high] */ + numbers, + mid + 1, + high, + ); /* min in range [mid + 1, high] */ return leftMin <= rightMin ? leftMin : rightMin; } diff --git a/maths/hamming_distance.dart b/maths/hamming_distance.dart index 7394bbf1..74fba95a 100644 --- a/maths/hamming_distance.dart +++ b/maths/hamming_distance.dart @@ -9,7 +9,7 @@ int hamming_distance(String stringA, String stringB) { //strings must be of equal length if (stringA.length != stringB.length) { print('String lengths must be same!'); - return null; + return 0; } else { distance = 0; for (var i = 0; i < stringA.length; i++) { diff --git a/maths/lu_decomposition.dart b/maths/lu_decomposition.dart index 857a8cc6..d0350a7e 100644 --- a/maths/lu_decomposition.dart +++ b/maths/lu_decomposition.dart @@ -20,19 +20,19 @@ class LUPDecomposition { } class Matrix { - List> _values; + List> values; @override - String toString() => this._values.toString(); + String toString() => this.values.toString(); - int get nRows => this._values.length; - int get nColumns => this.nRows == 0 ? 0 : this._values[0].length; + int get nRows => this.values.length; + int get nColumns => this.nRows == 0 ? 0 : this.values[0].length; bool get isSquare => this.nRows == this.nColumns; - List> get rows => this._values; + List> get rows => this.values; - List operator [](int n) => this._values[n]; + List operator [](int n) => this.values[n]; Matrix operator +(Matrix other) { if (this.nRows != other.nRows || this.nColumns != other.nColumns) { @@ -48,7 +48,7 @@ class Matrix { values.add(newRow); } - return new Matrix(values); + return new Matrix(values: values); } Matrix operator -(Matrix other) { @@ -66,7 +66,7 @@ class Matrix { values.add(newRow); } - return new Matrix(values); + return new Matrix(values: values); } Matrix times(double n) { @@ -99,7 +99,7 @@ class Matrix { values.add(newRow); } - return new Matrix(values); + return new Matrix(values: values); } LUPDecomposition decompose() { @@ -203,33 +203,33 @@ class Matrix { } } - Matrix.eye(int size) { - this._values = []; + Matrix.eye(int size, {this.values = const []}) { + this.values = []; for (int i = 0; i < size; i++) { List row = List.generate(size, (x) => 0); row[i] = 0; - this._values.add(row); + this.values.add(row); } } - Matrix.from(Matrix matrix) { - this._values = matrix.rows.map((row) => List.from(row)).toList(); + Matrix.from(Matrix matrix, {this.values = const []}) { + this.values = matrix.rows.map((row) => List.from(row)).toList(); } - Matrix.zeros(int nRows, int nColumns) { - this._values = []; + Matrix.zeros(int nRows, int nColumns, {this.values = const []}) { + this.values = []; for (int i = 0; i < nRows; i++) { List row = []; for (int j = 0; j < nColumns; j++) { row.add(0); } - this._values.add(row); + this.values.add(row); } } - Matrix(List> values) { + Matrix({List> this.values = const []}) { if (values.length != 0) { int rowLength = values[0].length; if (values.any((row) => row.length != rowLength)) { @@ -237,7 +237,7 @@ class Matrix { } } - this._values = values; + this.values = values; } } @@ -280,11 +280,13 @@ double f(double x, double y) { } void main() { - Matrix a = new Matrix([ - [3, 2, -1], - [2, -2, 4], - [-1, 0.5, -1] - ]); + Matrix a = new Matrix( + values: [ + [3, 2, -1], + [2, -2, 4], + [-1, 0.5, -1], + ], + ); List b = [1, -2, 0]; List solution = solve(a, b); diff --git a/maths/newton_method.dart b/maths/newton_method.dart index 49d6418d..4862181a 100644 --- a/maths/newton_method.dart +++ b/maths/newton_method.dart @@ -6,8 +6,12 @@ double derivative(double Function(double) f, double x, [double h = 1e-10]) { } /// Find root of given [f] (x where [f(x)] == 0) -double findRoot(double Function(double) f, - [double initialValue = 0, int iterations = 10, double h = 1e-10]) { +double findRoot( + double Function(double) f, [ + double initialValue = 0, + int iterations = 10, + double h = 1e-10, +]) { double currentValue = initialValue; for (int i = 0; i < iterations; i++) { currentValue -= f(currentValue) / derivative(f, currentValue); diff --git a/maths/sigmoid.dart b/maths/sigmoid.dart index c0ba4e8d..c2235164 100644 --- a/maths/sigmoid.dart +++ b/maths/sigmoid.dart @@ -1,7 +1,9 @@ import 'dart:math'; double sigmoid( - double x, double a) //x is the function variable and a is the gain + double x, + double a, +) //x is the function variable and a is the gain { double p = exp(-a * x); return 1 / (1 + p); diff --git a/maths/symmetric_derivative.dart b/maths/symmetric_derivative.dart index b192f4c8..d14c0e8d 100644 --- a/maths/symmetric_derivative.dart +++ b/maths/symmetric_derivative.dart @@ -8,6 +8,7 @@ double derivative(double Function(double) f, double x, [double h = 1e-10]) { void main() { print("derivative(sin, pi) = ${derivative(sin, pi)}, cos(pi) = ${cos(pi)}"); print( - "derivative(sin, 2 * pi) = ${derivative(sin, 2 * pi)}, cos(2 * pi) = ${cos(2 * pi)}"); + "derivative(sin, 2 * pi) = ${derivative(sin, 2 * pi)}, cos(2 * pi) = ${cos(2 * pi)}", + ); print("derivative(exp, 3) = ${derivative(exp, 3)}, exp(3) = ${exp(3)}"); } diff --git a/other/LCM.dart b/other/LCM.dart index cdb005ab..3eefc880 100644 --- a/other/LCM.dart +++ b/other/LCM.dart @@ -30,20 +30,24 @@ void main() { a = 15; b = 20; //print the result - print("LCM of " + - a.toString() + - " and " + - b.toString() + - " is " + - lcm(a, b).toString()); + print( + "LCM of " + + a.toString() + + " and " + + b.toString() + + " is " + + lcm(a, b).toString(), + ); //Test case2: a = 12; b = 18; //print the result - print("LCM of " + - a.toString() + - " and " + - b.toString() + - " is " + - lcm(a, b).toString()); + print( + "LCM of " + + a.toString() + + " and " + + b.toString() + + " is " + + lcm(a, b).toString(), + ); } diff --git a/other/N_bonacci.dart b/other/N_bonacci.dart index 217417a7..14ba7b48 100644 --- a/other/N_bonacci.dart +++ b/other/N_bonacci.dart @@ -1,7 +1,7 @@ import 'package:test/test.dart'; List N_bonacci(int n, int m) { - List v = new List(m); + List v = List.generate(m, (index) => 0); var i; for (i = 0; i < m; i++) { v[i] = 0; diff --git a/other/haversine_formula.dart b/other/haversine_formula.dart index 653c9b80..caee0b3b 100644 --- a/other/haversine_formula.dart +++ b/other/haversine_formula.dart @@ -12,7 +12,7 @@ class Coordinates { Coordinates(this.latitude, this.longitude); } -double haversine(fi) => pow(sin(fi / 2), 2); +double haversine(fi) => pow(sin(fi / 2), 2).toDouble(); /// Convert [angle] to radians double radians(double angle) => (angle * pi) / 180; @@ -26,7 +26,8 @@ double distance(Coordinates p1, Coordinates p2) { double latitude2 = radians(p2.latitude); double longitudeChange = radians(p2.longitude - p1.longitude); - double a = haversine(latitudeChange) + + double a = + haversine(latitudeChange) + cos(latitude1) * cos(latitude2) * haversine(longitudeChange); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); diff --git a/other/kadaneAlgo.dart b/other/kadaneAlgo.dart index a66daca8..e23b5065 100644 --- a/other/kadaneAlgo.dart +++ b/other/kadaneAlgo.dart @@ -8,7 +8,7 @@ int max(int a, int b) { } // Function to find the Maximum contiguous Sum in the array -int maxSubArraySum(List a, int size) { +int maxSubArraySum(List a, int size) { int max_so_far = a[0]; int curr_max = a[0]; @@ -21,7 +21,7 @@ int maxSubArraySum(List a, int size) { // main function for validation of the above int main() { - List a = [-2, -3, 4, -1, -2, 1, 5, -3]; + List a = [-2, -3, 4, -1, -2, 1, 5, -3]; int n = a.length; int max_sum = maxSubArraySum(a, n); print("Maximum contiguous sum is " + max_sum.toString()); diff --git a/project_euler/problem_17/sol17.dart b/project_euler/problem_17/sol17.dart index a9ae1a1c..6a5eb24d 100644 --- a/project_euler/problem_17/sol17.dart +++ b/project_euler/problem_17/sol17.dart @@ -23,7 +23,7 @@ const ONES = [ 'Seven', 'Eight', 'Nine', - 'Ten' + 'Ten', ]; const TEN_TWENTY = [ @@ -35,7 +35,7 @@ const TEN_TWENTY = [ 'Sixteen', 'Seventeen', 'Eighteen', - 'Nineteen' + 'Nineteen', ]; const TENS = [ @@ -47,7 +47,7 @@ const TENS = [ 'Sixty', 'Seventy', 'Eighty', - 'Ninety' + 'Ninety', ]; const HUNDRED = 'Hundred'; @@ -56,10 +56,10 @@ const AND = 'And'; String inWords = ""; -convertToWords(int number) { +String convertToWords(int number) { String numString = number.toString(); int length = numString.length; - int place = pow(10, length - 1); + int place = pow(10, length - 1).toInt(); if (number == 0) return inWords = "Zero"; diff --git a/project_euler/problem_8/sol8.dart b/project_euler/problem_8/sol8.dart index 49ce87ce..4a1449e6 100644 --- a/project_euler/problem_8/sol8.dart +++ b/project_euler/problem_8/sol8.dart @@ -32,7 +32,8 @@ */ void main() { - String series = "73167176531330624919225119674426574742355349194934" + String series = + "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" diff --git a/pubspec.yaml b/pubspec.yaml index 0ce0039e..5f2cab02 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,4 +10,4 @@ dev_dependencies: stack: ^0.2.1 environment: - sdk: ">=2.10.0 <3.0.0" + sdk: ^3.11.0 diff --git a/search/binary_search_recursion.dart b/search/binary_search_recursion.dart index 3ee40a68..359449f6 100644 --- a/search/binary_search_recursion.dart +++ b/search/binary_search_recursion.dart @@ -22,9 +22,17 @@ int binarySearch(List list, int low, int high, int key) { return mid; /* found */ } else if (key > list[mid]) { return binarySearch( - list, mid + 1, high, key); /* search in range[mid + 1, high] */ + list, + mid + 1, + high, + key, + ); /* search in range[mid + 1, high] */ } else { return binarySearch( - list, low, mid - 1, key); /* search in range[low, mid - 1] */ + list, + low, + mid - 1, + key, + ); /* search in range[low, mid - 1] */ } } diff --git a/search/fibonacci_Search.dart b/search/fibonacci_Search.dart index eba8fb04..ea7069e5 100644 --- a/search/fibonacci_Search.dart +++ b/search/fibonacci_Search.dart @@ -42,7 +42,6 @@ int fibMaonaccianSearch(List arr, int x, int n) { fibMMm2 = fibM - fibMMm1; offset = i; } - /* If x is greater than the value at index fibMmm2 * cut the subarray array after i + 1. */ @@ -51,7 +50,6 @@ int fibMaonaccianSearch(List arr, int x, int n) { fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } - //elwment found.Return index else { return i; diff --git a/search/interpolation_Search.dart b/search/interpolation_Search.dart index 594dcc1c..5e45089c 100644 --- a/search/interpolation_Search.dart +++ b/search/interpolation_Search.dart @@ -16,7 +16,8 @@ int interpolationSearch(List arr, int n, int key) { int low = 0, high = n - 1; while (low <= high && key >= arr[low] && key <= arr[high]) { /* Calculate the nearest possible position of key */ - int pos = low + + int pos = + low + (((key - arr[low]) * (high - low)) / (arr[high] - arr[low])).round(); if (key > arr[pos]) low = pos + 1; diff --git a/sort/bubble_Sort.dart b/sort/bubble_Sort.dart index 3dd5010c..a2e56f04 100644 --- a/sort/bubble_Sort.dart +++ b/sort/bubble_Sort.dart @@ -3,8 +3,11 @@ import 'dart:math' show Random; //main function,the program start void main() { final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); + var list = List.generate( + length, + (i) => rnd.nextInt(seed), + growable: false, + ); print('before sorting:'); print(list); print('---------------------------------------------'); diff --git a/sort/count_sort.dart b/sort/count_sort.dart index 38575c87..6ead83eb 100644 --- a/sort/count_sort.dart +++ b/sort/count_sort.dart @@ -61,8 +61,10 @@ int main() { expect(countSort(lst), equals(lst)); }); test("count sort", () { - expect(countSort([34, -2, 122, 24435, 23, 434, 232, 1323]), - equals([-2, 23, 34, 122, 232, 434, 1323, 24435])); + expect( + countSort([34, -2, 122, 24435, 23, 434, 232, 1323]), + equals([-2, 23, 34, 122, 232, 434, 1323, 24435]), + ); }); print(countSort([-10, -4, 1, 5, 2, -2])); diff --git a/sort/gnome_Sort.dart b/sort/gnome_Sort.dart index b6d1a9d3..52a6e8d5 100644 --- a/sort/gnome_Sort.dart +++ b/sort/gnome_Sort.dart @@ -4,7 +4,7 @@ //Function sort the array using gnome sort void gnomeSort(List arr, var n) { - if (arr == null || n == 0) return; + if (arr.isEmpty || n == 0) return; int first = 1; int second = 2; diff --git a/sort/heap_Sort.dart b/sort/heap_Sort.dart index e040f99c..8aeb6442 100644 --- a/sort/heap_Sort.dart +++ b/sort/heap_Sort.dart @@ -19,11 +19,11 @@ void sort(List arr) { } } -void heapify(List arr, var n, var i) { +void heapify(List arr, var n, int i) { //Init largest as root var largest = i; //left = 2*i + 1 - var l = 2 * i + 1; + int l = 2 * i + 1; //right = 2*i + 2 var r = 2 * i + 2; diff --git a/sort/insert_Sort.dart b/sort/insert_Sort.dart index 0dfec3ef..3ca0bec3 100644 --- a/sort/insert_Sort.dart +++ b/sort/insert_Sort.dart @@ -2,8 +2,11 @@ import 'dart:math' show Random; void main() { final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); + var list = List.generate( + length, + (i) => rnd.nextInt(seed), + growable: false, + ); print('before sorting:'); print(list); print('----------------------------------------------'); diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 5bd9355f..522e2c9b 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -51,25 +51,35 @@ List mergeSort(List list, int lIndex, int rIndex) { void main() { List list = [5, 4, 3, 2, 1]; - test('test case 1', - () => expect(mergeSort(list, 0, list.length - 1), [1, 2, 3, 4, 5])); + test( + 'test case 1', + () => expect(mergeSort(list, 0, list.length - 1), [1, 2, 3, 4, 5]), + ); List list1 = []; test('test case 2', () => expect(mergeSort(list1, 0, list1.length - 1), [])); List list2 = [1, 1, 1, 1, 1]; - test('test case 3', - () => expect(mergeSort(list2, 0, list2.length - 1), [1, 1, 1, 1, 1])); + test( + 'test case 3', + () => expect(mergeSort(list2, 0, list2.length - 1), [1, 1, 1, 1, 1]), + ); List list3 = [-1, -11, -1221, -123121, -1111111]; test( - 'test case 4', - () => expect(mergeSort(list3, 0, list3.length - 1), - [-1111111, -123121, -1221, -11, -1])); + 'test case 4', + () => expect(mergeSort(list3, 0, list3.length - 1), [ + -1111111, + -123121, + -1221, + -11, + -1, + ]), + ); List list4 = [11, 1, 1200, -1, 5]; test( - 'test case 1', - () => - expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200])); + 'test case 1', + () => expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200]), + ); } diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index 8415600d..adf562dd 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -21,10 +21,7 @@ void pigeonholeSort(List arr) { int range = max - min; range++; - List phole = new List(range); - for (int i = 0; i < range; i++) { - phole[i] = 0; - } + List phole = List.generate(range, (i) => 0); //Populate the pigeonholes. for (int i = 0; i < n; i++) { diff --git a/sort/quick_Sort.dart b/sort/quick_Sort.dart index 891432dc..055a866c 100644 --- a/sort/quick_Sort.dart +++ b/sort/quick_Sort.dart @@ -3,7 +3,7 @@ import 'dart:math' show Random; // quickSort // O(n*log n) void main() { - var list = List(); + var list = []; Random random = new Random(); for (var i = 0; i < 100; i++) { list.add(random.nextInt(100)); diff --git a/sort/radix_sort.dart b/sort/radix_sort.dart index 4dc393e1..52d55d45 100644 --- a/sort/radix_sort.dart +++ b/sort/radix_sort.dart @@ -25,13 +25,18 @@ main() { expect(radixSort(lst), equals(lst)); }); test("radix sort", () { - expect(radixSort([34, -2, 122, 24435, 23, 434, 232, 1323]), - equals([-2, 23, 34, 122, 232, 434, 1323, 24435])); + expect( + radixSort([34, -2, 122, 24435, 23, 434, 232, 1323]), + equals([-2, 23, 34, 122, 232, 434, 1323, 24435]), + ); }); final seed = 10, rnd = Random(), length = 10; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); + var list = List.generate( + length, + (i) => rnd.nextInt(seed), + growable: false, + ); print('before sorting:'); print(list); print('----------------------------------------------'); diff --git a/sort/select_Sort.dart b/sort/select_Sort.dart index dd766542..4a1161a9 100644 --- a/sort/select_Sort.dart +++ b/sort/select_Sort.dart @@ -3,8 +3,11 @@ import 'dart:math' show Random; //main function,the program start void main() { final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); + var list = List.generate( + length, + (i) => rnd.nextInt(seed), + growable: false, + ); print('before sorting:'); print(list); print('--------------------------------------'); diff --git a/sort/shell_Sort.dart b/sort/shell_Sort.dart index c4f93cc8..6d5275d1 100644 --- a/sort/shell_Sort.dart +++ b/sort/shell_Sort.dart @@ -2,8 +2,11 @@ import 'dart:math' show Random; void main() { final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); + var list = List.generate( + length, + (i) => rnd.nextInt(seed), + growable: false, + ); print('before sorting:'); print(list); print('----------------------------------------------'); diff --git a/strings/isomorphic_strings.dart b/strings/isomorphic_strings.dart new file mode 100644 index 00000000..7c33c51c --- /dev/null +++ b/strings/isomorphic_strings.dart @@ -0,0 +1,33 @@ +import 'package:test/test.dart'; + +// Leetcode problem url: https://leetcode.com/problems/isomorphic-strings/ +bool isIsomorphic(String string1, String string2) { + Map sMap = {}; + Map tMap = {}; + + for (int i = 0; i < string1.length; ++i) { + String s = string1[i]; + String c = string2[i]; + + // Both characters are not mapped so far. + if (!sMap.containsKey(s) && !tMap.containsKey(c)) { + sMap[s] = c; + tMap[c] = s; + } + // One of the characters is mapped. + else if (!sMap.containsKey(s) || !tMap.containsKey(c)) { + return false; + } + // Both characters are mapped + else if (sMap[s] != c || tMap[c] != s) { + return false; + } + } + return true; +} + +void main() { + test('test case 1', () => expect(isIsomorphic('egg', 'add'), true)); + test('test case 2', () => expect(isIsomorphic('foo', 'bar'), false)); + test('test case 3', () => expect(isIsomorphic('paper', 'title'), true)); +} diff --git a/strings/knuth_morris_prat.dart b/strings/knuth_morris_prat.dart index 5564ddcb..2841bdb3 100644 --- a/strings/knuth_morris_prat.dart +++ b/strings/knuth_morris_prat.dart @@ -13,8 +13,10 @@ bool stringCompare(String string, String subString) { return false; } - List pattern = - new List.generate(subString.length, (int index) => -1); + List pattern = new List.generate( + subString.length, + (int index) => -1, + ); int i = 1; int j = 0; diff --git a/strings/reverse_words_of_string.dart b/strings/reverse_words_of_string.dart index dfb41f26..4b73b5fc 100644 --- a/strings/reverse_words_of_string.dart +++ b/strings/reverse_words_of_string.dart @@ -34,7 +34,9 @@ void main() { }); test("reverseStringWords", () { - expect(reverseStringWords("abhishek.is.a.good.boy"), - equals("boy.good.a.is.abhishek")); + expect( + reverseStringWords("abhishek.is.a.good.boy"), + equals("boy.good.a.is.abhishek"), + ); }); } diff --git a/trees/path_sum.dart b/trees/path_sum.dart index acfab1ed..a601ff0e 100644 --- a/trees/path_sum.dart +++ b/trees/path_sum.dart @@ -3,8 +3,8 @@ import 'package:test/test.dart'; // Question URL: https://leetcode.com/problems/path-sum/description/ class TreeNode { int val; - TreeNode left; - TreeNode right; + TreeNode? left; + TreeNode? right; TreeNode([this.val = 0, this.left, this.right]); } @@ -15,7 +15,7 @@ bool isLeaf(TreeNode node) { return false; } -bool traverse(TreeNode node, int targetSum, int runningSum) { +bool traverse(TreeNode? node, int targetSum, int runningSum) { if (node == null) { return false; } @@ -36,23 +36,8 @@ bool hasPathSum(TreeNode root, int targetSum) { void main() { TreeNode root = TreeNode( 5, - TreeNode( - 4, - TreeNode( - 11, - TreeNode(7), - TreeNode(2), - ), - ), - TreeNode( - 8, - TreeNode(13), - TreeNode( - 4, - null, - TreeNode(1), - ), - ), + TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))), + TreeNode(8, TreeNode(13), TreeNode(4, null, TreeNode(1))), ); test('Test Case 1: true case', () {