From 74a403d96c03037d49efc6d81c985012f1c5e442 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sat, 16 May 2020 12:33:10 +0800 Subject: [PATCH 001/443] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 550ccdda..98cf1251 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # The Algorithms - Dart +[![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)   From 15571e36623df2793cdd2e0b9fc0c9a20e9f3c8b Mon Sep 17 00:00:00 2001 From: Shivam Verma <50954641+sarcastic-verma@users.noreply.github.com> Date: Mon, 18 May 2020 17:05:39 +0530 Subject: [PATCH 002/443] Added types. --- maths/hamming_distance.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/maths/hamming_distance.dart b/maths/hamming_distance.dart index 6fdf4fd8..7394bbf1 100644 --- a/maths/hamming_distance.dart +++ b/maths/hamming_distance.dart @@ -22,9 +22,9 @@ int hamming_distance(String stringA, String stringB) { } void main() { - var stringA; - var stringB; - var dist; + String stringA; + String stringB; + int dist; stringA = 'karolin'; stringB = 'kathrin'; From 6e2d1fd8b9b450322bd71253152f0509b061d61f Mon Sep 17 00:00:00 2001 From: Shivam Verma <50954641+sarcastic-verma@users.noreply.github.com> Date: Mon, 18 May 2020 17:23:52 +0530 Subject: [PATCH 003/443] Create FizzBuzz.dart --- other/FizzBuzz.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 other/FizzBuzz.dart diff --git a/other/FizzBuzz.dart b/other/FizzBuzz.dart new file mode 100644 index 00000000..de38a706 --- /dev/null +++ b/other/FizzBuzz.dart @@ -0,0 +1,26 @@ +//Title:FizzBuzz +// Author:ShivamVerma +// Email:shivamthegreat.sv@gmail.com + +// 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". + +void main() { + fizzBuzz(); +} + +void fizzBuzz(){ + for(int i = 1;i<=100;i++){ + if(i%3==0 && i%5==0) { + print("FizzBuzz"); + } + else if(i%3==0){ + print("Fizz"); + } + else if(i%5==0){ + print("Buzz"); + } + else{ + print(i); + } + } +} From 870cb4f5902c14b68b2d785842a11624042a60d6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 18 May 2020 13:00:51 +0000 Subject: [PATCH 004/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 61f81363..053bfca2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -49,6 +49,7 @@ * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) * [Collatz](https://github.com/TheAlgorithms/Dart/blob/master/other/collatz.dart) * [Fisher Yates Shuffle](https://github.com/TheAlgorithms/Dart/blob/master/other/fisher_yates_shuffle.dart) + * [Fizzbuzz](https://github.com/TheAlgorithms/Dart/blob/master/other/FizzBuzz.dart) * [Gcd](https://github.com/TheAlgorithms/Dart/blob/master/other/gcd.dart) * [Haversine Formula](https://github.com/TheAlgorithms/Dart/blob/master/other/haversine_formula.dart) * [Heaps Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/heaps_algorithm.dart) From c9c0b4b10fae246e9b09ca150c44de2ed85fbf0d Mon Sep 17 00:00:00 2001 From: Anup Kumar Panwar <1anuppanwar@gmail.com> Date: Mon, 18 May 2020 18:31:43 +0530 Subject: [PATCH 005/443] Update README.md --- README.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/README.md b/README.md index 98cf1251..78509147 100644 --- a/README.md +++ b/README.md @@ -8,21 +8,6 @@ These implementations are for learning purposes. They may be less efficient than the implementations in the Dart standard library. -## Owners/Maintainer - -Anup Kumar Panwar -  [[Gmail](mailto:1anuppanwar@gmail.com?Subject=The%20Algorithms%20-%20Python) -  [GitHub](https://github.com/anupkumarpanwar) -  [LinkedIn](https://www.linkedin.com/in/anupkumarpanwar/)] - -Chetan Kaushik -  [[Gmail](mailto:dynamitechetan@gmail.com?Subject=The%20Algorithms%20-%20Python) -  [GitHub](https://github.com/dynamitechetan) -  [LinkedIn](https://www.linkedin.com/in/chetankaushik/)] - -Shawn -  [[GitHub](https://github.com/StepfenShawn)] - ## List of Algorithms See our [directory](https://github.com/TheAlgorithms/Dart/blob/master/DIRECTORY.md) From 444f5e61ffddd1c2c2f20777b1ca218399c8649f Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sat, 18 Jul 2020 23:50:03 +0800 Subject: [PATCH 006/443] Create Integer_To_Roman.dart Add a alogorithm. --- conversions/Integer_To_Roman.dart | 50 +++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 conversions/Integer_To_Roman.dart diff --git a/conversions/Integer_To_Roman.dart b/conversions/Integer_To_Roman.dart new file mode 100644 index 00000000..92d83767 --- /dev/null +++ b/conversions/Integer_To_Roman.dart @@ -0,0 +1,50 @@ +///Author: Shawn +///Email: stepfencurryxiao@gmail.com + +/* + * + * Concerting Integers into Roman Numerals + * + */ + +List ArabianRomanNumbers = [1000, 900, 500, 400, 100, 90, + 50, 40, 10, 9, 5, 4, 1 + ]; + +List RomanNumbers = ["M", "CM", "D", "CD", + "C", "XC", "L", "XL", + "X", "IX", "V", "IV", "I" + ]; + +List integer_to_roman(int num) +{ + if(num < 0) + { + return null; + } + + List result = []; + for(int i = 0; i < ArabianRomanNumbers.length; i++) + { + int times = num ~/ ArabianRomanNumbers[i]; + for(int j = 0; j < times; j++) + { + print(RomanNumbers[i]); + } + num -= times * ArabianRomanNumbers[i]; + } + + return result; +} + + +int main() +{ + /* IV */ + integer_to_roman(4); + /* II */ + integer_to_roman(2); + /* M */ + integer_to_roman(1000); + return 0; +} From ba9f4ee0a1c2d5c8ac05005e96a3146a1b0a0fad Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 18 Jul 2020 15:50:18 +0000 Subject: [PATCH 007/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 053bfca2..cc0d4240 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Conversions * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) + * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) ## Data Structures * Binary Tree From f6c147c3dfbd0d0fb5a519f24d43168dfd94da02 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Tue, 28 Jul 2020 05:48:54 -0500 Subject: [PATCH 008/443] Rename Pow.dart to pow.dart --- maths/{Pow.dart => pow.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename maths/{Pow.dart => pow.dart} (100%) diff --git a/maths/Pow.dart b/maths/pow.dart similarity index 100% rename from maths/Pow.dart rename to maths/pow.dart From 1277552167aa3a0ecd8a6b63952c691350c59a20 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 28 Jul 2020 10:49:12 +0000 Subject: [PATCH 009/443] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index cc0d4240..bbe60bdd 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -41,7 +41,7 @@ * [Palindrome Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_number.dart) * [Palindrome String](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string.dart) * [Palindrome String Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string_recursion.dart) - * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/Pow.dart) + * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) From 02c078868122fc13d0020510300accb7f64359a7 Mon Sep 17 00:00:00 2001 From: SirjaMi <68983857+SirjaMi@users.noreply.github.com> Date: Thu, 30 Jul 2020 15:45:26 +0800 Subject: [PATCH 010/443] Update binary_Search.dart --- search/binary_Search.dart | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/search/binary_Search.dart b/search/binary_Search.dart index a3dbec8d..b89b5933 100644 --- a/search/binary_Search.dart +++ b/search/binary_Search.dart @@ -18,15 +18,15 @@ int binary_search(List a, int l, int r, int x) { } void main() { - var list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; - var x = 55; + List list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; + int x = 55; int n = list.length; - var index = binary_search(list, 0, n - 1, x); + int index = binary_search(list, 0, n - 1, x); print('list:'); print(list); if (index != -1) { - print(x.toString() + ' found at positions: ' + index.toString()); + print('$x found at positions: $index'); } else { - print(x.toString() + ' Not found'); + print('$x Not found'); } } From 3f785b916cbe07757d09a1a6a2e1e9bf49b2db18 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Fri, 31 Jul 2020 23:12:01 +0800 Subject: [PATCH 011/443] Create sol1.dart --- project_euler/problem_1/sol1.dart | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 project_euler/problem_1/sol1.dart diff --git a/project_euler/problem_1/sol1.dart b/project_euler/problem_1/sol1.dart new file mode 100644 index 00000000..b5921917 --- /dev/null +++ b/project_euler/problem_1/sol1.dart @@ -0,0 +1,33 @@ +///Author: Shawn +///Email: stepfencurryxiao@gmail.com + +/* + * [Problem 1](https://projecteuler.net/problem=1) solution + * Problem Statement: + * If we list all the natural numbers below 10 that are multiples of 3 + * or 5, + * we get 3,5,6 and 9. The sum of these multiples is 23. + * Find the sum of all the multiples of 3 or 5 below N. + */ + +int sol(int t) +{ + int sum = 0; + int terms = (t - 1) ~/ 3; + sum += ((terms) * (6 + (terms - 1) * 3)) ~/ 2; // sum of an A.P. + terms = (t - 1) ~/ 5; + sum += ((terms) * (10 + (terms - 1) * 5)) ~/ 2; + terms = (t - 1) ~/ 15; + sum -= ((terms) * (30 + (terms - 1) * 15)) ~/ 2; + + return sum; +} + +int main() +{ + int value = sol(4); + print("solution(4): $value"); + value = sol(3); + print("solution(3): $value"); + return 0; +} From a39bda26fc35be5c71824b729c74976d16277884 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 31 Jul 2020 15:12:18 +0000 Subject: [PATCH 012/443] updating DIRECTORY.md --- DIRECTORY.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index bbe60bdd..b41c8183 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -57,6 +57,10 @@ * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) +## Project Euler + * Problem 1 + * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) + ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) * [Binary Search Recursion](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_search_recursion.dart) From 3a95f45cdfdb021e75b030e1ba869cb4343deeab Mon Sep 17 00:00:00 2001 From: Iftee360 Date: Wed, 16 Sep 2020 16:30:31 +0600 Subject: [PATCH 013/443] Update README.md --- README.md | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 104 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 78509147..8a5d1291 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# The Algorithms - Dart +# The Algorithms - Dart [![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)   @@ -10,7 +10,109 @@ These implementations are for learning purposes. They may be less efficient than ## List of Algorithms -See our [directory](https://github.com/TheAlgorithms/Dart/blob/master/DIRECTORY.md) +See our [directory](https://github.com/TheAlgorithms/Dart/blob/master/DIRECTORY.md) for full list of all algorithms. A few of the algorithms (the most common ones) are explained here. + +## Search Algorithms + +### Linear +![alt text][linear-image] + +From [Wikipedia][linear-wiki]: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. + Linear search runs in at the worst linear time and makes at most n comparisons, where n is the length of the list. + +__Properties__ +* Worst case performance O(n) +* Best case performance O(1) +* Average case performance O(n) +* Worst case space complexity O(1) iterative + + +### Binary +![alt text][binary-image] + +From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. + +__Properties__ +* Worst case performance O(log n) +* Best case performance O(1) +* Average case performance O(log n) +* Worst case space complexity O(1) + +---------------------------------------------------------------------------------------------------------------------- + +## Sort Algorithms + + +### Bubble +![alt text][bubble-image] + +From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][bubble-toptal] + + + +### Insertion +![alt text][insertion-image] + +From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][insertion-toptal] + + +### Quick +![alt text][quick-image] + +From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n log n) or O(n) with three-way partition +* Average case performance O(n^2) + +###### View the algorithm in [action][quick-toptal] + +### Selection +![alt text][selection-image] + +From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n^2) +* Average case performance O(n^2) + +###### View the algorithm in [action][selection-toptal] + +### Shell +![alt text][shell-image] + +From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. + +__Properties__ +* Worst case performance O(nlog2 2n) +* Best case performance O(n log n) +* Average case performance depends on gap sequence + +###### View the algorithm in [action][shell-toptal] + +### Time-Complexity Graphs + +Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) + +[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) + +---------------------------------------------------------------------------------- ## Community Channel From 8c7acc2f97a09b3be0886c0da59a10ca383ab980 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Wed, 16 Sep 2020 13:16:22 +0100 Subject: [PATCH 014/443] Create Decimal_to_Hexadecimal.dart --- conversions/Decimal_to_Hexadecimal.dart | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 conversions/Decimal_to_Hexadecimal.dart diff --git a/conversions/Decimal_to_Hexadecimal.dart b/conversions/Decimal_to_Hexadecimal.dart new file mode 100644 index 00000000..3a95ab38 --- /dev/null +++ b/conversions/Decimal_to_Hexadecimal.dart @@ -0,0 +1,37 @@ +Map hex_table = { + "10": "A", + "11": "B", + "12": "C", + "13": "D", + "14": "E", + "15": "F", +}; +void main() { + print(decimal_to_hexadecimal(-123)); + print(decimal_to_hexadecimal(0)); + print(decimal_to_hexadecimal(404)); +} + +String decimal_to_hexadecimal(int decimal_val) { + if (decimal_val == 0) { + return "0"; + } + bool negative = false; + if (decimal_val < 0) { + negative = true; + decimal_val *= -1; + } + String hex_string = ""; + while (decimal_val > 0) { + String hex_val = ""; + int remainder = decimal_val % 16; + decimal_val = decimal_val ~/ 16; + if (hex_table.containsKey(remainder.toString())) { + hex_val = hex_table[remainder.toString()]; + } else { + hex_val = remainder.toString(); + } + hex_string = hex_val + hex_string; + } + return negative ? "-" + hex_string : hex_string; +} From 670118c0b4363615271f405b76dffdd4e937dd4c Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Wed, 16 Sep 2020 13:19:32 +0100 Subject: [PATCH 015/443] Create Decimal_to_Octal --- conversions/Decimal_to_Octal | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 conversions/Decimal_to_Octal diff --git a/conversions/Decimal_to_Octal b/conversions/Decimal_to_Octal new file mode 100644 index 00000000..1719c089 --- /dev/null +++ b/conversions/Decimal_to_Octal @@ -0,0 +1,23 @@ +void main() { + print(decimal_to_octal(-123)); + print(decimal_to_octal(0)); + print(decimal_to_octal(404)); +} + +String decimal_to_octal(int decimal_val) { + if (decimal_val == 0){ + return "0"; + } + bool negative = false; + if (decimal_val < 0){ + negative = true; + decimal_val *= -1; + } + String oct_string = ""; + while (decimal_val > 0) { + int remainder = decimal_val % 8; + decimal_val = decimal_val ~/ 8; + oct_string = remainder.toString() + oct_string; + } + return negative?"-"+oct_string:oct_string; +} From 7f4f77a470fdbb7d4f34f2f9316c18b910ae5f34 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 16 Sep 2020 14:13:59 +0000 Subject: [PATCH 016/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b41c8183..736c80de 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Conversions * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) + * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) ## Data Structures From 6dd09b80f3844b8478b703eb56a6492d6c2ccbf3 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Wed, 16 Sep 2020 16:49:41 +0100 Subject: [PATCH 017/443] Rename Decimal_to_Octal to Decimal_to_Octal.dart --- conversions/{Decimal_to_Octal => Decimal_to_Octal.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename conversions/{Decimal_to_Octal => Decimal_to_Octal.dart} (100%) diff --git a/conversions/Decimal_to_Octal b/conversions/Decimal_to_Octal.dart similarity index 100% rename from conversions/Decimal_to_Octal rename to conversions/Decimal_to_Octal.dart From 6d701cd4300bd046570166ab1c2b8a9c9b4dbbae Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 17 Sep 2020 04:39:44 +0000 Subject: [PATCH 018/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 736c80de..15abe921 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -2,6 +2,7 @@ ## Conversions * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) + * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) ## Data Structures From 77554cc5028b0ec27d8af43bd50ab2f9d1205b46 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Thu, 17 Sep 2020 13:31:35 +0100 Subject: [PATCH 019/443] binary_to_decimal --- conversions/binary_to_decimal.dart | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 conversions/binary_to_decimal.dart diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart new file mode 100644 index 00000000..83790d4a --- /dev/null +++ b/conversions/binary_to_decimal.dart @@ -0,0 +1,23 @@ +import "dart:math" show pow; + +void main() { + print(binary_to_decimal("111")); // 7 + print(binary_to_decimal(" 101011 ")); // 43 + print(binary_to_decimal("1a1")); //error +} + +int binary_to_decimal(String bin_string){ + bin_string = bin_string.trim(); + if(bin_string == null || bin_string == ""){ + throw Exception("An empty value was passed to the function"); + } + int decimal_val = 0; + for (int i = 0; i Date: Thu, 17 Sep 2020 13:36:20 +0100 Subject: [PATCH 020/443] Update binary_to_decimal.dart --- conversions/binary_to_decimal.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 83790d4a..aa53f5cf 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -1,7 +1,7 @@ import "dart:math" show pow; void main() { - print(binary_to_decimal("111")); // 7 + print(binary_to_decimal("-111")); // -7 print(binary_to_decimal(" 101011 ")); // 43 print(binary_to_decimal("1a1")); //error } @@ -11,6 +11,8 @@ int binary_to_decimal(String bin_string){ if(bin_string == null || bin_string == ""){ throw Exception("An empty value was passed to the function"); } + bool isNegative = bin_string[0]=="-"; + if(isNegative) bin_string = bin_string.substring(1); int decimal_val = 0; for (int i = 0; i Date: Thu, 17 Sep 2020 13:48:21 +0100 Subject: [PATCH 021/443] hexadecimal_to_decimal --- conversions/hexadecimal_to_decimal.dart | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 conversions/hexadecimal_to_decimal.dart diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart new file mode 100644 index 00000000..e3b2fd1b --- /dev/null +++ b/conversions/hexadecimal_to_decimal.dart @@ -0,0 +1,35 @@ +import "dart:math" show pow; + +Map hex_table = { + "A": 10, + "B": 11, + "C": 12, + "D": 13, + "E": 14, + "F": 15, +}; +void main() { + print(hexadecimal_to_decimal("1abc")); // 6844 + print(hexadecimal_to_decimal(" -123 ")); // -291 + print(hexadecimal_to_decimal("1x")); //error +} + +int hexadecimal_to_decimal(String hex_string) { + hex_string = hex_string.trim().toUpperCase(); + if (hex_string == null || hex_string == "") { + throw Exception("An empty value was passed to the function"); + } + bool isNegative = hex_string[0] == "-"; + if (isNegative) 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 && + hex_table.containsKey(hex_string[i]) == false) { + throw Exception("Non-hex value wass 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]]); + } + } + return isNegative ? -1 * decimal_val : decimal_val; +} From b18ababe42705254894dd90de13de6662eed060c Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Thu, 17 Sep 2020 13:57:14 +0100 Subject: [PATCH 022/443] Update hexadecimal_to_decimal.dart --- conversions/hexadecimal_to_decimal.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index e3b2fd1b..edd48e9e 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -19,8 +19,8 @@ int hexadecimal_to_decimal(String hex_string) { if (hex_string == null || hex_string == "") { throw Exception("An empty value was passed to the function"); } - bool isNegative = hex_string[0] == "-"; - if (isNegative) hex_string = hex_string.substring(1); + 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 && @@ -31,5 +31,5 @@ int hexadecimal_to_decimal(String hex_string) { int.parse((hex_string[i]), onError: (e) => hex_table[hex_string[i]]); } } - return isNegative ? -1 * decimal_val : decimal_val; + return is_negative ? -1 * decimal_val : decimal_val; } From 37e83c3f4bf95a938c53f1d0bccdeae266a6846f Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Thu, 17 Sep 2020 13:57:47 +0100 Subject: [PATCH 023/443] Update binary_to_decimal.dart --- conversions/binary_to_decimal.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index aa53f5cf..f9cd4871 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -11,8 +11,8 @@ int binary_to_decimal(String bin_string){ if(bin_string == null || bin_string == ""){ throw Exception("An empty value was passed to the function"); } - bool isNegative = bin_string[0]=="-"; - if(isNegative) bin_string = bin_string.substring(1); + bool is_negative = bin_string[0]=="-"; + if(is_negative) bin_string = bin_string.substring(1); int decimal_val = 0; for (int i = 0; i Date: Thu, 17 Sep 2020 15:13:12 +0000 Subject: [PATCH 024/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 15abe921..5e7efaa6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,5 +1,6 @@ ## Conversions + * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) From 8383a1ac94d255bf3a1b15b5ac27006aa1c45cdf Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Mon, 21 Sep 2020 13:54:37 +0100 Subject: [PATCH 025/443] Create factors.dart --- maths/factors.dart | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 maths/factors.dart diff --git a/maths/factors.dart b/maths/factors.dart new file mode 100644 index 00000000..ef098c8a --- /dev/null +++ b/maths/factors.dart @@ -0,0 +1,14 @@ +void main() { + print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] + print(factorsOf(-1).toString());//Unhandled exception: Exception: A non-positive value was passed to the function +} + +List factorsOf(int num) { + if (num <= 0) + throw Exception("A non-positive value was passed to the function"); + List factors = [1]; + for (int i = 2; i <= num; i++) { + if (num % i == 0) factors.add(i); + } + return factors; +} From 11e32873c69ab5da60717da8a5a947a6a8d0a88d Mon Sep 17 00:00:00 2001 From: Iftee360 Date: Tue, 22 Sep 2020 12:14:41 +0600 Subject: [PATCH 026/443] Update README.d to show image and wiki for algorithms Added the links for the images and wikis for the Algorithms that are briefly explained. --- README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.md b/README.md index 8a5d1291..996200a2 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,36 @@ Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Sel [Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) +[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort +[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort +[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" + +[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort +[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort +[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" + +[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort +[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort +[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort" + +[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort +[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort +[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort" + +[selection-toptal]: https://www.toptal.com/developers/sorting-algorithms/selection-sort +[selection-wiki]: https://en.wikipedia.org/wiki/Selection_sort +[selection-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Selection_sort_animation.gif/250px-Selection_sort_animation.gif "Selection Sort Sort" + +[shell-toptal]: https://www.toptal.com/developers/sorting-algorithms/shell-sort +[shell-wiki]: https://en.wikipedia.org/wiki/Shellsort +[shell-image]: https://upload.wikimedia.org/wikipedia/commons/d/d8/Sorting_shellsort_anim.gif "Shell Sort" + +[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search +[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif + +[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm +[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png + ---------------------------------------------------------------------------------- ## Community Channel From 5050d04454841cbbb98645b6f2446b953c08e83c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 22 Sep 2020 15:13:12 +0000 Subject: [PATCH 027/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5e7efaa6..6b093d67 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,6 +32,7 @@ * [Factorial](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial.dart) * [Factorial Approximation](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial_approximation.dart) * [Factorial Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial_recursion.dart) + * [Factors](https://github.com/TheAlgorithms/Dart/blob/master/maths/factors.dart) * [Fermats Little Theorem](https://github.com/TheAlgorithms/Dart/blob/master/maths/fermats_little_theorem.dart) * [Fibonacci Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/fibonacci_recursion.dart) * [Find Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_max.dart) From 593fc2b55243b72af0aa02f19ba651255acdbeb4 Mon Sep 17 00:00:00 2001 From: KaushalDevrari <71590645+KaushalDevrari@users.noreply.github.com> Date: Thu, 1 Oct 2020 00:54:10 +0530 Subject: [PATCH 028/443] comb_sort.dart --- sort/comb_sort.dart | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sort/comb_sort.dart diff --git a/sort/comb_sort.dart b/sort/comb_sort.dart new file mode 100644 index 00000000..b2bdd918 --- /dev/null +++ b/sort/comb_sort.dart @@ -0,0 +1,42 @@ +// function for combsort +void combSort(List list) { + int gpVal = list.length; + double shrink = 1.3; + bool sortedBool = false; + + while (!sortedBool) { + gpVal = (gpVal / shrink).floor(); + if (gpVal > 1) { + sortedBool = false; + } else { + gpVal = 1; + sortedBool = true; + } + + int i = 0; + while (i + gpVal < list.length) { + if (list[i] > list[i + gpVal]) { + swap(list, i, gpVal); + sortedBool = false; + } + i++; + } + } +} +// function to swap the values +void swap(List list, int i, int gpVal) { + int temp = list[i]; + list[i] = list[i + gpVal]; + list[i + gpVal] = temp; +} + +void main(){ + //Get the dummy array + List arr = [1,451,562,2,99,78,5]; + // for printing the array before sorting + print("Before sorting the array: $arr\n"); + // applying combSort function + combSort(arr); + // printing the sortedBool value + print("After sorting the array: $arr"); +} From 10dc01c1675b0147b59d045188daa00dd23e6d76 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Thu, 1 Oct 2020 00:54:16 +0530 Subject: [PATCH 029/443] Create cocktail_sort.dart --- sort/cocktail_sort.dart | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 sort/cocktail_sort.dart diff --git a/sort/cocktail_sort.dart b/sort/cocktail_sort.dart new file mode 100644 index 00000000..0d498e09 --- /dev/null +++ b/sort/cocktail_sort.dart @@ -0,0 +1,40 @@ +void cocktailSort(List lst) //function to sort a list +{ + bool swap_done = true; + do { + swap_done = false; + for (int i = 0; i < lst.length - 2; i++) { + swap_done = swapItemCocktail(lst, i, swap_done); + } + + if (swap_done) { + swap_done = false; + for (int i = lst.length - 2; i >=0 ; i--) { + swap_done = swapItemCocktail(lst, i, swap_done); + } + } + } while (swap_done); +} + +bool swapItemCocktail(List lst, int i, bool swap_done) { + if(lst[i] > lst[i+1]) { + swap(lst, i); + swap_done = true; + } + return swap_done; +} + +void swap(List lst, int i) { + int tmp = lst[i]; + lst[i] = lst[i+1]; + lst[i+1] = tmp; +} + +void main()//driver function +{ + var lst = [5,3,6,7,3,378,3,1,-1]; + print(lst); + cocktailSort(lst); + print(lst); + +} From 442e77cac80d7b49e1dbc90d86ce4cf811185309 Mon Sep 17 00:00:00 2001 From: KaushalDevrari <71590645+KaushalDevrari@users.noreply.github.com> Date: Thu, 1 Oct 2020 01:56:15 +0530 Subject: [PATCH 030/443] Create binpow.dart --- other/binpow.dart | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 other/binpow.dart diff --git a/other/binpow.dart b/other/binpow.dart new file mode 100644 index 00000000..c3650369 --- /dev/null +++ b/other/binpow.dart @@ -0,0 +1,20 @@ +// Effective computation of large exponents modulo a number +// Function binpow to calculate (x^n mod m) +int binPow(int a, int b, int m) { + int result = 1; + a %= m; + if (a == 0) return 0; + while (b > 0) { + if (b % 2 == 1) { + result = (result * a) % m; + } + b >>= 1; + a = (a * a) % m; + } + return result; +} + +void main() { + print('binary power of (2,5,13) = ' + binPow(2, 5, 13).toString()); + print('binary power of (5, 3,13) = ' + binPow(5, 3, 13).toString()); +} From f92f9341b460bad6a7a57143aed45c980c9ae6f3 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Thu, 1 Oct 2020 01:58:01 +0530 Subject: [PATCH 031/443] Create Armstrong_number.dart --- maths/Armstrong_number.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 maths/Armstrong_number.dart diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart new file mode 100644 index 00000000..30b2ced0 --- /dev/null +++ b/maths/Armstrong_number.dart @@ -0,0 +1,26 @@ +import 'dart:math'; +void Armstrong_no(var x) +{ + var n=x; + var s =n.toString(); + var d=s.length; + var sum=0; + while(n!=0) + { + var r=n%10; + sum = sum + pow(r,d); + n=n~/10; + } + if(sum == x){ + print('yes'); + } + else{ + print('no'); + } +} +void main(){ + + var x = 10; + Armstrong_no(x); + +} From 3d593c9e8e05248803c249ca3ae717ec52c84288 Mon Sep 17 00:00:00 2001 From: KaushalDevrari <71590645+KaushalDevrari@users.noreply.github.com> Date: Thu, 1 Oct 2020 02:22:39 +0530 Subject: [PATCH 032/443] Create kadaneAlgo.dart --- other/kadaneAlgo.dart | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 other/kadaneAlgo.dart diff --git a/other/kadaneAlgo.dart b/other/kadaneAlgo.dart new file mode 100644 index 00000000..1411c035 --- /dev/null +++ b/other/kadaneAlgo.dart @@ -0,0 +1,29 @@ +// Program to find the Maximum contiguous sum (Kadane's Algorithm) +// Function to Calculate Maximum of Two Number +int max(int a, int b) { + if (a > b) + return a; + else + return b; +} + +// Function to find the Maximum contiguous Sum in the array +int maxSubArraySum(List a, int size) { + int max_so_far = a[0]; + int curr_max = a[0]; + + for (int i = 1; i < size; i++) { + curr_max = max(a[i], curr_max + a[i]); + max_so_far = max(max_so_far, curr_max); + } + return max_so_far; +} + +// main function for validation of the above +int main() { + 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()); + return 0; +} From 58dc7125d5d3d63d1158ba37743ac3555a4cf9a2 Mon Sep 17 00:00:00 2001 From: KaushalDevrari <71590645+KaushalDevrari@users.noreply.github.com> Date: Thu, 1 Oct 2020 03:29:15 +0530 Subject: [PATCH 033/443] Create LinearDiophantineEqn.dart --- maths/LinearDiophantineEqn.dart | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 maths/LinearDiophantineEqn.dart diff --git a/maths/LinearDiophantineEqn.dart b/maths/LinearDiophantineEqn.dart new file mode 100644 index 00000000..4a2ad996 --- /dev/null +++ b/maths/LinearDiophantineEqn.dart @@ -0,0 +1,29 @@ +// Program Linear Diophantine equation + +//Find the GCD of two numbers +int gcd(int a, int b) { + return (a % b == 0) ? b.abs() : gcd(b, a % b); +} + +// This function checks if integral solutions are possible +bool Isposs(int a, int b, int c) { + return (c % gcd(a, b) == 0); +} + +//Driver function for Linear Diophantine Equations +int main() { + int a = 3, b = 6, c = 9; + if (Isposs(a, b, c) == true) { + print("Possible"); + } else { + print("Not Possible"); + } + int x = 3, y = 6, z = 8; + if (Isposs(x, y, z) == true) { + print("Possible"); + } else { + print("Not Possible"); + } + + return 0; +} From 311cf1ec40f5b2a3b788f293f561c5f1551c86d8 Mon Sep 17 00:00:00 2001 From: sarcastic-verma Date: Thu, 1 Oct 2020 18:34:54 +0530 Subject: [PATCH 034/443] - problem 2 solved --- project_euler/problem_2/sol2.dart | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 project_euler/problem_2/sol2.dart diff --git a/project_euler/problem_2/sol2.dart b/project_euler/problem_2/sol2.dart new file mode 100644 index 00000000..3e581f27 --- /dev/null +++ b/project_euler/problem_2/sol2.dart @@ -0,0 +1,47 @@ +//Title:Project Euler Prob 2 - Even Fibonacci numbers +// Author:ShivamVerma +// Email:shivamthegreat.sv@gmail.com + +// Each new term in the Fibonacci sequence is generated by adding the previous two terms. +// By starting with 1 and 2, the first 10 terms will be: + +// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... + +// By considering the terms in the Fibonacci sequence whose values do not exceed four million, +// find the sum of the even-valued terms. + + +int evenFibSum(int limit) +{ + if (limit < 2) + return 0; + + // Initialize first two even prime numbers + // and their sum + int ef1 = 0, ef2 = 2; + int sum = ef1 + ef2; + + // calculating sum of even Fibonacci value + while (ef2 <= limit) + { + // get next even value of Fibonacci sequence + int ef3 = 4*ef2 + ef1; + + // If we go beyond limit, we break loop + if (ef3 > limit) + break; + + // Move to next even number and update sum + ef1 = ef2; + ef2 = ef3; + sum += ef2; + } + + return sum; +} + +//driver code +void main(){ + int limit = 4000000; + print(evenFibSum(limit)); +} \ No newline at end of file From b9ed37feedf91b60a3c86da562dd9946ed22cae0 Mon Sep 17 00:00:00 2001 From: sarcastic-verma Date: Thu, 1 Oct 2020 22:55:24 +0530 Subject: [PATCH 035/443] - problem 3 solved --- project_euler/problem_3/sol3.dart | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 project_euler/problem_3/sol3.dart diff --git a/project_euler/problem_3/sol3.dart b/project_euler/problem_3/sol3.dart new file mode 100644 index 00000000..ca292c33 --- /dev/null +++ b/project_euler/problem_3/sol3.dart @@ -0,0 +1,15 @@ +//Title:Project Euler Prob 3 +// Author:Shivam Verma +// Email:shivamthegreat.sv@gmail.com + +// The prime factors of 13195 are 5, 7, 13 and 29. + +// What is the largest prime factor of the number 600851475143 ? + +void main() { + double i, n = 600851475143; + + for (i = 3; n > 1; i += 2) while (n % i == 0) n /= i; + + print(i - 2); +} From 9775c894203f3440ffcf3ee3435fa355228f94e9 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Fri, 2 Oct 2020 11:47:47 +0800 Subject: [PATCH 036/443] Add type --- search/linear_Search.dart | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/search/linear_Search.dart b/search/linear_Search.dart index 80639b19..b568cdef 100644 --- a/search/linear_Search.dart +++ b/search/linear_Search.dart @@ -1,5 +1,5 @@ -int linear_search(List a, number) { - for (var i = 0; i < a.length; i++) { +int linear_search(List a, number) { + for (int i = 0; i < a.length; i++) { if (a[i] == number) { return i; } @@ -8,14 +8,14 @@ int linear_search(List a, number) { } void main() { - var list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; - var x = 15; - var index = linear_search(list, x); + List list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; + int x = 15; + int index = linear_search(list, x); print('list:'); print(list); if (index != -1) { - print(x.toString() + ' found at positions: ' + index.toString()); + print('$x found at positions: $index'); } else { - print(x.toString() + ' Not found'); + print('$x Not found'); } } From 4874d02db0ac32808d02d87597430c51a1f9dd20 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Fri, 2 Oct 2020 20:13:55 +0530 Subject: [PATCH 037/443] Create sigmoid.dart --- maths/sigmoid.dart | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 maths/sigmoid.dart diff --git a/maths/sigmoid.dart b/maths/sigmoid.dart new file mode 100644 index 00000000..dc68109a --- /dev/null +++ b/maths/sigmoid.dart @@ -0,0 +1,13 @@ +import 'dart:math'; +double sigmoid(double x,double a) //x is the function variable and a is the gain +{ + double p = exp(-a*x); + return 1/(1+p); +} +void main() +{ + double gain=1.00,x=0.5; + double p=sigmoid(x,gain); + print(p); + +} From d56bafd04c64397f616cfa3e7bff60a814f8cfec Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sat, 3 Oct 2020 13:26:38 +0800 Subject: [PATCH 038/443] Create pull_request_template.md --- .github/pull_request_template.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..314b9b78 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,17 @@ +# Welcome to Dart community + +### **Describe your change:** + +* [ ] Add an algorithm? +* [ ] Fix a bug or typo in an existing algorithm? +* [ ] Documentation change? + + +### **Checklist:** +* [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Dart/blob/master/CONTRIBUTING.md). +* [ ] This pull request is all my own work -- I have not plagiarized. +* [ ] I know that pull requests will not be merged if they fail the automated tests. +* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. +* [ ] All new Dart files are placed inside an existing directory. +* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. +* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. From 2d42a6aacb3c5759648bf81645f3a77d015e860e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 3 Oct 2020 05:29:04 +0000 Subject: [PATCH 039/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 6b093d67..14d765ad 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -47,6 +47,7 @@ * [Palindrome String Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string_recursion.dart) * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) + * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) From 4a90636ceed9af0512371e927d032cf54ee25b37 Mon Sep 17 00:00:00 2001 From: KAUSHAL DEVRARI <71590645+KaushalDevrari@users.noreply.github.com> Date: Sat, 3 Oct 2020 12:45:16 +0530 Subject: [PATCH 040/443] Create relu_function.dart Implements relu function in machine learning. --- maths/relu_function.dart | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 maths/relu_function.dart diff --git a/maths/relu_function.dart b/maths/relu_function.dart new file mode 100644 index 00000000..f770362d --- /dev/null +++ b/maths/relu_function.dart @@ -0,0 +1,18 @@ +// Program to Implement RELU function +// RELU function is commonly used in Machine learning as an activation function + +int relu_func(var x){ // here x passed is value passed in the function relu + if(x>0) return x; + else + return 0; +} + + +//Driver function for RELU function +int main() { + var a=5; + print(relu_func(a)); + var b=-1; + print(relu_func(b)); + return 0; +} From 1b5c5cf072ca20b7cf7df6275943dca0915de147 Mon Sep 17 00:00:00 2001 From: Tavernini Gabriel Date: Sat, 3 Oct 2020 18:34:00 +0200 Subject: [PATCH 041/443] Added Decimal_To_Any algorithm --- DIRECTORY.md | 1 + conversions/Decimal_To_Any.dart | 48 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 conversions/Decimal_To_Any.dart diff --git a/DIRECTORY.md b/DIRECTORY.md index 14d765ad..3dd5107c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) + * [Decimal To Any](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Any.dart) * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart new file mode 100644 index 00000000..a796be44 --- /dev/null +++ b/conversions/Decimal_To_Any.dart @@ -0,0 +1,48 @@ +//Convert a positive Decimal Number to Any Other Representation + +void main() { + print(decimal_to_any(0, 2)); //Expected '0' + print(decimal_to_any(5, 4)); //Expected '11' + print(decimal_to_any(20, 3)); //Expected '202' + print(decimal_to_any(-58, 16)); //Expected '-3A' + print(decimal_to_any(243, 17)); //Expected 'E5' + print(decimal_to_any(34923, 36)); //Expected 'QY3' + print(decimal_to_any(10, 11)); //Expected 'A' + print(decimal_to_any(-16, 16)); //Expected '-10' + print(decimal_to_any(36, 36)); //Expected '10' + + try { + print(decimal_to_any(10, 37)); //Expected Error + } on FormatException { + print("Base value is not supported"); + } +} + +String decimal_to_any(int value, int base) { + var ALPHABET_VALUES = { 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', + 16: 'G', 17: 'H', 18: 'I', 19: 'J', 20: 'K', 21: 'L', + 22: 'M', 23: 'N', 24: 'O', 25: 'P', 26: 'Q', 27: 'R', + 28: 'S', 29: 'T', 30: 'U', 31: 'V', 32: 'W', 33: 'X', + 34: 'Y', 35: 'Z'}; + + if (value == 0) + return "0"; + + if (base < 2 || base > 36) + throw FormatException("Base not supported!"); + + bool negative = false; + if (value < 0){ + negative = true; + value *= -1; + } + + String output = ""; + while (value > 0) { + int remainder = value % base; + value = value ~/ base; + output = (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder]) + output; + } + + return negative ? '-' + output : output; +} From 77c88e6741b9485639e5d11f657c4c3e8f28bb61 Mon Sep 17 00:00:00 2001 From: Tavernini Gabriel Date: Sat, 3 Oct 2020 18:40:14 +0200 Subject: [PATCH 042/443] Added Wikipedia link --- conversions/Decimal_To_Any.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index a796be44..4ffe763c 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -1,4 +1,5 @@ -//Convert a positive Decimal Number to Any Other Representation +//Convert a Decimal Number to Any Other Representation +//https://en.wikipedia.org/wiki/Positional_notation#Base_conversion void main() { print(decimal_to_any(0, 2)); //Expected '0' From 5168b22b06cafcd23379189929cf866abc01e86f Mon Sep 17 00:00:00 2001 From: utkarsh Date: Sat, 3 Oct 2020 23:09:03 +0530 Subject: [PATCH 043/443] Added Euler's Totient (Phi function) --- maths/eulers_totient.dart | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 maths/eulers_totient.dart diff --git a/maths/eulers_totient.dart b/maths/eulers_totient.dart new file mode 100644 index 00000000..9d3e7b54 --- /dev/null +++ b/maths/eulers_totient.dart @@ -0,0 +1,38 @@ +/* Source: + * https://en.wikipedia.org/wiki/Euler%27s_totient_function + * + * Description: + * eulers_totient(n) = n * product(1 - 1/p for all prime p dividing n) + * + * Time Complexity: + * O(sqrt(n)) + */ + +int eulers_totient(int n) { + // Input: n: int + // Output: phi(n): count of numbers b/w 1 and n that are coprime to n + int res = n; + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { + n = n ~/ i; + } + // i is a prime dividing n, multiply res bu 1 - 1/i + // res = res * (1 - 1/i) = res - (res/i) + res = res - (res ~/ i); + } + } + if (n > 1) { + res = res - (res ~/ n); + } + return res; +} + +main() { + // eulers_totient(9) = 6 as 1, 2, 4, 5, 6, 7, 8 are coprime to 9 + // > 6 + print(eulers_totient(9)); + // eulers_totient(10) = 4 as 1, 3, 7, 9 are coprime to 10 + // > 4 + print(eulers_totient(10)); +} From 1024f71b783f1f8c58e43500adddbc47e85b1aa5 Mon Sep 17 00:00:00 2001 From: utkarsh Date: Sun, 4 Oct 2020 00:00:57 +0530 Subject: [PATCH 044/443] Added Sieve of Eratosthenes --- maths/sieve_of_eratosthenes.dart | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 maths/sieve_of_eratosthenes.dart diff --git a/maths/sieve_of_eratosthenes.dart b/maths/sieve_of_eratosthenes.dart new file mode 100644 index 00000000..847478a5 --- /dev/null +++ b/maths/sieve_of_eratosthenes.dart @@ -0,0 +1,37 @@ +/* + * Source: + * https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + * + * Description: + * Calculates prime numbers till a number n + * + * Time Complexity: + * O(n log(log(n))) + */ + +List sieve_of_eratosthenes(int n) { + // Input: n: int + // Output: is_prime: List denoting whether ith element is prime or not + List is_prime = new List.filled(n + 1, true); + is_prime[0] = false; + is_prime[1] = false; + for (int i = 2; i * i <= n; i++) { + if (is_prime[i]) { + for (int j = i * i; j <= n; j += i) { + // mark all multiples of i as false + is_prime[j] = false; + } + } + } + return is_prime; +} + +main () { + // Prints all the primes under 50 + List primes = sieve_of_eratosthenes(50); + for (int i = 2; i <= 50; i++) { + if (primes[i]) { + print(i); + } + } +} From 2f9837737981ec0edecdacc6abc53589dc106f44 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Tue, 6 Oct 2020 12:59:07 +0530 Subject: [PATCH 045/443] Create shreedharacharya.dart --- maths/shreedharacharya.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 maths/shreedharacharya.dart diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart new file mode 100644 index 00000000..25f4447a --- /dev/null +++ b/maths/shreedharacharya.dart @@ -0,0 +1,26 @@ +import 'dart:math'; +//this function return a list of roots of a quadratic equation +// [x1, x2] where x1 and x2 are roots of +// aX^2 + bX + c = 0 +List shreedharacharya(double a,double b,double c) +{ + double d = b*b - 4*a*c; + List A=[0,0]; + if(d<0) + { + print('Imaginary roots'); + } + else{ + A[0] = (-b + pow(d,0.5))/(2*a); + A[1] = (-b - pow(d,0.5))/(2*a); + return A; + } + +} +void main() +{ + double a=1.00,b=0.00,c=-4.00; + List p=shreedharacharya(a,b,c); + print(p); + +} From 4bc05e13196c405de9dedd5ddbfb751b536dd67f Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 9 Oct 2020 23:46:43 +0200 Subject: [PATCH 046/443] Update DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 14d765ad..d580a58b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -50,6 +50,7 @@ * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) + * [Sieve of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) From 92e549d1858c2ab59269fd3a05711782f75f6d10 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 9 Oct 2020 23:53:55 +0200 Subject: [PATCH 047/443] Update DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d580a58b..eea2fd92 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -51,6 +51,7 @@ * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) * [Sieve of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) + * [Euler's totient function](https://github.com/TheAlgorithms/Dart/blob/master/maths/eulers_totient.dart) ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) From 18c974c9ab6c0c02312dcab203212c89366eedc9 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 9 Oct 2020 22:28:29 +0000 Subject: [PATCH 048/443] updating DIRECTORY.md --- DIRECTORY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9855e018..fbe76f1d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -30,6 +30,7 @@ * [Abs Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_max.dart) * [Abs Min](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_min.dart) * [Average](https://github.com/TheAlgorithms/Dart/blob/master/maths/average.dart) + * [Eulers Totient](https://github.com/TheAlgorithms/Dart/blob/master/maths/eulers_totient.dart) * [Factorial](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial.dart) * [Factorial Approximation](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial_approximation.dart) * [Factorial Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial_recursion.dart) @@ -48,11 +49,10 @@ * [Palindrome String Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string_recursion.dart) * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) + * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) - * [Sieve of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) - * [Euler's totient function](https://github.com/TheAlgorithms/Dart/blob/master/maths/eulers_totient.dart) ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) From 4f134b61aec8f5867e6fb0dcce16134a81b4b60d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 9 Oct 2020 22:42:38 +0000 Subject: [PATCH 049/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index fbe76f1d..f620d7b5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -5,6 +5,7 @@ * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) + * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_decimal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) ## Data Structures From c0ee9be131fb6e0bcbd37c582b6477ac4c6f8aba Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:43:41 +0530 Subject: [PATCH 050/443] Update maths/shreedharacharya.dart Co-authored-by: Parowicz --- maths/shreedharacharya.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 25f4447a..2c005652 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -11,7 +11,7 @@ List shreedharacharya(double a,double b,double c) print('Imaginary roots'); } else{ - A[0] = (-b + pow(d,0.5))/(2*a); + A.add((-b + sqrt(d))/(2*a)); A[1] = (-b - pow(d,0.5))/(2*a); return A; } From 5ee01d60b850d38c4138cbcb1e49b7c95750eaf6 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:46:17 +0530 Subject: [PATCH 051/443] Update maths/shreedharacharya.dart Co-authored-by: Parowicz --- maths/shreedharacharya.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 2c005652..9d05dddf 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -12,7 +12,7 @@ List shreedharacharya(double a,double b,double c) } else{ A.add((-b + sqrt(d))/(2*a)); - A[1] = (-b - pow(d,0.5))/(2*a); + A.add((-b - sqrt(d))/(2*a)); return A; } From 8da4df9bacea7c6d29b55fadba4f960069accb9a Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:47:10 +0530 Subject: [PATCH 052/443] Update maths/shreedharacharya.dart Co-authored-by: Parowicz --- maths/shreedharacharya.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 9d05dddf..1d7ded97 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -5,7 +5,7 @@ import 'dart:math'; List shreedharacharya(double a,double b,double c) { double d = b*b - 4*a*c; - List A=[0,0]; + List A= []; if(d<0) { print('Imaginary roots'); From 235720b10088b936e7a0e95dc0028e9ec121f982 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:57:45 +0530 Subject: [PATCH 053/443] Update shreedharacharya.dart --- maths/shreedharacharya.dart | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 1d7ded97..144d2921 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -9,18 +9,21 @@ List shreedharacharya(double a,double b,double c) if(d<0) { print('Imaginary roots'); + A=[null,null]; + } + else if(d==0){ + A.add(-b/(2*a)); + A.add(-b/(2*a)); } else{ A.add((-b + sqrt(d))/(2*a)); A.add((-b - sqrt(d))/(2*a)); - return A; } - + return A; } void main() { - double a=1.00,b=0.00,c=-4.00; + double a=1.00,b=-4.00,c=4.00; List p=shreedharacharya(a,b,c); - print(p); - + print(p); } From 902229746eb9690a5b28b62dc835f0e598d869ac Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Sat, 10 Oct 2020 12:30:46 +0100 Subject: [PATCH 054/443] Create perfect_number.dart --- maths/perfect_number.dart | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 maths/perfect_number.dart diff --git a/maths/perfect_number.dart b/maths/perfect_number.dart new file mode 100644 index 00000000..c331a6ff --- /dev/null +++ b/maths/perfect_number.dart @@ -0,0 +1,29 @@ +/* + * From: https://www.britannica.com/science/perfect-number + * + * A positive integer that is equal to the sum of its proper divisors. + * The smallest perfect number is 6, which is the sum of 1, 2, and 3. + * Other perfect numbers are 28, 496, and 8,128. + * + * */ + +//this function returns true if number is perfect and false otherwise +bool perfect_number(int number) { + if (number <= 1) return false; + List divisors = []; + for (int i = 1; i < number; i++) { + if (number % i == 0) divisors.add(i); + } + return divisors.reduce((a, b) => a + b) == number; + +} + +void main() { + print(perfect_number(-1)); // false + print(perfect_number(6)); // true + print(perfect_number(12)); // false + print(perfect_number(16)); // false + print(perfect_number(26)); // false + print(perfect_number(27)); // false + print(perfect_number(28)); // true +} From 564c105a053c7e636e2b87e59820afa42ac92d44 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 11:31:01 +0000 Subject: [PATCH 055/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f620d7b5..d9e5bb0a 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -48,6 +48,7 @@ * [Palindrome Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_number.dart) * [Palindrome String](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string.dart) * [Palindrome String Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string_recursion.dart) + * [Perfect Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/perfect_number.dart) * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) From 6ec068711c69a7e5f9d06a3b13e5e4bc8cd7eb86 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:03:12 +0000 Subject: [PATCH 056/443] updating DIRECTORY.md --- DIRECTORY.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d9e5bb0a..d67d9b75 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -70,6 +70,10 @@ ## Project Euler * Problem 1 * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) + * Problem 2 + * [Sol2](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_2/sol2.dart) + * Problem 3 + * [Sol3](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_3/sol3.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) From e42ad540ececbdb9c000f146fd0f0a11bc456bc1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:07:51 +0000 Subject: [PATCH 057/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d67d9b75..8c64b471 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -64,6 +64,7 @@ * [Gcd](https://github.com/TheAlgorithms/Dart/blob/master/other/gcd.dart) * [Haversine Formula](https://github.com/TheAlgorithms/Dart/blob/master/other/haversine_formula.dart) * [Heaps Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/heaps_algorithm.dart) + * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) From c17f3dc620d4164cd2534506f9ccfddb1c5f9d0c Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sat, 10 Oct 2020 17:08:38 +0200 Subject: [PATCH 058/443] Update DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 8c64b471..c4477712 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -67,6 +67,7 @@ * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) + * [Kadane's Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) ## Project Euler * Problem 1 From 0c0711d08d53aa53f24f76841bcf7788cd3ea69f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:08:52 +0000 Subject: [PATCH 059/443] updating DIRECTORY.md --- DIRECTORY.md | 1 - 1 file changed, 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index c4477712..8c64b471 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -67,7 +67,6 @@ * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) - * [Kadane's Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) ## Project Euler * Problem 1 From 5d4783922c22bda3fdfc8c8b18024852317694ee Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:18:15 +0000 Subject: [PATCH 060/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 8c64b471..c8ae74b7 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -58,6 +58,7 @@ ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) + * [Binpow](https://github.com/TheAlgorithms/Dart/blob/master/other/binpow.dart) * [Collatz](https://github.com/TheAlgorithms/Dart/blob/master/other/collatz.dart) * [Fisher Yates Shuffle](https://github.com/TheAlgorithms/Dart/blob/master/other/fisher_yates_shuffle.dart) * [Fizzbuzz](https://github.com/TheAlgorithms/Dart/blob/master/other/FizzBuzz.dart) From 9767d35cb1c54a9d4fa10e221837b83144fecc3f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 17:41:10 +0000 Subject: [PATCH 061/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c8ae74b7..c7bf65b3 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -88,6 +88,7 @@ ## Sort * [Bubble Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/bubble_Sort.dart) + * [Comb Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/comb_sort.dart) * [Gnome Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/gnome_Sort.dart) * [Heap Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/heap_Sort.dart) * [Insert Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/insert_Sort.dart) From aee568e97f80d13a93f2ac23a4c43c94368eb506 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 17:42:54 +0000 Subject: [PATCH 062/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c7bf65b3..c8de3a3e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -43,6 +43,7 @@ * [Find Min](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_min.dart) * [Find Min Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_min_recursion.dart) * [Hamming Distance](https://github.com/TheAlgorithms/Dart/blob/master/maths/hamming_distance.dart) + * [Lineardiophantineeqn](https://github.com/TheAlgorithms/Dart/blob/master/maths/LinearDiophantineEqn.dart) * [Lu Decomposition](https://github.com/TheAlgorithms/Dart/blob/master/maths/lu_decomposition.dart) * [Newton Method](https://github.com/TheAlgorithms/Dart/blob/master/maths/newton_method.dart) * [Palindrome Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_number.dart) From b3e77538e09e1bc5d8b11b11053f3180efbb7a6d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 17:45:14 +0000 Subject: [PATCH 063/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c8de3a3e..92209021 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -52,6 +52,7 @@ * [Perfect Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/perfect_number.dart) * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) + * [Relu Function](https://github.com/TheAlgorithms/Dart/blob/master/maths/relu_function.dart) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) From c18c89a317e7e0a4a68c99d7bda2586eb4f97a0f Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Sat, 10 Oct 2020 15:26:43 -0500 Subject: [PATCH 064/443] Problem 4 solved --- project_euler/problem_4/sol4.dart | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 project_euler/problem_4/sol4.dart diff --git a/project_euler/problem_4/sol4.dart b/project_euler/problem_4/sol4.dart new file mode 100644 index 00000000..7f43155e --- /dev/null +++ b/project_euler/problem_4/sol4.dart @@ -0,0 +1,21 @@ + +void main(){ + int max = 0; + for(int i = 100; i<1000;i++){ + for(int j = 100; j<1000;j++){ + int result = i * j; + if(isPanlindrome("$result")){ + if(result>max){ + max = result; + } + } + } + } + print("MAX $max"); +} +bool isPanlindrome(String word) { + for (int i = 0; i < word.length ~/ 2; i++) { + if (word[i] != word[word.length - i - 1]) return false; + } + return true; +} \ No newline at end of file From a308c5216222e63becb506178f81f5a9b9d1f532 Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Sat, 10 Oct 2020 15:33:56 -0500 Subject: [PATCH 065/443] solution problem 5 --- project_euler/problem_5/sol5.dart | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 project_euler/problem_5/sol5.dart diff --git a/project_euler/problem_5/sol5.dart b/project_euler/problem_5/sol5.dart new file mode 100644 index 00000000..b06110c6 --- /dev/null +++ b/project_euler/problem_5/sol5.dart @@ -0,0 +1,15 @@ +void main(){ + int number = 21; + LOOP: while(true){ + bool isSolution = true; + for(int i = 1; i<=21;i++){ + if( number % i !=0 ){ + isSolution = false; + break; + } + } + if(isSolution) break LOOP; + number++; + } + print("Solution problem 5 = $number"); +} \ No newline at end of file From cb8293c394784a97e198fabcb81c253b608fc577 Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Sat, 10 Oct 2020 15:45:35 -0500 Subject: [PATCH 066/443] Problem description --- project_euler/problem_4/sol4.dart | 11 +++++++++++ project_euler/problem_5/sol5.dart | 14 ++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/project_euler/problem_4/sol4.dart b/project_euler/problem_4/sol4.dart index 7f43155e..fc0985c5 100644 --- a/project_euler/problem_4/sol4.dart +++ b/project_euler/problem_4/sol4.dart @@ -1,4 +1,15 @@ +// Author : Devmaufh +// Email : mau1361317@gmail.com + +/** + * [Problem 4](https://projecteuler.net/problem=4) solution + * Problem Statement: + * A palindromic number reads the same both ways. + * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. + * Find the largest palindrome made from the product of two 3-digit numbers. + */ + void main(){ int max = 0; for(int i = 100; i<1000;i++){ diff --git a/project_euler/problem_5/sol5.dart b/project_euler/problem_5/sol5.dart index b06110c6..85d34bb3 100644 --- a/project_euler/problem_5/sol5.dart +++ b/project_euler/problem_5/sol5.dart @@ -1,3 +1,13 @@ +// Author : Devmaufh +// Email : mau1361317@gmail.com + +/** + * [Problem 5](https://projecteuler.net/problem=5) solution + * Problem Statement: + * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. + * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? + */ + void main(){ int number = 21; LOOP: while(true){ @@ -5,10 +15,10 @@ void main(){ for(int i = 1; i<=21;i++){ if( number % i !=0 ){ isSolution = false; - break; + break; // Break if have a remainder } } - if(isSolution) break LOOP; + if(isSolution) break LOOP; //If any number hasn't a remainder, break main loop because we found the solution number++; } print("Solution problem 5 = $number"); From 7bdb3fd69047ca9c1c76ac92fe5e5b926a4bf9c2 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Oct 2020 21:31:37 +0000 Subject: [PATCH 067/443] updating DIRECTORY.md --- DIRECTORY.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 92209021..a921ad3e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -78,6 +78,10 @@ * [Sol2](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_2/sol2.dart) * Problem 3 * [Sol3](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_3/sol3.dart) + * Problem 4 + * [Sol4](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_4/sol4.dart) + * Problem 5 + * [Sol5](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_5/sol5.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) From b461771f8666cb3ddb8786f0b172106fd3dad5e5 Mon Sep 17 00:00:00 2001 From: pasanjg <44201430+pasanjg@users.noreply.github.com> Date: Sun, 11 Oct 2020 07:02:33 +0530 Subject: [PATCH 068/443] Project Euler Problem 6 solved --- project_euler/problem_6/sol6.dart | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 project_euler/problem_6/sol6.dart diff --git a/project_euler/problem_6/sol6.dart b/project_euler/problem_6/sol6.dart new file mode 100644 index 00000000..aff408d9 --- /dev/null +++ b/project_euler/problem_6/sol6.dart @@ -0,0 +1,32 @@ +/// Author: Pasan Godamune +/// Email: pasanjg@gmail.com + +/** + * [Problem 6](https://projecteuler.net/problem=6) solution + * Problem Statement: + * The sum of the squares of the first ten natural numbers is, + * 1^2 + 2^2 + … + 10^2 = 385 + * The square of the sum of the first ten natural numbers is, + * (1 + 2 + … + 10)^2 = 552 = 3025 + * 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. + * Find the difference between the sum of the squares of the first one hundred natural numbers natural numbers and the square of the sum. + */ + +import 'dart:math'; + +squareDifference(n) { + return squareSumOfFirst(n) - sumOfSquare(n); +} + +sumOfSquare(n) { + return (((n * (n + 1)) * (n + (n + 1))) / 6); +} + +squareSumOfFirst(n) { + return pow((n + 1) * (n / 2), 2); +} + +void main() { + int n = 100; + print(squareDifference(n)); /// 25164150 +} From 69f7d8f20089c6ce4b077312de7be02effee4286 Mon Sep 17 00:00:00 2001 From: Triman Kaur Date: Sun, 11 Oct 2020 00:04:37 -0700 Subject: [PATCH 069/443] Added merge sort --- sort/merge_sort.dart | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sort/merge_sort.dart diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart new file mode 100644 index 00000000..0fad0576 --- /dev/null +++ b/sort/merge_sort.dart @@ -0,0 +1,62 @@ +void merge(List list, int lIndex, int mIndex, int rIndex) { + int lSize = mIndex - lIndex + 1; + int rSize = rIndex - mIndex; + + List lList = new List(lSize); + List rList = new List(rSize); + + for (int i = 0; i < lSize; i++) lList[i] = list[lIndex + i]; + for (int j = 0; j < rSize; j++) rList[j] = list[mIndex + j + 1]; + + int i = 0, j = 0; + int k = lIndex; + + while (i < lSize && j < rSize) { + if (lList[i] <= rList[j]) { + list[k] = lList[i]; + i++; + } else { + list[k] = rList[j]; + j++; + } + k++; + } + + while (i < lSize) { + list[k] = lList[i]; + i++; + k++; + } + + while (j < rSize) { + list[k] = rList[j]; + j++; + k++; + } +} + +void mergeSort(List list, int lIndex, int rIndex) { + if (lIndex < rIndex) { + int mIndex = (rIndex + lIndex) ~/ 2; // finds the middle index + + mergeSort(list, lIndex, mIndex); // sorts the first half of the list + mergeSort(list, mIndex + 1, rIndex); // sorts the second half of the list + + merge(list, lIndex, mIndex, rIndex); + } +} + + +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); + print('before sorting:'); + print(list); + print('--------------------------------------'); + print('After sorting:'); + mergeSort(list); + print(list); +} From 16cea40f9e3652fc4363496f5393656d6bcc61bc Mon Sep 17 00:00:00 2001 From: Triman Kaur Date: Sun, 11 Oct 2020 00:10:25 -0700 Subject: [PATCH 070/443] Added Merge sort in the Readme.md Proper definition , visualization and links for merge sort have been added to the readme file --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 996200a2..c49f19f2 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,20 @@ __Properties__ ###### View the algorithm in [action][selection-toptal] + +### Merge +![alt text][merge-image] + +From [Wikipedia][merge-wiki]: Merge sort (also commonly spelled mergesort) is a divide and conquer algorithm that was invented by John von Neumann in 1945. The algorithm dirst divides the list into the smallest unit (1 element), then compares each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged. It is an efficient, general-purpose, comparison-based sorting algorithm. + +__Properties__ +* Worst case performance O(n log n) +* Best case performance O(n log n) +* Average case performance O(n log n) + +###### View the algorithm in [action][merge-toptal] + + ### Shell ![alt text][shell-image] From 013d2e1cca755d4848e1f77e6d91e0260bea570c Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sun, 11 Oct 2020 14:19:04 +0530 Subject: [PATCH 071/443] Update maths/shreedharacharya.dart Co-authored-by: Parowicz --- maths/shreedharacharya.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 144d2921..592b3368 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -13,7 +13,6 @@ List shreedharacharya(double a,double b,double c) } else if(d==0){ A.add(-b/(2*a)); - A.add(-b/(2*a)); } else{ A.add((-b + sqrt(d))/(2*a)); From 7e90e14aa80084b39da97f5d72440bc029ff4750 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sun, 11 Oct 2020 14:22:08 +0530 Subject: [PATCH 072/443] Update maths/shreedharacharya.dart Co-authored-by: Parowicz --- maths/shreedharacharya.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 592b3368..0d219741 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -9,7 +9,6 @@ List shreedharacharya(double a,double b,double c) if(d<0) { print('Imaginary roots'); - A=[null,null]; } else if(d==0){ A.add(-b/(2*a)); From 8974c4e11b24e7a5f2b29e00128f2c8859f7c611 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 09:38:10 +0000 Subject: [PATCH 073/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index a921ad3e..f36234bb 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -53,6 +53,7 @@ * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) * [Relu Function](https://github.com/TheAlgorithms/Dart/blob/master/maths/relu_function.dart) + * [Shreedharacharya](https://github.com/TheAlgorithms/Dart/blob/master/maths/shreedharacharya.dart) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) From 0c0e0a1bcc008baaa5629a155a5a3649f4603ad6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 09:49:55 +0000 Subject: [PATCH 074/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f36234bb..c6e2973e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -95,6 +95,7 @@ ## Sort * [Bubble Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/bubble_Sort.dart) + * [Cocktail Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/cocktail_sort.dart) * [Comb Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/comb_sort.dart) * [Gnome Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/gnome_Sort.dart) * [Heap Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/heap_Sort.dart) From be0000006a06ed35c15428f7c8dd4d4e80521a33 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 10:05:13 +0000 Subject: [PATCH 075/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c6e2973e..e099498b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -83,6 +83,8 @@ * [Sol4](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_4/sol4.dart) * Problem 5 * [Sol5](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_5/sol5.dart) + * Problem 6 + * [Sol6](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_6/sol6.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) From c003bfb58266fa3384aa0fa33ee624a3aa3c6412 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 10:06:28 +0000 Subject: [PATCH 076/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e099498b..f92b44b0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -102,6 +102,7 @@ * [Gnome Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/gnome_Sort.dart) * [Heap Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/heap_Sort.dart) * [Insert Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/insert_Sort.dart) + * [Merge Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/merge_sort.dart) * [Quick Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/quick_Sort.dart) * [Select Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/select_Sort.dart) * [Shell Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/shell_Sort.dart) From 3308188fe1167197805f2e6de1f25e19ec4b1dd0 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sun, 11 Oct 2020 15:40:24 +0530 Subject: [PATCH 077/443] Update maths/Armstrong_number.dart Co-authored-by: Parowicz --- maths/Armstrong_number.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart index 30b2ced0..48401fc1 100644 --- a/maths/Armstrong_number.dart +++ b/maths/Armstrong_number.dart @@ -1,5 +1,5 @@ import 'dart:math'; -void Armstrong_no(var x) +bool Armstrong_no(var x) { var n=x; var s =n.toString(); From b1ecf3d6b0f249661d959d8d6886f36cee56271f Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sun, 11 Oct 2020 15:40:40 +0530 Subject: [PATCH 078/443] Update maths/Armstrong_number.dart Co-authored-by: Parowicz --- maths/Armstrong_number.dart | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart index 48401fc1..338b47c4 100644 --- a/maths/Armstrong_number.dart +++ b/maths/Armstrong_number.dart @@ -11,12 +11,7 @@ bool Armstrong_no(var x) sum = sum + pow(r,d); n=n~/10; } - if(sum == x){ - print('yes'); - } - else{ - print('no'); - } + return sum == x; } void main(){ From d36719f2f1b7cd0eb414c9c3e8b52648b09779e5 Mon Sep 17 00:00:00 2001 From: Abhishek Maletha <67141747+Abhishek-photon@users.noreply.github.com> Date: Sun, 11 Oct 2020 15:40:51 +0530 Subject: [PATCH 079/443] Update maths/Armstrong_number.dart Co-authored-by: Parowicz --- maths/Armstrong_number.dart | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart index 338b47c4..bdb46bf5 100644 --- a/maths/Armstrong_number.dart +++ b/maths/Armstrong_number.dart @@ -14,8 +14,15 @@ bool Armstrong_no(var x) return sum == x; } void main(){ - - var x = 10; - Armstrong_no(x); - + for (var x in [0, 10, 370, 371]) + { + if (Armstrong_no(x)) + { + print("${x} is armstrong number"); + } + else + { + print("${x} is not Armstrong number"); + } + } } From 6dbad00d5b064210acad44931877024f653b85a4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 10:29:23 +0000 Subject: [PATCH 080/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f92b44b0..ef5eb579 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -30,6 +30,7 @@ * [Abs](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs.dart) * [Abs Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_max.dart) * [Abs Min](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_min.dart) + * [Armstrong Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/Armstrong_number.dart) * [Average](https://github.com/TheAlgorithms/Dart/blob/master/maths/average.dart) * [Eulers Totient](https://github.com/TheAlgorithms/Dart/blob/master/maths/eulers_totient.dart) * [Factorial](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial.dart) From 1f4c714681a571723c28ea6ab113383dfeae651c Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Sun, 11 Oct 2020 12:36:31 +0100 Subject: [PATCH 081/443] Create amicable_numbers.dart --- maths/amicable_numbers.dart | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 maths/amicable_numbers.dart diff --git a/maths/amicable_numbers.dart b/maths/amicable_numbers.dart new file mode 100644 index 00000000..c2cb92bb --- /dev/null +++ b/maths/amicable_numbers.dart @@ -0,0 +1,30 @@ +/* + * https://en.wikipedia.org/wiki/Amicable_numbers + * + *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. + * + * */ + +//this function returns true if numbers are amicable and false otherwise +bool amicable_number(int first_number, int second_number) { + if (first_number <= 1 || second_number <= 1) return false; + List first_number_proper_divisors = []; + List second_number_proper_divisors = []; + for (int i = 1; i < first_number; i++) { + if (first_number % i == 0) first_number_proper_divisors.add(i); + } + for (int i = 1; i < second_number; i++) { + if (second_number % i == 0) second_number_proper_divisors.add(i); + } + return first_number == + second_number_proper_divisors.reduce((a, b) => a + b) && + second_number == first_number_proper_divisors.reduce((a, b) => a + b); +} + +void main() { + print(amicable_number(12, 14)); // false + print(amicable_number(220, 284)); // true + print(amicable_number(60, 84)); // true + print(amicable_number(1184, 1210)); //true + print(amicable_number(-14, 10)); //false +} From 7138b441efd98acd804037a6b8becfd6697f85ed Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 11:36:45 +0000 Subject: [PATCH 082/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ef5eb579..7d995757 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -30,6 +30,7 @@ * [Abs](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs.dart) * [Abs Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_max.dart) * [Abs Min](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_min.dart) + * [Amicable Numbers](https://github.com/TheAlgorithms/Dart/blob/master/maths/amicable_numbers.dart) * [Armstrong Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/Armstrong_number.dart) * [Average](https://github.com/TheAlgorithms/Dart/blob/master/maths/average.dart) * [Eulers Totient](https://github.com/TheAlgorithms/Dart/blob/master/maths/eulers_totient.dart) From ec89ad3533a4872b8d26a02da68e3168633cb564 Mon Sep 17 00:00:00 2001 From: pasanjg <44201430+pasanjg@users.noreply.github.com> Date: Sun, 11 Oct 2020 17:40:07 +0530 Subject: [PATCH 083/443] Bug fix in Merge Sort --- sort/merge_sort.dart | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 0fad0576..9da909e3 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -1,3 +1,5 @@ +import 'dart:math' show Random; + void merge(List list, int lIndex, int mIndex, int rIndex) { int lSize = mIndex - lIndex + 1; int rSize = rIndex - mIndex; @@ -42,13 +44,10 @@ void mergeSort(List list, int lIndex, int rIndex) { mergeSort(list, lIndex, mIndex); // sorts the first half of the list mergeSort(list, mIndex + 1, rIndex); // sorts the second half of the list - merge(list, lIndex, mIndex, rIndex); + merge(list, lIndex, mIndex, rIndex); } } - -import 'dart:math' show Random; - void main() { final seed = 100, rnd = Random(), length = 100; var list = @@ -57,6 +56,6 @@ void main() { print(list); print('--------------------------------------'); print('After sorting:'); - mergeSort(list); + mergeSort(list, 0, list.length - 1); print(list); } From fbefd116b506273784e7432f61f88aca554ab0b2 Mon Sep 17 00:00:00 2001 From: Abhishek Mehra <52788025+Triaro@users.noreply.github.com> Date: Sun, 11 Oct 2020 19:05:35 +0530 Subject: [PATCH 084/443] Create Priority_Queue.dart Priority Queue (Data Structure) --- data_structures/Queue/Priority_Queue.dart | 62 +++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 data_structures/Queue/Priority_Queue.dart diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart new file mode 100644 index 00000000..c5d0ef5a --- /dev/null +++ b/data_structures/Queue/Priority_Queue.dart @@ -0,0 +1,62 @@ +class PriorityQueue { + List> _dataStore = >[]; + + int get size => _dataStore.length; + + bool get isEmpty => _dataStore.isEmpty; + + enqueue(T item, int priority) { + QueueItem queueItem = new QueueItem(item, priority); + bool added = false; + for (int i = 0; i < _dataStore.length; i++) { + if (priority < _dataStore[i].priority) { + added = true; + _dataStore.insert(i, queueItem); + break; + } + } + if (!added) { + _dataStore.add(queueItem); + } + } + + T dequeue() { + if (_dataStore.isNotEmpty) { + return _dataStore.removeAt(0).item; + } + return null; + } + + T get front { + if (_dataStore.isNotEmpty) { + return _dataStore.first.item; + } + return null; + } + + T get end { + if (_dataStore.isNotEmpty) { + return _dataStore.last.item; + } + return null; + } + + clear() { + _dataStore.clear(); + } + + String toString() { + return _dataStore.toString(); + } +} + +class QueueItem { + T item; + int priority; + + QueueItem(this.item, this.priority); + + String toString() { + return '$item - $priority'; + } +} From 5d5fd63407f89b9b258c5819f60a7382e8bd0397 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sun, 11 Oct 2020 16:05:46 +0200 Subject: [PATCH 085/443] Update data_structures/Queue/Priority_Queue.dart --- data_structures/Queue/Priority_Queue.dart | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart index c5d0ef5a..f6519a04 100644 --- a/data_structures/Queue/Priority_Queue.dart +++ b/data_structures/Queue/Priority_Queue.dart @@ -60,3 +60,18 @@ class QueueItem { return '$item - $priority'; } } + +void main() +{ + PriorityQueue queue = new PriorityQueue(); + queue.enqueue(1, 2); + queue.enqueue(2, 1); + queue.enqueue(3, 3); + queue.enqueue(4, 2); + + + print(queue.dequeue()); + print(queue.dequeue()); + print(queue.dequeue()); + print(queue.dequeue()); +} From f64cc86d0b213df38f7a283b263d5e03d10e751d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Oct 2020 14:07:37 +0000 Subject: [PATCH 086/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7d995757..7ff17a0d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -19,6 +19,7 @@ * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list.dart) * Queue * [List Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/List_Queue.dart) + * [Priority Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Priority_Queue.dart) * Stack * [Array Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Array_Stack.dart) * [Linked List Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Linked_List_Stack.dart) From 32ae8b1bb0d8a5ada88488e7d8e99c58a28308dd Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Sun, 11 Oct 2020 21:34:11 -0500 Subject: [PATCH 087/443] problem 7 solved --- project_euler/problem_7/sol7.dart | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 project_euler/problem_7/sol7.dart diff --git a/project_euler/problem_7/sol7.dart b/project_euler/problem_7/sol7.dart new file mode 100644 index 00000000..fb5abda1 --- /dev/null +++ b/project_euler/problem_7/sol7.dart @@ -0,0 +1,29 @@ +// Author : Devmaufh +// Email : mau1361317@gmail.com + +/** + * [Problem 7](https://projecteuler.net/problem=7) solution + * Problem Statement: + * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. + * What is the 10 001st prime number? + */ + +void main(){ + int numberOfPrimes = 0; + int number = 1; + while ( numberOfPrimes < 10001 ){ + number++; + if( isPrime(number) ){ + numberOfPrimes++; + } + } + print(" 10 001st prime number is => $number "); +} + +bool isPrime(int number){ + if( number < 2 ) return false; + for( int i = 2; i < number; i++ ) + if( number % i == 0 ) + return false; + return true; +} \ No newline at end of file From ab6464dd13f4a9098bbe31e509fb05c6a930f9da Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Sun, 11 Oct 2020 22:15:18 -0500 Subject: [PATCH 088/443] Reverse string --- strings/reverse_string.dart | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 strings/reverse_string.dart diff --git a/strings/reverse_string.dart b/strings/reverse_string.dart new file mode 100644 index 00000000..c48b6c28 --- /dev/null +++ b/strings/reverse_string.dart @@ -0,0 +1,27 @@ +/** + * Reverse String + */ + +void main(){ + String stringToReverse = "The Algorithms:Dart"; + print('Method 1 => $stringToReverse\t ${reverseString(stringToReverse)}'); + print('Method 2 => $stringToReverse\t ${reverseString2(stringToReverse)}'); + +} + +/** + * * easiest way to reverses the string + */ +String reverseString(String str){ + return str.split('').reversed.join(); +} + +/** + * Second way to reverses the string + */ +String reverseString2(String str){ + String reversed = ""; + for(int i = str.length -1; i >=0; i--) + reversed+=str[i]; + return reversed; +} \ No newline at end of file From 637bc243c1977cd18d4d3145008e83d883245451 Mon Sep 17 00:00:00 2001 From: pasanjg <44201430+pasanjg@users.noreply.github.com> Date: Mon, 12 Oct 2020 19:45:03 +0530 Subject: [PATCH 089/443] Project Euler Problem 8 solved --- project_euler/problem_8/sol8.dart | 71 +++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 project_euler/problem_8/sol8.dart diff --git a/project_euler/problem_8/sol8.dart b/project_euler/problem_8/sol8.dart new file mode 100644 index 00000000..49ce87ce --- /dev/null +++ b/project_euler/problem_8/sol8.dart @@ -0,0 +1,71 @@ +/// Author: Pasan Godamune +/// Email: pasanjg@gmail.com + +/** + * [Problem 8](https://projecteuler.net/problem=8) solution + * Problem Statement: + * The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. + + 73167176531330624919225119674426574742355349194934 + 96983520312774506326239578318016984801869478851843 + 85861560789112949495459501737958331952853208805511 + 12540698747158523863050715693290963295227443043557 + 66896648950445244523161731856403098711121722383113 + 62229893423380308135336276614282806444486645238749 + 30358907296290491560440772390713810515859307960866 + 70172427121883998797908792274921901699720888093776 + 65727333001053367881220235421809751254540594752243 + 52584907711670556013604839586446706324415722155397 + 53697817977846174064955149290862569321978468622482 + 83972241375657056057490261407972968652414535100474 + 82166370484403199890008895243450658541227588666881 + 16427171479924442928230863465674813919123162824586 + 17866458359124566529476545682848912883142607690042 + 24219022671055626321111109370544217506941658960408 + 07198403850962455444362981230987879927244284909188 + 84580156166097919133875499200524063689912560717606 + 05886116467109405077541002256983155200055935729725 + 71636269561882670428252483600823257530420752963450 + + * Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. + * What is the value of this product? + */ + +void main() { + String series = "73167176531330624919225119674426574742355349194934" + "96983520312774506326239578318016984801869478851843" + "85861560789112949495459501737958331952853208805511" + "12540698747158523863050715693290963295227443043557" + "66896648950445244523161731856403098711121722383113" + "62229893423380308135336276614282806444486645238749" + "30358907296290491560440772390713810515859307960866" + "70172427121883998797908792274921901699720888093776" + "65727333001053367881220235421809751254540594752243" + "52584907711670556013604839586446706324415722155397" + "53697817977846174064955149290862569321978468622482" + "83972241375657056057490261407972968652414535100474" + "82166370484403199890008895243450658541227588666881" + "16427171479924442928230863465674813919123162824586" + "17866458359124566529476545682848912883142607690042" + "24219022671055626321111109370544217506941658960408" + "07198403850962455444362981230987879927244284909188" + "84580156166097919133875499200524063689912560717606" + "05886116467109405077541002256983155200055935729725" + "71636269561882670428252483600823257530420752963450"; + + largestAdjacentNumbers(series, {adjacentLength = 4}) { + var largestProduct = 0; + + for (int i = 0; i < series.length - adjacentLength + 1; i++) { + var subset = series.substring(i, adjacentLength + i); + + var numList = subset.split('').map((x) => int.parse(x)); + var product = numList.reduce((a, b) => a * b); + + if (product > largestProduct) largestProduct = product; + } + return largestProduct; + } + + print(largestAdjacentNumbers(series, adjacentLength: 13)); // 23514624000 +} From e22c1f3d59a9565413058175eef92aae410e3e05 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 12 Oct 2020 14:49:56 +0000 Subject: [PATCH 090/443] updating DIRECTORY.md --- DIRECTORY.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7ff17a0d..07c2486b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -88,6 +88,8 @@ * [Sol5](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_5/sol5.dart) * Problem 6 * [Sol6](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_6/sol6.dart) + * Problem 7 + * [Sol7](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_7/sol7.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) @@ -110,3 +112,6 @@ * [Select Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/select_Sort.dart) * [Shell Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/shell_Sort.dart) * [Tim Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/tim_Sort.dart) + +## Strings + * [Reverse String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_string.dart) From 59e5ed5ab8d8e6858d54c97b9c51f3784b991a5b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 12 Oct 2020 14:55:05 +0000 Subject: [PATCH 091/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 07c2486b..13eccaa6 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -90,6 +90,8 @@ * [Sol6](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_6/sol6.dart) * Problem 7 * [Sol7](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_7/sol7.dart) + * Problem 8 + * [Sol8](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_8/sol8.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) From c6fad058bc884f8405f3aebe0b2cd0c829ce0b22 Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Mon, 12 Oct 2020 14:05:59 -0500 Subject: [PATCH 092/443] Solution problem 9 --- project_euler/problem_9/sol9.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 project_euler/problem_9/sol9.dart diff --git a/project_euler/problem_9/sol9.dart b/project_euler/problem_9/sol9.dart new file mode 100644 index 00000000..0a8b19ea --- /dev/null +++ b/project_euler/problem_9/sol9.dart @@ -0,0 +1,26 @@ +// Author : Devmaufh +// Email : mau1361317@gmail.com + +/** + * [Problem 9](https://projecteuler.net/problem=8) solution + * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, + * a^2 + b^2 = c^2 + * For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. + * There exists exactly one Pythagorean triplet for which a + b + c = 1000. + * Find the product abc. + */ +import 'dart:math'; + +void main() { + + for (int i = 0; i <= 300; ++i) { + for (int j = 0; j <= 400; ++j) { + int k = 1000 - i - j; + if (i * i + j * j == k * k) { + var sol = i * j * k; + print("Solution : $sol"); + } + } + } + +} From 258a48f8bac82076a9fd0d2bffbf8a52bb919afe Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Mon, 12 Oct 2020 14:31:45 -0500 Subject: [PATCH 093/443] unused removed import --- project_euler/problem_9/sol9.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/project_euler/problem_9/sol9.dart b/project_euler/problem_9/sol9.dart index 0a8b19ea..1c34c8e4 100644 --- a/project_euler/problem_9/sol9.dart +++ b/project_euler/problem_9/sol9.dart @@ -9,7 +9,6 @@ * There exists exactly one Pythagorean triplet for which a + b + c = 1000. * Find the product abc. */ -import 'dart:math'; void main() { @@ -19,6 +18,7 @@ void main() { if (i * i + j * j == k * k) { var sol = i * j * k; print("Solution : $sol"); + break; } } } From ecea553375b22ffb2a64785f1ed2aa5676d22657 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 12 Oct 2020 19:36:22 +0000 Subject: [PATCH 094/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 13eccaa6..f5eef755 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -92,6 +92,8 @@ * [Sol7](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_7/sol7.dart) * Problem 8 * [Sol8](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_8/sol8.dart) + * Problem 9 + * [Sol9](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_9/sol9.dart) ## Search * [Binary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/binary_Search.dart) From b9957e4c8c6879259e9a372846b82264d7c5f33e Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Mon, 12 Oct 2020 16:43:51 -0500 Subject: [PATCH 095/443] problem 13 solved --- project_euler/problem_13/sol13.dart | 141 ++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 project_euler/problem_13/sol13.dart diff --git a/project_euler/problem_13/sol13.dart b/project_euler/problem_13/sol13.dart new file mode 100644 index 00000000..dbfa43a9 --- /dev/null +++ b/project_euler/problem_13/sol13.dart @@ -0,0 +1,141 @@ +// Email : mau1361317@gmail.com + + +import '../problem_9/sol9.dart'; + +/** + * [Problem 13](https://projecteuler.net/problem=13) solution + * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. + 37107287533902102798797998220837590246510135740250 + 46376937677490009712648124896970078050417018260538 + 74324986199524741059474233309513058123726617309629 + 91942213363574161572522430563301811072406154908250 + 23067588207539346171171980310421047513778063246676 + 89261670696623633820136378418383684178734361726757 + 28112879812849979408065481931592621691275889832738 + 44274228917432520321923589422876796487670272189318 + 47451445736001306439091167216856844588711603153276 + 70386486105843025439939619828917593665686757934951 + 62176457141856560629502157223196586755079324193331 + 64906352462741904929101432445813822663347944758178 + 92575867718337217661963751590579239728245598838407 + 58203565325359399008402633568948830189458628227828 + 80181199384826282014278194139940567587151170094390 + 35398664372827112653829987240784473053190104293586 + 86515506006295864861532075273371959191420517255829 + 71693888707715466499115593487603532921714970056938 + 54370070576826684624621495650076471787294438377604 + 53282654108756828443191190634694037855217779295145 + 36123272525000296071075082563815656710885258350721 + 45876576172410976447339110607218265236877223636045 + 17423706905851860660448207621209813287860733969412 + 81142660418086830619328460811191061556940512689692 + 51934325451728388641918047049293215058642563049483 + 62467221648435076201727918039944693004732956340691 + 15732444386908125794514089057706229429197107928209 + 55037687525678773091862540744969844508330393682126 + 18336384825330154686196124348767681297534375946515 + 80386287592878490201521685554828717201219257766954 + 78182833757993103614740356856449095527097864797581 + 16726320100436897842553539920931837441497806860984 + 48403098129077791799088218795327364475675590848030 + 87086987551392711854517078544161852424320693150332 + 59959406895756536782107074926966537676326235447210 + 69793950679652694742597709739166693763042633987085 + 41052684708299085211399427365734116182760315001271 + 65378607361501080857009149939512557028198746004375 + 35829035317434717326932123578154982629742552737307 + 94953759765105305946966067683156574377167401875275 + 88902802571733229619176668713819931811048770190271 + 25267680276078003013678680992525463401061632866526 + 36270218540497705585629946580636237993140746255962 + 24074486908231174977792365466257246923322810917141 + 91430288197103288597806669760892938638285025333403 + 34413065578016127815921815005561868836468420090470 + 23053081172816430487623791969842487255036638784583 + 11487696932154902810424020138335124462181441773470 + 63783299490636259666498587618221225225512486764533 + 67720186971698544312419572409913959008952310058822 + 95548255300263520781532296796249481641953868218774 + 76085327132285723110424803456124867697064507995236 + 37774242535411291684276865538926205024910326572967 + 23701913275725675285653248258265463092207058596522 + 29798860272258331913126375147341994889534765745501 + 18495701454879288984856827726077713721403798879715 + 38298203783031473527721580348144513491373226651381 + 34829543829199918180278916522431027392251122869539 + 40957953066405232632538044100059654939159879593635 + 29746152185502371307642255121183693803580388584903 + 41698116222072977186158236678424689157993532961922 + 62467957194401269043877107275048102390895523597457 + 23189706772547915061505504953922979530901129967519 + 86188088225875314529584099251203829009407770775672 + 11306739708304724483816533873502340845647058077308 + 82959174767140363198008187129011875491310547126581 + 97623331044818386269515456334926366572897563400500 + 42846280183517070527831839425882145521227251250327 + 55121603546981200581762165212827652751691296897789 + 32238195734329339946437501907836945765883352399886 + 75506164965184775180738168837861091527357929701337 + 62177842752192623401942399639168044983993173312731 + 32924185707147349566916674687634660915035914677504 + 99518671430235219628894890102423325116913619626622 + 73267460800591547471830798392868535206946944540724 + 76841822524674417161514036427982273348055556214818 + 97142617910342598647204516893989422179826088076852 + 87783646182799346313767754307809363333018982642090 + 10848802521674670883215120185883543223812876952786 + 71329612474782464538636993009049310363619763878039 + 62184073572399794223406235393808339651327408011116 + 66627891981488087797941876876144230030984490851411 + 60661826293682836764744779239180335110989069790714 + 85786944089552990653640447425576083659976645795096 + 66024396409905389607120198219976047599490197230297 + 64913982680032973156037120041377903785566085089252 + 16730939319872750275468906903707539413042652315011 + 94809377245048795150954100921645863754710598436791 + 78639167021187492431995700641917969777599028300699 + 15368713711936614952811305876380278410754449733078 + 40789923115535562561142322423255033685442488917353 + 44889911501440648020369068063960672322193204149535 + 41503128880339536053299340368006977710650566631954 + 81234880673210146739058568557934581403627822703280 + 82616570773948327592232845941706525094512325230608 + 22918802058777319719839450180888072429661980811197 + 77158542502016545090413245809786882778948721859617 + 72107838435069186155435662884062257473692284509516 + 20849603980134001723930671666823555245252804609722 + 53503534226472524250874054075591789781264330331690 + */ + +void main() { + // Listnumbers = "123".split('').map((e) => int.parse(e)).toList(); + List numbers = "37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690".split(' ').map((e) => BigInt.parse(e)).toList(); + String solution_1 = "${solution1(numbers)}"; + print("Solution 1 => " + solution_1.substring(0,10)); + + String solution_2 = "${solution2(numbers)}"; + print("Solution 2 => " + solution_2.substring(0,10)); + + String solution_3 = "${solution3(numbers)}"; + print("Solution 3 => " + solution_3.substring(0,10)); + +} + +BigInt solution1(List numbers){ + return numbers.reduce((n1,n2) => n1+n2); +} + +BigInt solution2(List numbers){ + BigInt result = new BigInt.from(0); + numbers.forEach((element) => result+=element); + return result; +} + +BigInt solution3(List numbers){ + BigInt result = new BigInt.from(0); + for (var i = 0; i < numbers.length; i++) { + result+=numbers[i]; + } + return result; +} From af0fa972c73625ce3a55dcd338e60eae51982cd1 Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Mon, 12 Oct 2020 16:44:30 -0500 Subject: [PATCH 096/443] problem 13 solved --- project_euler/problem_13/sol13.dart | 3 --- 1 file changed, 3 deletions(-) diff --git a/project_euler/problem_13/sol13.dart b/project_euler/problem_13/sol13.dart index dbfa43a9..03bc23e2 100644 --- a/project_euler/problem_13/sol13.dart +++ b/project_euler/problem_13/sol13.dart @@ -1,8 +1,5 @@ // Email : mau1361317@gmail.com - -import '../problem_9/sol9.dart'; - /** * [Problem 13](https://projecteuler.net/problem=13) solution * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. From 2899efdb2301040e83a0eb87d550299fb9321303 Mon Sep 17 00:00:00 2001 From: Mauricio Flores Hernandez Date: Mon, 12 Oct 2020 16:46:47 -0500 Subject: [PATCH 097/443] comment removed --- project_euler/problem_13/sol13.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/project_euler/problem_13/sol13.dart b/project_euler/problem_13/sol13.dart index 03bc23e2..03859865 100644 --- a/project_euler/problem_13/sol13.dart +++ b/project_euler/problem_13/sol13.dart @@ -106,7 +106,6 @@ */ void main() { - // Listnumbers = "123".split('').map((e) => int.parse(e)).toList(); List numbers = "37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690".split(' ').map((e) => BigInt.parse(e)).toList(); String solution_1 = "${solution1(numbers)}"; print("Solution 1 => " + solution_1.substring(0,10)); From f033dd2ccbe97a1a8e3c8da098962ef340a8ce64 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 12 Oct 2020 22:05:23 +0000 Subject: [PATCH 098/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f5eef755..09db1398 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -78,6 +78,8 @@ ## Project Euler * Problem 1 * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) + * Problem 13 + * [Sol13](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_13/sol13.dart) * Problem 2 * [Sol2](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_2/sol2.dart) * Problem 3 From 8fb08c1e330731ed4ade475b6b81882ef1c9a418 Mon Sep 17 00:00:00 2001 From: Akash Date: Tue, 13 Oct 2020 23:19:56 +0530 Subject: [PATCH 099/443] LinkedList --- data_structures/linked_list/linked_list.dart | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 data_structures/linked_list/linked_list.dart diff --git a/data_structures/linked_list/linked_list.dart b/data_structures/linked_list/linked_list.dart new file mode 100644 index 00000000..840e01a0 --- /dev/null +++ b/data_structures/linked_list/linked_list.dart @@ -0,0 +1,40 @@ +class Node { + int value; + Node next = null; + Node(this.value); +} + +class LinkedList { + Node head; + Node tail; + + Node getHead() { + return this.head; + } + + void insert(int value) { + Node newNode = Node(value); + + if (this.head == null) { + this.head = newNode; + this.tail = newNode; + } else { + this.tail.next = newNode; + this.tail = this.tail.next; + } + } +} + +void main() { + LinkedList linkedList = LinkedList(); + + for (var i = 0; i < 10; i++) { + linkedList.insert(i); + } + Node head = linkedList.head; + Node node = head; + while (node != null) { + print('${node.value}'); + node = node.next; + } +} From 8379fefbd5628a12ea361c9e304897b551f8b21c Mon Sep 17 00:00:00 2001 From: pasanjg <44201430+pasanjg@users.noreply.github.com> Date: Wed, 14 Oct 2020 00:12:25 +0530 Subject: [PATCH 100/443] Project Euler Problem 17 solved --- project_euler/problem_17/sol17.dart | 118 ++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 project_euler/problem_17/sol17.dart diff --git a/project_euler/problem_17/sol17.dart b/project_euler/problem_17/sol17.dart new file mode 100644 index 00000000..a9ae1a1c --- /dev/null +++ b/project_euler/problem_17/sol17.dart @@ -0,0 +1,118 @@ +/// Author: Pasan Godamune +/// Email: pasanjg@gmail.com + +/** + * [Problem 17](https://projecteuler.net/problem=17) solution + * Problem Statement: + * 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. + * If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? + * + * 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. + * The use of "and" when writing out numbers is in compliance with British usage. + */ + +import 'dart:math'; + +const ONES = [ + 'One', + 'Two', + 'Three', + 'Four', + 'Five', + 'Six', + 'Seven', + 'Eight', + 'Nine', + 'Ten' +]; + +const TEN_TWENTY = [ + 'Eleven', + 'Twelve', + 'Thirteen', + 'Fourteen', + 'Fifteen', + 'Sixteen', + 'Seventeen', + 'Eighteen', + 'Nineteen' +]; + +const TENS = [ + 'Ten', + 'Twenty', + 'Thirty', + 'Forty', // [It's 'Forty' NOT 'Fourty'](https://www.grammarly.com/blog/forty-fourty/) + 'Fifty', + 'Sixty', + 'Seventy', + 'Eighty', + 'Ninety' +]; + +const HUNDRED = 'Hundred'; +const THOUSDAND = 'Thousand'; +const AND = 'And'; + +String inWords = ""; + +convertToWords(int number) { + String numString = number.toString(); + int length = numString.length; + int place = pow(10, length - 1); + + if (number == 0) return inWords = "Zero"; + + if (length == 1) { + inWords = ONES[number - 1]; + } + + if (length == 2) { + inWords = TENS[(number / place).floor() - 1]; + + if (number % place != 0) { + if (number < 20) { + return inWords = TEN_TWENTY[(number % place) - 1]; + } + + inWords += convertToWords(number % place); + } + } + + if (length == 3) { + inWords = convertToWords((number / place).floor()) + HUNDRED; + + if (number % place != 0) { + inWords += AND + convertToWords(number % place); + } + } + + if (length == 4) { + inWords = convertToWords((number / place).floor()) + THOUSDAND; + + if (number % place != 0) { + inWords += AND + convertToWords(number % place); + } + } + + return inWords; +} + +calculateWithRange({int start = 1, end = 1000}) { + int count = 0; + + if (end > 1000) { + print("Max safe range is 0 - 1000 inclusive"); + return; + } + + for (int i = start; i <= end; i++) { + count += convertToWords(i).length; + } + + print(count); +} + +void main() { + calculateWithRange(start: 1, end: 1000); // 21124 +} From 4de068ccb2eefc16be0da1988501f391cb518958 Mon Sep 17 00:00:00 2001 From: Akash Date: Wed, 14 Oct 2020 10:52:19 +0530 Subject: [PATCH 101/443] added in the changes renamed file renamed references adding singly linked list easier version with O(1) insert and access --- ...st.dart => simple_singly_linked_list.dart} | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) rename data_structures/linked_list/{linked_list.dart => simple_singly_linked_list.dart} (54%) diff --git a/data_structures/linked_list/linked_list.dart b/data_structures/linked_list/simple_singly_linked_list.dart similarity index 54% rename from data_structures/linked_list/linked_list.dart rename to data_structures/linked_list/simple_singly_linked_list.dart index 840e01a0..1f03cb17 100644 --- a/data_structures/linked_list/linked_list.dart +++ b/data_structures/linked_list/simple_singly_linked_list.dart @@ -2,25 +2,29 @@ class Node { int value; Node next = null; Node(this.value); + + int get nodeValue { + return this.value; + } } class LinkedList { - Node head; - Node tail; + Node _headNode; + Node _tailNode; - Node getHead() { - return this.head; + Node get head { + return this._headNode; } void insert(int value) { Node newNode = Node(value); - if (this.head == null) { - this.head = newNode; - this.tail = newNode; + if (this._headNode == null) { + this._headNode = newNode; + this._tailNode = newNode; } else { - this.tail.next = newNode; - this.tail = this.tail.next; + this._tailNode.next = newNode; + this._tailNode = this._tailNode.next; } } } @@ -34,7 +38,7 @@ void main() { Node head = linkedList.head; Node node = head; while (node != null) { - print('${node.value}'); + print('${node.nodeValue}'); node = node.next; } } From c3de5c56b6912d82291534b81305098606cfb84d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 14 Oct 2020 12:02:22 +0000 Subject: [PATCH 102/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 09db1398..67bc8533 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -80,6 +80,8 @@ * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) * Problem 13 * [Sol13](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_13/sol13.dart) + * Problem 17 + * [Sol17](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_17/sol17.dart) * Problem 2 * [Sol2](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_2/sol2.dart) * Problem 3 From 7fab5e8f51e4c954ed77660b2ec5c8d99029bdc3 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 14 Oct 2020 14:09:31 +0200 Subject: [PATCH 103/443] Travis CI: test, dartanalyzer, and dartfmt (#85) * Travis CI: test, dartanalyzer, and dartfmt * updating DIRECTORY.md * dartanalyzer: Remove unused local variable * dartanalyzer: Remove unused import * dartanalyzer: x ~/ y is more efficient than (x / y).toInt() * allow_failures * allow_failures: Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- .travis.yml | 19 ++++++++++--------- data_structures/HashMap/Hashing.dart | 1 - .../Heap/Binary_Heap/Min_Heap.dart | 6 +++--- maths/factorial_recursion.dart | 2 -- 4 files changed, 13 insertions(+), 15 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8d3f8098..5a5e363e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,11 @@ +os: linux +dist: focal language: dart -dart: -# Install the latest stable release -- stable -# Install the latest dev release -- dev -# Install a specific stable release - 1.15.0 -- "1.15.0" -# Install a specific dev release, using a partial download URL - 2.9.0-2.0.dev -- "dev/release/2.9.0-2.0.dev" +dart_task: + - test + - dartanalyzer + - dartfmt +jobs: + allow_failures: + - dart_task: dartanalyzer # TODO: remove after #86 is closed + - dart_task: dartfmt # TODO: remove after #87 is closed diff --git a/data_structures/HashMap/Hashing.dart b/data_structures/HashMap/Hashing.dart index 277248f8..1b2dfc52 100644 --- a/data_structures/HashMap/Hashing.dart +++ b/data_structures/HashMap/Hashing.dart @@ -22,7 +22,6 @@ class LinkedList{ void insert(int data){ - Node temp = head; Node newnode = new Node(data); size++; diff --git a/data_structures/Heap/Binary_Heap/Min_Heap.dart b/data_structures/Heap/Binary_Heap/Min_Heap.dart index c12d7486..16d57a1c 100644 --- a/data_structures/Heap/Binary_Heap/Min_Heap.dart +++ b/data_structures/Heap/Binary_Heap/Min_Heap.dart @@ -20,7 +20,7 @@ List upAdjust(List arr,int length){ //Mark inserted nodes var child = length - 1; //Father nodes - int parent = ((child - 1) / 2).toInt(); + int parent = (child - 1) ~/ 2; //Save the inserted node temporarily int temp = arr[child]; @@ -28,7 +28,7 @@ List upAdjust(List arr,int length){ //When temp finds the correct location, we will assign the value of temp to this node arr[child] = arr[parent]; child = parent; - parent = ((child - 1) / 2).toInt(); + parent = (child - 1) ~/ 2; } arr[child] = temp; return arr; @@ -65,7 +65,7 @@ List downAdjust(List arr,int parent,int length){ List buildHead(List arr,int length) { //Sink from the last non leaf node - for (int i = ((length - 2) / 2).toInt(); i >= 0; i--) { + for (int i = (length - 2) ~/ 2; i >= 0; i--) { arr = downAdjust(arr, i, length); } return arr; diff --git a/maths/factorial_recursion.dart b/maths/factorial_recursion.dart index d1f3f8f9..d620fcaa 100644 --- a/maths/factorial_recursion.dart +++ b/maths/factorial_recursion.dart @@ -1,5 +1,3 @@ -import 'dart:math'; - void main() { var n = 5; var fac = factorial(n); From babdeab8374a9e1965dbdcc6793e19bb1d94cf29 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 14 Oct 2020 16:15:42 +0200 Subject: [PATCH 104/443] Add GitHub Action dart-package-analyzer.yml (#84) * Add GitHub Action test_flutter.yml @chimon2000 Your review please? * updating DIRECTORY.md * Update test_flutter.yml * Update test_flutter.yml * Create pubspec.yaml * Update test_flutter.yml * Delete pubspec.yaml * Update and rename test_flutter.yml to dart-package-analyzer.yml * Update and rename dart-package-analyzer.yml to dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * echo $OUTPUT * printf $OUTPUT * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * dartfmt --> dart format * Update dart_test_analyze_format.yml Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> --- .github/workflows/dart_test_analyze_format.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .github/workflows/dart_test_analyze_format.yml diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml new file mode 100644 index 00000000..0c1a90c1 --- /dev/null +++ b/.github/workflows/dart_test_analyze_format.yml @@ -0,0 +1,11 @@ +name: dart_test_analyze_format +on: [push, pull_request] +jobs: + dart_test_analyze_format: + runs-on: ubuntu-latest + container: google/dart + steps: + - uses: actions/checkout@v2 + # - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 + - run: dart analyze || true # TODO: remove `|| true` when #86 is closed + - run: dart format . || true # TODO: remove `|| true` when #87 is closed From 8e52a566ae497d47046b1e9ea74bda682c35f19b Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 14 Oct 2020 17:42:30 +0200 Subject: [PATCH 105/443] Fix Dart formatting issues (#89) --- .../workflows/dart_test_analyze_format.yml | 2 +- .travis.yml | 1 - conversions/Decimal_To_Any.dart | 47 ++++++--- conversions/Decimal_To_Binary.dart | 10 +- conversions/Decimal_to_Octal.dart | 12 +-- conversions/Integer_To_Roman.dart | 57 +++++++---- conversions/binary_to_decimal.dart | 23 ++--- data_structures/HashMap/Hashing.dart | 97 +++++++++---------- .../Heap/Binary_Heap/Min_Heap.dart | 48 ++++----- data_structures/Queue/List_Queue.dart | 34 +++---- data_structures/Queue/Priority_Queue.dart | 6 +- data_structures/Stack/Array_Stack.dart | 34 +++---- data_structures/Stack/Linked_List_Stack.dart | 51 +++++----- .../binary_tree/basic_binary_tree.dart | 56 +++++------ data_structures/linked_list.dart | 2 +- maths/Armstrong_number.dart | 34 +++---- maths/factors.dart | 3 +- maths/perfect_number.dart | 3 +- maths/pow.dart | 13 ++- maths/relu_function.dart | 13 +-- maths/shreedharacharya.dart | 33 +++---- maths/sieve_of_eratosthenes.dart | 4 +- maths/sigmoid.dart | 17 ++-- maths/symmetric_derivative.dart | 3 +- other/FizzBuzz.dart | 25 +++-- other/LCM.dart | 28 ++++-- other/collatz.dart | 14 +-- other/kadaneAlgo.dart | 4 +- project_euler/problem_1/sol1.dart | 12 +-- project_euler/problem_13/sol13.dart | 25 ++--- project_euler/problem_2/sol2.dart | 53 +++++----- project_euler/problem_4/sol4.dart | 14 +-- project_euler/problem_5/sol5.dart | 16 +-- project_euler/problem_6/sol6.dart | 4 +- project_euler/problem_7/sol7.dart | 20 ++-- project_euler/problem_9/sol9.dart | 2 - search/fibonacci_Search.dart | 64 ++++++------ search/interpolation_Search.dart | 57 ++++++----- search/ternary_Search.dart | 58 +++++------ sort/cocktail_sort.dart | 17 ++-- sort/comb_sort.dart | 11 ++- sort/gnome_Sort.dart | 19 ++-- sort/heap_Sort.dart | 40 ++++---- sort/tim_Sort.dart | 28 +++--- strings/reverse_string.dart | 12 +-- 45 files changed, 562 insertions(+), 564 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 0c1a90c1..f0a60eff 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,4 +8,4 @@ jobs: - uses: actions/checkout@v2 # - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - - run: dart format . || true # TODO: remove `|| true` when #87 is closed + - run: dart format . diff --git a/.travis.yml b/.travis.yml index 5a5e363e..87dd0b13 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,4 +8,3 @@ dart_task: jobs: allow_failures: - dart_task: dartanalyzer # TODO: remove after #86 is closed - - dart_task: dartfmt # TODO: remove after #87 is closed diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index 4ffe763c..4c396f6e 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -20,20 +20,41 @@ void main() { } String decimal_to_any(int value, int base) { - var ALPHABET_VALUES = { 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', - 16: 'G', 17: 'H', 18: 'I', 19: 'J', 20: 'K', 21: 'L', - 22: 'M', 23: 'N', 24: 'O', 25: 'P', 26: 'Q', 27: 'R', - 28: 'S', 29: 'T', 30: 'U', 31: 'V', 32: 'W', 33: 'X', - 34: 'Y', 35: 'Z'}; + var ALPHABET_VALUES = { + 10: 'A', + 11: 'B', + 12: 'C', + 13: 'D', + 14: 'E', + 15: 'F', + 16: 'G', + 17: 'H', + 18: 'I', + 19: 'J', + 20: 'K', + 21: 'L', + 22: 'M', + 23: 'N', + 24: 'O', + 25: 'P', + 26: 'Q', + 27: 'R', + 28: 'S', + 29: 'T', + 30: 'U', + 31: 'V', + 32: 'W', + 33: 'X', + 34: 'Y', + 35: 'Z' + }; - if (value == 0) - return "0"; + if (value == 0) return "0"; - if (base < 2 || base > 36) - throw FormatException("Base not supported!"); + if (base < 2 || base > 36) throw FormatException("Base not supported!"); bool negative = false; - if (value < 0){ + if (value < 0) { negative = true; value *= -1; } @@ -41,8 +62,10 @@ String decimal_to_any(int value, int base) { String output = ""; while (value > 0) { int remainder = value % base; - value = value ~/ base; - output = (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder]) + output; + value = value ~/ base; + output = + (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder]) + + output; } return negative ? '-' + output : output; diff --git a/conversions/Decimal_To_Binary.dart b/conversions/Decimal_To_Binary.dart index 09fc423f..f871fa8c 100644 --- a/conversions/Decimal_To_Binary.dart +++ b/conversions/Decimal_To_Binary.dart @@ -8,18 +8,18 @@ import "dart:math" show pow; * to a binary number using a bitwise * algorithm */ -void bitwiseConversion(var n){ - int b = 0,c = 0,d; +void bitwiseConversion(var n) { + int b = 0, c = 0, d; print("Bitwise conversion.\n"); - while(n != 0){ + while (n != 0) { d = (n & 1); - b += d * (pow(10,c++).toInt()); + b += d * (pow(10, c++).toInt()); n >>= 1; } print("\tBinary number: $b"); } //Main method -void main(){ +void main() { bitwiseConversion(8); } diff --git a/conversions/Decimal_to_Octal.dart b/conversions/Decimal_to_Octal.dart index 1719c089..a1d3cadf 100644 --- a/conversions/Decimal_to_Octal.dart +++ b/conversions/Decimal_to_Octal.dart @@ -5,19 +5,19 @@ void main() { } String decimal_to_octal(int decimal_val) { - if (decimal_val == 0){ - return "0"; + if (decimal_val == 0) { + return "0"; } bool negative = false; - if (decimal_val < 0){ + if (decimal_val < 0) { negative = true; decimal_val *= -1; - } + } String oct_string = ""; while (decimal_val > 0) { int remainder = decimal_val % 8; - decimal_val = decimal_val ~/ 8; + decimal_val = decimal_val ~/ 8; oct_string = remainder.toString() + oct_string; } - return negative?"-"+oct_string:oct_string; + return negative ? "-" + oct_string : oct_string; } diff --git a/conversions/Integer_To_Roman.dart b/conversions/Integer_To_Roman.dart index 92d83767..a2e9db54 100644 --- a/conversions/Integer_To_Roman.dart +++ b/conversions/Integer_To_Roman.dart @@ -7,39 +7,56 @@ * */ -List ArabianRomanNumbers = [1000, 900, 500, 400, 100, 90, - 50, 40, 10, 9, 5, 4, 1 - ]; +List ArabianRomanNumbers = [ + 1000, + 900, + 500, + 400, + 100, + 90, + 50, + 40, + 10, + 9, + 5, + 4, + 1 +]; -List RomanNumbers = ["M", "CM", "D", "CD", - "C", "XC", "L", "XL", - "X", "IX", "V", "IV", "I" - ]; +List RomanNumbers = [ + "M", + "CM", + "D", + "CD", + "C", + "XC", + "L", + "XL", + "X", + "IX", + "V", + "IV", + "I" +]; -List integer_to_roman(int num) -{ - if(num < 0) - { +List integer_to_roman(int num) { + if (num < 0) { return null; } - + List result = []; - for(int i = 0; i < ArabianRomanNumbers.length; i++) - { + for (int i = 0; i < ArabianRomanNumbers.length; i++) { int times = num ~/ ArabianRomanNumbers[i]; - for(int j = 0; j < times; j++) - { + for (int j = 0; j < times; j++) { print(RomanNumbers[i]); } num -= times * ArabianRomanNumbers[i]; } - + return result; } - -int main() -{ +int main() { /* IV */ integer_to_roman(4); /* II */ diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index f9cd4871..5e0c145b 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -6,20 +6,21 @@ void main() { print(binary_to_decimal("1a1")); //error } -int binary_to_decimal(String bin_string){ +int binary_to_decimal(String bin_string) { bin_string = bin_string.trim(); - if(bin_string == null || bin_string == ""){ - throw Exception("An empty value was passed to the function"); + if (bin_string == null || bin_string == "") { + throw Exception("An empty value was passed to the function"); } - bool is_negative = bin_string[0]=="-"; - if(is_negative) bin_string = bin_string.substring(1); + bool is_negative = bin_string[0] == "-"; + if (is_negative) bin_string = bin_string.substring(1); int decimal_val = 0; - for (int i = 0; i buckets; - - HashMap(int hsize){ + + HashMap(int hsize) { buckets = new List(hsize); - for(int i = 0;i < hsize;i++){ + for (int i = 0; i < hsize; i++) { buckets[i] = new LinkedList(); } this.hsize = hsize; } - - int hashing(int key){ + + int hashing(int key) { int hash = key % hsize; - if(hash < 0){ + if (hash < 0) { hash += hsize; } return hash; } - - void insertHash(int key){ + + void insertHash(int key) { int hash = hashing(key); buckets[hash].insert(key); } - - void deleteHash(int key){ + + void deleteHash(int key) { int hash = hashing(key); buckets[hash].delete(key); } - - void displayHashtable(){ - for(int i = 0;i < hsize;i++){ + + void displayHashtable() { + for (int i = 0; i < hsize; i++) { print("Bucket $i:"); buckets[i].display(); } } } -void main(){ - - HashMap h = new HashMap(7); - +void main() { + HashMap h = new HashMap(7); + print("Add key 5"); h.insertHash(5); - + print("Add key 28"); h.insertHash(28); - + print("Add key 1"); h.insertHash(1); - + print("Delete Key 28"); h.deleteHash(28); - + print("Print Table:\n"); h.displayHashtable(); - + print("Delete Key 1"); h.deleteHash(1); - + print("Print Table:\n"); h.displayHashtable(); } diff --git a/data_structures/Heap/Binary_Heap/Min_Heap.dart b/data_structures/Heap/Binary_Heap/Min_Heap.dart index 16d57a1c..ca6962af 100644 --- a/data_structures/Heap/Binary_Heap/Min_Heap.dart +++ b/data_structures/Heap/Binary_Heap/Min_Heap.dart @@ -16,15 +16,15 @@ * leftcgild : 2n + 1 */ -List upAdjust(List arr,int length){ +List upAdjust(List arr, int length) { //Mark inserted nodes var child = length - 1; //Father nodes int parent = (child - 1) ~/ 2; //Save the inserted node temporarily int temp = arr[child]; - - while(child > 0 && temp < arr[parent]){ + + while (child > 0 && temp < arr[parent]) { //When temp finds the correct location, we will assign the value of temp to this node arr[child] = arr[parent]; child = parent; @@ -33,6 +33,7 @@ List upAdjust(List arr,int length){ arr[child] = temp; return arr; } + /* * ** Sink operation, delete operation is equivalent to ** after an element is assigned to the root element, the sink operation is performed on the root element @@ -40,39 +41,38 @@ List upAdjust(List arr,int length){ *@ param parent subscript of element to sink *@ param length array length */ -List downAdjust(List arr,int parent,int length){ +List downAdjust(List arr, int parent, int length) { //Save elements to sink int temp = arr[parent]; //Locate left child node location int child = 2 * parent + 1; //Begin to sink while (child < length) { - //If the right child node is smaller than the left child, locate the right child - if (child + 1 < length && arr[child] > arr[child + 1]) { - child++; - } - //Sink ends if parent is smaller or equal to child - if (temp <= arr[child]) - break; - - arr[parent] = arr[child]; - parent = child; - child = 2 * parent + 1; + //If the right child node is smaller than the left child, locate the right child + if (child + 1 < length && arr[child] > arr[child + 1]) { + child++; + } + //Sink ends if parent is smaller or equal to child + if (temp <= arr[child]) break; + + arr[parent] = arr[child]; + parent = child; + child = 2 * parent + 1; } arr[parent] = temp; return arr; } -List buildHead(List arr,int length) { - //Sink from the last non leaf node - for (int i = (length - 2) ~/ 2; i >= 0; i--) { - arr = downAdjust(arr, i, length); - } - return arr; +List buildHead(List arr, int length) { + //Sink from the last non leaf node + for (int i = (length - 2) ~/ 2; i >= 0; i--) { + arr = downAdjust(arr, i, length); + } + return arr; } -void main(){ - List arr = [1,3,0,5,4,6,7,8,9]; - List BinaryHeap = buildHead(arr,arr.length); +void main() { + List arr = [1, 3, 0, 5, 4, 6, 7, 8, 9]; + List BinaryHeap = buildHead(arr, arr.length); print(BinaryHeap); } diff --git a/data_structures/Queue/List_Queue.dart b/data_structures/Queue/List_Queue.dart index 74db4de6..ed156c9a 100644 --- a/data_structures/Queue/List_Queue.dart +++ b/data_structures/Queue/List_Queue.dart @@ -3,41 +3,37 @@ const int MAX_SIZE = 10; -class ListQueue{ - +class ListQueue { int count = 0; List queue = new List(MAX_SIZE); - + //Checks if the queue has elements (not empty) - bool hasElements(){ - if(queue.length == 0){ + bool hasElements() { + if (queue.length == 0) { return false; - } - else{ + } else { return true; } } - + //Add an elment to the queue - void enque(T elment){ - if(count == MAX_SIZE){ + void enque(T elment) { + if (count == MAX_SIZE) { print("The queue is full!!!"); - } - else{ + } else { queue[count] = elment; count++; } } - + //Takes the next element from the queue - T deque(){ + T deque() { T result = null; - if(count == 0){ + if (count == 0) { print("The queue is empty!!!"); - } - else{ + } else { result = queue[0]; - for(int i = 0; i < queue.length - 1; i++){ + for (int i = 0; i < queue.length - 1; i++) { queue[i] = queue[i + 1]; } } @@ -45,7 +41,7 @@ class ListQueue{ } } -void main(){ +void main() { ListQueue Queue = new ListQueue(); Queue.enque(12); Queue.enque(2); diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart index f6519a04..970eee82 100644 --- a/data_structures/Queue/Priority_Queue.dart +++ b/data_structures/Queue/Priority_Queue.dart @@ -61,15 +61,13 @@ class QueueItem { } } -void main() -{ +void main() { PriorityQueue queue = new PriorityQueue(); queue.enqueue(1, 2); queue.enqueue(2, 1); queue.enqueue(3, 3); queue.enqueue(4, 2); - - + print(queue.dequeue()); print(queue.dequeue()); print(queue.dequeue()); diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index 4b8e481a..809ca624 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -1,33 +1,33 @@ //Author: Shawn //Email: stepfencurryxiao@gmail.com -class ArrayStack{ +class ArrayStack { //stack List stack; //element of the stack int count; //size of stack int n; - + //Init the array stack - ArrayStack(var n){ + ArrayStack(var n) { this.n = n; this.stack = new List(n); this.count = 0; } - + //Push a item to the stack - void push(T item){ - if(count == n){ + void push(T item) { + if (count == n) { print("The stack is full\n"); } stack[count] = item; count++; } - + //Pop a item from the stack - T pop(){ - if(count == 0){ + T pop() { + if (count == 0) { print("No data in the stack!\n"); } T pop_data = stack[count - 1]; @@ -35,29 +35,29 @@ class ArrayStack{ count--; return pop_data; } - - void Display(){ + + void Display() { print("ArrayStack: $stack\n"); } } -void main(){ +void main() { ArrayStack array_stack = new ArrayStack(6); - + array_stack.push('1'); array_stack.push("2"); array_stack.push('3'); array_stack.push("4"); array_stack.push('5'); array_stack.push("6"); - + array_stack.Display(); - + var pop_data; pop_data = array_stack.pop(); print("Pop $pop_data from stack\n"); pop_data = array_stack.pop(); print("Pop $pop_data from stack\n"); print("Now the stock:"); - array_stack.Display(); -} \ No newline at end of file + array_stack.Display(); +} diff --git a/data_structures/Stack/Linked_List_Stack.dart b/data_structures/Stack/Linked_List_Stack.dart index 6efa5f71..db9f15f0 100644 --- a/data_structures/Stack/Linked_List_Stack.dart +++ b/data_structures/Stack/Linked_List_Stack.dart @@ -1,46 +1,45 @@ //Author: Shawn //Email: stepfencurryxiao@gmail.com -class Node{ +class Node { //the data of the Node T data; Node next; - - Node(T data){ + + Node(T data) { this.data = data; this.next = null; } } -class LinkedListStack{ +class LinkedListStack { //Top of stack Node head; - + //Size of stack int size; - - LinkedListStack(){ + + LinkedListStack() { this.head = null; this.size = 0; } - + //Add element at top of the stack - - void push(T element){ - Node newNode = new Node(element); - newNode.next = this.head; - this.head = newNode; - this.size++; + + void push(T element) { + Node newNode = new Node(element); + newNode.next = this.head; + this.head = newNode; + this.size++; } - + //Pop element from top at the stack - - T pop(){ + + T pop() { T returnData = null; - if(size == 0){ + if (size == 0) { print("The stack is empty!!!"); - } - else{ + } else { Node destroy = this.head; this.head = this.head.next; returnData = destroy.data; @@ -48,17 +47,17 @@ class LinkedListStack{ } return returnData; } - - bool isEmpty(){ + + bool isEmpty() { return this.size == 0; } - - int getSize(){ + + int getSize() { return this.size; } } -int main(){ +int main() { LinkedListStack Stack = new LinkedListStack(); var returnData; print("Push 2 5 9 7 to the stack\n"); @@ -74,4 +73,4 @@ int main(){ returnData = Stack.pop(); print("Pop a data: $returnData\n"); return 0; -} \ No newline at end of file +} diff --git a/data_structures/binary_tree/basic_binary_tree.dart b/data_structures/binary_tree/basic_binary_tree.dart index 3e03a2c3..e89398be 100644 --- a/data_structures/binary_tree/basic_binary_tree.dart +++ b/data_structures/binary_tree/basic_binary_tree.dart @@ -4,35 +4,34 @@ /*This is Class Node with constructor that contains * data variable to type data and left,right pointers */ -class Node{ +class Node { var data; var left; var right; - - Node(var data){ + + Node(var data) { this.data = data; this.left = null; this.right = null; - } + } } /*In order traversal of the tree*/ -void display(var tree){ - - if(tree == null){ +void display(var tree) { + if (tree == null) { return; } - - if(tree.left != null){ + + if (tree.left != null) { display(tree.left); } - + print(tree.data); - - if(tree.right != null){ + + if (tree.right != null) { display(tree.right); } - + return; } @@ -40,42 +39,38 @@ void display(var tree){ *This is the recursive function to find the depth of * binary tree. */ -double depth_of_tree(var tree){ - - if(tree == null){ +double depth_of_tree(var tree) { + if (tree == null) { return 0; - } - else{ + } else { var depth_l_tree = depth_of_tree(tree.left); var depth_r_tree = depth_of_tree(tree.right); - - if(depth_l_tree > depth_r_tree){ + + if (depth_l_tree > depth_r_tree) { return (1 + depth_l_tree); - } - else{ + } else { return (1 + depth_r_tree); } } } /*This function returns that is it full binary tree or not*/ -bool is_full_binary_tree(var tree){ - if(tree == null){ +bool is_full_binary_tree(var tree) { + if (tree == null) { return true; } - if(tree.left == null && tree.right == null){ + if (tree.left == null && tree.right == null) { return true; } - if(tree.left != null && tree.right != null){ + if (tree.left != null && tree.right != null) { return (is_full_binary_tree(tree.left) && is_full_binary_tree(tree.right)); - } - else{ + } else { return false; } } //Main function for testing -void main(){ +void main() { var tree = Node(1); tree.left = Node(2); tree.right = Node(3); @@ -85,10 +80,9 @@ void main(){ tree.right.left = Node(7); tree.right.left.left = Node(8); tree.right.left.left.right = Node(9); - + print(is_full_binary_tree(tree)); print(depth_of_tree(tree)); print("Tree is:\n"); display(tree); } - diff --git a/data_structures/linked_list.dart b/data_structures/linked_list.dart index 0fd320d0..7494bce8 100644 --- a/data_structures/linked_list.dart +++ b/data_structures/linked_list.dart @@ -60,7 +60,7 @@ class LinkedList extends Iterable { return value; } - + return null; } diff --git a/maths/Armstrong_number.dart b/maths/Armstrong_number.dart index bdb46bf5..0c42469d 100644 --- a/maths/Armstrong_number.dart +++ b/maths/Armstrong_number.dart @@ -1,27 +1,23 @@ import 'dart:math'; -bool Armstrong_no(var x) -{ - var n=x; - var s =n.toString(); - var d=s.length; - var sum=0; - while(n!=0) - { - var r=n%10; - sum = sum + pow(r,d); - n=n~/10; + +bool Armstrong_no(var x) { + var n = x; + var s = n.toString(); + var d = s.length; + var sum = 0; + while (n != 0) { + var r = n % 10; + sum = sum + pow(r, d); + n = n ~/ 10; } return sum == x; } -void main(){ - for (var x in [0, 10, 370, 371]) - { - if (Armstrong_no(x)) - { + +void main() { + for (var x in [0, 10, 370, 371]) { + if (Armstrong_no(x)) { print("${x} is armstrong number"); - } - else - { + } else { print("${x} is not Armstrong number"); } } diff --git a/maths/factors.dart b/maths/factors.dart index ef098c8a..d27bdccd 100644 --- a/maths/factors.dart +++ b/maths/factors.dart @@ -1,6 +1,7 @@ void main() { print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] - 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 } List factorsOf(int num) { diff --git a/maths/perfect_number.dart b/maths/perfect_number.dart index c331a6ff..f6a5519f 100644 --- a/maths/perfect_number.dart +++ b/maths/perfect_number.dart @@ -15,12 +15,11 @@ bool perfect_number(int number) { if (number % i == 0) divisors.add(i); } return divisors.reduce((a, b) => a + b) == number; - } void main() { print(perfect_number(-1)); // false - print(perfect_number(6)); // true + print(perfect_number(6)); // true print(perfect_number(12)); // false print(perfect_number(16)); // false print(perfect_number(26)); // false diff --git a/maths/pow.dart b/maths/pow.dart index 9d0d2d64..390c3ee8 100644 --- a/maths/pow.dart +++ b/maths/pow.dart @@ -1,13 +1,12 @@ -void main(){ - print(pow(10,2)); // 100 - print(pow(2,0)); // 1 - print(pow(2,10)); // 1024 +void main() { + print(pow(10, 2)); // 100 + print(pow(2, 0)); // 1 + print(pow(2, 10)); // 1024 } - -double pow(int a,int b){ +double pow(int a, int b) { double result = 1; - for(int i = 1;i <= b;i++){ + for (int i = 1; i <= b; i++) { result *= a; } return result; diff --git a/maths/relu_function.dart b/maths/relu_function.dart index f770362d..5f7d9872 100644 --- a/maths/relu_function.dart +++ b/maths/relu_function.dart @@ -1,18 +1,19 @@ // Program to Implement RELU function // RELU function is commonly used in Machine learning as an activation function -int relu_func(var x){ // here x passed is value passed in the function relu - if(x>0) return x; +int relu_func(var x) { + // here x passed is value passed in the function relu + if (x > 0) + return x; else return 0; } - //Driver function for RELU function int main() { - var a=5; - print(relu_func(a)); - var b=-1; + var a = 5; + print(relu_func(a)); + var b = -1; print(relu_func(b)); return 0; } diff --git a/maths/shreedharacharya.dart b/maths/shreedharacharya.dart index 0d219741..99e66a83 100644 --- a/maths/shreedharacharya.dart +++ b/maths/shreedharacharya.dart @@ -1,27 +1,24 @@ import 'dart:math'; + //this function return a list of roots of a quadratic equation // [x1, x2] where x1 and x2 are roots of // aX^2 + bX + c = 0 -List shreedharacharya(double a,double b,double c) -{ - double d = b*b - 4*a*c; - List A= []; - if(d<0) - { +List shreedharacharya(double a, double b, double c) { + double d = b * b - 4 * a * c; + List A = []; + if (d < 0) { print('Imaginary roots'); - } - else if(d==0){ - A.add(-b/(2*a)); - } - else{ - A.add((-b + sqrt(d))/(2*a)); - A.add((-b - sqrt(d))/(2*a)); + } else if (d == 0) { + A.add(-b / (2 * a)); + } else { + A.add((-b + sqrt(d)) / (2 * a)); + A.add((-b - sqrt(d)) / (2 * a)); } return A; } -void main() -{ - double a=1.00,b=-4.00,c=4.00; - List p=shreedharacharya(a,b,c); - print(p); + +void main() { + double a = 1.00, b = -4.00, c = 4.00; + List p = shreedharacharya(a, b, c); + print(p); } diff --git a/maths/sieve_of_eratosthenes.dart b/maths/sieve_of_eratosthenes.dart index 847478a5..ebe2dc64 100644 --- a/maths/sieve_of_eratosthenes.dart +++ b/maths/sieve_of_eratosthenes.dart @@ -11,7 +11,7 @@ List sieve_of_eratosthenes(int n) { // Input: n: int - // Output: is_prime: List denoting whether ith element is prime or not + // Output: is_prime: List denoting whether ith element is prime or not List is_prime = new List.filled(n + 1, true); is_prime[0] = false; is_prime[1] = false; @@ -26,7 +26,7 @@ List sieve_of_eratosthenes(int n) { return is_prime; } -main () { +main() { // Prints all the primes under 50 List primes = sieve_of_eratosthenes(50); for (int i = 2; i <= 50; i++) { diff --git a/maths/sigmoid.dart b/maths/sigmoid.dart index dc68109a..c0ba4e8d 100644 --- a/maths/sigmoid.dart +++ b/maths/sigmoid.dart @@ -1,13 +1,14 @@ import 'dart:math'; -double sigmoid(double x,double a) //x is the function variable and a is the gain + +double sigmoid( + double x, double a) //x is the function variable and a is the gain { - double p = exp(-a*x); - return 1/(1+p); + double p = exp(-a * x); + return 1 / (1 + p); } -void main() -{ - double gain=1.00,x=0.5; - double p=sigmoid(x,gain); + +void main() { + double gain = 1.00, x = 0.5; + double p = sigmoid(x, gain); print(p); - } diff --git a/maths/symmetric_derivative.dart b/maths/symmetric_derivative.dart index 9cb1829c..b192f4c8 100644 --- a/maths/symmetric_derivative.dart +++ b/maths/symmetric_derivative.dart @@ -7,6 +7,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)}"); + print( + "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/FizzBuzz.dart b/other/FizzBuzz.dart index de38a706..75883690 100644 --- a/other/FizzBuzz.dart +++ b/other/FizzBuzz.dart @@ -8,19 +8,16 @@ void main() { fizzBuzz(); } -void fizzBuzz(){ - for(int i = 1;i<=100;i++){ - if(i%3==0 && i%5==0) { - print("FizzBuzz"); - } - else if(i%3==0){ - print("Fizz"); - } - else if(i%5==0){ - print("Buzz"); - } - else{ - print(i); - } +void fizzBuzz() { + for (int i = 1; i <= 100; i++) { + if (i % 3 == 0 && i % 5 == 0) { + print("FizzBuzz"); + } else if (i % 3 == 0) { + print("Fizz"); + } else if (i % 5 == 0) { + print("Buzz"); + } else { + print(i); + } } } diff --git a/other/LCM.dart b/other/LCM.dart index 3967cf31..392c516f 100644 --- a/other/LCM.dart +++ b/other/LCM.dart @@ -11,29 +11,39 @@ */ //Recursive function to return gcd of a and b -double gcd(var a,var b){ - if(a == 0){ +double gcd(var a, var b) { + if (a == 0) { return b; } - return gcd(b % a,a); + return gcd(b % a, a); } //Function to return LCM of two numbers -double lcm(var a,var b){ - return (a * b) / gcd(a,b); +double lcm(var a, var b) { + return (a * b) / gcd(a, b); } //Driver program -void main(){ - var a,b; +void main() { + var a, b; //Test case1: 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/collatz.dart b/other/collatz.dart index 0f59bb90..a509d8a8 100644 --- a/other/collatz.dart +++ b/other/collatz.dart @@ -8,22 +8,22 @@ //Email:stepfencurryxiao@gmail.com //Reference the C repo -void main(){ +void main() { //The number - double n = 20; + double n = 20; //curr_no stores number n double curr_no = n; //Loop till series reaches 1 - while(curr_no != 1){ + while (curr_no != 1) { //condition for even number - if(curr_no % 2 == 0){ + if (curr_no % 2 == 0) { curr_no = curr_no / 2; - print(curr_no.toString()+"->"); + print(curr_no.toString() + "->"); } //condition for odd number - else{ + else { curr_no = (curr_no * 3) + 1; - print(curr_no.toString()+"->"); + print(curr_no.toString() + "->"); } } print("1"); diff --git a/other/kadaneAlgo.dart b/other/kadaneAlgo.dart index 1411c035..a66daca8 100644 --- a/other/kadaneAlgo.dart +++ b/other/kadaneAlgo.dart @@ -1,4 +1,4 @@ -// Program to find the Maximum contiguous sum (Kadane's Algorithm) +// Program to find the Maximum contiguous sum (Kadane's Algorithm) // Function to Calculate Maximum of Two Number int max(int a, int b) { if (a > b) @@ -19,7 +19,7 @@ int maxSubArraySum(List a, int size) { return max_so_far; } -// main function for validation of the above +// main function for validation of the above int main() { List a = [-2, -3, 4, -1, -2, 1, 5, -3]; int n = a.length; diff --git a/project_euler/problem_1/sol1.dart b/project_euler/problem_1/sol1.dart index b5921917..f5c5ddb3 100644 --- a/project_euler/problem_1/sol1.dart +++ b/project_euler/problem_1/sol1.dart @@ -9,22 +9,20 @@ * we get 3,5,6 and 9. The sum of these multiples is 23. * Find the sum of all the multiples of 3 or 5 below N. */ - -int sol(int t) -{ + +int sol(int t) { int sum = 0; int terms = (t - 1) ~/ 3; - sum += ((terms) * (6 + (terms - 1) * 3)) ~/ 2; // sum of an A.P. + sum += ((terms) * (6 + (terms - 1) * 3)) ~/ 2; // sum of an A.P. terms = (t - 1) ~/ 5; sum += ((terms) * (10 + (terms - 1) * 5)) ~/ 2; terms = (t - 1) ~/ 15; sum -= ((terms) * (30 + (terms - 1) * 15)) ~/ 2; - + return sum; } -int main() -{ +int main() { int value = sol(4); print("solution(4): $value"); value = sol(3); diff --git a/project_euler/problem_13/sol13.dart b/project_euler/problem_13/sol13.dart index 03859865..bf3c7267 100644 --- a/project_euler/problem_13/sol13.dart +++ b/project_euler/problem_13/sol13.dart @@ -106,32 +106,35 @@ */ void main() { - List numbers = "37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690".split(' ').map((e) => BigInt.parse(e)).toList(); + List numbers = + "37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690" + .split(' ') + .map((e) => BigInt.parse(e)) + .toList(); String solution_1 = "${solution1(numbers)}"; - print("Solution 1 => " + solution_1.substring(0,10)); + print("Solution 1 => " + solution_1.substring(0, 10)); String solution_2 = "${solution2(numbers)}"; - print("Solution 2 => " + solution_2.substring(0,10)); + print("Solution 2 => " + solution_2.substring(0, 10)); String solution_3 = "${solution3(numbers)}"; - print("Solution 3 => " + solution_3.substring(0,10)); - + print("Solution 3 => " + solution_3.substring(0, 10)); } -BigInt solution1(List numbers){ - return numbers.reduce((n1,n2) => n1+n2); +BigInt solution1(List numbers) { + return numbers.reduce((n1, n2) => n1 + n2); } -BigInt solution2(List numbers){ +BigInt solution2(List numbers) { BigInt result = new BigInt.from(0); - numbers.forEach((element) => result+=element); + numbers.forEach((element) => result += element); return result; } -BigInt solution3(List numbers){ +BigInt solution3(List numbers) { BigInt result = new BigInt.from(0); for (var i = 0; i < numbers.length; i++) { - result+=numbers[i]; + result += numbers[i]; } return result; } diff --git a/project_euler/problem_2/sol2.dart b/project_euler/problem_2/sol2.dart index 3e581f27..1ef37973 100644 --- a/project_euler/problem_2/sol2.dart +++ b/project_euler/problem_2/sol2.dart @@ -10,38 +10,33 @@ // By considering the terms in the Fibonacci sequence whose values do not exceed four million, // find the sum of the even-valued terms. +int evenFibSum(int limit) { + if (limit < 2) return 0; -int evenFibSum(int limit) -{ - if (limit < 2) - return 0; - - // Initialize first two even prime numbers - // and their sum - int ef1 = 0, ef2 = 2; - int sum = ef1 + ef2; - - // calculating sum of even Fibonacci value - while (ef2 <= limit) - { - // get next even value of Fibonacci sequence - int ef3 = 4*ef2 + ef1; - - // If we go beyond limit, we break loop - if (ef3 > limit) - break; - - // Move to next even number and update sum - ef1 = ef2; - ef2 = ef3; - sum += ef2; - } - - return sum; + // Initialize first two even prime numbers + // and their sum + int ef1 = 0, ef2 = 2; + int sum = ef1 + ef2; + + // calculating sum of even Fibonacci value + while (ef2 <= limit) { + // get next even value of Fibonacci sequence + int ef3 = 4 * ef2 + ef1; + + // If we go beyond limit, we break loop + if (ef3 > limit) break; + + // Move to next even number and update sum + ef1 = ef2; + ef2 = ef3; + sum += ef2; + } + + return sum; } //driver code -void main(){ +void main() { int limit = 4000000; print(evenFibSum(limit)); -} \ No newline at end of file +} diff --git a/project_euler/problem_4/sol4.dart b/project_euler/problem_4/sol4.dart index fc0985c5..d79e2a18 100644 --- a/project_euler/problem_4/sol4.dart +++ b/project_euler/problem_4/sol4.dart @@ -1,4 +1,3 @@ - // Author : Devmaufh // Email : mau1361317@gmail.com @@ -10,13 +9,13 @@ * Find the largest palindrome made from the product of two 3-digit numbers. */ -void main(){ +void main() { int max = 0; - for(int i = 100; i<1000;i++){ - for(int j = 100; j<1000;j++){ + for (int i = 100; i < 1000; i++) { + for (int j = 100; j < 1000; j++) { int result = i * j; - if(isPanlindrome("$result")){ - if(result>max){ + if (isPanlindrome("$result")) { + if (result > max) { max = result; } } @@ -24,9 +23,10 @@ void main(){ } print("MAX $max"); } + bool isPanlindrome(String word) { for (int i = 0; i < word.length ~/ 2; i++) { if (word[i] != word[word.length - i - 1]) return false; } return true; -} \ No newline at end of file +} diff --git a/project_euler/problem_5/sol5.dart b/project_euler/problem_5/sol5.dart index 85d34bb3..09600625 100644 --- a/project_euler/problem_5/sol5.dart +++ b/project_euler/problem_5/sol5.dart @@ -8,18 +8,20 @@ * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ -void main(){ +void main() { int number = 21; - LOOP: while(true){ + LOOP: + while (true) { bool isSolution = true; - for(int i = 1; i<=21;i++){ - if( number % i !=0 ){ + for (int i = 1; i <= 21; i++) { + if (number % i != 0) { isSolution = false; break; // Break if have a remainder - } + } } - if(isSolution) break LOOP; //If any number hasn't a remainder, break main loop because we found the solution + if (isSolution) + break LOOP; //If any number hasn't a remainder, break main loop because we found the solution number++; } print("Solution problem 5 = $number"); -} \ No newline at end of file +} diff --git a/project_euler/problem_6/sol6.dart b/project_euler/problem_6/sol6.dart index aff408d9..8c96edbb 100644 --- a/project_euler/problem_6/sol6.dart +++ b/project_euler/problem_6/sol6.dart @@ -28,5 +28,7 @@ squareSumOfFirst(n) { void main() { int n = 100; - print(squareDifference(n)); /// 25164150 + print(squareDifference(n)); + + /// 25164150 } diff --git a/project_euler/problem_7/sol7.dart b/project_euler/problem_7/sol7.dart index fb5abda1..f93399eb 100644 --- a/project_euler/problem_7/sol7.dart +++ b/project_euler/problem_7/sol7.dart @@ -8,22 +8,20 @@ * What is the 10 001st prime number? */ -void main(){ +void main() { int numberOfPrimes = 0; int number = 1; - while ( numberOfPrimes < 10001 ){ + while (numberOfPrimes < 10001) { number++; - if( isPrime(number) ){ + if (isPrime(number)) { numberOfPrimes++; } } - print(" 10 001st prime number is => $number "); + print(" 10 001st prime number is => $number "); } -bool isPrime(int number){ - if( number < 2 ) return false; - for( int i = 2; i < number; i++ ) - if( number % i == 0 ) - return false; - return true; -} \ No newline at end of file +bool isPrime(int number) { + if (number < 2) return false; + for (int i = 2; i < number; i++) if (number % i == 0) return false; + return true; +} diff --git a/project_euler/problem_9/sol9.dart b/project_euler/problem_9/sol9.dart index 1c34c8e4..97a6a4b8 100644 --- a/project_euler/problem_9/sol9.dart +++ b/project_euler/problem_9/sol9.dart @@ -11,7 +11,6 @@ */ void main() { - for (int i = 0; i <= 300; ++i) { for (int j = 0; j <= 400; ++j) { int k = 1000 - i - j; @@ -22,5 +21,4 @@ void main() { } } } - } diff --git a/search/fibonacci_Search.dart b/search/fibonacci_Search.dart index 972355a5..eba8fb04 100644 --- a/search/fibonacci_Search.dart +++ b/search/fibonacci_Search.dart @@ -2,7 +2,7 @@ //Author:Shawn //Email:stepfencurryxiao@gmail.com -int fibMaonaccianSearch(List arr,int x,int n){ +int fibMaonaccianSearch(List arr, int x, int n) { //Initialize fibonacci numbers //(m - 2)'th Fibonacci No int fibMMm2 = 0; @@ -10,89 +10,81 @@ int fibMaonaccianSearch(List arr,int x,int n){ int fibMMm1 = 1; //m'th Fibonacci int fibM = fibMMm2 + fibMMm1; - + //fibM is going to store the smallest Fibonacci //Number greater than or equal to n - while(fibM < n){ + while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } - + // Marks the eliminated range from front int offset = -1; - + /*While three are elements to be inspected. * Note that we compare arr[fibMMm2] with x. * When fibM becomes 1, * fibMm2 becomes 0 */ - while(fibM > 1){ + while (fibM > 1) { //Check if fibMMm2 is a valid location - + //sets i to the min. of (offset + fibMMm2) and (n - 1) - int i = ((offset + fibMMm2) < (n -1)) ? - (offset + fibMMm2) : (n - 1); - + int i = ((offset + fibMMm2) < (n - 1)) ? (offset + fibMMm2) : (n - 1); + /* If x is greater than the value at index fibMmm2 * cut the subarray array from offset to i */ - - if(arr[i] < x){ + + if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } - + /* If x is greater than the value at index fibMmm2 * cut the subarray array after i + 1. */ - else if(arr[i] > x){ - fibM =fibMMm2; + else if (arr[i] > x) { + fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } - + //elwment found.Return index - else{ + else { return i; } - } - + //Comparing the last element with x - if(arr[offset + 1] == x){ + if (arr[offset + 1] == x) { return offset + 1; } - + //element not found :( return -1; } -void main(){ +void main() { //Get the array - var arr = [1,2,3,4,5,6,7,8,9,10]; - + var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + var result; - + //Print the array print(arr); - + //The size of the array var n = arr.length; - + //Key to be searched in the array var key = 7; - + //Search the key using ternarySearch - result = fibMaonaccianSearch(arr,key,n); - + result = fibMaonaccianSearch(arr, key, n); + //Print the result print("Index of " + key.toString() + " is " + result.toString()); - - } - - - - diff --git a/search/interpolation_Search.dart b/search/interpolation_Search.dart index 12d08dd8..2fc3735a 100644 --- a/search/interpolation_Search.dart +++ b/search/interpolation_Search.dart @@ -12,36 +12,33 @@ //Author:Shawn //Email:stepfencurryxiao@gmail.com -int interpolationSearch(List arr, var n, var key) -{ - int low = 0, high = n - 1; - while (low <= high && key >= arr[low] && key <= arr[high]) { - /* Calculate the nearest posible position of key */ - int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); - if (key > arr[pos]) - low = pos + 1; - else if (key < arr[pos]) - high = pos - 1; - else /* Found */ - return pos; - } - /* Not found */ - return -1; +int interpolationSearch(List arr, var n, var key) { + int low = 0, high = n - 1; + while (low <= high && key >= arr[low] && key <= arr[high]) { + /* Calculate the nearest posible position of key */ + int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); + if (key > arr[pos]) + low = pos + 1; + else if (key < arr[pos]) + high = pos - 1; + else /* Found */ + return pos; + } + /* Not found */ + return -1; } - -int main() -{ - //Get the arr - List arr = [0,1,2,3,4,5,6,7,8,9]; - //The size of the arr - var n = arr.length; - //The Key - var key = 5; - print("I want to found $key at $arr"); - //Get the index - var index = interpolationSearch(arr, n, key); - //print the result - print("Element found at position: $index"); - return 0; +int main() { + //Get the arr + List arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + //The size of the arr + var n = arr.length; + //The Key + var key = 5; + print("I want to found $key at $arr"); + //Get the index + var index = interpolationSearch(arr, n, key); + //print the result + print("Element found at position: $index"); + return 0; } diff --git a/search/ternary_Search.dart b/search/ternary_Search.dart index 9fa805d5..b9526ee8 100644 --- a/search/ternary_Search.dart +++ b/search/ternary_Search.dart @@ -2,68 +2,62 @@ //Author:Shawn //Email:stepfencurryxiao@gmail.com -int ternarySearch(var l,var r,var key,var arr){ - if(r >= 1){ - +int ternarySearch(var l, var r, var key, var arr) { + if (r >= 1) { //Find the mid1 and mid2 var mid1 = (l + (r - l) / 3).toInt(); var mid2 = (r - (r - 1) / 3).toInt(); - + //Check if key is present at any mid - if(arr[mid1] == key) - return mid1; - - if(arr[mid2] == key) - return mid2; - + if (arr[mid1] == key) return mid1; + + if (arr[mid2] == key) return mid2; + /*Since Key is not present at mid * check in which region it is present * then repeat the Search operation * in that region */ - - if(key < arr[mid1]){ + + if (key < arr[mid1]) { //The Key lies in between 1 and mid1 - return ternarySearch(l,mid1 - 1,key,arr); - } - else if(key > arr[mid2]){ + return ternarySearch(l, mid1 - 1, key, arr); + } else if (key > arr[mid2]) { //The key lies in between mid2 and r - return ternarySearch(mid2 + 1,r,key,arr); - } - else{ + return ternarySearch(mid2 + 1, r, key, arr); + } else { //The key lies in between mid1 and mid2 - return ternarySearch(mid1 + 1,mid2 - 1,key,arr); + return ternarySearch(mid1 + 1, mid2 - 1, key, arr); } } - + //Key not found return -1; } //Driver code -void main(){ - var l,r,p,key; - +void main() { + var l, r, p, key; + //Get the array - var arr = [1,2,3,4,5,6,7,8,9,10]; - + var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + //Print the array print(arr); - + //Starting index l = 0; - + // length of array r = arr.length; - + //Checking for 5 //Key to be searched in the array key = 5; - + //Search the key using ternarySearch - p = ternarySearch(l,r,key,arr); - + p = ternarySearch(l, r, key, arr); + //Print the result print("Index of " + key.toString() + " is " + p.toString()); - } diff --git a/sort/cocktail_sort.dart b/sort/cocktail_sort.dart index 0d498e09..721a51db 100644 --- a/sort/cocktail_sort.dart +++ b/sort/cocktail_sort.dart @@ -9,7 +9,7 @@ void cocktailSort(List lst) //function to sort a list if (swap_done) { swap_done = false; - for (int i = lst.length - 2; i >=0 ; i--) { + for (int i = lst.length - 2; i >= 0; i--) { swap_done = swapItemCocktail(lst, i, swap_done); } } @@ -17,7 +17,7 @@ void cocktailSort(List lst) //function to sort a list } bool swapItemCocktail(List lst, int i, bool swap_done) { - if(lst[i] > lst[i+1]) { + if (lst[i] > lst[i + 1]) { swap(lst, i); swap_done = true; } @@ -26,15 +26,14 @@ bool swapItemCocktail(List lst, int i, bool swap_done) { void swap(List lst, int i) { int tmp = lst[i]; - lst[i] = lst[i+1]; - lst[i+1] = tmp; + lst[i] = lst[i + 1]; + lst[i + 1] = tmp; } -void main()//driver function -{ - var lst = [5,3,6,7,3,378,3,1,-1]; - print(lst); +void main() //driver function +{ + var lst = [5, 3, 6, 7, 3, 378, 3, 1, -1]; + print(lst); cocktailSort(lst); print(lst); - } diff --git a/sort/comb_sort.dart b/sort/comb_sort.dart index b2bdd918..d9cae753 100644 --- a/sort/comb_sort.dart +++ b/sort/comb_sort.dart @@ -1,4 +1,4 @@ -// function for combsort +// function for combsort void combSort(List list) { int gpVal = list.length; double shrink = 1.3; @@ -23,6 +23,7 @@ void combSort(List list) { } } } + // function to swap the values void swap(List list, int i, int gpVal) { int temp = list[i]; @@ -30,12 +31,12 @@ void swap(List list, int i, int gpVal) { list[i + gpVal] = temp; } -void main(){ - //Get the dummy array - List arr = [1,451,562,2,99,78,5]; +void main() { + //Get the dummy array + List arr = [1, 451, 562, 2, 99, 78, 5]; // for printing the array before sorting print("Before sorting the array: $arr\n"); - // applying combSort function + // applying combSort function combSort(arr); // printing the sortedBool value print("After sorting the array: $arr"); diff --git a/sort/gnome_Sort.dart b/sort/gnome_Sort.dart index 0a302fac..8613ec79 100644 --- a/sort/gnome_Sort.dart +++ b/sort/gnome_Sort.dart @@ -3,12 +3,11 @@ //Email:stepfencurryxiao@gmail.com //Function sort the array using gnome sort -void gnomeSort(List arr,var n) { +void gnomeSort(List arr, var n) { if (arr == null || n == 0) return; int first = 1; int second = 2; - while (first < n) { if (arr[first - 1] <= arr[first]) { first = second; @@ -18,7 +17,7 @@ void gnomeSort(List arr,var n) { arr[first - 1] = arr[first]; arr[first] = temp; first -= 1; - if (first ==0){ + if (first == 0) { first = 1; second = 2; } @@ -26,19 +25,19 @@ void gnomeSort(List arr,var n) { } } -void main(){ +void main() { //Get the array - List arr = [10,34,6,323,7]; - + List arr = [10, 34, 6, 323, 7]; + //Get size of the array int n = arr.length; - + //print the arrary print(arr); - + //Sorting of array using gnome sort - gnomeSort(arr,n); - + gnomeSort(arr, n); + //print the result print("Sorted:\n" + arr.toString()); } diff --git a/sort/heap_Sort.dart b/sort/heap_Sort.dart index a26d9618..f5948032 100644 --- a/sort/heap_Sort.dart +++ b/sort/heap_Sort.dart @@ -1,53 +1,51 @@ -void sort(List arr){ +void sort(List arr) { //The length of the list int n = arr.length; - + //Build heap (rearrange arrary) - for(var i = n / 2 - 1; i >= 0; i--){ - heapify(arr,n,i); + for (var i = n / 2 - 1; i >= 0; i--) { + heapify(arr, n, i); } - + // One by one extract an element from heap - for(var i = n - 1; i >= 0; i--){ + for (var i = n - 1; i >= 0; i--) { //Move current root to end var temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; - + //call max heapify on the reduce heap - heapify(arr,i,0); + heapify(arr, i, 0); } } -void heapify(List arr,var n,var i){ +void heapify(List arr, var n, var i) { //Init largest as root var largest = i; //left = 2*i + 1 var l = 2 * i + 1; //right = 2*i + 2 var r = 2 * i + 2; - + // If left child is lager than root - if(l < n && arr[l] > arr[largest]) - largest = l; - + if (l < n && arr[l] > arr[largest]) largest = l; + // If right child is larger than largest so far - if(r < n && arr[r] > arr[largest]) - largest = r; - + if (r < n && arr[r] > arr[largest]) largest = r; + // If largest is not root - if(largest != i){ + if (largest != i) { var swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; - + //Recursively heapify the affected sub-tree - heapify(arr,n,largest); + heapify(arr, n, largest); } } -void main(){ - List list = [19,48,5,7,99,10]; +void main() { + List list = [19, 48, 5, 7, 99, 10]; sort(list); print(list); } diff --git a/sort/tim_Sort.dart b/sort/tim_Sort.dart index f8de1610..8a4b16d5 100644 --- a/sort/tim_Sort.dart +++ b/sort/tim_Sort.dart @@ -1,15 +1,15 @@ import 'dart:math'; + const int RUN = 32; -void insertionSort(List list, int left, int right) -{ +void insertionSort(List list, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = list[i]; int j = i - 1; while (j >= left && list[j] > temp) { - list[j+1] = list[j]; + list[j + 1] = list[j]; j--; } - list[j+1] = temp; + list[j + 1] = temp; } } @@ -17,16 +17,16 @@ void merge(List list, int left, int middle, int right) { int length1 = middle - left + 1, length2 = right - middle; List leftList = new List(length1), rightList = new List(length2); - for(int i = 0; i < length1; i++) { + for (int i = 0; i < length1; i++) { leftList[i] = list[left + i]; } - for(int i = 0; i $stringToReverse\t ${reverseString(stringToReverse)}'); print('Method 2 => $stringToReverse\t ${reverseString2(stringToReverse)}'); - } /** * * easiest way to reverses the string */ -String reverseString(String str){ +String reverseString(String str) { return str.split('').reversed.join(); } /** * Second way to reverses the string */ -String reverseString2(String str){ +String reverseString2(String str) { String reversed = ""; - for(int i = str.length -1; i >=0; i--) - reversed+=str[i]; + for (int i = str.length - 1; i >= 0; i--) reversed += str[i]; return reversed; -} \ No newline at end of file +} From 19e4f2865305e6b9d88dfc7944a4bc7640715c76 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 14 Oct 2020 18:02:09 +0200 Subject: [PATCH 106/443] Delete .travis.yml --- .travis.yml | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 87dd0b13..00000000 --- a/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -os: linux -dist: focal -language: dart -dart_task: - - test - - dartanalyzer - - dartfmt -jobs: - allow_failures: - - dart_task: dartanalyzer # TODO: remove after #86 is closed From faba8fcdb92adcd729661bd198da3176827ee64b Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 14 Oct 2020 18:42:18 +0200 Subject: [PATCH 107/443] GitHub Action: dart format --set-exit-if-changed . (#90) * Test dart format * dart format -n . * dart format --set-exit-if-changed . * Update Decimal_To_Any.dart --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index f0a60eff..5b607419 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,4 +8,4 @@ jobs: - uses: actions/checkout@v2 # - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - - run: dart format . + - run: dart format --set-exit-if-changed . From d2c92d43441c80849bab73f8eade3f7c5060c506 Mon Sep 17 00:00:00 2001 From: Akash Date: Thu, 15 Oct 2020 23:15:17 +0530 Subject: [PATCH 108/443] kadanes algorithm with dart --- dynamic_programming/kadanes_algorithm.dart | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 dynamic_programming/kadanes_algorithm.dart diff --git a/dynamic_programming/kadanes_algorithm.dart b/dynamic_programming/kadanes_algorithm.dart new file mode 100644 index 00000000..715e4a45 --- /dev/null +++ b/dynamic_programming/kadanes_algorithm.dart @@ -0,0 +1,37 @@ +import 'dart:math'; + +int kadanesAlgorithm(List array) { + int maxEndingHere = array[0]; + int maxSoFar = array[0]; + + for (int num in array.sublist(1, array.length)) { + maxEndingHere = [maxEndingHere + num , num ].reduce(max); + maxSoFar = [maxSoFar, maxEndingHere].reduce(max); + } + return maxSoFar; +} + +void main() { + List array = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]; + int maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + print('${maxContiniousSubarraySum == 19}'); + + + array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + print('${maxContiniousSubarraySum == 55}'); + + + array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + print('${maxContiniousSubarraySum == -1}'); + + + array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + print('${maxContiniousSubarraySum == 34}'); +} From 4f1cf9ce43f34e671b599c0fb422fe5ae0119354 Mon Sep 17 00:00:00 2001 From: Akash Date: Thu, 15 Oct 2020 23:20:17 +0530 Subject: [PATCH 109/443] removed unwanted commited files --- .../simple_singly_linked_list.dart | 44 ------------------- 1 file changed, 44 deletions(-) delete mode 100644 data_structures/linked_list/simple_singly_linked_list.dart diff --git a/data_structures/linked_list/simple_singly_linked_list.dart b/data_structures/linked_list/simple_singly_linked_list.dart deleted file mode 100644 index 1f03cb17..00000000 --- a/data_structures/linked_list/simple_singly_linked_list.dart +++ /dev/null @@ -1,44 +0,0 @@ -class Node { - int value; - Node next = null; - Node(this.value); - - int get nodeValue { - return this.value; - } -} - -class LinkedList { - Node _headNode; - Node _tailNode; - - Node get head { - return this._headNode; - } - - void insert(int value) { - Node newNode = Node(value); - - if (this._headNode == null) { - this._headNode = newNode; - this._tailNode = newNode; - } else { - this._tailNode.next = newNode; - this._tailNode = this._tailNode.next; - } - } -} - -void main() { - LinkedList linkedList = LinkedList(); - - for (var i = 0; i < 10; i++) { - linkedList.insert(i); - } - Node head = linkedList.head; - Node node = head; - while (node != null) { - print('${node.nodeValue}'); - node = node.next; - } -} From c9a225ca3649e1762d8207cd551447e2da04e47f Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Thu, 15 Oct 2020 23:23:33 +0530 Subject: [PATCH 110/443] Updated kadanes algorithm reformatted the dart code --- dynamic_programming/kadanes_algorithm.dart | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/dynamic_programming/kadanes_algorithm.dart b/dynamic_programming/kadanes_algorithm.dart index 715e4a45..d4dfcc12 100644 --- a/dynamic_programming/kadanes_algorithm.dart +++ b/dynamic_programming/kadanes_algorithm.dart @@ -5,7 +5,7 @@ int kadanesAlgorithm(List array) { int maxSoFar = array[0]; for (int num in array.sublist(1, array.length)) { - maxEndingHere = [maxEndingHere + num , num ].reduce(max); + maxEndingHere = [maxEndingHere + num, num].reduce(max); maxSoFar = [maxSoFar, maxEndingHere].reduce(max); } return maxSoFar; @@ -16,22 +16,19 @@ void main() { int maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); print('${maxContiniousSubarraySum == 19}'); - - + array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); print('${maxContiniousSubarraySum == 55}'); - - + array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); print('${maxContiniousSubarraySum == -1}'); - - + array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; - maxContiniousSubarraySum; + maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); print('${maxContiniousSubarraySum == 34}'); } From 974ae1f5de07bdf939cf484c018c896c51303869 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 21:53:14 +0200 Subject: [PATCH 111/443] Update CONTRIBUTING.md --- CONTRIBUTING.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe634161..f6beee79 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,14 +6,18 @@ Welcome to [TheAlgorithms/Dart](https://github.com/TheAlgorithms/Dart)! * Fork this [repo](https://github.com/TheAlgorithms/Dart) * Make some changes and pull a request * Your algorithm must be able to run on [dartpad](https://dartpad.dev/) +* [Automated tests are run](https://github.com/TheAlgorithms/Dart/actions) on all pull requests + * `dart analyze` is mandatory + * `dart format` is mandatory + * `dart test` is recommended ## New File Name guidelines * Use lowercase words with "_" as separator -* For example +* For example: ``` MyNewAlgorithm.dart is incorrect -my_new_algorithm.dart is correct format -My_New_Algorithm.dart is correct format +my_new_algorithm.dart is correct format +My_New_Algorithm.dart is correct format ``` Writer [@StepfenShawn](https://github.com/StepfenShawn), Feb 2020. From 7cec959cad83441c50344882d5bddb1e5885902e Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Thu, 15 Oct 2020 22:14:48 +0200 Subject: [PATCH 112/443] Add test suit and test cases for linked list --- data_structures/linked_list.dart | 98 ++++++++++++++++++++++---------- pubspec.yaml | 4 ++ 2 files changed, 71 insertions(+), 31 deletions(-) create mode 100644 pubspec.yaml diff --git a/data_structures/linked_list.dart b/data_structures/linked_list.dart index 7494bce8..e3e805b5 100644 --- a/data_structures/linked_list.dart +++ b/data_structures/linked_list.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + class Node { Node next; T value; @@ -84,35 +86,69 @@ class LinkedList extends Iterable { } } -main(List args) { - LinkedList linkedList = new LinkedList(); - linkedList.add(2); - linkedList.add(4); - linkedList.add(6); - linkedList.add(8); - - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(6); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(2); - print("5 in linkedList - ${linkedList.contains(5)}"); - print("4 in linkedList - ${linkedList.contains(4)}"); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(8); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(4); - print(linkedList.join(", ") + " size=${linkedList.length}"); - - LinkedList stack = new LinkedList(); - stack.push(2); - stack.push(4); - stack.push(6); - - print(stack.join(", ") + " size=${stack.length}"); - stack.pop(); - print(stack.join(", ") + " size=${stack.length}"); - stack.pop(); - stack.pop(); - stack.pop(); - print(stack.join(", ") + " size=${stack.length}"); +main() { + test(".add is adding elements in order", () { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + + expect(linkedList, equals([1, 2, 3])); + }); + + test(".remove is removing all elements with given value", () { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(2); + + linkedList.remove(2); + + expect(linkedList, equals([1, 3])); + }); + + test(".remove on empty list do nothing", () { + LinkedList linkedList = new LinkedList(); + + linkedList.remove(2); + + expect(linkedList, isEmpty); + }); + + test(".push is appending first element", () { + LinkedList linkedList = new LinkedList(); + + linkedList.push(1); + expect(linkedList, equals([1])); + + linkedList.push(2); + expect(linkedList, equals([2, 1])); + + linkedList.push(3); + expect(linkedList, equals([3, 2, 1])); + }); + + test(".pop is returning and removing first element", () { + LinkedList linkedList = new LinkedList(); + + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + + expect(linkedList.pop(), equals(1)); + expect(linkedList, equals([2, 3])); + + expect(linkedList.pop(), equals(2)); + expect(linkedList, equals([3])); + + expect(linkedList.pop(), equals(3)); + expect(linkedList, equals([])); + }); + + test(".pop is returning null when list is empty", () { + LinkedList linkedList = new LinkedList(); + + expect(linkedList.pop(), isNull); + }); } diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 00000000..edf643d6 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,4 @@ +name: dart + +dependencies: + test: ^1.15.4 From 1e70c4fe027808dce246f04d32e425fd14cd8863 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 22:52:05 +0200 Subject: [PATCH 113/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 5b607419..5b3aa20c 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,6 +6,6 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - # - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 + - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From 75017c5a5d1fcc72e3913883a0d24085821cc21c Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 22:54:19 +0200 Subject: [PATCH 114/443] dart pub get --- .github/workflows/dart_test_analyze_format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 5b3aa20c..6934ab98 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,6 +6,7 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 + - run: dart pub get + - run: dart test - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From c11ac7d5b21f80e7074472bbf45e14a59a62fe20 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 22:57:13 +0200 Subject: [PATCH 115/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 6934ab98..2ea818a8 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,8 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test + - run: dart test data_structures/linked_list.dart + - run: dart test data_structures || true + - run: dart test . || true - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From 522d6916c9d4d6a6ac991fe42df92fcf3f90ff92 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 22:58:57 +0200 Subject: [PATCH 116/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 2ea818a8..dc96c38a 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,8 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test data_structures/linked_list.dart - - run: dart test data_structures || true - - run: dart test . || true + - run: pub run test . - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From 0512b33c4a17d94440e799597bd7ccd0a507cc13 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 23:03:02 +0200 Subject: [PATCH 117/443] Create README.md --- tests/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 tests/README.md diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..dfe2938a --- /dev/null +++ b/tests/README.md @@ -0,0 +1 @@ +# Put dart test files here... From fd50f44a0b68a530b7ff1c2018d8bd822ee0a251 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 23:06:31 +0200 Subject: [PATCH 118/443] dart test data_structures/linked_list.dart --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index dc96c38a..e45d4e5e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: pub run test . + - run: dart test data_structures/linked_list.dart - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From f352726f5cd64d042a2a4cda058eeeaf9383217c Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:07:56 +0200 Subject: [PATCH 119/443] Linked list tests (#93) * Add test suit and test cases for linked list * Update dart_test_analyze_format.yml * dart pub get * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Create README.md * dart test data_structures/linked_list.dart Co-authored-by: Christian Clauss --- .../workflows/dart_test_analyze_format.yml | 3 +- data_structures/linked_list.dart | 98 +++++++++++++------ pubspec.yaml | 4 + tests/README.md | 1 + 4 files changed, 74 insertions(+), 32 deletions(-) create mode 100644 pubspec.yaml create mode 100644 tests/README.md diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 5b607419..e45d4e5e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,6 +6,7 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - # - run: dart test # See https://github.com/TheAlgorithms/Dart/issues/88 + - run: dart pub get + - run: dart test data_structures/linked_list.dart - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . diff --git a/data_structures/linked_list.dart b/data_structures/linked_list.dart index 7494bce8..e3e805b5 100644 --- a/data_structures/linked_list.dart +++ b/data_structures/linked_list.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + class Node { Node next; T value; @@ -84,35 +86,69 @@ class LinkedList extends Iterable { } } -main(List args) { - LinkedList linkedList = new LinkedList(); - linkedList.add(2); - linkedList.add(4); - linkedList.add(6); - linkedList.add(8); - - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(6); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(2); - print("5 in linkedList - ${linkedList.contains(5)}"); - print("4 in linkedList - ${linkedList.contains(4)}"); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(8); - print(linkedList.join(", ") + " size=${linkedList.length}"); - linkedList.remove(4); - print(linkedList.join(", ") + " size=${linkedList.length}"); - - LinkedList stack = new LinkedList(); - stack.push(2); - stack.push(4); - stack.push(6); - - print(stack.join(", ") + " size=${stack.length}"); - stack.pop(); - print(stack.join(", ") + " size=${stack.length}"); - stack.pop(); - stack.pop(); - stack.pop(); - print(stack.join(", ") + " size=${stack.length}"); +main() { + test(".add is adding elements in order", () { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + + expect(linkedList, equals([1, 2, 3])); + }); + + test(".remove is removing all elements with given value", () { + LinkedList linkedList = new LinkedList(); + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + linkedList.add(2); + + linkedList.remove(2); + + expect(linkedList, equals([1, 3])); + }); + + test(".remove on empty list do nothing", () { + LinkedList linkedList = new LinkedList(); + + linkedList.remove(2); + + expect(linkedList, isEmpty); + }); + + test(".push is appending first element", () { + LinkedList linkedList = new LinkedList(); + + linkedList.push(1); + expect(linkedList, equals([1])); + + linkedList.push(2); + expect(linkedList, equals([2, 1])); + + linkedList.push(3); + expect(linkedList, equals([3, 2, 1])); + }); + + test(".pop is returning and removing first element", () { + LinkedList linkedList = new LinkedList(); + + linkedList.add(1); + linkedList.add(2); + linkedList.add(3); + + expect(linkedList.pop(), equals(1)); + expect(linkedList, equals([2, 3])); + + expect(linkedList.pop(), equals(2)); + expect(linkedList, equals([3])); + + expect(linkedList.pop(), equals(3)); + expect(linkedList, equals([])); + }); + + test(".pop is returning null when list is empty", () { + LinkedList linkedList = new LinkedList(); + + expect(linkedList.pop(), isNull); + }); } diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 00000000..edf643d6 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,4 @@ +name: dart + +dependencies: + test: ^1.15.4 diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..dfe2938a --- /dev/null +++ b/tests/README.md @@ -0,0 +1 @@ +# Put dart test files here... From f74fc0dc2ce38372bee5ad52f47d6f3b67aea793 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:20:41 +0200 Subject: [PATCH 120/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index e45d4e5e..efd3365e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test data_structures/linked_list.dart + - run: dart test . -n */*.dart - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From c3ad8e31a386fe973d63bdcff3db4e237ba59281 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 23:24:43 +0200 Subject: [PATCH 121/443] Update pubspec.yaml --- pubspec.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index edf643d6..5649f57c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,4 +1,6 @@ -name: dart +name: the_algorithms_dart + +repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 From 3f91119c91cc280a58c87a69b4ce6e2db06fef12 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:29:29 +0200 Subject: [PATCH 122/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index efd3365e..59dc6870 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test . -n */*.dart + - run: dart test . -n **/*.dart - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From 394cfd63caef56dc6fc9e7bc0a067dfc1099c77b Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:41:29 +0200 Subject: [PATCH 123/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 59dc6870..9869f910 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test . -n **/*.dart + - run: dart test . -n */*.dart -n */*/*.dart - run: dart analyze || true # TODO: remove `|| true` when #86 is closed - run: dart format --set-exit-if-changed . From 5c64d98c2dc2693776532a9e5fb92d906ee667e2 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Thu, 15 Oct 2020 23:41:56 +0200 Subject: [PATCH 124/443] Fix small test errors --- conversions/hexadecimal_to_decimal.dart | 7 ++++++- maths/factorial_approximation.dart | 2 +- maths/factors.dart | 9 +++++++-- other/fisher_yates_shuffle.dart | 2 +- other/heaps_algorithm.dart | 2 +- 5 files changed, 16 insertions(+), 6 deletions(-) diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index edd48e9e..8c4a2536 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -10,8 +10,13 @@ Map hex_table = { }; void main() { print(hexadecimal_to_decimal("1abc")); // 6844 + print(hexadecimal_to_decimal(" -123 ")); // -291 - print(hexadecimal_to_decimal("1x")); //error + try { + print(hexadecimal_to_decimal("1x")); //error + } catch (ex) { + print(ex); + } } int hexadecimal_to_decimal(String hex_string) { diff --git a/maths/factorial_approximation.dart b/maths/factorial_approximation.dart index 71f8790e..821dd655 100644 --- a/maths/factorial_approximation.dart +++ b/maths/factorial_approximation.dart @@ -7,7 +7,7 @@ double factorial(double x) { pow(8 * pow(x, 3) + 4 * pow(x, 2) + x + 1 / 30, 1 / 6); } -main(List args) { +main() { for (int i = 0; i < 10; i++) { print("$i! ~= ${factorial(i.toDouble())}"); } diff --git a/maths/factors.dart b/maths/factors.dart index d27bdccd..8f624505 100644 --- a/maths/factors.dart +++ b/maths/factors.dart @@ -1,7 +1,12 @@ void main() { print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] - print(factorsOf(-1) - .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function + + try { + print(factorsOf(-1) + .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function + } catch (ex) { + print(ex); + } } List factorsOf(int num) { diff --git a/other/fisher_yates_shuffle.dart b/other/fisher_yates_shuffle.dart index 61952759..e6ba37a4 100644 --- a/other/fisher_yates_shuffle.dart +++ b/other/fisher_yates_shuffle.dart @@ -16,7 +16,7 @@ void shuffle(List collection) { } } -main(List args) { +main() { List someList = [1, 2, 3, 4, 5]; print(someList); shuffle(someList); diff --git a/other/heaps_algorithm.dart b/other/heaps_algorithm.dart index 5b361fac..81c021e1 100644 --- a/other/heaps_algorithm.dart +++ b/other/heaps_algorithm.dart @@ -31,7 +31,7 @@ List> permutations(List collection) { return output; } -main(List args) { +main() { print(permutations([])); print(permutations([1, 2])); print(permutations([1, 2, 3])); From 0cf6fd05c56f5e356bd86ea1cd79218dacac25aa Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 15 Oct 2020 23:43:24 +0200 Subject: [PATCH 125/443] analyzer: exclude: maths/fermats_little_theorem.dart (#94) * analyzer: exclude: maths/fermats_little_theorem.dart * Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- analysis_options.yaml | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 analysis_options.yaml diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index e45d4e5e..4f67559a 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,5 +8,5 @@ jobs: - uses: actions/checkout@v2 - run: dart pub get - run: dart test data_structures/linked_list.dart - - run: dart analyze || true # TODO: remove `|| true` when #86 is closed + - run: dart analyze - run: dart format --set-exit-if-changed . diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 00000000..00cb9e66 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + exclude: + - maths/fermats_little_theorem.dart From 29c441a6f442bd82d3326e68ef250927319e0e1f Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:53:35 +0200 Subject: [PATCH 126/443] Update pubspec.yaml --- pubspec.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pubspec.yaml b/pubspec.yaml index da5fb265..cd65b472 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,2 +1,7 @@ + +name: the_algorithms_dart + +repository: https://github.com/TheAlgorithms/Dart + dependencies: test: ^1.15.4 From 08ffd73cef0f947e88a0bf8fd545573a6c45c59b Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 15 Oct 2020 23:54:30 +0200 Subject: [PATCH 127/443] Update pubspec.yaml Co-authored-by: Christian Clauss --- pubspec.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index cd65b472..5649f57c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,4 +1,3 @@ - name: the_algorithms_dart repository: https://github.com/TheAlgorithms/Dart From 01e4825806e60bee5a3f283e2ae7cccf5c3ca4de Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 00:36:21 +0200 Subject: [PATCH 128/443] Skip fermant_little_theorem and fix type errors --- maths/fermats_little_theorem.dart | 4 ++++ other/LCM.dart | 4 ++-- search/interpolation_Search.dart | 5 +++-- sort/heap_Sort.dart | 4 ++-- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/maths/fermats_little_theorem.dart b/maths/fermats_little_theorem.dart index 9f4378a7..56073fe7 100644 --- a/maths/fermats_little_theorem.dart +++ b/maths/fermats_little_theorem.dart @@ -1,3 +1,7 @@ +@Skip('currently failing (see issue #86)') + +import 'package:test/test.dart'; + /* Fermat's little Theorem Translated from TheAlgorithms/Python diff --git a/other/LCM.dart b/other/LCM.dart index 392c516f..cdb005ab 100644 --- a/other/LCM.dart +++ b/other/LCM.dart @@ -11,7 +11,7 @@ */ //Recursive function to return gcd of a and b -double gcd(var a, var b) { +int gcd(int a, int b) { if (a == 0) { return b; } @@ -19,7 +19,7 @@ double gcd(var a, var b) { } //Function to return LCM of two numbers -double lcm(var a, var b) { +double lcm(int a, int b) { return (a * b) / gcd(a, b); } diff --git a/search/interpolation_Search.dart b/search/interpolation_Search.dart index 2fc3735a..6b60727c 100644 --- a/search/interpolation_Search.dart +++ b/search/interpolation_Search.dart @@ -12,11 +12,12 @@ //Author:Shawn //Email:stepfencurryxiao@gmail.com -int interpolationSearch(List arr, var n, var key) { +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 posible position of key */ - int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); + int pos = low + + (((key - arr[low]) * (high - low)) / (arr[high] - arr[low])).round(); if (key > arr[pos]) low = pos + 1; else if (key < arr[pos]) diff --git a/sort/heap_Sort.dart b/sort/heap_Sort.dart index f5948032..4e789551 100644 --- a/sort/heap_Sort.dart +++ b/sort/heap_Sort.dart @@ -3,12 +3,12 @@ void sort(List arr) { int n = arr.length; //Build heap (rearrange arrary) - for (var i = n / 2 - 1; i >= 0; i--) { + for (int i = (n / 2 - 1).round(); i >= 0; i--) { heapify(arr, n, i); } // One by one extract an element from heap - for (var i = n - 1; i >= 0; i--) { + for (int i = n - 1; i >= 0; i--) { //Move current root to end var temp = arr[0]; arr[0] = arr[i]; From ff748dca21f86922187faf8250291a830f74c018 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 00:40:54 +0200 Subject: [PATCH 129/443] Catch error in binary_to_decimal --- conversions/binary_to_decimal.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 5e0c145b..e83ee4af 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -3,7 +3,11 @@ import "dart:math" show pow; void main() { print(binary_to_decimal("-111")); // -7 print(binary_to_decimal(" 101011 ")); // 43 - print(binary_to_decimal("1a1")); //error + try { + print(binary_to_decimal("1a1")); //error + } catch (ex) { + print(ex); + } } int binary_to_decimal(String bin_string) { From cdf0653631d563680cb1f932580fd6dda72190d0 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Fri, 16 Oct 2020 00:46:48 +0200 Subject: [PATCH 130/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 4f67559a..521d5db0 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -10,3 +10,6 @@ jobs: - run: dart test data_structures/linked_list.dart - run: dart analyze - run: dart format --set-exit-if-changed . + - uses: actions/setup-python@v2 + - run: pip install codespell + - run: codespell --quiet-level=2 || true # --ignore-words-list="" --skip="" From 9121e5e414a9e698c7db55960382b894268583b8 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Fri, 16 Oct 2020 00:58:25 +0200 Subject: [PATCH 131/443] Revert a mistake --- .github/workflows/dart_test_analyze_format.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 521d5db0..4f67559a 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -10,6 +10,3 @@ jobs: - run: dart test data_structures/linked_list.dart - run: dart analyze - run: dart format --set-exit-if-changed . - - uses: actions/setup-python@v2 - - run: pip install codespell - - run: codespell --quiet-level=2 || true # --ignore-words-list="" --skip="" From 17d530d673e04b4fd8c15984902783f6a50d36ff Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Fri, 16 Oct 2020 01:08:25 +0200 Subject: [PATCH 132/443] Update update_directory_md.yml --- .github/workflows/update_directory_md.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml index 730d4e13..32dcf94d 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory_md.yml @@ -4,8 +4,8 @@ jobs: update_directory_md: runs-on: ubuntu-latest steps: - - uses: actions/checkout@master - - uses: actions/setup-python@master + - uses: actions/checkout@v1 # v1, NOT v2 + - uses: actions/setup-python@v2 - name: update_directory_md shell: python run: | From c5c9aa548a1263c5d2829a78f70913cefc658563 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 01:11:38 +0200 Subject: [PATCH 133/443] Add dart_test.yaml --- dart_test.yaml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 dart_test.yaml diff --git a/dart_test.yaml b/dart_test.yaml new file mode 100644 index 00000000..53f6bf6c --- /dev/null +++ b/dart_test.yaml @@ -0,0 +1,3 @@ +paths: [.] + +filename: "*.dart" From e058fc0a0506e95cdf79584ae5b4b03637c337f2 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 01:15:05 +0200 Subject: [PATCH 134/443] Update github action to use dart_test.yaml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 6c82827a..dddfa643 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test . -n */*.dart -n */*/*.dart + - run: dart test - run: dart analyze - run: dart format --set-exit-if-changed . From 41d45b7c847b0ea60680759479b3f81bcdf52ab1 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 07:43:46 +0200 Subject: [PATCH 135/443] Linked list tests (#95) * Add test suit and test cases for linked list * Update dart_test_analyze_format.yml * dart pub get * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Create README.md * dart test data_structures/linked_list.dart * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Update dart_test_analyze_format.yml * Fix small test errors * Update pubspec.yaml * Update pubspec.yaml Co-authored-by: Christian Clauss * Skip fermant_little_theorem and fix type errors * Catch error in binary_to_decimal * Add dart_test.yaml * Update github action to use dart_test.yaml Co-authored-by: Christian Clauss --- .github/workflows/dart_test_analyze_format.yml | 2 +- conversions/binary_to_decimal.dart | 6 +++++- conversions/hexadecimal_to_decimal.dart | 7 ++++++- dart_test.yaml | 3 +++ maths/factorial_approximation.dart | 2 +- maths/factors.dart | 9 +++++++-- maths/fermats_little_theorem.dart | 4 ++++ other/LCM.dart | 4 ++-- other/fisher_yates_shuffle.dart | 2 +- other/heaps_algorithm.dart | 2 +- search/interpolation_Search.dart | 5 +++-- sort/heap_Sort.dart | 4 ++-- 12 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 dart_test.yaml diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 4f67559a..dddfa643 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,6 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test data_structures/linked_list.dart + - run: dart test - run: dart analyze - run: dart format --set-exit-if-changed . diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 5e0c145b..e83ee4af 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -3,7 +3,11 @@ import "dart:math" show pow; void main() { print(binary_to_decimal("-111")); // -7 print(binary_to_decimal(" 101011 ")); // 43 - print(binary_to_decimal("1a1")); //error + try { + print(binary_to_decimal("1a1")); //error + } catch (ex) { + print(ex); + } } int binary_to_decimal(String bin_string) { diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index edd48e9e..8c4a2536 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -10,8 +10,13 @@ Map hex_table = { }; void main() { print(hexadecimal_to_decimal("1abc")); // 6844 + print(hexadecimal_to_decimal(" -123 ")); // -291 - print(hexadecimal_to_decimal("1x")); //error + try { + print(hexadecimal_to_decimal("1x")); //error + } catch (ex) { + print(ex); + } } int hexadecimal_to_decimal(String hex_string) { diff --git a/dart_test.yaml b/dart_test.yaml new file mode 100644 index 00000000..53f6bf6c --- /dev/null +++ b/dart_test.yaml @@ -0,0 +1,3 @@ +paths: [.] + +filename: "*.dart" diff --git a/maths/factorial_approximation.dart b/maths/factorial_approximation.dart index 71f8790e..821dd655 100644 --- a/maths/factorial_approximation.dart +++ b/maths/factorial_approximation.dart @@ -7,7 +7,7 @@ double factorial(double x) { pow(8 * pow(x, 3) + 4 * pow(x, 2) + x + 1 / 30, 1 / 6); } -main(List args) { +main() { for (int i = 0; i < 10; i++) { print("$i! ~= ${factorial(i.toDouble())}"); } diff --git a/maths/factors.dart b/maths/factors.dart index d27bdccd..8f624505 100644 --- a/maths/factors.dart +++ b/maths/factors.dart @@ -1,7 +1,12 @@ void main() { print("factors: ${factorsOf(12)}"); //factors: [1, 2, 3, 4, 6, 12] - print(factorsOf(-1) - .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function + + try { + print(factorsOf(-1) + .toString()); //Unhandled exception: Exception: A non-positive value was passed to the function + } catch (ex) { + print(ex); + } } List factorsOf(int num) { diff --git a/maths/fermats_little_theorem.dart b/maths/fermats_little_theorem.dart index 9f4378a7..56073fe7 100644 --- a/maths/fermats_little_theorem.dart +++ b/maths/fermats_little_theorem.dart @@ -1,3 +1,7 @@ +@Skip('currently failing (see issue #86)') + +import 'package:test/test.dart'; + /* Fermat's little Theorem Translated from TheAlgorithms/Python diff --git a/other/LCM.dart b/other/LCM.dart index 392c516f..cdb005ab 100644 --- a/other/LCM.dart +++ b/other/LCM.dart @@ -11,7 +11,7 @@ */ //Recursive function to return gcd of a and b -double gcd(var a, var b) { +int gcd(int a, int b) { if (a == 0) { return b; } @@ -19,7 +19,7 @@ double gcd(var a, var b) { } //Function to return LCM of two numbers -double lcm(var a, var b) { +double lcm(int a, int b) { return (a * b) / gcd(a, b); } diff --git a/other/fisher_yates_shuffle.dart b/other/fisher_yates_shuffle.dart index 61952759..e6ba37a4 100644 --- a/other/fisher_yates_shuffle.dart +++ b/other/fisher_yates_shuffle.dart @@ -16,7 +16,7 @@ void shuffle(List collection) { } } -main(List args) { +main() { List someList = [1, 2, 3, 4, 5]; print(someList); shuffle(someList); diff --git a/other/heaps_algorithm.dart b/other/heaps_algorithm.dart index 5b361fac..81c021e1 100644 --- a/other/heaps_algorithm.dart +++ b/other/heaps_algorithm.dart @@ -31,7 +31,7 @@ List> permutations(List collection) { return output; } -main(List args) { +main() { print(permutations([])); print(permutations([1, 2])); print(permutations([1, 2, 3])); diff --git a/search/interpolation_Search.dart b/search/interpolation_Search.dart index 2fc3735a..6b60727c 100644 --- a/search/interpolation_Search.dart +++ b/search/interpolation_Search.dart @@ -12,11 +12,12 @@ //Author:Shawn //Email:stepfencurryxiao@gmail.com -int interpolationSearch(List arr, var n, var key) { +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 posible position of key */ - int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]); + int pos = low + + (((key - arr[low]) * (high - low)) / (arr[high] - arr[low])).round(); if (key > arr[pos]) low = pos + 1; else if (key < arr[pos]) diff --git a/sort/heap_Sort.dart b/sort/heap_Sort.dart index f5948032..4e789551 100644 --- a/sort/heap_Sort.dart +++ b/sort/heap_Sort.dart @@ -3,12 +3,12 @@ void sort(List arr) { int n = arr.length; //Build heap (rearrange arrary) - for (var i = n / 2 - 1; i >= 0; i--) { + for (int i = (n / 2 - 1).round(); i >= 0; i--) { heapify(arr, n, i); } // One by one extract an element from heap - for (var i = n - 1; i >= 0; i--) { + for (int i = n - 1; i >= 0; i--) { //Move current root to end var temp = arr[0]; arr[0] = arr[i]; From 20de67573558f017652cc53114cd23b18a6716b9 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 15:47:11 +0530 Subject: [PATCH 136/443] Added Kadanes Algorithm Added in Unit test cases Made changes related to maxFunction --- dynamic_programming/kadanes_algorithm.dart | 52 +++++++++++++--------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/dynamic_programming/kadanes_algorithm.dart b/dynamic_programming/kadanes_algorithm.dart index d4dfcc12..df03a339 100644 --- a/dynamic_programming/kadanes_algorithm.dart +++ b/dynamic_programming/kadanes_algorithm.dart @@ -1,3 +1,4 @@ +import 'package:test/test.dart'; import 'dart:math'; int kadanesAlgorithm(List array) { @@ -5,30 +6,41 @@ int kadanesAlgorithm(List array) { int maxSoFar = array[0]; for (int num in array.sublist(1, array.length)) { - maxEndingHere = [maxEndingHere + num, num].reduce(max); - maxSoFar = [maxSoFar, maxEndingHere].reduce(max); + maxEndingHere = max(maxEndingHere + num, num); + maxSoFar = max(maxSoFar, maxEndingHere); } return maxSoFar; } void main() { - List array = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]; + List array; int maxContiniousSubarraySum; - maxContiniousSubarraySum = kadanesAlgorithm(array); - print('${maxContiniousSubarraySum == 19}'); - - array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - maxContiniousSubarraySum; - maxContiniousSubarraySum = kadanesAlgorithm(array); - print('${maxContiniousSubarraySum == 55}'); - - array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; - maxContiniousSubarraySum; - maxContiniousSubarraySum = kadanesAlgorithm(array); - print('${maxContiniousSubarraySum == -1}'); - - array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; - maxContiniousSubarraySum; - maxContiniousSubarraySum = kadanesAlgorithm(array); - print('${maxContiniousSubarraySum == 34}'); + + test(('.Check the response for each test case'), () { + array = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]; + + maxContiniousSubarraySum = kadanesAlgorithm(array); + expect(maxContiniousSubarraySum, equals(19)); + }); + + test(('.Check the response for each test case'), () { + array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + expect(maxContiniousSubarraySum, equals(55)); + }); + + test(('.Check the response for each test case'), () { + array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + expect(maxContiniousSubarraySum, equals(-1)); + }); + + test(('.Check the response for each test case'), () { + array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; + maxContiniousSubarraySum; + maxContiniousSubarraySum = kadanesAlgorithm(array); + expect(maxContiniousSubarraySum, equals(34)); + }); } From 5672cf20e2941c556bcab8b7ede4b9ec5674b47d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Oct 2020 10:17:26 +0000 Subject: [PATCH 137/443] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 09db1398..3466c4a4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -24,6 +24,9 @@ * [Array Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Array_Stack.dart) * [Linked List Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Linked_List_Stack.dart) +## Dynamic Programming + * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) + ## Graphs * [Nearest Neighbour Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/graphs/nearest_neighbour_algorithm.dart) From 5cad9be06b7b26ea45f55a5c58e4dea042d23bcd Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 15:57:10 +0530 Subject: [PATCH 138/443] Update kadanes_algorithm.dart --- dynamic_programming/kadanes_algorithm.dart | 3 --- 1 file changed, 3 deletions(-) diff --git a/dynamic_programming/kadanes_algorithm.dart b/dynamic_programming/kadanes_algorithm.dart index df03a339..75934623 100644 --- a/dynamic_programming/kadanes_algorithm.dart +++ b/dynamic_programming/kadanes_algorithm.dart @@ -25,21 +25,18 @@ void main() { test(('.Check the response for each test case'), () { array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); expect(maxContiniousSubarraySum, equals(55)); }); test(('.Check the response for each test case'), () { array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]; - maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); expect(maxContiniousSubarraySum, equals(-1)); }); test(('.Check the response for each test case'), () { array = [1, 2, 3, 4, 5, 6, -22, 7, 8, 9, 10]; - maxContiniousSubarraySum; maxContiniousSubarraySum = kadanesAlgorithm(array); expect(maxContiniousSubarraySum, equals(34)); }); From f80d15a7cb202a94555a3bbf8b0ddd7f147bbda8 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 16:54:52 +0530 Subject: [PATCH 139/443] DART implementation Knuth Morris Pratt Algorithm Implemented a new file with tests for Knuth Morris pratt algorithm Added test cases both positive and negative --- strings/knuth_morris_prat.dart | 78 ++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 strings/knuth_morris_prat.dart diff --git a/strings/knuth_morris_prat.dart b/strings/knuth_morris_prat.dart new file mode 100644 index 00000000..8b3471f1 --- /dev/null +++ b/strings/knuth_morris_prat.dart @@ -0,0 +1,78 @@ +import 'package:test/test.dart'; + +bool stringCompare(String string, String subString) { + List pattern = + new List.generate(subString.length, (int index) => -1); + + int i = 1; + int j = 0; + + while (i < subString.length) { + if (subString[i] == subString[j]) { + pattern[i] = j; + i++; + j++; + } else if (j > 0) { + j = pattern[j - 1] + 1; + } else { + i++; + } + } + + return stringCompareHelper(string, subString, pattern); +} + +bool stringCompareHelper(String string, String subString, List pattern) { + int i = 0; + int j = 0; + + while (i + subString.length - j <= string.length) { + if (string[i] == subString[j]) { + if (j == subString.length - 1) { + return true; + } + i++; + j++; + } else if (j > 0) { + j = pattern[j - 1] + 1; + } else { + i++; + } + } + return false; +} + +void main() { + String string; + String subString; + + test(('KMP: '), () { + string = 'aefoaefcdaefcdaed'; + subString = 'aefcdaed'; + expect(stringCompare(string, subString), equals(true)); + }); + + test(('KMP: '), () { + string = 'testwafwafawfawfawfawfawfawfawfa'; + subString = 'fawfawfawfawfa'; + expect(stringCompare(string, subString), equals(true)); + }); + + test(('KMP: '), () { + string = 'aabc'; + subString = 'abc'; + expect(stringCompare(string, subString), equals(true)); + }); + + test(('KMP: '), () { + string = 'adafccfefbbbfeeccbcfd'; + subString = 'ecb'; + expect(stringCompare(string, subString), equals(false)); + }); + + test(('KMP: '), () { + string = 'akash'; + subString = 'christy'; + expect(stringCompare(string, subString), equals(false)); + }); +} From 4703efedc12cac3230e4f9d28989fd65dc772ba2 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Oct 2020 11:25:11 +0000 Subject: [PATCH 140/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 67bc8533..0e9d3283 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -122,4 +122,5 @@ * [Tim Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/tim_Sort.dart) ## Strings + * [Knuth Morris Prat](https://github.com/TheAlgorithms/Dart/blob/master/strings/knuth_morris_prat.dart) * [Reverse String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_string.dart) From bef6b62aca1e0dbf6c33631da617da1d661102d1 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 18:25:17 +0530 Subject: [PATCH 141/443] Added the balanced bracket stack problem Dart implementation of the balanced bracket problem added test cases --- data_structures/Stack/balanced_brackets.dart | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 data_structures/Stack/balanced_brackets.dart diff --git a/data_structures/Stack/balanced_brackets.dart b/data_structures/Stack/balanced_brackets.dart new file mode 100644 index 00000000..0ca4493f --- /dev/null +++ b/data_structures/Stack/balanced_brackets.dart @@ -0,0 +1,50 @@ +import 'package:test/test.dart'; +import 'package:stack/stack.dart'; + +bool isBalancedBrackets(String string) { + Stack stack = Stack(); + + List openingBrackets = ['(', '{', '[']; + final Map matchingBracket = {'}': '{', ')': '(', ']': '['}; + + for (int i = 0; i < string.length; i++) { + var currentChar = string[i]; + + if (openingBrackets.contains(currentChar)) { + stack.push(currentChar); + } else { + if (stack.isNotEmpty) { + if (stack.top() == matchingBracket[currentChar]) { + stack.pop(); + } else { + return false; + } + } else { + return false; + } + } + } + return !stack.isNotEmpty; +} + +void main() { + test(('Balanced Bracket'), () { + expect(isBalancedBrackets('([])(){}(())()()'), equals(true)); + }); + + test(('Balanced Bracket'), () { + expect(isBalancedBrackets('()[]{}{'), equals(false)); + }); + + test(('Balanced Bracket'), () { + expect(isBalancedBrackets('()()[{()})]'), equals(false)); + }); + + test(('Balanced Bracket'), () { + expect(isBalancedBrackets('()([])'), equals(true)); + }); + + test(('Balanced Bracket'), () { + expect(isBalancedBrackets('(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), equals(true)); + }); +} From 16ea47f781e3ce50bc4d09a78cacfdabbe8a50e7 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Oct 2020 12:55:42 +0000 Subject: [PATCH 142/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 67bc8533..6a2c978e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -22,6 +22,7 @@ * [Priority Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Priority_Queue.dart) * Stack * [Array Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Array_Stack.dart) + * [Balanced Brackets](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/balanced_brackets.dart) * [Linked List Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Linked_List_Stack.dart) ## Graphs From 943d7e5818e3e4289797f148dfdc98611f1c4720 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 18:36:02 +0530 Subject: [PATCH 143/443] Update pubspec.yaml up --- pubspec.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pubspec.yaml b/pubspec.yaml index 5649f57c..590913e9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,3 +4,6 @@ repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 + +dev_dependencies: + stack: ^0.0.1 From 576a991cbe248475e960256588433858c60e5502 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 15:11:02 +0200 Subject: [PATCH 144/443] Run coverage --- .github/workflows/dart_test_analyze_format.yml | 3 ++- pubspec.yaml | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index dddfa643..be613df3 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,7 @@ jobs: steps: - uses: actions/checkout@v2 - run: dart pub get - - run: dart test + - run: dart test --coverage . + - run: dart coverage:format_coverage -i . - run: dart analyze - run: dart format --set-exit-if-changed . diff --git a/pubspec.yaml b/pubspec.yaml index 5649f57c..1516e02a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,3 +4,4 @@ repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 + coverage: ^0.14.1 From 28c653d9c83bd85cf834d6b7822a788441c71987 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 18:41:03 +0530 Subject: [PATCH 145/443] Update pubspec.yaml --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 590913e9..26c54751 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,6 +4,6 @@ repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 - + dev_dependencies: stack: ^0.0.1 From aa1d64533a50acd238072987403f9cdd3b0e0ed0 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 18:58:00 +0530 Subject: [PATCH 146/443] Update balanced_brackets.dart --- data_structures/Stack/balanced_brackets.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/data_structures/Stack/balanced_brackets.dart b/data_structures/Stack/balanced_brackets.dart index 0ca4493f..ccba330e 100644 --- a/data_structures/Stack/balanced_brackets.dart +++ b/data_structures/Stack/balanced_brackets.dart @@ -45,6 +45,9 @@ void main() { }); test(('Balanced Bracket'), () { - expect(isBalancedBrackets('(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), equals(true)); + expect( + isBalancedBrackets( + '(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), + equals(true)); }); } From 18c47a536cda40724cede7e4dd8033be4b518e83 Mon Sep 17 00:00:00 2001 From: Artur Parowicz Date: Fri, 16 Oct 2020 15:32:15 +0200 Subject: [PATCH 147/443] Format covarage to lcov format --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index be613df3..0b53ce23 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,6 +8,6 @@ jobs: - uses: actions/checkout@v2 - run: dart pub get - run: dart test --coverage . - - run: dart coverage:format_coverage -i . + - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov - run: dart analyze - run: dart format --set-exit-if-changed . From 40f2d97c3611590752faaffb8aa19926e25e48a3 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 16:28:45 +0200 Subject: [PATCH 148/443] Update .github/workflows/dart_test_analyze_format.yml Co-authored-by: Christian Clauss --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 0b53ce23..b4af93c2 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,6 +8,6 @@ jobs: - uses: actions/checkout@v2 - run: dart pub get - run: dart test --coverage . - - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov + - run: dart pub run coverage:format_coverage -i . --pretty-print - run: dart analyze - run: dart format --set-exit-if-changed . From 963f76b7be6f7bd6e5694b711cc4e456af808265 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 16:54:02 +0200 Subject: [PATCH 149/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index b4af93c2..38066ac3 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,8 +6,10 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 + - run: apt-get install lcov - run: dart pub get - run: dart test --coverage . - - run: dart pub run coverage:format_coverage -i . --pretty-print + - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov + - run: lcov -l coverage.lcov - run: dart analyze - run: dart format --set-exit-if-changed . From 4223106652afc3e0a6b4c53a7608b6e920ad8d6f Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 17:08:44 +0200 Subject: [PATCH 150/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 38066ac3..8774a5ee 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,7 +6,8 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - - run: apt-get install lcov + - run: git clone https://github.com/linux-test-project/lcov.git + - run: make -C lcov install - run: dart pub get - run: dart test --coverage . - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov From 7e9f02922e9791b22227a72f2d819e29b9b54e5f Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 17:11:56 +0200 Subject: [PATCH 151/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 8774a5ee..b0f3cb2f 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,6 +6,7 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 + - run: sudo apt-get install make - run: git clone https://github.com/linux-test-project/lcov.git - run: make -C lcov install - run: dart pub get From 907abdf1cb8450132b2c489a41b31d1ad72ac19a Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 17:13:06 +0200 Subject: [PATCH 152/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index b0f3cb2f..1d977fab 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,7 +6,7 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - - run: sudo apt-get install make + - run: apt-get install make - run: git clone https://github.com/linux-test-project/lcov.git - run: make -C lcov install - run: dart pub get From 4588a4e811bcab7c02703d5a3d193d3310332ef3 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 21:26:08 +0530 Subject: [PATCH 153/443] Added explanatory comments to the Functions Added in comments as reviewed --- strings/knuth_morris_prat.dart | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/strings/knuth_morris_prat.dart b/strings/knuth_morris_prat.dart index 8b3471f1..acab889d 100644 --- a/strings/knuth_morris_prat.dart +++ b/strings/knuth_morris_prat.dart @@ -1,5 +1,13 @@ import 'package:test/test.dart'; +/// Preprocess pattern to identify any suffixes that are identical to prefixes +/// in the given string. +/// +/// Build a pattern which tells us where to continue iteration from if we +/// get a mismatch between the character +/// +/// Step through the text one character at a time and compare it to a character in +/// the pattern updating our location within the pattern if necessary bool stringCompare(String string, String subString) { List pattern = new List.generate(subString.length, (int index) => -1); From e76a90d917d0d25b29cc336d4a8250c2efe84f99 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Fri, 16 Oct 2020 17:58:14 +0200 Subject: [PATCH 154/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 1d977fab..4ea76c5e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -6,9 +6,9 @@ jobs: container: google/dart steps: - uses: actions/checkout@v2 - - run: apt-get install make - - run: git clone https://github.com/linux-test-project/lcov.git - - run: make -C lcov install + - 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 - run: dart pub get - run: dart test --coverage . - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov From 7a5cbac9cf0916bdafc1cd2d528f48775c1b95a6 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 22:57:57 +0530 Subject: [PATCH 155/443] Update balanced_brackets.dart Update with the review changes --- data_structures/Stack/balanced_brackets.dart | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/data_structures/Stack/balanced_brackets.dart b/data_structures/Stack/balanced_brackets.dart index ccba330e..b10abba9 100644 --- a/data_structures/Stack/balanced_brackets.dart +++ b/data_structures/Stack/balanced_brackets.dart @@ -24,30 +24,30 @@ bool isBalancedBrackets(String string) { } } } - return !stack.isNotEmpty; + return stack.isEmpty; } void main() { test(('Balanced Bracket'), () { - expect(isBalancedBrackets('([])(){}(())()()'), equals(true)); + expect(isBalancedBrackets('([])(){}(())()()'), isTrue); }); test(('Balanced Bracket'), () { - expect(isBalancedBrackets('()[]{}{'), equals(false)); + expect(isBalancedBrackets('()[]{}{'), isFalse); }); test(('Balanced Bracket'), () { - expect(isBalancedBrackets('()()[{()})]'), equals(false)); + expect(isBalancedBrackets('()()[{()})]'), isFalse); }); test(('Balanced Bracket'), () { - expect(isBalancedBrackets('()([])'), equals(true)); + expect(isBalancedBrackets('()([])'), isTrue); }); test(('Balanced Bracket'), () { expect( isBalancedBrackets( '(((((([[[[[[{{{{{{{{{{{{()}}}}}}}}}}}}]]]]]]))))))((([])({})[])[])[]([]){}(())'), - equals(true)); + isTrue); }); } From c7a9293ca7e80dea2643e3bb75ee997239a5cd8c Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 23:01:28 +0530 Subject: [PATCH 156/443] Binary tree Traversal Implemented Binary tree DS implemented the inOrder, postOrder, and preOrder traversal of the tree added test cases. --- .../binary_tree/binary_tree_traversal.dart | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 data_structures/binary_tree/binary_tree_traversal.dart diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart new file mode 100644 index 00000000..649bfeb0 --- /dev/null +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -0,0 +1,108 @@ +import 'package:test/test.dart'; + +class TreeNode { + int data; + var leftNode = null; + var rightNode = null; + + int get value { + return this.data; + } + + TreeNode get left { + return this.leftNode; + } + + void set left(TreeNode value) { + this.leftNode = value; + } + + void set right(TreeNode value) { + this.rightNode = value; + } + + TreeNode get right { + return this.rightNode; + } + + TreeNode(this.data); +} + +List inOrder(TreeNode root, List result) { + if (root != null) { + inOrder(root.left, result); + result.add(root.value); + inOrder(root.right, result); + } + return result; +} + +List preOrder(TreeNode root, List result) { + if (root != null) { + result.add(root.value); + preOrder(root.left, result); + preOrder(root.right, result); + } + return result; +} + +List postOrder(TreeNode root, List result) { + if (root != null) { + postOrder(root.left, result); + postOrder(root.right, result); + result.add(root.value); + } + return result; +} + +void main() { + var 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); + + List result; + result = List(); + var ans = postOrder(root, result); + for (int i in ans) { + print(i); + } + + test(('inOrder traversal'), () { + result = List(); + expect(inOrder(root, result), equals([4, 2, 6, 5, 1, 8, 9, 7, 3])); + }); + + test(('preOrder traversal'), () { + result = []; + expect(preOrder(root, result), equals([1, 2, 4, 5, 6, 3, 7, 8, 9])); + }); + + test(('postOrder traversal'), () { + result = []; + expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); + }); + + test(('postOrder traversal'), () { + result = []; + root = null; + expect(postOrder(root, result), equals([])); + }); + + test(('inOrder traversal'), () { + result = []; + root = null; + expect(inOrder(root, result), equals([])); + }); + + test(('preOrder traversal'), () { + result = []; + root = null; + expect(preOrder(root, result), equals([])); + }); +} From 196bccb56a36d896963c628b3f556786357b5df1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Oct 2020 17:31:48 +0000 Subject: [PATCH 157/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5cca334f..2af6a3f9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -11,6 +11,7 @@ ## Data Structures * Binary Tree * [Basic Binary Tree](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/binary_tree/basic_binary_tree.dart) + * [Binary Tree Traversal](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/binary_tree/binary_tree_traversal.dart) * Hashmap * [Hashing](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/Hashing.dart) * Heap From 20c89e44363a161ed207f8f29016b38a4fd87a50 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 23:11:13 +0530 Subject: [PATCH 158/443] Update knuth_morris_prat.dart fixed for the empty string test case fixed spacing format changed equals(true) -> isTrue --- strings/knuth_morris_prat.dart | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/strings/knuth_morris_prat.dart b/strings/knuth_morris_prat.dart index acab889d..50e90e9a 100644 --- a/strings/knuth_morris_prat.dart +++ b/strings/knuth_morris_prat.dart @@ -9,6 +9,10 @@ import 'package:test/test.dart'; /// Step through the text one character at a time and compare it to a character in /// the pattern updating our location within the pattern if necessary bool stringCompare(String string, String subString) { + if (subString.isEmpty || string.isEmpty) { + return true; + } + List pattern = new List.generate(subString.length, (int index) => -1); @@ -57,30 +61,35 @@ void main() { test(('KMP: '), () { string = 'aefoaefcdaefcdaed'; subString = 'aefcdaed'; - expect(stringCompare(string, subString), equals(true)); + expect(stringCompare(string, subString), isTrue); }); test(('KMP: '), () { string = 'testwafwafawfawfawfawfawfawfawfa'; subString = 'fawfawfawfawfa'; - expect(stringCompare(string, subString), equals(true)); + expect(stringCompare(string, subString), isTrue); }); test(('KMP: '), () { string = 'aabc'; subString = 'abc'; - expect(stringCompare(string, subString), equals(true)); + expect(stringCompare(string, subString), isTrue); }); test(('KMP: '), () { string = 'adafccfefbbbfeeccbcfd'; subString = 'ecb'; - expect(stringCompare(string, subString), equals(false)); + expect(stringCompare(string, subString), isFalse); }); test(('KMP: '), () { string = 'akash'; subString = 'christy'; - expect(stringCompare(string, subString), equals(false)); + expect(stringCompare(string, subString), isFalse); + }); + test(('KMP: '), () { + string = ''; + subString = ''; + expect(stringCompare(string, subString), isTrue); }); } From 13d2470803d03625d1c88c00aa4cea9545b24188 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 16 Oct 2020 23:26:00 +0530 Subject: [PATCH 159/443] Update binary_tree_traversal.dart fixed formatting issue for pre-commit fails --- data_structures/binary_tree/binary_tree_traversal.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index 649bfeb0..e977a90d 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -94,13 +94,13 @@ void main() { expect(postOrder(root, result), equals([])); }); - test(('inOrder traversal'), () { + test(('inOrder traversal'), () { result = []; root = null; expect(inOrder(root, result), equals([])); }); - test(('preOrder traversal'), () { + test(('preOrder traversal'), () { result = []; root = null; expect(preOrder(root, result), equals([])); From f188d158d05d1511723a3eb3b9c81ce502f373f8 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 07:22:45 +0530 Subject: [PATCH 160/443] Update binary_tree_traversal.dart updated the line result = [ ] to result = List() removed unwanted code --- .../binary_tree/binary_tree_traversal.dart | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index e977a90d..5712453c 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -68,10 +68,6 @@ void main() { List result; result = List(); - var ans = postOrder(root, result); - for (int i in ans) { - print(i); - } test(('inOrder traversal'), () { result = List(); @@ -79,29 +75,29 @@ void main() { }); test(('preOrder traversal'), () { - result = []; + result = List(); expect(preOrder(root, result), equals([1, 2, 4, 5, 6, 3, 7, 8, 9])); }); test(('postOrder traversal'), () { - result = []; + result = List(); expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); }); test(('postOrder traversal'), () { - result = []; + result = List(); root = null; expect(postOrder(root, result), equals([])); }); test(('inOrder traversal'), () { - result = []; + result = List(); root = null; expect(inOrder(root, result), equals([])); }); test(('preOrder traversal'), () { - result = []; + result = List(); root = null; expect(preOrder(root, result), equals([])); }); From 7bc9ab2a9765f1bbe4e76ddcbe07ebdc65f0eba8 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 10:52:53 +0530 Subject: [PATCH 161/443] Min Heap implementation DART added more methods and functions for the minheap ds created tests --- .../Heap/Binary_Heap/min_heap_two.dart | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 data_structures/Heap/Binary_Heap/min_heap_two.dart diff --git a/data_structures/Heap/Binary_Heap/min_heap_two.dart b/data_structures/Heap/Binary_Heap/min_heap_two.dart new file mode 100644 index 00000000..05512749 --- /dev/null +++ b/data_structures/Heap/Binary_Heap/min_heap_two.dart @@ -0,0 +1,113 @@ +import 'package:test/test.dart'; + +class MinHeap { + List heap; + + void buildHeap(List array) { + this.heap = _heapify(array); + } + + List _heapify(List array) { + int firstParent; + firstParent = (array.length - 2) ~/ 2; + for (int i = firstParent; i >= 0; i--) { + _siftDown(i, array.length - 1, array); + } + return array; + } + + int peek() { + if (!isEmpty()) { + return this.heap[0]; + } + return null; + } + + bool isEmpty() { + return this.heap.length == 0; + } + + void _siftUp(int currentIndex) { + int parentIndex; + parentIndex = (currentIndex - 1) ~/ 2; + while ( + parentIndex >= 0 && this.heap[parentIndex] > this.heap[currentIndex]) { + _swap(parentIndex, currentIndex, this.heap); + currentIndex = parentIndex; + parentIndex = (currentIndex - 1) ~/ 2; + } + } + + void _siftDown(int currentIndex, int endIndex, List heap) { + int childOneIndex = (2 * currentIndex) + 1; + int childTwoIndex; + + while (childOneIndex <= endIndex) { + childTwoIndex = + 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; + int indexToSwap; + if (childTwoIndex != -1 && heap[childTwoIndex] < heap[childOneIndex]) { + indexToSwap = childTwoIndex; + } else { + indexToSwap = childOneIndex; + } + + if (heap[currentIndex] > heap[indexToSwap]) { + _swap(currentIndex, indexToSwap, heap); + currentIndex = indexToSwap; + childOneIndex = (2 * currentIndex) + 1; + } else { + break; + } + } + } + + void insert(int value) { + this.heap.add(value); + _siftUp(this.heap.length - 1); + } + + int remove() { + if (!isEmpty()) { + _swap(0, this.heap.length - 1, this.heap); + int minElement = this.heap.removeLast(); + _siftDown(0, this.heap.length - 1, this.heap); + return minElement; + } + return null; + } + + void _swap(int left, int right, List array) { + int temp; + temp = array[left]; + array[left] = array[right]; + array[right] = temp; + } +} + +void main() { + MinHeap minheap = new MinHeap(); + List array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]; + minheap.buildHeap(array); + test(('remove'), () { + expect(minheap.remove(), equals(-5)); + }); + + test(('insert and peek'), () { + minheap.insert(-100); + expect(minheap.peek(), equals(-100)); + }); + + test(('insert and remove'), () { + minheap.insert(-100); + expect(minheap.remove(), equals(-100)); + }); + + test(('remove'), () { + expect(minheap.remove(), equals(-100)); + }); + + test(('remove'), () { + expect(minheap.peek(), equals(2)); + }); +} From 3ecf4f4da03b64f61067db6416d15311ed615732 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 17 Oct 2020 05:23:06 +0000 Subject: [PATCH 162/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b762924d..243d56d3 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -16,6 +16,7 @@ * Heap * Binary Heap * [Min Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Min_Heap.dart) + * [Min Heap Two](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/min_heap_two.dart) * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list.dart) * Queue * [List Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/List_Queue.dart) From 91d9a02dadb8fad0b36421e02957e169572bb1cc Mon Sep 17 00:00:00 2001 From: richikchanda1999 Date: Sat, 17 Oct 2020 15:22:12 +0530 Subject: [PATCH 163/443] Added implementation for Nth Fibonacci Number using Dynamic Programming --- maths/fibonacci_dynamic_programming.dart | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 maths/fibonacci_dynamic_programming.dart diff --git a/maths/fibonacci_dynamic_programming.dart b/maths/fibonacci_dynamic_programming.dart new file mode 100644 index 00000000..ecc092d3 --- /dev/null +++ b/maths/fibonacci_dynamic_programming.dart @@ -0,0 +1,22 @@ +//Title: Nth Fibonacci Number using Dynamic Programming +//Author: Richik Chanda +//Email: richikchanda1999@gmail.com +List dp; +int mod = (1e9 + 7).toInt(); + +//Get the nth Fibonacci number modulo 10^9 + 7 since it can be a very large number +int getFib(int n) { + if (dp[n] == -1) dp[n] = (getFib(n - 1) % mod) + (getFib(n - 2) % mod); + return dp[n] % mod; +} + +//Driver +void main() { + dp = List.generate((1e6 + 1).toInt(), (e) => -1); + dp[0] = 0; + dp[1] = 1; + + getFib(100); + //Printing the first 100 fibonacci numbers + print("First 100 Fibonacci numbers: ${dp.sublist(1, 100)}"); +} From 781d1ca5bf9b8516cea1e2abd993257569b9f744 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sat, 17 Oct 2020 20:30:29 +0530 Subject: [PATCH 164/443] Added pigeonhole sort --- sort/pigeonhole_sort.dart | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sort/pigeonhole_sort.dart diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart new file mode 100644 index 00000000..dc3b75e6 --- /dev/null +++ b/sort/pigeonhole_sort.dart @@ -0,0 +1,48 @@ +void pigeonholeSort(List arr) { + //The length of the list + int n = arr.length; + + //Find minimum and maximum values in arr + int min = arr[0]; + int max = arr[0]; + + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + if (arr[i] > max) + max = arr[i]; + } + + int range = max - min; + range++; + + List phole = new List(range); + for(int i =0; i0) + arr[index++]=j+min; + +} + +void main() { + List list = [87, 48, 5, 7, 135, 85]; + print('Before sorting:'); + print(list); + print('--------------------------------------'); + print('After sorting:'); + pigeonholeSort(list); + print(list); +} From 565d757f6e21492fa121ae30bf462660ac0c8884 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 17 Oct 2020 15:01:02 +0000 Subject: [PATCH 165/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5cca334f..416c7ec4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -119,6 +119,7 @@ * [Heap Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/heap_Sort.dart) * [Insert Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/insert_Sort.dart) * [Merge Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/merge_sort.dart) + * [Pigeonhole Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/pigeonhole_sort.dart) * [Quick Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/quick_Sort.dart) * [Select Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/select_Sort.dart) * [Shell Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/shell_Sort.dart) From 0d60347e2d055344632b0c2d2dbdf5978f2e9d37 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sat, 17 Oct 2020 20:37:37 +0530 Subject: [PATCH 166/443] Pigeonhole sort updated --- sort/pigeonhole_sort.dart | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index dc3b75e6..7f4eb3b2 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -4,38 +4,38 @@ void pigeonholeSort(List arr) { //Find minimum and maximum values in arr int min = arr[0]; - int max = arr[0]; + int max = arr[0]; - for (int i = 1; i < n; i++) - { - if (arr[i] < min) - min = arr[i]; - if (arr[i] > max) - max = arr[i]; - } + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + if (arr[i] > max) + max = arr[i]; + } int range = max - min; range++; - List phole = new List(range); + List phole = new List(range); for(int i =0; i0) - arr[index++]=j+min; + int index = 0; -} + for(int j = 0; j0) + arr[index++]=j+min; + +} void main() { List list = [87, 48, 5, 7, 135, 85]; From 69b547f545db4c229b67c0a27afc726df973652b Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sat, 17 Oct 2020 20:43:02 +0530 Subject: [PATCH 167/443] Updaetd --- sort/pigeonhole_sort.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index 7f4eb3b2..e7d01ad1 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -18,12 +18,12 @@ void pigeonholeSort(List arr) { range++; List phole = new List(range); - for(int i =0; i Date: Sat, 17 Oct 2020 20:58:15 +0530 Subject: [PATCH 168/443] Foramted the dart file --- sort/pigeonhole_sort.dart | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index e7d01ad1..e769fd40 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -6,35 +6,29 @@ void pigeonholeSort(List arr) { int min = arr[0]; int max = arr[0]; - for (int i = 1; i < n; i++) - { - if (arr[i] < min) - min = arr[i]; - if (arr[i] > max) - max = arr[i]; + for (int i = 1; i < n; i++) { + if (arr[i] < min) min = arr[i]; + if (arr[i] > max) max = arr[i]; } int range = max - min; range++; List phole = new List(range); - for(int i =0; i0) - arr[index++]=j+min; + for (int j = 0; j < range; j++) while (phole[j]-- > 0) arr[index++] = j + min; } void main() { From 3643c59e0998394f2e0b04f67df9cf30025836d8 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 20:59:20 +0530 Subject: [PATCH 169/443] Fixed tests for edge cases corrected and fixed the edge case of the empty string. --- strings/knuth_morris_prat.dart | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/strings/knuth_morris_prat.dart b/strings/knuth_morris_prat.dart index 50e90e9a..5564ddcb 100644 --- a/strings/knuth_morris_prat.dart +++ b/strings/knuth_morris_prat.dart @@ -9,8 +9,8 @@ import 'package:test/test.dart'; /// Step through the text one character at a time and compare it to a character in /// the pattern updating our location within the pattern if necessary bool stringCompare(String string, String subString) { - if (subString.isEmpty || string.isEmpty) { - return true; + if (subString.isEmpty) { + return false; } List pattern = @@ -89,7 +89,13 @@ void main() { }); test(('KMP: '), () { string = ''; + subString = 'asd'; + expect(stringCompare(string, subString), isFalse); + }); + + test(('KMP: '), () { + string = 'asd'; subString = ''; - expect(stringCompare(string, subString), isTrue); + expect(stringCompare(string, subString), isFalse); }); } From c8b1f9b18bfd4e0c84b328f9a6c82dbbfcc5826a Mon Sep 17 00:00:00 2001 From: Vishnu P <36571320+VishnuPothan@users.noreply.github.com> Date: Sat, 17 Oct 2020 21:44:25 +0530 Subject: [PATCH 170/443] Update sort/pigeonhole_sort.dart Co-authored-by: Parowicz --- sort/pigeonhole_sort.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index e769fd40..2ef1b113 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + void pigeonholeSort(List arr) { //The length of the list int n = arr.length; From 71518ee48824f7ee657347c74b25bb73b73cf0b1 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sat, 17 Oct 2020 21:50:15 +0530 Subject: [PATCH 171/443] empty list warning fixed --- sort/pigeonhole_sort.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index e769fd40..03803281 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -2,6 +2,11 @@ void pigeonholeSort(List arr) { //The length of the list int n = arr.length; + //checking the size + if (n <= 0) { + return; + } + //Find minimum and maximum values in arr int min = arr[0]; int max = arr[0]; From 665fc823ad5a9de6e305d056a1665bce04c24476 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 22:22:28 +0530 Subject: [PATCH 172/443] Update min_heap_two.dart Updated test cases removed improper test cases added a single complete test for a single heap and verified major scenarios --- .../Heap/Binary_Heap/min_heap_two.dart | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/data_structures/Heap/Binary_Heap/min_heap_two.dart b/data_structures/Heap/Binary_Heap/min_heap_two.dart index 05512749..2d32bde0 100644 --- a/data_structures/Heap/Binary_Heap/min_heap_two.dart +++ b/data_structures/Heap/Binary_Heap/min_heap_two.dart @@ -8,8 +8,7 @@ class MinHeap { } List _heapify(List array) { - int firstParent; - firstParent = (array.length - 2) ~/ 2; + int firstParent = (array.length - 2) ~/ 2; for (int i = firstParent; i >= 0; i--) { _siftDown(i, array.length - 1, array); } @@ -28,8 +27,7 @@ class MinHeap { } void _siftUp(int currentIndex) { - int parentIndex; - parentIndex = (currentIndex - 1) ~/ 2; + int parentIndex = (currentIndex - 1) ~/ 2; while ( parentIndex >= 0 && this.heap[parentIndex] > this.heap[currentIndex]) { _swap(parentIndex, currentIndex, this.heap); @@ -93,6 +91,10 @@ void main() { expect(minheap.remove(), equals(-5)); }); + test(('is empty'), () { + expect(minheap.isEmpty(), isFalse); + }); + test(('insert and peek'), () { minheap.insert(-100); expect(minheap.peek(), equals(-100)); @@ -101,13 +103,21 @@ void main() { test(('insert and remove'), () { minheap.insert(-100); expect(minheap.remove(), equals(-100)); - }); - - test(('remove'), () { expect(minheap.remove(), equals(-100)); }); - test(('remove'), () { - expect(minheap.peek(), equals(2)); + test(('combined min heap tests'), () { + array = [-7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8]; + minheap = new MinHeap(); + minheap.buildHeap(array); + expect(minheap.remove(), equals(-10)); + expect(minheap.peek(), equals(-10)); + minheap.insert(-8); + expect(minheap.peek(), equals(-10)); + expect(minheap.remove(), equals(-10)); + expect(minheap.peek(), equals(-9)); + expect(minheap.isEmpty(), isFalse); + minheap.insert(-8); + expect(minheap.peek(), equals(-9)); }); } From 5d79dfea408c9a95aa50f6e97b6e85806ce23023 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 23:01:53 +0530 Subject: [PATCH 173/443] Update min_heap_two.dart Combined multiple tests to one single case to avoid runtime/ parallel execution errors --- data_structures/Heap/Binary_Heap/min_heap_two.dart | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/data_structures/Heap/Binary_Heap/min_heap_two.dart b/data_structures/Heap/Binary_Heap/min_heap_two.dart index 2d32bde0..35493280 100644 --- a/data_structures/Heap/Binary_Heap/min_heap_two.dart +++ b/data_structures/Heap/Binary_Heap/min_heap_two.dart @@ -87,26 +87,17 @@ void main() { MinHeap minheap = new MinHeap(); List array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]; minheap.buildHeap(array); - test(('remove'), () { + test(('Test case 1'), () { expect(minheap.remove(), equals(-5)); - }); - - test(('is empty'), () { expect(minheap.isEmpty(), isFalse); - }); - - test(('insert and peek'), () { minheap.insert(-100); expect(minheap.peek(), equals(-100)); - }); - - test(('insert and remove'), () { minheap.insert(-100); expect(minheap.remove(), equals(-100)); expect(minheap.remove(), equals(-100)); }); - test(('combined min heap tests'), () { + test(('Test case 2'), () { array = [-7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8]; minheap = new MinHeap(); minheap.buildHeap(array); From 9521c1f406ae33f176a9594c46c3f24637b7ef53 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 23:55:50 +0530 Subject: [PATCH 174/443] coin change Dynamic programming Adding the Famous DP problem of coin change where we are given a target amount and an array which consists of the coin denominations we have. we have to find the minimum number of coins required to make the amount Note: I have used 10^12 as int max in this case as I was reluctant to use double.infinity --- dynamic_programming/coin_change.dart | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 dynamic_programming/coin_change.dart diff --git a/dynamic_programming/coin_change.dart b/dynamic_programming/coin_change.dart new file mode 100644 index 00000000..4f3367be --- /dev/null +++ b/dynamic_programming/coin_change.dart @@ -0,0 +1,39 @@ +import 'dart:math'; +import 'package:test/test.dart'; + +/// we build an array which calculates the min coins for all amounts upto n +/// +/// bottom up approach where we calculate the number of coins used for each +/// amount from 1 to n for each coin. +/// 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); + + amounts[0] = 0; + + for (int currentCoin in coinDenoms) { + for (int amount = currentCoin; amount <= targetAmount; amount++) { + amounts[amount] = min(amounts[amount], amounts[amount - currentCoin] + 1); + } + } + if (amounts[targetAmount] != 1000000000000) { + return amounts[targetAmount]; + } + return -1; +} + +void main() { + test(('testCase #1'), () { + expect(minNumberOfCoins(7, [1, 5, 10]), equals(3)); + }); + + test(('testCase #2'), () { + expect(minNumberOfCoins(7, [3, 5]), equals(-1)); + }); + + test(('testCase #3'), () { + expect(minNumberOfCoins(9, [3, 4, 5]), equals(2)); + }); +} From db901990093afb0467f87ffa65c04097e5ad748f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 17 Oct 2020 18:26:06 +0000 Subject: [PATCH 175/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b1f538b7..fc8513a9 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -27,6 +27,7 @@ * [Linked List Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Linked_List_Stack.dart) ## Dynamic Programming + * [Coin Change](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/coin_change.dart) * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) ## Graphs From 89f3523772e2a73add7d453160ff658f19a681c9 Mon Sep 17 00:00:00 2001 From: Vishnu P <36571320+VishnuPothan@users.noreply.github.com> Date: Sun, 18 Oct 2020 07:33:37 +0530 Subject: [PATCH 176/443] Update test cases Co-authored-by: Parowicz --- sort/pigeonhole_sort.dart | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/sort/pigeonhole_sort.dart b/sort/pigeonhole_sort.dart index e92ea4f5..8415600d 100644 --- a/sort/pigeonhole_sort.dart +++ b/sort/pigeonhole_sort.dart @@ -39,11 +39,28 @@ void pigeonholeSort(List arr) { } void main() { - List list = [87, 48, 5, 7, 135, 85]; - print('Before sorting:'); - print(list); - print('--------------------------------------'); - print('After sorting:'); - pigeonholeSort(list); - print(list); + test("Sort empty list returns empty list", () { + List list = []; + pigeonholeSort(list); + expect(list, isEmpty); + }); + + test("Already sorted list remain sorted", () { + List list = [1, 2, 3, 4, 5]; + pigeonholeSort(list); + expect(list, equals([1, 2, 3, 4, 5])); + }); + + test("Sort", () { + List list = [87, 48, 5, 7, 135, 85]; + pigeonholeSort(list); + expect(list, equals([5, 7, 48, 85, 87, 135])); + }); + + test("Sorted list size doesnt change", () { + List list = [1, 1, 4, 1, -12, -12, 77]; + pigeonholeSort(list); + expect(list.length, equals(7)); + expect(list, [-12, -12, 1, 1, 1, 4, 77]); + }); } From f22d79d54cfa95772dc792c379954b2394901dcb Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sun, 18 Oct 2020 09:51:22 +0530 Subject: [PATCH 177/443] Create Max_heap.dart Added maxHeap implementation in dart re raising PR as the last PR did not show checks Added required test cases --- .../Heap/Binary_Heap/Max_heap.dart | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 data_structures/Heap/Binary_Heap/Max_heap.dart diff --git a/data_structures/Heap/Binary_Heap/Max_heap.dart b/data_structures/Heap/Binary_Heap/Max_heap.dart new file mode 100644 index 00000000..f7b4b4de --- /dev/null +++ b/data_structures/Heap/Binary_Heap/Max_heap.dart @@ -0,0 +1,115 @@ +import 'package:test/test.dart'; + +class MaxHeap { + List heap; + + void buildHeap(List array) { + this.heap = _heapify(array); + } + + List _heapify(List array) { + int firstParent = (array.length - 2) ~/ 2; + for (int i = firstParent; i >= 0; i--) { + _siftDown(i, array.length - 1, array); + } + return array; + } + + int peek() { + if (!isEmpty()) { + return this.heap[0]; + } + return null; + } + + bool isEmpty() { + return this.heap.length == 0; + } + + void _siftUp(int currentIndex) { + int parentIndex = (currentIndex - 1) ~/ 2; + while ( + parentIndex >= 0 && this.heap[parentIndex] < this.heap[currentIndex]) { + _swap(parentIndex, currentIndex, this.heap); + currentIndex = parentIndex; + parentIndex = (currentIndex - 1) ~/ 2; + } + } + + void _siftDown(int currentIndex, int endIndex, List heap) { + int childOneIndex = (2 * currentIndex) + 1; + int childTwoIndex; + + while (childOneIndex <= endIndex) { + childTwoIndex = + 2 * currentIndex + 2 <= endIndex ? 2 * currentIndex + 2 : -1; + int indexToSwap; + if (childTwoIndex != -1 && heap[childTwoIndex] > heap[childOneIndex]) { + indexToSwap = childTwoIndex; + } else { + indexToSwap = childOneIndex; + } + + if (heap[currentIndex] < heap[indexToSwap]) { + _swap(currentIndex, indexToSwap, heap); + currentIndex = indexToSwap; + childOneIndex = (2 * currentIndex) + 1; + } else { + break; + } + } + } + + void insert(int value) { + this.heap.add(value); + _siftUp(this.heap.length - 1); + } + + int remove() { + if (!isEmpty()) { + _swap(0, this.heap.length - 1, this.heap); + int maxElement = this.heap.removeLast(); + _siftDown(0, this.heap.length - 1, this.heap); + return maxElement; + } + return null; + } + + void _swap(int left, int right, List array) { + int temp; + temp = array[left]; + array[left] = array[right]; + array[right] = temp; + } +} + +void main() { + MaxHeap maxHeap = new MaxHeap(); + List array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]; + maxHeap.buildHeap(array); + test(('Test case 1'), () { + expect(maxHeap.remove(), equals(391)); + maxHeap.insert(-100); + expect(maxHeap.isEmpty(), isFalse); + expect(maxHeap.peek(), equals(56)); + maxHeap.insert(1000); + expect(maxHeap.peek(), equals(1000)); + expect(maxHeap.remove(), equals(1000)); + expect(maxHeap.remove(), equals(56)); + }); + + test(('Test case 2'), () { + array = [-7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8]; + maxHeap = new MaxHeap(); + maxHeap.buildHeap(array); + expect(maxHeap.remove(), equals(10)); + expect(maxHeap.peek(), equals(9)); + maxHeap.insert(890); + expect(maxHeap.peek(), equals(890)); + expect(maxHeap.remove(), equals(890)); + expect(maxHeap.peek(), equals(9)); + expect(maxHeap.isEmpty(), isFalse); + maxHeap.insert(1); + expect(maxHeap.peek(), equals(9)); + }); +} From cfaaf6e427a47181b756bd0d048cc4fc536b4b4b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 04:21:34 +0000 Subject: [PATCH 178/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index eaa7aacd..1b757341 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -16,6 +16,7 @@ * [Hashing](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/Hashing.dart) * Heap * Binary Heap + * [Max Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Max_heap.dart) * [Min Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Min_Heap.dart) * [Min Heap Two](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/min_heap_two.dart) * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list.dart) From d96f3919c22b9a2c4e364ee13bea6249fa97876e Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 15:22:06 +0530 Subject: [PATCH 179/443] Create magic_number.dart This Pull request is for HacktoberFest 2020 --- magic_number.dart | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 magic_number.dart diff --git a/magic_number.dart b/magic_number.dart new file mode 100644 index 00000000..2d83fabe --- /dev/null +++ b/magic_number.dart @@ -0,0 +1,22 @@ +import 'dart:math'; + +bool Magic_no(var x) { + var n = x; + var s = n.toString(); + var d = s.length; + var result = x%9; + if(result != 1) { + return false; + } + else return true; +} + +void main() { + for (var x in [0, 10, 370, 371, 509, 501]) { + if (Magic_no(x)) { + print("${x} is magic number"); + } else { + print("${x} is not magic number"); + } + } +} From 4134c5c1946dfd15d0ac4a093f6d76601563179b Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 15:50:48 +0530 Subject: [PATCH 180/443] Update magic_number.dart --- magic_number.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/magic_number.dart b/magic_number.dart index 2d83fabe..7d2dc284 100644 --- a/magic_number.dart +++ b/magic_number.dart @@ -4,11 +4,11 @@ bool Magic_no(var x) { var n = x; var s = n.toString(); var d = s.length; - var result = x%9; - if(result != 1) { + var result = x % 9; + if (result != 1) { return false; - } - else return true; + } else + return true; } void main() { From a9a7b80f06be0733d6e61a2f58cea593148d8c51 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 16:24:19 +0530 Subject: [PATCH 181/443] Create N_bonacci.dart This Pull Request is for HacktoberFest 2020 --- N_bonacci.dart | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 N_bonacci.dart diff --git a/N_bonacci.dart b/N_bonacci.dart new file mode 100644 index 00000000..a5f2d3a3 --- /dev/null +++ b/N_bonacci.dart @@ -0,0 +1,21 @@ +void N_bonacci(int n, int m) { + var v = new List(m); + var i; + for (i = 0; i < m; i++) { + v[i] = 0; + } + v[n - 1] = 1; + v[n] = 1; + for (i = n + 1; i < m; i++) { + v[i] = 2 * v[i - 1] - v[i - 1 - n]; + } + + print(v); +} + +void main() { + N_bonacci(5, 10); + N_bonacci(4, 12); + N_bonacci(6, 13); + N_bonacci(8, 19); +} From a87cc3a1ca1c895795a536f81baf0e1473889145 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 16:43:30 +0530 Subject: [PATCH 182/443] Update magic_number.dart Co-authored-by: Parowicz --- magic_number.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/magic_number.dart b/magic_number.dart index 7d2dc284..92efc632 100644 --- a/magic_number.dart +++ b/magic_number.dart @@ -1,4 +1,4 @@ -import 'dart:math'; +import 'package:test/test.dart'; bool Magic_no(var x) { var n = x; From ea550529383dafa807cb8dd99f7ad5d94a3d20e3 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 16:43:40 +0530 Subject: [PATCH 183/443] Update magic_number.dart Co-authored-by: Parowicz --- magic_number.dart | 3 --- 1 file changed, 3 deletions(-) diff --git a/magic_number.dart b/magic_number.dart index 92efc632..b75c9d69 100644 --- a/magic_number.dart +++ b/magic_number.dart @@ -1,9 +1,6 @@ import 'package:test/test.dart'; bool Magic_no(var x) { - var n = x; - var s = n.toString(); - var d = s.length; var result = x % 9; if (result != 1) { return false; From 5ac48e11613c28f7edb0ee457dbb55c6a4e03417 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 16:43:49 +0530 Subject: [PATCH 184/443] Update magic_number.dart Co-authored-by: Parowicz --- magic_number.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/magic_number.dart b/magic_number.dart index b75c9d69..232bc322 100644 --- a/magic_number.dart +++ b/magic_number.dart @@ -2,10 +2,7 @@ import 'package:test/test.dart'; bool Magic_no(var x) { var result = x % 9; - if (result != 1) { - return false; - } else - return true; + return result == 1; } void main() { From 71f1f6155a23d407ff58d3ac057c2da790e983aa Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 16:46:38 +0530 Subject: [PATCH 185/443] Update magic_number.dart Co-authored-by: Parowicz --- magic_number.dart | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/magic_number.dart b/magic_number.dart index 232bc322..b13e92e7 100644 --- a/magic_number.dart +++ b/magic_number.dart @@ -6,11 +6,15 @@ bool Magic_no(var x) { } void main() { - for (var x in [0, 10, 370, 371, 509, 501]) { - if (Magic_no(x)) { - print("${x} is magic number"); - } else { - print("${x} is not magic number"); - } - } + test("Test Magic_no returns false for non-magic numbers", () { + expect(Magic_no(0), isFalse); + expect(Magic_no(371), isFalse); + expect(Magic_no(509), isFalse); + expect(Magic_no(501), isFalse); + }); + + test("Test Magic_no returns true for magic numbers", () { + expect(Magic_no(10), isTrue); + expect(Magic_no(370), isTrue); + }); } From a6a30b6d32945fe421e8b1881421d8c9d4abde9e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 11:34:43 +0000 Subject: [PATCH 186/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 939e84ee..097c0427 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -35,6 +35,8 @@ ## Graphs * [Nearest Neighbour Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/graphs/nearest_neighbour_algorithm.dart) +## [Magic Number](https://github.com/TheAlgorithms/Dart/blob/master//magic_number.dart) + ## Maths * [Abs](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs.dart) * [Abs Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_max.dart) From 88390c21f19b69ce207dcfa076814621525b84b4 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 17:22:49 +0530 Subject: [PATCH 187/443] Update N_bonacci.dart Co-authored-by: Parowicz --- N_bonacci.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/N_bonacci.dart b/N_bonacci.dart index a5f2d3a3..4c6b28f6 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -1,5 +1,7 @@ -void N_bonacci(int n, int m) { - var v = new List(m); +import 'package:test/test.dart'; + +List N_bonacci(int n, int m) { + List v = new List(m); var i; for (i = 0; i < m; i++) { v[i] = 0; From 73887857db6457eb14369d74c4e142dd184ea598 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 17:22:58 +0530 Subject: [PATCH 188/443] Update N_bonacci.dart Co-authored-by: Parowicz --- N_bonacci.dart | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/N_bonacci.dart b/N_bonacci.dart index 4c6b28f6..d64f7012 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -16,8 +16,24 @@ List N_bonacci(int n, int m) { } void main() { - N_bonacci(5, 10); - N_bonacci(4, 12); - N_bonacci(6, 13); - N_bonacci(8, 19); + test("For n=2 N_bonacci is same as fibbonaci", () { + expect(N_bonacci(2, 6), equals([0, 1, 1, 2, 3, 5])); + }); + + test("For n=3 N_bonacci is same as tribbonaci", () { + expect(N_bonacci(3, 7), equals([0, 0, 1, 1, 2, 4, 7])); + }); + + test("n=4 N_bonacci", () { + expect(N_bonacci(4, 10), equals([0, 0, 0, 1, 1, 2, 4, 8, 15, 29])); + }); + + test("n=6 N_bonacci", () { + expect(N_bonacci(6, 10), equals([0, 0, 0, 0, 0, 1, 1, 2, 4, 8])); + }); + + test("n=8 N_bonacci", () { + expect(N_bonacci(8, 10), equals([0, 0, 0, 0, 0, 0, 0, 1, 1, 2])); + }); + } From 9ec82710d3f87aade5914c15e5957f581b48c3fa Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 17:23:10 +0530 Subject: [PATCH 189/443] Update N_bonacci.dart Co-authored-by: Parowicz --- N_bonacci.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/N_bonacci.dart b/N_bonacci.dart index d64f7012..784f41bc 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -12,7 +12,7 @@ List N_bonacci(int n, int m) { v[i] = 2 * v[i - 1] - v[i - 1 - n]; } - print(v); + return v; } void main() { From 7c7e9d9898fe0ba932b232dd222ed7517c25f7ed Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 18:12:26 +0530 Subject: [PATCH 190/443] Update N_bonacci.dart --- N_bonacci.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/N_bonacci.dart b/N_bonacci.dart index 784f41bc..04ade76e 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -1,3 +1,5 @@ + + import 'package:test/test.dart'; List N_bonacci(int n, int m) { From 4a30c3339b5c655c20b7f2efee70efbc15712d0e Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sun, 18 Oct 2020 14:55:39 +0200 Subject: [PATCH 191/443] Update N_bonacci.dart --- N_bonacci.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/N_bonacci.dart b/N_bonacci.dart index 04ade76e..784f41bc 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -1,5 +1,3 @@ - - import 'package:test/test.dart'; List N_bonacci(int n, int m) { From bf3b2c65a60f96b9eee3212cd824bcfe904bf78e Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sun, 18 Oct 2020 14:59:45 +0200 Subject: [PATCH 192/443] Update N_bonacci.dart --- N_bonacci.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/N_bonacci.dart b/N_bonacci.dart index 784f41bc..217417a7 100644 --- a/N_bonacci.dart +++ b/N_bonacci.dart @@ -35,5 +35,4 @@ void main() { test("n=8 N_bonacci", () { expect(N_bonacci(8, 10), equals([0, 0, 0, 0, 0, 0, 0, 1, 1, 2])); }); - } From ba1a5b4aeb661f1e37cbb280b371cc7feee782c5 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 13:04:10 +0000 Subject: [PATCH 193/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 097c0427..306f2efa 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -72,6 +72,8 @@ * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) +## [N Bonacci](https://github.com/TheAlgorithms/Dart/blob/master//N_bonacci.dart) + ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) * [Binpow](https://github.com/TheAlgorithms/Dart/blob/master/other/binpow.dart) From 85bdea5b86af13975819b474bcfe1f6f768c9010 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sun, 18 Oct 2020 19:25:14 +0530 Subject: [PATCH 194/443] Added binary to octal conversion --- conversions/binary_to_octal.dart | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 conversions/binary_to_octal.dart diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart new file mode 100644 index 00000000..05cf60f3 --- /dev/null +++ b/conversions/binary_to_octal.dart @@ -0,0 +1,42 @@ +//Author:VishnuPothan +//Binary number to octal number conversion +void main() { + print(binary_to_octal("-1111")); // -17 + print(binary_to_octal("101011")); // 53 + print(binary_to_octal("1011a01")); // error + print(binary_to_octal("")); // error +} + +String binary_to_octal(String bin_string) { + bin_string = bin_string.trim(); + if (bin_string == null || bin_string == "") { + return ("An empty value was passed to the function"); + } + bool is_negative = bin_string[0] == "-"; + if (is_negative) bin_string = bin_string.substring(1); + + String octal_val = ""; + int binary; + try { + binary = int.parse(bin_string); + } catch (e) { + return ("An invalid value was passed to the function"); + } + int curr_bit; + int j = 1; + while (binary > 0) { + int code_3 = 0; + for (int i = 0; i < 3; i++) { + curr_bit = binary % 10; + binary = binary ~/ 10; + code_3 += curr_bit * j; + j *= 2; + } + octal_val = code_3.toString() + octal_val; + j = 1; + } + if (is_negative) { + return "-" + octal_val; + } + return octal_val; +} From 7533d61d94b0bf5c3d7b39c12e6745acbcd7ac29 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 13:55:51 +0000 Subject: [PATCH 195/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 097c0427..a9d73001 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) + * [Binary To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_octal.dart) * [Decimal To Any](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Any.dart) * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) From 48e2c5465389a3f62cf82217622b5690599e9b95 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 19:42:38 +0530 Subject: [PATCH 196/443] Create sphenic_number.dart This Pull Request is for HacktoberFest 2020 --- maths/sphenic_number.dart | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 maths/sphenic_number.dart diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart new file mode 100644 index 00000000..26504463 --- /dev/null +++ b/maths/sphenic_number.dart @@ -0,0 +1,50 @@ +var arr = new List.filled(1001, 1, growable: false); +void simple_seive() { + var i; + + var p; + for (p = 2; p * p < 1001; p++) { + if (arr[p] == 1) { + for (i = p * 2; i < 1001; i = i + p) arr[i] = 0; + } + } +} + +int sphenic_number(int N) { + var arr1 = new List.filled(9, 0, growable: false); + var i; + + var count; + var j; + count = 0; + j = 0; + + for (i = 1; i <= N; i++) { + if (N % i == 0 && count < 9) { + count++; + arr1[j] = i; + j++; + } + } + + if (count == 8 && + (arr[arr1[0]] == 1 && arr[arr1[1]] == 1 && arr[arr1[2]] == 1)) return 1; + return 0; +} + +void main() { + simple_seive(); + var ans; + ans = sphenic_number(30); + print(ans); + ans = sphenic_number(60); + print(ans); + ans = sphenic_number(70); + print(ans); + ans = sphenic_number(101); + print(ans); + ans = sphenic_number(130); + print(ans); + ans = sphenic_number(240); + print(ans); +} From 60b24c4c4803f81477c14a6a92e04f56c102744d Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 19:56:27 +0530 Subject: [PATCH 197/443] Create power_of_two.dart This pull request is for HacktoberFest 2020 In this I have checked if a number is a power of 2 or not, without using logarithmic operations and by using bit manipulation. --- maths/power_of_two.dart | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 maths/power_of_two.dart diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart new file mode 100644 index 00000000..df8b6a66 --- /dev/null +++ b/maths/power_of_two.dart @@ -0,0 +1,17 @@ +void power_of_two(int n) { + int result = n & (n - 1); + if (result == 0) + print("Yes, the number $n is a power of 2"); + else + print("No, the number $n is not a power of 2"); +} + +void main() { + power_of_two(10); + power_of_two(23); + power_of_two(32); + power_of_two(2234); + power_of_two(2048); + + return; +} From 0e59beef65e244891cd3baa482221af81798f715 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:18:59 +0530 Subject: [PATCH 198/443] Create Moore_voting_algorithm.dart This is an algorithm which is used to find the majority element in an array This pull request is for HacktoberFest 2020 --- other/Moore_voting_algorithm.dart | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 other/Moore_voting_algorithm.dart diff --git a/other/Moore_voting_algorithm.dart b/other/Moore_voting_algorithm.dart new file mode 100644 index 00000000..32b5c2e9 --- /dev/null +++ b/other/Moore_voting_algorithm.dart @@ -0,0 +1,37 @@ +int majorityElement(List arr, int n) { + arr.sort(); + + var count = 1, max_ele = -1, temp = arr[0], ele = 0, f = 0; + + for (int i = 1; i < n; i++) { + if (temp == arr[i]) { + count++; + } else { + count = 1; + temp = arr[i]; + } + if (max_ele < count) { + max_ele = count; + ele = arr[i]; + + if (max_ele > (n / 2)) { + f = 1; + break; + } + } + } + return (f == 1 ? ele : -1); +} + +// Driver code +void main() { + List a1 = [1, 2, 2, 2, 2, 5, 1]; + print(majorityElement(a1, a1.length)); + List a2 = [3, 3, 22, 21, 21, 5, 21]; + print(majorityElement(a2, a2.length)); + List a3 = [30, 30, 40, 30, 40, 30, 40]; + print(majorityElement(a3, a3.length)); + List a4 = [100, 4000, 220, 220, 220, 100, 4000]; + print(majorityElement(a4, a4.length)); + return; +} From 8bce82f3a052cec7a81a974798ab396d14c7cf79 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sun, 18 Oct 2020 21:42:11 +0530 Subject: [PATCH 199/443] Floyds Algorithm for detecting loop in linkedlist Added the tortoise hare algorithm/ Floyds Algorithm for loop detection in LinkedList Added multiple verifying test cases. --- .../linked_list/cycle_in_linked_list.dart | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 data_structures/linked_list/cycle_in_linked_list.dart diff --git a/data_structures/linked_list/cycle_in_linked_list.dart b/data_structures/linked_list/cycle_in_linked_list.dart new file mode 100644 index 00000000..5582046c --- /dev/null +++ b/data_structures/linked_list/cycle_in_linked_list.dart @@ -0,0 +1,138 @@ +import 'dart:math'; +import 'package:test/test.dart'; + +class Node { + int value; + Node next = null; + Node(this.value); + + int get nodeValue { + return this.value; + } + + Node get nextNode { + return this.next; + } +} + +class LinkedList { + Node _headNode; + Node _tailNode; + + Node get head { + return this._headNode; + } + + Node get tail { + return this._tailNode; + } + + void insert(Node newNode) { + if (head == null) { + this._headNode = newNode; + this._tailNode = newNode; + } else { + this._tailNode.next = newNode; + this._tailNode = this._tailNode.next; + } + } +} + +Node createNode(int value) { + return Node(value); +} + +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 + /// and the slow pointer jumps one node at a time + /// eventually the fast and slow will coincide on a node + /// + /// Then we place one of the node back to the head. + /// 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; + + while (fastNode != null && fastNode.next != null) { + slowNode = slowNode.next; + fastNode = fastNode.next.next; + + if (slowNode == fastNode) { + break; + } + } + + if (slowNode == fastNode) { + slowNode = headNode; + while (slowNode != fastNode) { + slowNode = slowNode.next; + fastNode = fastNode.next; + } + return slowNode; + } else { + return null; + } +} + +void main() { + LinkedList linkedList = LinkedList(); + List allNodes = List(); + for (var i = 0; i <= 10; i++) { + Node newNode = createNode(i); + linkedList.insert(newNode); + allNodes.add(newNode); + } + 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); + expect(cycleNode, equals(allNodes[randomIndex])); + }); + test(('test 2'), () { + int randomIndex = random.nextInt(9); + 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); + expect(cycleNode, equals(allNodes[randomIndex])); + }); + + test(('test 4'), () { + int randomIndex = random.nextInt(9); + 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); + expect(cycleNode, equals(allNodes[randomIndex])); + }); + + test(('test 6'), () { + int randomIndex = random.nextInt(9); + 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); + expect(cycleNode, equals(allNodes[randomIndex])); + }); +} From 6370e0430a5659ef4b9cc696fc7056e66b5986bd Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:47:19 +0530 Subject: [PATCH 200/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index 26504463..b816fa9c 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -1,11 +1,8 @@ var arr = new List.filled(1001, 1, growable: false); void simple_seive() { - var i; - - var p; - for (p = 2; p * p < 1001; p++) { + for (int p = 2; p * p < 1001; p++) { if (arr[p] == 1) { - for (i = p * 2; i < 1001; i = i + p) arr[i] = 0; + for (int i = p * 2; i < 1001; i = i + p) arr[i] = 0; } } } From a2fa5080e7e51634b97dac47e096a19cd7b52724 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:47:58 +0530 Subject: [PATCH 201/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index b816fa9c..6f2bc8cf 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -16,7 +16,7 @@ int sphenic_number(int N) { count = 0; j = 0; - for (i = 1; i <= N; i++) { + for (int i = 1; i <= N; i++) { if (N % i == 0 && count < 9) { count++; arr1[j] = i; From c9719019b501efcf66bc9b437275729dbd897ef6 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:48:12 +0530 Subject: [PATCH 202/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index 6f2bc8cf..cfb5d44b 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -11,10 +11,8 @@ int sphenic_number(int N) { var arr1 = new List.filled(9, 0, growable: false); var i; - var count; - var j; - count = 0; - j = 0; + var count 0; + var j = 0; for (int i = 1; i <= N; i++) { if (N % i == 0 && count < 9) { From da56cfa8cac6bf19ba592989af4fcf7a3fe876c2 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:48:24 +0530 Subject: [PATCH 203/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index cfb5d44b..a4029247 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -9,7 +9,6 @@ void simple_seive() { int sphenic_number(int N) { var arr1 = new List.filled(9, 0, growable: false); - var i; var count 0; var j = 0; From 608d8a05614cce0bd01b11027046f5c8b120662d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 16:20:56 +0000 Subject: [PATCH 204/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 306f2efa..b4b832de 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -20,6 +20,8 @@ * [Min Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Min_Heap.dart) * [Min Heap Two](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/min_heap_two.dart) * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list.dart) + * Linked List + * [Cycle In Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/cycle_in_linked_list.dart) * Queue * [List Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/List_Queue.dart) * [Priority Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Priority_Queue.dart) From fff6ad330705f4b5a722e0f958ac153a4cf9091f Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 21:52:32 +0530 Subject: [PATCH 205/443] Update sphenic_number.dart --- maths/sphenic_number.dart | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index a4029247..97fb4515 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -1,16 +1,16 @@ -var arr = new List.filled(1001, 1, growable: false); +var arr = new List.filled(1001, true, growable: false); void simple_seive() { for (int p = 2; p * p < 1001; p++) { - if (arr[p] == 1) { - for (int i = p * 2; i < 1001; i = i + p) arr[i] = 0; + if (arr[p] == true) { + for (int i = p * 2; i < 1001; i = i + p) arr[i] = false; } } } -int sphenic_number(int N) { +bool sphenic_number(int N) { var arr1 = new List.filled(9, 0, growable: false); - var count 0; + var count = 0; var j = 0; for (int i = 1; i <= N; i++) { @@ -22,8 +22,9 @@ int sphenic_number(int N) { } if (count == 8 && - (arr[arr1[0]] == 1 && arr[arr1[1]] == 1 && arr[arr1[2]] == 1)) return 1; - return 0; + (arr[arr1[0]] == true && arr[arr1[1]] == true && arr[arr1[2]] == true)) + return true; + return false; } void main() { From 39d4d908d6995d0ea741de37102fd4ef4c75dd8b Mon Sep 17 00:00:00 2001 From: Vishnu P <36571320+VishnuPothan@users.noreply.github.com> Date: Sun, 18 Oct 2020 22:10:17 +0530 Subject: [PATCH 206/443] Update conversions/binary_to_octal.dart Co-authored-by: Parowicz --- conversions/binary_to_octal.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 05cf60f3..e1a3b958 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author:VishnuPothan //Binary number to octal number conversion void main() { From e8e8bf56b86ba8659144cac629ad1b447b0fbde2 Mon Sep 17 00:00:00 2001 From: Vishnu P <36571320+VishnuPothan@users.noreply.github.com> Date: Sun, 18 Oct 2020 22:10:55 +0530 Subject: [PATCH 207/443] Update conversions/binary_to_octal.dart Co-authored-by: Parowicz --- conversions/binary_to_octal.dart | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index e1a3b958..40adfbba 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -3,10 +3,21 @@ import 'package:test/test.dart'; //Author:VishnuPothan //Binary number to octal number conversion void main() { - print(binary_to_octal("-1111")); // -17 - print(binary_to_octal("101011")); // 53 - print(binary_to_octal("1011a01")); // error - print(binary_to_octal("")); // error + test("binary_to_octal -1111", () { + expect(binary_to_octal("-1111"), equals("-17")); + }); + + test("binary_to_octal 101011", () { + expect(binary_to_octal("101011"), equals("53")); + }); + + test("binary_to_octal rasies error when number is invalid", () { + expect(() => binary_to_octal("-1011a01"), throwsFormatException); + }); + + test("binary_to_octal of empty string raises error", () { + expect(() => binary_to_octal(""), throwsFormatException); + }); } String binary_to_octal(String bin_string) { From 999b66648b863fe0a4ef87b7ce6d1e77bb8e3479 Mon Sep 17 00:00:00 2001 From: Vishnu P <36571320+VishnuPothan@users.noreply.github.com> Date: Sun, 18 Oct 2020 22:11:17 +0530 Subject: [PATCH 208/443] Update conversions/binary_to_octal.dart Co-authored-by: Parowicz --- conversions/binary_to_octal.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 40adfbba..1119e35b 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -23,7 +23,7 @@ void main() { String binary_to_octal(String bin_string) { bin_string = bin_string.trim(); if (bin_string == null || bin_string == "") { - return ("An empty value was passed to the function"); + throw new FormatException("An empty value was passed to the function"); } bool is_negative = bin_string[0] == "-"; if (is_negative) bin_string = bin_string.substring(1); From b3148420d4de6fd56adb03f181d9448c4a59f58f Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sun, 18 Oct 2020 22:18:25 +0530 Subject: [PATCH 209/443] tests added --- conversions/binary_to_octal.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 1119e35b..30062637 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -33,7 +33,7 @@ String binary_to_octal(String bin_string) { try { binary = int.parse(bin_string); } catch (e) { - return ("An invalid value was passed to the function"); + throw new FormatException("An invalid value was passed to the function"); } int curr_bit; int j = 1; From dcee11aa7e6b54c36a1adeb1b72d3c7ba2087526 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Sun, 18 Oct 2020 22:19:56 +0530 Subject: [PATCH 210/443] Updated --- conversions/binary_to_octal.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 30062637..90126459 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -1,6 +1,5 @@ import 'package:test/test.dart'; -//Author:VishnuPothan //Binary number to octal number conversion void main() { test("binary_to_octal -1111", () { From 0ace107b76e5af8005f905a94f8707922befd54b Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 22:20:35 +0530 Subject: [PATCH 211/443] Update sphenic_number.dart --- maths/sphenic_number.dart | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index 97fb4515..a639f1d9 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + var arr = new List.filled(1001, true, growable: false); void simple_seive() { for (int p = 2; p * p < 1001; p++) { @@ -29,17 +31,14 @@ bool sphenic_number(int N) { void main() { simple_seive(); - var ans; - ans = sphenic_number(30); - print(ans); - ans = sphenic_number(60); - print(ans); - ans = sphenic_number(70); - print(ans); - ans = sphenic_number(101); - print(ans); - ans = sphenic_number(130); - print(ans); - ans = sphenic_number(240); - print(ans); +test("Test Sphenic_no returns false for non-magic numbers", () { + expect(sphenic_number(0), isFalse); + expect(sphenic_number(371), isFalse); + expect(sphenic_number(509), isFalse); + expect(sphenic_number(501), isFalse); + }); + test("Test sphenic_no returns true for magic numbers", () { + expect(sphenic_number(10), isTrue); + expect(sphenic_number(370), isTrue); + }); } From 10708600c29c599d87138106bacec9441d21e3aa Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 22:22:31 +0530 Subject: [PATCH 212/443] Update sphenic_number.dart --- maths/sphenic_number.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index a639f1d9..d9b91add 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -31,13 +31,13 @@ bool sphenic_number(int N) { void main() { simple_seive(); -test("Test Sphenic_no returns false for non-magic numbers", () { +test("Test Sphenic_no returns false for non-sphenic numbers", () { expect(sphenic_number(0), isFalse); expect(sphenic_number(371), isFalse); expect(sphenic_number(509), isFalse); expect(sphenic_number(501), isFalse); }); - test("Test sphenic_no returns true for magic numbers", () { + test("Test sphenic_no returns true for sphenic numbers", () { expect(sphenic_number(10), isTrue); expect(sphenic_number(370), isTrue); }); From 10ea524ee449c6520adbb8ccdcef9c5ad6531545 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 22:28:24 +0530 Subject: [PATCH 213/443] Update maths/power_of_two.dart Co-authored-by: Parowicz --- maths/power_of_two.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index df8b6a66..84ba7b1d 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -12,6 +12,4 @@ void main() { power_of_two(32); power_of_two(2234); power_of_two(2048); - - return; } From c8f6e2947da4251527d2f603d443e9f660b6021f Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 22:29:39 +0530 Subject: [PATCH 214/443] Update other/Moore_voting_algorithm.dart Co-authored-by: Parowicz --- other/Moore_voting_algorithm.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/other/Moore_voting_algorithm.dart b/other/Moore_voting_algorithm.dart index 32b5c2e9..4d28c94d 100644 --- a/other/Moore_voting_algorithm.dart +++ b/other/Moore_voting_algorithm.dart @@ -33,5 +33,4 @@ void main() { print(majorityElement(a3, a3.length)); List a4 = [100, 4000, 220, 220, 220, 100, 4000]; print(majorityElement(a4, a4.length)); - return; } From 6b8458f95b844580c81cb6b8df62d8a03d138cee Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:14:13 +0530 Subject: [PATCH 215/443] Create peak_element.dart This is a program to find the index of the peak element in a given array using binary search approach. A peak element is an element which is greater than both of its neighbors. This Pull Request is for HacktoberFest 2020 --- search/peak_element.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 search/peak_element.dart diff --git a/search/peak_element.dart b/search/peak_element.dart new file mode 100644 index 00000000..ea3f2d7a --- /dev/null +++ b/search/peak_element.dart @@ -0,0 +1,26 @@ +int findPeakUtil(List arr, int low, int high, int n) { + var x = (low + high) / 2; + int mid = x.toInt(); + if ((mid == 0 || arr[mid - 1] <= arr[mid]) && + (mid == n - 1 || arr[mid + 1] <= arr[mid])) + return mid; + else if (mid > 0 && arr[mid - 1] > arr[mid]) + return findPeakUtil(arr, low, (mid - 1), n); + else + return findPeakUtil(arr, (mid + 1), high, n); +} + +int findPeak(List arr, int n) { + return findPeakUtil(arr, 0, n - 1, n); +} + +void main() { + List a = [1, 3, 20, 6, 1, 2]; + print(findPeak(a, a.length)); + List b = [1, 3, 20, 32, 1, 2]; + print(findPeak(b, b.length)); + List c = [321, 4353, 22320, 232, 23, 223]; + print(findPeak(c, c.length)); + List d = [121, 54, 2100, 36, 155, 90]; + print(findPeak(d, d.length)); +} From a27051cd9a7f6e7c1b15b2a9a26754a5dc5aaadb Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:47:35 +0530 Subject: [PATCH 216/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index d9b91add..0e4961fa 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -38,7 +38,6 @@ test("Test Sphenic_no returns false for non-sphenic numbers", () { expect(sphenic_number(501), isFalse); }); test("Test sphenic_no returns true for sphenic numbers", () { - expect(sphenic_number(10), isTrue); expect(sphenic_number(370), isTrue); }); } From 430b54d5fc6a99bd8b405c80ba935af4a83eb607 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:50:02 +0530 Subject: [PATCH 217/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index 0e4961fa..8d38410a 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -31,7 +31,7 @@ bool sphenic_number(int N) { void main() { simple_seive(); -test("Test Sphenic_no returns false for non-sphenic numbers", () { + test("Test Sphenic_no returns false for non-sphenic numbers", () { expect(sphenic_number(0), isFalse); expect(sphenic_number(371), isFalse); expect(sphenic_number(509), isFalse); From 8db2085c4e581e96963df301cf096b0d8e7ed6e2 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:50:20 +0530 Subject: [PATCH 218/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index 8d38410a..ac8e1b40 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -3,7 +3,7 @@ import 'package:test/test.dart'; var arr = new List.filled(1001, true, growable: false); void simple_seive() { for (int p = 2; p * p < 1001; p++) { - if (arr[p] == true) { + if (arr[p]) { for (int i = p * 2; i < 1001; i = i + p) arr[i] = false; } } From 773f755f94095fcc702c2b3b9415526ffdd8d358 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:50:51 +0530 Subject: [PATCH 219/443] Update maths/sphenic_number.dart Co-authored-by: Parowicz --- maths/sphenic_number.dart | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/maths/sphenic_number.dart b/maths/sphenic_number.dart index ac8e1b40..4f7725ea 100644 --- a/maths/sphenic_number.dart +++ b/maths/sphenic_number.dart @@ -23,10 +23,7 @@ bool sphenic_number(int N) { } } - if (count == 8 && - (arr[arr1[0]] == true && arr[arr1[1]] == true && arr[arr1[2]] == true)) - return true; - return false; + return (count == 8 && arr[arr1[0]] && arr[arr1[1]] && arr[arr1[2]]); } void main() { From 9be216af6d4c53857752bd1e2ffd6ee1783a743a Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:57:39 +0530 Subject: [PATCH 220/443] Update maths/power_of_two.dart Co-authored-by: Parowicz --- maths/power_of_two.dart | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index 84ba7b1d..96c6774f 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -1,9 +1,7 @@ -void power_of_two(int n) { - int result = n & (n - 1); - if (result == 0) - print("Yes, the number $n is a power of 2"); - else - print("No, the number $n is not a power of 2"); +import 'package:test/test.dart'; + +bool power_of_two(int n) { + return (n & (n - 1)) == 0; } void main() { From 6a842863bb0dafbc8fa07fe9aa590665cbe2f5d8 Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Sun, 18 Oct 2020 23:58:18 +0530 Subject: [PATCH 221/443] Update maths/power_of_two.dart Co-authored-by: Parowicz --- maths/power_of_two.dart | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index 96c6774f..34e1b990 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -5,9 +5,35 @@ bool power_of_two(int n) { } void main() { - power_of_two(10); - power_of_two(23); - power_of_two(32); - power_of_two(2234); - power_of_two(2048); + test("Test power_of_two 0 returns false", () { + expect(power_of_two(0), isFalse); + }); + + test("Test power_of_two 1 returns true", () { + expect(power_of_two(1), isTrue); + }); + + test("Test power_of_two 10 returns false", () { + expect(power_of_two(10), isFalse); + }); + + test("Test power_of_two 10 returns false", () { + expect(power_of_two(10), isFalse); + }); + + test("Test power_of_two 23 returns false", () { + expect(power_of_two(23), isFalse); + }); + + test("Test power_of_two 32 returns true", () { + expect(power_of_two(32), isTrue); + }); + + test("Test power_of_two 2234 returns false", () { + expect(power_of_two(2234), isFalse); + }); + + test("Test power_of_two 2048 returns true", () { + expect(power_of_two(2048), isTrue); + }); } From 923897bfab51b43cb608285da8c8869b66eaa9cf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 18:28:38 +0000 Subject: [PATCH 222/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 7701c6ec..3119f941 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -73,6 +73,7 @@ * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Dart/blob/master/maths/sieve_of_eratosthenes.dart) * [Sigmoid](https://github.com/TheAlgorithms/Dart/blob/master/maths/sigmoid.dart) * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) + * [Sphenic Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/sphenic_number.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) ## [N Bonacci](https://github.com/TheAlgorithms/Dart/blob/master//N_bonacci.dart) From d004b76f7d63bb60e2a3acea1364d32757ee442d Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Mon, 19 Oct 2020 00:08:08 +0530 Subject: [PATCH 223/443] Update other/Moore_voting_algorithm.dart Co-authored-by: Parowicz --- other/Moore_voting_algorithm.dart | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/other/Moore_voting_algorithm.dart b/other/Moore_voting_algorithm.dart index 4d28c94d..6ef263f2 100644 --- a/other/Moore_voting_algorithm.dart +++ b/other/Moore_voting_algorithm.dart @@ -25,12 +25,19 @@ int majorityElement(List arr, int n) { // Driver code void main() { - List a1 = [1, 2, 2, 2, 2, 5, 1]; - print(majorityElement(a1, a1.length)); - List a2 = [3, 3, 22, 21, 21, 5, 21]; - print(majorityElement(a2, a2.length)); - List a3 = [30, 30, 40, 30, 40, 30, 40]; - print(majorityElement(a3, a3.length)); - List a4 = [100, 4000, 220, 220, 220, 100, 4000]; - print(majorityElement(a4, a4.length)); + test("majorityElement", () { + List a1 = [1, 2, 2, 2, 2, 5, 1]; + expect(majorityElement(a1, a1.length), equals(2)); + + List a2 = [30, 30, 40, 30, 40, 30, 40]; + expect(majorityElement(a2, a2.length), equals(30)); + }); + + test("majorityElement returns -1 when there is no dominant element", () { + List a1 = [3, 3, 22, 21, 21, 5, 21]; + expect(majorityElement(a1, a1.length), equals(-1)); + + List a2 = [100, 4000, 220, 220, 220, 100, 4000]; + expect(majorityElement(a2, a2.length), equals(-1)); + }); } From 5cf9065d01570a6aa7d9c55a5660ed62a9b2039f Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Mon, 19 Oct 2020 00:08:31 +0530 Subject: [PATCH 224/443] Update other/Moore_voting_algorithm.dart Co-authored-by: Parowicz --- other/Moore_voting_algorithm.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/other/Moore_voting_algorithm.dart b/other/Moore_voting_algorithm.dart index 6ef263f2..30806c58 100644 --- a/other/Moore_voting_algorithm.dart +++ b/other/Moore_voting_algorithm.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + int majorityElement(List arr, int n) { arr.sort(); From 1836433e68b9d597beaf8d82f2377d42a59919bd Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 18 Oct 2020 20:26:16 +0000 Subject: [PATCH 225/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 3119f941..9ab96f0d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -89,6 +89,7 @@ * [Heaps Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/heaps_algorithm.dart) * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) + * [Moore Voting Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/Moore_voting_algorithm.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) ## Project Euler From 465b3c5db8b8c56eb812a0c5ec7e996d0ff1c976 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Mon, 19 Oct 2020 09:07:45 +0530 Subject: [PATCH 226/443] Added binary to hexadecimal vale --- conversions/binary_to_hexadecimal.dart | 78 ++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 conversions/binary_to_hexadecimal.dart diff --git a/conversions/binary_to_hexadecimal.dart b/conversions/binary_to_hexadecimal.dart new file mode 100644 index 00000000..40aa70be --- /dev/null +++ b/conversions/binary_to_hexadecimal.dart @@ -0,0 +1,78 @@ +import 'package:test/test.dart'; + +//Binary number to hexadecimal number conversion +Map hex_table = { + "0000": '0', + "0001": '1', + "0010": '2', + "0011": '3', + "0100": '4', + "0101": '5', + "0110": '6', + "0111": '7', + "1000": '8', + "1001": '9', + "1010": 'A', + "1011": 'B', + "1100": 'C', + "1101": 'D', + "1110": 'E', + "1111": 'F', +}; + +// function to take a binary string and to return hex value +String binary_to_hexadecimal(String bin_string) { + // checking for unexpected values + bin_string = bin_string.trim(); + if (bin_string == null || bin_string == "") { + throw new FormatException("An empty value was passed to the function"); + } + try { + int.parse(bin_string); + } catch (e) { + throw new FormatException("An invalid value was passed to the function"); + } + + // negative number check + bool is_negative = bin_string[0] == "-"; + if (is_negative) bin_string = bin_string.substring(1); + + // add min 0's in the end to make right substring length divisible by 4 + var len_bin = bin_string.length; + for (int i = 1; i <= (4 - len_bin % 4) % 4; i++) + bin_string = '0' + bin_string; + + // coverting the binary values to hex by diving into substring + String hex_val = ""; + int i = 0; + while (i != bin_string.length) { + String bin_curr = bin_string.substring(i, i + 4); + hex_val += hex_table[bin_curr]; + i += 4; + } + + // returning the value + if (is_negative) { + return "-" + hex_val; + } + return hex_val; +} + +// driver function +void main() { + test("binary_to_hexadecimal -1111", () { + expect(binary_to_hexadecimal("-1111"), equals("-F")); + }); + + test("binary_to_hexadecimal 101011", () { + expect(binary_to_hexadecimal("101011"), equals("2B")); + }); + + test("binary_to_hexadecimal rasies error when number is invalid", () { + expect(() => binary_to_hexadecimal("-1011a01"), throwsFormatException); + }); + + test("binary_to_hexadecimal of empty string raises error", () { + expect(() => binary_to_hexadecimal(""), throwsFormatException); + }); +} From b6863d1c92de797af6e995892c3e6144a5d855cf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 19 Oct 2020 03:38:18 +0000 Subject: [PATCH 227/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9ab96f0d..9b27e40f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) + * [Binary To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_hexadecimal.dart) * [Binary To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_octal.dart) * [Decimal To Any](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Any.dart) * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) From 768767ec8150d8416fa0ef54c4ceab89e248bc50 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 19 Oct 2020 13:35:52 +0530 Subject: [PATCH 228/443] remove duplicates from string This PR is for Hacktober fest 2020. --- strings/remove duplicates | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 strings/remove duplicates diff --git a/strings/remove duplicates b/strings/remove duplicates new file mode 100644 index 00000000..47c8bb47 --- /dev/null +++ b/strings/remove duplicates @@ -0,0 +1,28 @@ +// function to remove duplicate in string +String removeDups(String s) { + int j = 0; + String l = ''; + int i = 0; + var check = 0; + for (i = 0; i < s.length; i++) { + check = 0; + var c = s[i]; + if (l.length != 0) { + for (j = 0; j < l.length; j++) { + if (c == l[j]) { + check = 1; + break; + } else + check = 0; + } + if (check == 0) l += c; + } else + l += c; + } + return l; +} + +void main() { + String s = "dsasadshadjhs"; + print(removeDups(s)); +} From fd667fb5bc07eff3e5cbb0b27ca8a3c3dd014dae Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 19 Oct 2020 14:11:41 +0530 Subject: [PATCH 229/443] roman to integer This PR is for Hactober fest 2020. --- conversions/roman to integer | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 conversions/roman to integer diff --git a/conversions/roman to integer b/conversions/roman to integer new file mode 100644 index 00000000..d8fb55c2 --- /dev/null +++ b/conversions/roman to integer @@ -0,0 +1,36 @@ +int value(var r) { + if (r == 'I') + return 1; + else if (r == 'V') + return 5; + else if (r == 'X') + return 10; + else if (r == 'L') + return 50; + else if (r == 'C') + return 100; + else if (r == 'D') + return 500; + else if (r == 'M') return 1000; + return 0; +} + +void main() { + String s = 'newnewnew'; + + int ans = 0; + for (int i = 0; i < s.length; i++) { + int num1 = value(s[i]); + if (i + 1 < s.length) { + int num2 = value(s[i + 1]); + if (num1 < num2) { + ans = ans + num2 - num1; + i++; + } else { + ans = ans + num1; + } + } else { + ans = ans + num1; + } + } +} From d7ee942390a4037613ab39db43b36a9bf65ac194 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 19 Oct 2020 15:35:14 +0530 Subject: [PATCH 230/443] reverse words of a string This PR is for Hacktober fest 2020. --- strings/reverse words of string | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 strings/reverse words of string diff --git a/strings/reverse words of string b/strings/reverse words of string new file mode 100644 index 00000000..02ec2ff7 --- /dev/null +++ b/strings/reverse words of string @@ -0,0 +1,24 @@ +String reverseStringWords(String s) { + String res = ""; + int m = s.length; + int j = m - 1; + for (int i = m - 1; i >= 0; i--) { + if (s[i] == '.') { + for (int j1 = i + 1; j1 <= j; j1++) { + res += s[j1]; + } + res += s[i]; + j = i - 1; + } else if (i == 0) { + for (int j1 = i; j1 <= j; j1++) { + res += s[j1]; + } + } + } + return res; +} + +void main() { + String s = "abhishek.is.a.good.boy"; + print(reverseStringWords(s)); +} From 1c79a8a8b05dd3811c177c1324c0c245f7ff4946 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 19 Oct 2020 16:44:47 +0530 Subject: [PATCH 231/443] swap all odd and even bits The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). This PR is for Hacktober fest 2020. --- other/swap all odd and even bits | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 other/swap all odd and even bits diff --git a/other/swap all odd and even bits b/other/swap all odd and even bits new file mode 100644 index 00000000..c501ef3a --- /dev/null +++ b/other/swap all odd and even bits @@ -0,0 +1,9 @@ +//we are given an integer,the tast is to get its binary representation,swap all odd and even bits and print the new number +int swapbits(int n) { + return (((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)); +} + +void main() { + int n = 2; + print(swapbits(n)); +} From 454e9d217f2783313c58ffd3ffb6d4870f87f260 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 17:20:30 +0530 Subject: [PATCH 232/443] Create Ugly_numbers.dart This pull request is for Hacktober Fest 2020 --- maths/Ugly_numbers.dart | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 maths/Ugly_numbers.dart diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart new file mode 100644 index 00000000..ca46a819 --- /dev/null +++ b/maths/Ugly_numbers.dart @@ -0,0 +1,37 @@ +int maxDivide(int a, int b) { + var n; + while (a % b == 0) { + n = a / b; + a = n.toInt(); + } + return a; +} + +/* Function to check if a number is ugly or not */ +int isUgly(int no) { + no = maxDivide(no, 2); + no = maxDivide(no, 3); + no = maxDivide(no, 5); + + return (no == 1) ? 1 : 0; +} + +/* Function to get the nth ugly number*/ +int getNthUglyNo(int n) { + int i = 1; + int count = 1; /* ugly number count */ + +/*Check for all integers untill ugly count + becomes n*/ + while (n > count) { + i++; + if (isUgly(i) == 1) count++; + } + return i; +} + +/* Driver program to test above functions */ +void main() { + var no = getNthUglyNo(150); + print('150th ugly no. is $no'); +} From 4b5a038f86b7a0c99a626efdd82d48448a700a06 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 17:34:43 +0200 Subject: [PATCH 233/443] Rename remove duplicates to remove duplicates.dart --- strings/{remove duplicates => remove duplicates.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename strings/{remove duplicates => remove duplicates.dart} (100%) diff --git a/strings/remove duplicates b/strings/remove duplicates.dart similarity index 100% rename from strings/remove duplicates rename to strings/remove duplicates.dart From eec72be9436c9cb5f887377dbd52e12090619b19 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 17:36:36 +0200 Subject: [PATCH 234/443] Rename roman to integer to roman_to_integer.dart --- conversions/{roman to integer => roman_to_integer.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename conversions/{roman to integer => roman_to_integer.dart} (100%) diff --git a/conversions/roman to integer b/conversions/roman_to_integer.dart similarity index 100% rename from conversions/roman to integer rename to conversions/roman_to_integer.dart From 21082caf0a68d58a186709e8f53176f4e1d0b1fd Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 17:37:10 +0200 Subject: [PATCH 235/443] Rename reverse words of string to reverse_words_of_string.dart --- strings/{reverse words of string => reverse_words_of_string.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename strings/{reverse words of string => reverse_words_of_string.dart} (100%) diff --git a/strings/reverse words of string b/strings/reverse_words_of_string.dart similarity index 100% rename from strings/reverse words of string rename to strings/reverse_words_of_string.dart From 61c2d3be69f704bf962dab6ee024b6561e7eb204 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 17:38:29 +0200 Subject: [PATCH 236/443] Rename swap all odd and even bits to swap_all_odd_and_even_bits.dart --- ...swap all odd and even bits => swap_all_odd_and_even_bits.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename other/{swap all odd and even bits => swap_all_odd_and_even_bits.dart} (100%) diff --git a/other/swap all odd and even bits b/other/swap_all_odd_and_even_bits.dart similarity index 100% rename from other/swap all odd and even bits rename to other/swap_all_odd_and_even_bits.dart From 9452f0b38169bb976e5daabb6c4d827e04376205 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Mon, 19 Oct 2020 21:37:31 +0530 Subject: [PATCH 237/443] Added map for hex to binary --- conversions/hexadecimal_to_binary.dart | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 conversions/hexadecimal_to_binary.dart diff --git a/conversions/hexadecimal_to_binary.dart b/conversions/hexadecimal_to_binary.dart new file mode 100644 index 00000000..414e87c8 --- /dev/null +++ b/conversions/hexadecimal_to_binary.dart @@ -0,0 +1,42 @@ +import 'package:test/test.dart'; + +// hexadecimal number to binary number conversion +Map hex_table = { + "0" : "0", + "1" : "1", + "2" : "10", + "3" : "11", + "4" : "100", + "5" : "101", + "6" : "110", + "7" : "111", + "8" : "1000", + "9" : "1001", + "A" : "1010", + "B" : "1011", + "C" : "1100", + "D" : "1101", + "E" : "1110", + "F" : "1111", +}; + +int hexadecimal_to_binary(String hex_value) { +} + +void main() { + test("hexadecimal_to_binary -F", () { + expect(hexadecimal_to_binary("-F"), equals("-1111")); + }); + + test("hexadecimal_to_binaryl 2B", () { + expect(hexadecimal_to_binary("2B"), equals("101011")); + }); + + test("hexadecimal_to_binary rasies error when number is invalid", () { + expect(() => hexadecimal_to_binary("AIO"), throwsFormatException); + }); + + test("hexadecimal_to_binary of empty string raises error", () { + expect(() => hexadecimal_to_binary(""), throwsFormatException); + }); +} \ No newline at end of file From c450a167ecc350db78717bd42bb7c1fdcd231c65 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 19 Oct 2020 21:48:42 +0530 Subject: [PATCH 238/443] Update strings/remove duplicates.dart Thankyou! Co-authored-by: Parowicz --- strings/remove duplicates.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/strings/remove duplicates.dart b/strings/remove duplicates.dart index 47c8bb47..6ae10a43 100644 --- a/strings/remove duplicates.dart +++ b/strings/remove duplicates.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + // function to remove duplicate in string String removeDups(String s) { int j = 0; From 44655f9ec757ce5731eb3cca8b83a4ba37086828 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Mon, 19 Oct 2020 21:55:35 +0530 Subject: [PATCH 239/443] Added hexadecimal to binary conversion --- conversions/hexadecimal_to_binary.dart | 66 ++++++++++++++++++-------- 1 file changed, 47 insertions(+), 19 deletions(-) diff --git a/conversions/hexadecimal_to_binary.dart b/conversions/hexadecimal_to_binary.dart index 414e87c8..af6b8431 100644 --- a/conversions/hexadecimal_to_binary.dart +++ b/conversions/hexadecimal_to_binary.dart @@ -1,26 +1,54 @@ import 'package:test/test.dart'; // hexadecimal number to binary number conversion -Map hex_table = { - "0" : "0", - "1" : "1", - "2" : "10", - "3" : "11", - "4" : "100", - "5" : "101", - "6" : "110", - "7" : "111", - "8" : "1000", - "9" : "1001", - "A" : "1010", - "B" : "1011", - "C" : "1100", - "D" : "1101", - "E" : "1110", - "F" : "1111", +Map bin_table = { + "0": "0", + "1": "1", + "2": "10", + "3": "11", + "4": "100", + "5": "101", + "6": "110", + "7": "111", + "8": "1000", + "9": "1001", + "A": "1010", + "B": "1011", + "C": "1100", + "D": "1101", + "E": "1110", + "F": "1111", }; -int hexadecimal_to_binary(String hex_value) { +// function to take hex value as string and return binary value as string +String hexadecimal_to_binary(String hex_value) { + // checking for unexpected values + hex_value = hex_value.trim(); + if (hex_value == null || hex_value == "") { + throw new FormatException("An empty value was passed to the function"); + } + + // negative number check + bool is_negative = hex_value[0] == "-"; + if (is_negative) hex_value = hex_value.substring(1); + + // coverting the hex to binary values by diving into substring + String bin_val = ""; + int i = 0; + while (i != hex_value.length) { + String hex_cur = hex_value.substring(i, i + 1); + if (!bin_table.containsKey(hex_cur)) { + throw new FormatException("An invalid value was passed to the function"); + } + bin_val += bin_table[hex_cur]; + i++; + } + + // returning the value + if (is_negative) { + return "-" + bin_val; + } + return bin_val; } void main() { @@ -39,4 +67,4 @@ void main() { test("hexadecimal_to_binary of empty string raises error", () { expect(() => hexadecimal_to_binary(""), throwsFormatException); }); -} \ No newline at end of file +} From 5f1d08dd368dc3269d343a5f47722e969d40780c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 19 Oct 2020 16:26:07 +0000 Subject: [PATCH 240/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9b27e40f..c18ce667 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -7,6 +7,7 @@ * [Decimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_To_Binary.dart) * [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Hexadecimal.dart) * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) + * [Hexadecimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_binary.dart) * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_decimal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) From e5e8e232362494ec3d031f0b78fd6c8bbade67f9 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 21:56:32 +0530 Subject: [PATCH 241/443] Update maths/Ugly_numbers.dart Co-authored-by: Parowicz --- maths/Ugly_numbers.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index ca46a819..f849dea7 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -8,7 +8,7 @@ int maxDivide(int a, int b) { } /* Function to check if a number is ugly or not */ -int isUgly(int no) { +bool isUgly(int no) { no = maxDivide(no, 2); no = maxDivide(no, 3); no = maxDivide(no, 5); From adaef1aa960d2a3245908c82f50b4a0f3cf06409 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 21:57:23 +0530 Subject: [PATCH 242/443] Update maths/Ugly_numbers.dart Co-authored-by: Parowicz --- maths/Ugly_numbers.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index f849dea7..636151e3 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -13,7 +13,7 @@ bool isUgly(int no) { no = maxDivide(no, 3); no = maxDivide(no, 5); - return (no == 1) ? 1 : 0; + return no == 1; } /* Function to get the nth ugly number*/ From 67ccd0a8c422c11480443112b7cb9d5eeb9f6fae Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 21:57:37 +0530 Subject: [PATCH 243/443] Update maths/Ugly_numbers.dart Co-authored-by: Parowicz --- maths/Ugly_numbers.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index 636151e3..900f3859 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + int maxDivide(int a, int b) { var n; while (a % b == 0) { From f0e917a6b886826beeeb15e40d57bb4c347ed50c Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 21:59:41 +0530 Subject: [PATCH 244/443] Update maths/Ugly_numbers.dart Co-authored-by: Parowicz --- maths/Ugly_numbers.dart | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index 900f3859..1282f712 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -34,6 +34,19 @@ int getNthUglyNo(int n) { /* Driver program to test above functions */ void main() { - var no = getNthUglyNo(150); - print('150th ugly no. is $no'); + test("getNthUglyNo(150) returns 5832", () { + expect(getNthUglyNo(150), equals(5832)); + }); + + test("isUgly returns true for 6", () { + expect(isUgly(6), isTrue); + }); + + test("isUgly returns true for 5832", () { + expect(isUgly(5832), isTrue); + }); + + test("isUgly returns false for 5833", () { + expect(isUgly(5833), isFalse); + }); } From 97481d85cbd3103137194aedee8df01db9996607 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 18:30:02 +0200 Subject: [PATCH 245/443] Add tests --- search/peak_element.dart | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/search/peak_element.dart b/search/peak_element.dart index ea3f2d7a..6dc027a2 100644 --- a/search/peak_element.dart +++ b/search/peak_element.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + int findPeakUtil(List arr, int low, int high, int n) { var x = (low + high) / 2; int mid = x.toInt(); @@ -15,12 +17,33 @@ int findPeak(List arr, int n) { } void main() { - List a = [1, 3, 20, 6, 1, 2]; - print(findPeak(a, a.length)); - List b = [1, 3, 20, 32, 1, 2]; - print(findPeak(b, b.length)); - List c = [321, 4353, 22320, 232, 23, 223]; - print(findPeak(c, c.length)); - List d = [121, 54, 2100, 36, 155, 90]; - print(findPeak(d, d.length)); + test("findPeak returns 2 for [1, 3, 20, 6, 1, 2]", () { + List lst = [1, 3, 20, 6, 1, 2]; + expect(findPeak(lst, lst.length), equals(2)); + }); + + test("findPeak returns 3 for [1, 3, 20, 32, 1, 2]", () { + List lst = [1, 3, 20, 32, 1, 2]; + expect(findPeak(lst, lst.length), equals(3)); + }); + + test("findPeak returns 2 for [321, 4353, 22320, 232, 23, 223]", () { + List lst = [321, 4353, 22320, 232, 23, 223]; + expect(findPeak(lst, lst.length), equals(2)); + }); + + test("findPeak returns 2 for [121, 54, 2100, 36, 155, 90]", () { + List lst = [121, 54, 2100, 36, 155, 90]; + expect(findPeak(lst, lst.length), equals(2)); + }); + + test("findPeak returns 2 for [5, 10, 20, 15]", () { + List lst = [5, 10, 20, 15]; + expect(findPeak(lst, lst.length), equals(2)); + }); + + test("findPeak returns 1 for [10, 20, 15, 2, 23, 90, 67]", () { + List lst = [10, 20, 15, 2, 23, 90, 67]; + expect(findPeak(lst, lst.length), equals(1)); + }); } From 4eb4494608f9f3e13498224e8ae8f44ea8b8d981 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 19 Oct 2020 16:34:26 +0000 Subject: [PATCH 246/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9b27e40f..21668c76 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -124,6 +124,7 @@ * [Interpolation Search](https://github.com/TheAlgorithms/Dart/blob/master/search/interpolation_Search.dart) * [Jump Search](https://github.com/TheAlgorithms/Dart/blob/master/search/jump_Search.dart) * [Linear Search](https://github.com/TheAlgorithms/Dart/blob/master/search/linear_Search.dart) + * [Peak Element](https://github.com/TheAlgorithms/Dart/blob/master/search/peak_element.dart) * [Ternary Search](https://github.com/TheAlgorithms/Dart/blob/master/search/ternary_Search.dart) ## Sort From 7c46c728509f1c18de0710b7b7bf9065ee2f3deb Mon Sep 17 00:00:00 2001 From: Neha Hasija Date: Mon, 19 Oct 2020 22:17:32 +0530 Subject: [PATCH 247/443] Update power_of_two.dart --- maths/power_of_two.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index 34e1b990..a419fb1f 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -1,6 +1,8 @@ import 'package:test/test.dart'; bool power_of_two(int n) { + if(n==0) + return false; return (n & (n - 1)) == 0; } From 0f8c0cfcb6b7890653f2a457ca8a8ba8b40a46ab Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 18:51:44 +0200 Subject: [PATCH 248/443] Update power_of_two.dart --- maths/power_of_two.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index a419fb1f..967784fc 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -1,8 +1,8 @@ import 'package:test/test.dart'; bool power_of_two(int n) { - if(n==0) - return false; + if (n == 0) return false; + return (n & (n - 1)) == 0; } From c67b4549f15a9346b2e1e45df0dcf887a97ae963 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 18:55:30 +0200 Subject: [PATCH 249/443] Update power_of_two.dart --- maths/power_of_two.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/power_of_two.dart b/maths/power_of_two.dart index 967784fc..cd8f485e 100644 --- a/maths/power_of_two.dart +++ b/maths/power_of_two.dart @@ -2,7 +2,7 @@ import 'package:test/test.dart'; bool power_of_two(int n) { if (n == 0) return false; - + return (n & (n - 1)) == 0; } From 107dd529c8a5a157437757e71ce7c33d5f526700 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 19 Oct 2020 16:58:53 +0000 Subject: [PATCH 250/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 96fef2c1..79c06b25 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -69,6 +69,7 @@ * [Palindrome String Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/palindrome_string_recursion.dart) * [Perfect Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/perfect_number.dart) * [Pow](https://github.com/TheAlgorithms/Dart/blob/master/maths/pow.dart) + * [Power Of Two](https://github.com/TheAlgorithms/Dart/blob/master/maths/power_of_two.dart) * [Prime Check](https://github.com/TheAlgorithms/Dart/blob/master/maths/prime_check.dart) * [Relu Function](https://github.com/TheAlgorithms/Dart/blob/master/maths/relu_function.dart) * [Shreedharacharya](https://github.com/TheAlgorithms/Dart/blob/master/maths/shreedharacharya.dart) From 2d5b983e05e7fad9573c25a6515a4523bf2ed2ab Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 22:45:33 +0530 Subject: [PATCH 251/443] Create Kynea_numbers.dart Kynea number is a positive integer of the form: 4^n + 2^(n+1)- 1 This pull request is for Hacktober Fest 2020. --- maths/Kynea_numbers.dart | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 maths/Kynea_numbers.dart diff --git a/maths/Kynea_numbers.dart b/maths/Kynea_numbers.dart new file mode 100644 index 00000000..85e93378 --- /dev/null +++ b/maths/Kynea_numbers.dart @@ -0,0 +1,37 @@ +// CPP code to find nth Kynea number + +//#include +//using namespace std; + +// Function to calculate nth kynea number +int nthKyneaNumber(int n) { + // Calculate nth kynea number + // using formula ((2^n + 1)^2 ) -2 + + // Firstly calculate 2^n + 1 + n = (1 << n) + 1; + + // Now calculate (2^n + 1)^2 + n = n * n; + + // Now calculate ((2^n + 1)^2 ) - 2 + n = n - 2; + + // return nth Kynea number + return n; +} + +// Driver Program +int main() { + int n = 8; + + // print nth kynea number + print(nthKyneaNumber(n)); + + return 0; +} +/*void main() { + for (int i = 0; i < 5; i++) { + print('hello ${i + 1}'); + } +}*/ From 153ebb247c2e60bb136c3421fc655af4416dc751 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 22:57:03 +0530 Subject: [PATCH 252/443] Update maths/Kynea_numbers.dart Co-authored-by: Parowicz --- maths/Kynea_numbers.dart | 5 ----- 1 file changed, 5 deletions(-) diff --git a/maths/Kynea_numbers.dart b/maths/Kynea_numbers.dart index 85e93378..08e5eb4d 100644 --- a/maths/Kynea_numbers.dart +++ b/maths/Kynea_numbers.dart @@ -30,8 +30,3 @@ int main() { return 0; } -/*void main() { - for (int i = 0; i < 5; i++) { - print('hello ${i + 1}'); - } -}*/ From 95642a8bff37bbbac20f2b3f2ca61c664784751d Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Mon, 19 Oct 2020 23:22:47 +0530 Subject: [PATCH 253/443] Depth First Search implementation Dart: Created Graph as Adjacency List representation using HashMap to store nodes as Keys and values as Dynamic List Depth-first Search and helper methods Added in test cases --- graphs/depth_first_search.dart | 106 +++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 graphs/depth_first_search.dart diff --git a/graphs/depth_first_search.dart b/graphs/depth_first_search.dart new file mode 100644 index 00000000..2d3fd513 --- /dev/null +++ b/graphs/depth_first_search.dart @@ -0,0 +1,106 @@ +import 'dart:collection'; +import 'package:test/test.dart'; + +/// Implementation of Depth First Search +/// https://en.wikipedia.org/wiki/Depth-first_search + +class Graph { + /// Adjacency List representation using dynamic list and HashMap + HashMap graph = new HashMap>(); + int numberOfNodes; + + void makeGraph() { + /// initialise all nodes with empty lists. + /// each node will have a list as value which stores + /// the nodes to which it is connected to + for (int i = 0; i < this.numberOfNodes; i++) { + this.graph[i] = List(); + } + } + + Graph(this.numberOfNodes); + + int get numberOfNodesInGraph { + return this.numberOfNodes; + } + + HashMap get graphDataStructure { + return this.graph; + } + + void addEdges(int start, int end) { + this.graph[start].add(end); + } +} + +void depthFirstSearchHelper(graph, visitedNodes, node, answer) { + if (visitedNodes[node]) { + return null; + } + visitedNodes[node] = true; + answer.add(node); + if (graph.containsKey(node)) { + for (int child in graph[node]) { + if (!visitedNodes[child]) { + depthFirstSearchHelper(graph, visitedNodes, child, answer); + } + } + } +} + +List depthFirstSearch(Graph graph, int numberOfNodes, int startNode) { + List visitedNodes = + new List.generate(numberOfNodes, (index) => false); + + List answer = List(); + depthFirstSearchHelper(graph.graph, visitedNodes, startNode, answer); + return answer; +} + +void main() { + test(('Test case 1:'), () { + int numberOfNodes = 4; + int numberOfEdges = 3; + + List> edges = [ + [0, 1], + [1, 2], + [0, 3] + ]; + Graph graph = Graph(numberOfNodes); + graph.makeGraph(); + + for (int i = 0; i < numberOfEdges; i++) { + int start = edges[i][0]; + int end = edges[i][1]; + graph.addEdges(start, end); + } + int startNode = 0; + List answer = depthFirstSearch(graph, numberOfNodes, startNode); + expect(answer, equals([0, 1, 2, 3])); + }); + + test(('Test case 2:'), () { + int numberOfNodes = 5; + int numberOfEdges = 4; + + List> edges = [ + [0, 1], + [0, 2], + [0, 3], + [2, 4] + ]; + Graph graph = Graph(numberOfNodes); + + graph.makeGraph(); + + for (int i = 0; i < numberOfEdges; i++) { + int start = edges[i][0]; + int end = edges[i][1]; + graph.addEdges(start, end); + } + int startNode = 0; + List answer = depthFirstSearch(graph, numberOfNodes, startNode); + expect(answer, equals([0, 1, 2, 4, 3])); + }); +} From 2927526f7d7d5ded8f3cb7478a4f1a05a9002d51 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Mon, 19 Oct 2020 23:31:44 +0530 Subject: [PATCH 254/443] Update Kynea_numbers.dart --- maths/Kynea_numbers.dart | 5 ----- 1 file changed, 5 deletions(-) diff --git a/maths/Kynea_numbers.dart b/maths/Kynea_numbers.dart index 08e5eb4d..88de8224 100644 --- a/maths/Kynea_numbers.dart +++ b/maths/Kynea_numbers.dart @@ -1,8 +1,3 @@ -// CPP code to find nth Kynea number - -//#include -//using namespace std; - // Function to calculate nth kynea number int nthKyneaNumber(int n) { // Calculate nth kynea number From 6b70a72a2efec1adbdd5020912a3676974ed37f0 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 19 Oct 2020 21:04:26 +0200 Subject: [PATCH 255/443] Update Ugly_numbers.dart --- maths/Ugly_numbers.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/Ugly_numbers.dart b/maths/Ugly_numbers.dart index 1282f712..d09dc210 100644 --- a/maths/Ugly_numbers.dart +++ b/maths/Ugly_numbers.dart @@ -27,7 +27,7 @@ int getNthUglyNo(int n) { becomes n*/ while (n > count) { i++; - if (isUgly(i) == 1) count++; + if (isUgly(i)) count++; } return i; } From 0f163e4890725b95f195dc17669bd3720b2dfb5e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 19 Oct 2020 19:08:01 +0000 Subject: [PATCH 256/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 79c06b25..d8e63b94 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -78,6 +78,7 @@ * [Simpson Rule](https://github.com/TheAlgorithms/Dart/blob/master/maths/simpson_rule.dart) * [Sphenic Number](https://github.com/TheAlgorithms/Dart/blob/master/maths/sphenic_number.dart) * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) + * [Ugly Numbers](https://github.com/TheAlgorithms/Dart/blob/master/maths/Ugly_numbers.dart) ## [N Bonacci](https://github.com/TheAlgorithms/Dart/blob/master//N_bonacci.dart) From 570028fde5317a1493bfbafdfd7875b259799e8a Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Tue, 20 Oct 2020 07:12:19 +0530 Subject: [PATCH 257/443] Update depth_first_search.dart nodes can be added dynamically and size need not be specified makeGaph function call added into the constructor of Graph instead of manually calling for each new Graph --- graphs/depth_first_search.dart | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/graphs/depth_first_search.dart b/graphs/depth_first_search.dart index 2d3fd513..c60ca4fc 100644 --- a/graphs/depth_first_search.dart +++ b/graphs/depth_first_search.dart @@ -7,27 +7,34 @@ import 'package:test/test.dart'; class Graph { /// Adjacency List representation using dynamic list and HashMap HashMap graph = new HashMap>(); - int numberOfNodes; + List nodes; void makeGraph() { /// initialise all nodes with empty lists. /// each node will have a list as value which stores /// the nodes to which it is connected to - for (int i = 0; i < this.numberOfNodes; i++) { - this.graph[i] = List(); + for (int i = 0; i < this.nodes.length; i++) { + this.graph[nodes[i]] = List(); } } - Graph(this.numberOfNodes); + Graph(this.nodes) { + this.makeGraph(); + } int get numberOfNodesInGraph { - return this.numberOfNodes; + return this.nodes.length; } HashMap get graphDataStructure { return this.graph; } + void addNodes(int newNode) { + this.nodes.add(newNode); + this.graph[newNode] = List(); + } + void addEdges(int start, int end) { this.graph[start].add(end); } @@ -59,7 +66,7 @@ List depthFirstSearch(Graph graph, int numberOfNodes, int startNode) { void main() { test(('Test case 1:'), () { - int numberOfNodes = 4; + List nodes = [0, 1, 2, 3]; int numberOfEdges = 3; List> edges = [ @@ -67,8 +74,7 @@ void main() { [1, 2], [0, 3] ]; - Graph graph = Graph(numberOfNodes); - graph.makeGraph(); + Graph graph = Graph(nodes); for (int i = 0; i < numberOfEdges; i++) { int start = edges[i][0]; @@ -76,12 +82,13 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = depthFirstSearch(graph, numberOfNodes, startNode); + List answer = + depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); expect(answer, equals([0, 1, 2, 3])); }); test(('Test case 2:'), () { - int numberOfNodes = 5; + List nodes = [0, 1, 2, 3, 4]; int numberOfEdges = 4; List> edges = [ @@ -90,9 +97,7 @@ void main() { [0, 3], [2, 4] ]; - Graph graph = Graph(numberOfNodes); - - graph.makeGraph(); + Graph graph = Graph(nodes); for (int i = 0; i < numberOfEdges; i++) { int start = edges[i][0]; @@ -100,7 +105,8 @@ void main() { graph.addEdges(start, end); } int startNode = 0; - List answer = depthFirstSearch(graph, numberOfNodes, startNode); + List answer = + depthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); expect(answer, equals([0, 1, 2, 4, 3])); }); } From df28d918207475e02e9142fd4a71da86cf04bf77 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 08:27:09 +0530 Subject: [PATCH 258/443] Map for hex to octal formed --- conversions/hexadecimal_to_octal.dart | 77 +++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 conversions/hexadecimal_to_octal.dart diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart new file mode 100644 index 00000000..44efd4e0 --- /dev/null +++ b/conversions/hexadecimal_to_octal.dart @@ -0,0 +1,77 @@ +import "dart:math" show pow; + +// Hexadecimal nuber to octal number conversion program +String hexadecimal_to_octal(String hex_val) { + int dec = 0; + int c = hex_val.length - 1; + // finding the decimal equivalent of the hexa decimal number + for (int i = 0; i < hex_val.length; i++) { + //extracting each character from the string. + var ch = hex_val.substring(i, i + 1); + switch (ch) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + dec = dec + int.parse(ch) * pow(16, c); + c--; + break; + case 'a': + case 'A': + dec = dec + 10 * pow(16, c); + c--; + break; + case 'b': + case 'B': + dec = dec + 11 * pow(16, c); + c--; + break; + case 'c': + case 'C': + dec = dec + 12 * pow(16, c); + c--; + break; + case 'd': + case 'D': + dec = dec + 13 * pow(16, c); + c--; + break; + case 'e': + case 'E': + dec = dec + 14 * pow(16, c); + c--; + break; + case 'f': + case 'F': + dec = dec + 15 * pow(16, c); + c--; + break; + default: + print("Invalid hexa input"); + break; + } + } + // String oct to store the octal equivalent of a hexadecimal number. + String oct = ""; + + //converting decimal to octal number. + while (dec > 0) { + oct = (dec % 8).toString() + oct; + dec ~/ 8; + } + + // Printing the final output. + return ("Equivalent Octal Value = " + oct); +} + +void main() { + // taking 1AC as an example of hexadecimal Number. + String hexa = "1AC"; + print(hexadecimal_to_octal(hexa)); +} From ac7f718affcb1c294bbf68d1302c54b2af72dc03 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 09:17:01 +0530 Subject: [PATCH 259/443] Added hex to octal --- conversions/hexadecimal_to_octal.dart | 47 +++++++++++++++++++++------ 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart index 44efd4e0..3920d56e 100644 --- a/conversions/hexadecimal_to_octal.dart +++ b/conversions/hexadecimal_to_octal.dart @@ -1,12 +1,22 @@ import "dart:math" show pow; +import 'package:test/test.dart'; // Hexadecimal nuber to octal number conversion program String hexadecimal_to_octal(String hex_val) { int dec = 0; + + // checking for null string passed to function + if (hex_val == null || hex_val == "") { + throw new FormatException("An empty value was passed to the function"); + } + + // negative number check + bool is_negative = hex_val[0] == "-"; + if (is_negative) hex_val = hex_val.substring(1); int c = hex_val.length - 1; + // finding the decimal equivalent of the hexa decimal number for (int i = 0; i < hex_val.length; i++) { - //extracting each character from the string. var ch = hex_val.substring(i, i + 1); switch (ch) { case '0': @@ -53,25 +63,42 @@ String hexadecimal_to_octal(String hex_val) { c--; break; default: - print("Invalid hexa input"); + throw new FormatException("An invalid value was passed to the function"); break; } } + // String oct to store the octal equivalent of a hexadecimal number. - String oct = ""; + String oct_val = ""; //converting decimal to octal number. while (dec > 0) { - oct = (dec % 8).toString() + oct; - dec ~/ 8; + oct_val = (dec % 8).toString() + oct_val; + dec = dec ~/ 8; } - // Printing the final output. - return ("Equivalent Octal Value = " + oct); + // returning the value + if (is_negative) { + return "-" + oct_val; + } + return oct_val; } void main() { - // taking 1AC as an example of hexadecimal Number. - String hexa = "1AC"; - print(hexadecimal_to_octal(hexa)); + // test cases with various input + test("hexadecimal_to_octal 43DF", () { + expect(hexadecimal_to_octal("43DF"), equals("41737")); + }); + + test("hexadecimal_to_octal -2CB", () { + expect(hexadecimal_to_octal("-2CB"), equals("-1313")); + }); + + test("hexadecimal_to_octal rasies error when number is invalid", () { + expect(() => hexadecimal_to_octal("AIO"), throwsFormatException); + }); + + test("hexadecimal_to_octal of empty string raises error", () { + expect(() => hexadecimal_to_octal(""), throwsFormatException); + }); } From 589dbfef0bf7fff23642842bca0b7019ab6a6781 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 09:18:05 +0530 Subject: [PATCH 260/443] Formated --- conversions/hexadecimal_to_octal.dart | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart index 3920d56e..0b272ffd 100644 --- a/conversions/hexadecimal_to_octal.dart +++ b/conversions/hexadecimal_to_octal.dart @@ -63,11 +63,12 @@ String hexadecimal_to_octal(String hex_val) { c--; break; default: - throw new FormatException("An invalid value was passed to the function"); + throw new FormatException( + "An invalid value was passed to the function"); break; } } - + // String oct to store the octal equivalent of a hexadecimal number. String oct_val = ""; From fe893bb91e1d6f4959eb8cdc30cd091fed478089 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 03:48:48 +0000 Subject: [PATCH 261/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d8e63b94..03891580 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -9,6 +9,7 @@ * [Decimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Decimal_to_Octal.dart) * [Hexadecimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_binary.dart) * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_decimal.dart) + * [Hexadecimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_octal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) ## Data Structures From f4ff79082bdd286231e00e3998973f6a12d1dfd6 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 09:21:05 +0530 Subject: [PATCH 262/443] Update --- conversions/hexadecimal_to_octal.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart index 0b272ffd..ffed7b58 100644 --- a/conversions/hexadecimal_to_octal.dart +++ b/conversions/hexadecimal_to_octal.dart @@ -1,7 +1,7 @@ import "dart:math" show pow; import 'package:test/test.dart'; -// Hexadecimal nuber to octal number conversion program +// Hexadecimal number to octal number conversion program String hexadecimal_to_octal(String hex_val) { int dec = 0; @@ -72,13 +72,13 @@ String hexadecimal_to_octal(String hex_val) { // String oct to store the octal equivalent of a hexadecimal number. String oct_val = ""; - //converting decimal to octal number. + // Converting decimal to octal number. while (dec > 0) { oct_val = (dec % 8).toString() + oct_val; dec = dec ~/ 8; } - // returning the value + // Returning the value if (is_negative) { return "-" + oct_val; } @@ -86,7 +86,7 @@ String hexadecimal_to_octal(String hex_val) { } void main() { - // test cases with various input + // Test cases with various input test("hexadecimal_to_octal 43DF", () { expect(hexadecimal_to_octal("43DF"), equals("41737")); }); From f699daef2da272902708b5eeadb58b62167c7a83 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 11:45:19 +0530 Subject: [PATCH 263/443] Added octal to binary --- conversions/octal_to_binary.dart | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 conversions/octal_to_binary.dart diff --git a/conversions/octal_to_binary.dart b/conversions/octal_to_binary.dart new file mode 100644 index 00000000..d872b2ac --- /dev/null +++ b/conversions/octal_to_binary.dart @@ -0,0 +1,22 @@ +import 'package:test/test.dart'; + +// octal number to binary number conversion +int ocatal_to_binary(String oct_val) { + // checking for unexpected values + oct_val = oct_val.trim(); + if (oct_val == null || oct_val == "") { + throw new FormatException("An empty value was passed to the function"); + } + + try { + // Actual conversion of Octal to Decimal: + int outputDecimal = int.parse(oct_val); + return outputDecimal; + } catch (e) { + throw new FormatException("An empty value was passed to the function"); + } +} + +void main() { + print(ocatal_to_binary("")); +} From 0ff3a93fefdc12d2d21bb489b00532a07656ba08 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Tue, 20 Oct 2020 19:00:09 +0530 Subject: [PATCH 264/443] Added octal to binary conversion --- conversions/octal_to_binary.dart | 64 +++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/conversions/octal_to_binary.dart b/conversions/octal_to_binary.dart index d872b2ac..ccb1fb42 100644 --- a/conversions/octal_to_binary.dart +++ b/conversions/octal_to_binary.dart @@ -1,22 +1,74 @@ +import "dart:math" show pow; import 'package:test/test.dart'; // octal number to binary number conversion -int ocatal_to_binary(String oct_val) { +String ocatal_to_binary(String oct_val) { // checking for unexpected values oct_val = oct_val.trim(); if (oct_val == null || oct_val == "") { throw new FormatException("An empty value was passed to the function"); } + // negative number check + bool is_negative = oct_val[0] == "-"; + if (is_negative) oct_val = oct_val.substring(1); + + int oct; try { - // Actual conversion of Octal to Decimal: - int outputDecimal = int.parse(oct_val); - return outputDecimal; + oct = int.parse(oct_val); } catch (e) { - throw new FormatException("An empty value was passed to the function"); + throw new FormatException("An invalid value was passed to the function"); + } + + // checking number not valid for octal is passed(0-7) + for (int i = 0; i < oct_val.length; i++) { + if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { + throw new FormatException("An invalid value was passed to the function"); + } + ; + } + + // 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)); + i++; + oct = oct ~/ 10; + } + + // converting to decimal to binary + i = 1; + while (dec_val != 0) { + bin_val = bin_val + (dec_val % 2) * i; + dec_val = dec_val ~/ 2; + i = i * 10; + } + + // returning the value + if (is_negative) { + return "-" + bin_val.toString(); } + return bin_val.toString(); } void main() { - print(ocatal_to_binary("")); + test("ocatal_to_binary 75", () { + expect(ocatal_to_binary("75"), equals("111101")); + }); + + test("ocatal_to_binary -62", () { + expect(ocatal_to_binary("-62"), equals("-110010")); + }); + + test("ocatal_to_binary rasies error when number is invalid", () { + expect(() => ocatal_to_binary("84"), throwsFormatException); + }); + + test("ocatal_to_binary rasies error when number is invalid", () { + expect(() => ocatal_to_binary("as23"), throwsFormatException); + }); + + test("ocatal_to_binary of empty string raises error", () { + expect(() => ocatal_to_binary(""), throwsFormatException); + }); } From 824c2f13265faed3effa34dc7b32e8eaf636c12d Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 13:30:45 +0000 Subject: [PATCH 265/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d8e63b94..10c8b0b7 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -10,6 +10,7 @@ * [Hexadecimal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_binary.dart) * [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_decimal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) + * [Octal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_binary.dart) ## Data Structures * Binary Tree From a2ddbdf70166f74b93ca5bcea568320752538d79 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 16:28:55 +0000 Subject: [PATCH 266/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index a227d181..e234a9c4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -40,6 +40,7 @@ * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) ## Graphs + * [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) ## [Magic Number](https://github.com/TheAlgorithms/Dart/blob/master//magic_number.dart) From 06a17f8f41361ecf9aa6a46b4f4076e0c8636abd Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Tue, 20 Oct 2020 23:23:14 +0530 Subject: [PATCH 267/443] Breadth first search Dart implementation Implemented BFS in the dart. --- graphs/breadth_first_search.dart | 101 +++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 graphs/breadth_first_search.dart diff --git a/graphs/breadth_first_search.dart b/graphs/breadth_first_search.dart new file mode 100644 index 00000000..fdd9546c --- /dev/null +++ b/graphs/breadth_first_search.dart @@ -0,0 +1,101 @@ +import 'dart:collection'; +import 'package:test/test.dart'; + +/// Implementation of Breadth First Search +/// https://en.wikipedia.org/wiki/Breadth-first_search + +class Graph { + /// Adjacency List representation using dynamic list and HashMap + HashMap graph = new HashMap>(); + List nodes; + + void makeGraph() { + /// initialise all nodes with empty lists. + /// 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(); + } + } + + Graph(this.nodes) { + this.makeGraph(); + } + + int get numberOfNodesInGraph { + return this.nodes.length; + } + + HashMap get graphDataStructure { + return this.graph; + } + + void addNodes(int newNode) { + this.nodes.add(newNode); + this.graph[newNode] = List(); + } + + void addEdges(int start, int end) { + this.graph[start].add(end); + } +} + +List breadthFirstSearch(Graph graph, int numberOfNodes, int startNode) { + Queue queue = new Queue(); + List answer = List(); + queue.add(startNode); + while (queue.isNotEmpty) { + int node = queue.removeFirst(); + answer.add(node); + for (int child in graph.graph[node]) { + queue.add(child); + } + } + return answer; +} + +void main() { + test(('Test case 1:'), () { + List nodes = [0, 1, 2]; + int numberOfEdges = 2; + + List> edges = [ + [0, 1], + [0, 2] + ]; + Graph graph = Graph(nodes); + + for (int i = 0; i < numberOfEdges; i++) { + int start = edges[i][0]; + int end = edges[i][1]; + graph.addEdges(start, end); + } + int startNode = 0; + List answer = + breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + expect(answer, equals([0, 1, 2])); + }); + + test(('Test case 2:'), () { + List nodes = [0, 1, 2, 3, 4]; + int numberOfEdges = 4; + + List> edges = [ + [0, 1], + [0, 2], + [0, 3], + [2, 4] + ]; + Graph graph = Graph(nodes); + + for (int i = 0; i < numberOfEdges; i++) { + int start = edges[i][0]; + int end = edges[i][1]; + graph.addEdges(start, end); + } + int startNode = 0; + List answer = + breadthFirstSearch(graph, graph.numberOfNodesInGraph, startNode); + expect(answer, equals([0, 1, 2, 3, 4])); + }); +} From 24389a3dd36caf45bc2d3e1b9a9ab9c8bca1c58a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 17:57:16 +0000 Subject: [PATCH 268/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e234a9c4..31d23c97 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -40,6 +40,7 @@ * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) ## Graphs + * [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) From 84b0774ee156cd4b8c73cdf02b1e78dfc0a576e6 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Wed, 21 Oct 2020 00:13:53 +0530 Subject: [PATCH 269/443] Update strings/reverse_words_of_string.dart Thankyou Co-authored-by: Parowicz --- strings/reverse_words_of_string.dart | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/strings/reverse_words_of_string.dart b/strings/reverse_words_of_string.dart index 02ec2ff7..b83995b4 100644 --- a/strings/reverse_words_of_string.dart +++ b/strings/reverse_words_of_string.dart @@ -19,6 +19,20 @@ String reverseStringWords(String s) { } void main() { - String s = "abhishek.is.a.good.boy"; - print(reverseStringWords(s)); + test("reverseStringWords single word returns same word", () { + expect(reverseStringWords("word"), equals("word")); + }); + + test("reverseStringWords w1.w2 returns w2.w1", () { + expect(reverseStringWords("w1.w2"), equals("w2.w1")); + }); + + test("reverseStringWords on empty string returns empty string", () { + expect(reverseStringWords(""), equals("")); + }); + + test("reverseStringWords", () { + expect(reverseStringWords("abhishek.is.a.good.boy"), + equals("boy.good.a.is.abhishek")); + }); } From 7a6ca41e614d334018a9a0cc0ed49d56210ff81b Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Wed, 21 Oct 2020 00:14:41 +0530 Subject: [PATCH 270/443] Update strings/reverse_words_of_string.dart Co-authored-by: Parowicz --- strings/reverse_words_of_string.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/strings/reverse_words_of_string.dart b/strings/reverse_words_of_string.dart index b83995b4..dfb41f26 100644 --- a/strings/reverse_words_of_string.dart +++ b/strings/reverse_words_of_string.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + String reverseStringWords(String s) { String res = ""; int m = s.length; From 72a5927ea9bc2fdac78b0c28a32c94c5d9e7ea45 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Wed, 21 Oct 2020 00:42:48 +0530 Subject: [PATCH 271/443] Update strings/remove duplicates.dart Co-authored-by: Parowicz --- strings/remove duplicates.dart | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/strings/remove duplicates.dart b/strings/remove duplicates.dart index 6ae10a43..fcedd8bd 100644 --- a/strings/remove duplicates.dart +++ b/strings/remove duplicates.dart @@ -25,6 +25,19 @@ String removeDups(String s) { } void main() { - String s = "dsasadshadjhs"; - print(removeDups(s)); + test("removeDups from string without duplicates returns same string", () { + expect(removeDups("1234"), equals("1234")); + }); + + test("removeDups from empty list returns empty list", () { + expect(removeDups(""), equals("")); + }); + + test("removeDups from 12341234 returns 1234", () { + expect(removeDups("12341234"), equals("1234")); + }); + + test("removeDups from aaaab returns ab", () { + expect(removeDups("aaaab"), equals("ab")); + }); } From d526c88ef15350096f9d38ca76d0634106147f40 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Wed, 21 Oct 2020 01:19:19 +0530 Subject: [PATCH 272/443] Update other/swap_all_odd_and_even_bits.dart Thankyou Co-authored-by: Parowicz --- other/swap_all_odd_and_even_bits.dart | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/other/swap_all_odd_and_even_bits.dart b/other/swap_all_odd_and_even_bits.dart index c501ef3a..e7c0639b 100644 --- a/other/swap_all_odd_and_even_bits.dart +++ b/other/swap_all_odd_and_even_bits.dart @@ -4,6 +4,15 @@ int swapbits(int n) { } void main() { - int n = 2; - print(swapbits(n)); + test("swapbits returns 1 for 2", () { + expect(swapbits(2), equals(1)); + }); + + test("swapbits returns 23 for 43", () { + expect(swapbits(43), equals(23)); + }); + + test("swapbits returns 43 for 23", () { + expect(swapbits(23), equals(43)); + }); } From 7f5d2e2c860e4e2c9f8cf868527dbf856903fe20 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Tue, 20 Oct 2020 21:52:59 +0200 Subject: [PATCH 273/443] Update swap_all_odd_and_even_bits.dart --- other/swap_all_odd_and_even_bits.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/other/swap_all_odd_and_even_bits.dart b/other/swap_all_odd_and_even_bits.dart index e7c0639b..36fa579e 100644 --- a/other/swap_all_odd_and_even_bits.dart +++ b/other/swap_all_odd_and_even_bits.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //we are given an integer,the tast is to get its binary representation,swap all odd and even bits and print the new number int swapbits(int n) { return (((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)); From 5db0c1d299754524ede84e9bd04ea541428fc2fe Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 19:59:41 +0000 Subject: [PATCH 274/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 31d23c97..cd3fb074 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -98,6 +98,7 @@ * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) * [Moore Voting Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/Moore_voting_algorithm.dart) + * [Swap All Odd And Even Bits](https://github.com/TheAlgorithms/Dart/blob/master/other/swap_all_odd_and_even_bits.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) ## Project Euler From f2078ce5d43c4f04370b8a9d67f31ffc8420e3e8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Oct 2020 20:07:58 +0000 Subject: [PATCH 275/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index cd3fb074..e6e09edc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -152,3 +152,4 @@ ## Strings * [Knuth Morris Prat](https://github.com/TheAlgorithms/Dart/blob/master/strings/knuth_morris_prat.dart) * [Reverse String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_string.dart) + * [Reverse Words Of String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_words_of_string.dart) From 09e569b29818d78d5bd7fc41ac6545d2afd164c3 Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Wed, 21 Oct 2020 01:39:11 +0530 Subject: [PATCH 276/443] Update remove duplicates.dart Time complexity is changed to O(N). --- strings/remove duplicates.dart | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/strings/remove duplicates.dart b/strings/remove duplicates.dart index fcedd8bd..839f77c4 100644 --- a/strings/remove duplicates.dart +++ b/strings/remove duplicates.dart @@ -2,24 +2,14 @@ import 'package:test/test.dart'; // function to remove duplicate in string String removeDups(String s) { - int j = 0; + var arr = new List.filled(256, 0); String l = ''; int i = 0; - var check = 0; for (i = 0; i < s.length; i++) { - check = 0; - var c = s[i]; - if (l.length != 0) { - for (j = 0; j < l.length; j++) { - if (c == l[j]) { - check = 1; - break; - } else - check = 0; - } - if (check == 0) l += c; - } else - l += c; + if (arr[s.codeUnitAt(i)] == 0) { + l += s[i]; + arr[s.codeUnitAt(i)]++; + } } return l; } From bc19a461935d4b61cff57021e0e783b786a7e005 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Wed, 21 Oct 2020 08:37:06 +0530 Subject: [PATCH 277/443] Added octal to deciaml conversion --- conversions/octal_to_decimal.dart | 67 +++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 conversions/octal_to_decimal.dart diff --git a/conversions/octal_to_decimal.dart b/conversions/octal_to_decimal.dart new file mode 100644 index 00000000..dd0dc14e --- /dev/null +++ b/conversions/octal_to_decimal.dart @@ -0,0 +1,67 @@ +import "dart:math" show pow; +import 'package:test/test.dart'; + +// octal number to decimal number conversion +String ocatal_to_decimal(String oct_val) { + // checking for unexpected values + oct_val = oct_val.trim(); + if (oct_val == null || oct_val == "") { + throw new FormatException("An empty value was passed to the function"); + } + + // negative number check + bool is_negative = oct_val[0] == "-"; + if (is_negative) oct_val = oct_val.substring(1); + + int oct; + try { + oct = int.parse(oct_val); + } catch (e) { + throw new FormatException("An invalid value was passed to the function"); + } + + // checking number not valid for octal is passed(0-7) + for (int i = 0; i < oct_val.length; i++) { + if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { + throw new FormatException("An invalid value was passed to the function"); + } + ; + } + + // converting octal to decimal + int dec_val = 0, i = 0; + while (oct != 0) { + dec_val = dec_val + ((oct % 10) * pow(8, i)); + i++; + oct = oct ~/ 10; + } + + // returning the value + if (is_negative) { + return "-" + dec_val.toString(); + } + return dec_val.toString(); +} + +void main() { + // test cases for different input + test("ocatal_to_decimal 75", () { + expect(ocatal_to_decimal("75"), equals("61")); + }); + + test("ocatal_to_decimal -62", () { + expect(ocatal_to_decimal("-62"), equals("-50")); + }); + + test("ocatal_to_decimal rasies error when number is invalid", () { + expect(() => ocatal_to_decimal("84"), throwsFormatException); + }); + + test("ocatal_to_decimal rasies error when number is invalid", () { + expect(() => ocatal_to_decimal("as23"), throwsFormatException); + }); + + test("ocatal_to_decimal of empty string raises error", () { + expect(() => ocatal_to_decimal(""), throwsFormatException); + }); +} From 876d007b2a3ae63770a213d3066f680f378a12fc Mon Sep 17 00:00:00 2001 From: Vishnu Date: Wed, 21 Oct 2020 08:39:09 +0530 Subject: [PATCH 278/443] Update --- conversions/octal_to_decimal.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/conversions/octal_to_decimal.dart b/conversions/octal_to_decimal.dart index dd0dc14e..c9038706 100644 --- a/conversions/octal_to_decimal.dart +++ b/conversions/octal_to_decimal.dart @@ -2,6 +2,8 @@ import "dart:math" show pow; import 'package:test/test.dart'; // octal number to decimal number conversion +// +// function to take oct string value and return decmal string value String ocatal_to_decimal(String oct_val) { // checking for unexpected values oct_val = oct_val.trim(); @@ -43,6 +45,7 @@ String ocatal_to_decimal(String oct_val) { return dec_val.toString(); } +// driver function void main() { // test cases for different input test("ocatal_to_decimal 75", () { From 3e38cc3ae92266344e14dc8470e4eb2fd9b28fef Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 21 Oct 2020 03:10:36 +0000 Subject: [PATCH 279/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e6e09edc..b19c92ba 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -12,6 +12,7 @@ * [Hexadecimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_octal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) * [Octal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_binary.dart) + * [Octal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_decimal.dart) ## Data Structures * Binary Tree From 035807cdcaa1670500d6accfb676956a77295c17 Mon Sep 17 00:00:00 2001 From: Vishnu Date: Wed, 21 Oct 2020 09:06:24 +0530 Subject: [PATCH 280/443] Added oct to dec --- conversions/octal_to_hexadecimal.dart | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 conversions/octal_to_hexadecimal.dart diff --git a/conversions/octal_to_hexadecimal.dart b/conversions/octal_to_hexadecimal.dart new file mode 100644 index 00000000..75c8d033 --- /dev/null +++ b/conversions/octal_to_hexadecimal.dart @@ -0,0 +1,93 @@ +import "dart:math" show pow; +import 'package:test/test.dart'; + +// octal number to hex number +Map hex_table = { + "10": "A", + "11": "B", + "12": "C", + "13": "D", + "14": "E", + "15": "F", +}; +// +// function take octal string value and return hexadecimal string value +String ocatal_to_hex(String oct_val) { + // checking for unexpected values + oct_val = oct_val.trim(); + if (oct_val == null || oct_val == "") { + throw new FormatException("An empty value was passed to the function"); + } + + // negative number check + bool is_negative = oct_val[0] == "-"; + if (is_negative) oct_val = oct_val.substring(1); + + int oct; + try { + oct = int.parse(oct_val); + } catch (e) { + throw new FormatException("An invalid value was passed to the function"); + } + + // checking number not valid for octal is passed(0-7) + for (int i = 0; i < oct_val.length; i++) { + if (!(int.parse(oct_val.substring(i, i + 1)) < 8)) { + throw new FormatException("An invalid value was passed to the function"); + } + ; + } + + // converting octal to decimal + int dec_val = 0, i = 0; + while (oct != 0) { + dec_val = dec_val + ((oct % 10) * pow(8, i)); + i++; + oct = oct ~/ 10; + } + + // converting to decimal to hex + if (dec_val == 0) { + return "0"; + } + String hex_string = ""; + while (dec_val > 0) { + String hex_val = ""; + int remainder = dec_val % 16; + dec_val = dec_val ~/ 16; + if (hex_table.containsKey(remainder.toString())) { + hex_val = hex_table[remainder.toString()]; + } else { + hex_val = remainder.toString(); + } + hex_string = hex_val + hex_string; + } + + // returning the value + if (is_negative) { + return "-" + hex_string; + } + return hex_string; +} + +void main() { + test("ocatal_to_hex 75", () { + expect(ocatal_to_hex("75"), equals("111101")); + }); + + test("ocatal_to_hex -62", () { + expect(ocatal_to_hex("-62"), equals("-110010")); + }); + + test("ocatal_to_hex rasies error when number is invalid", () { + expect(() => ocatal_to_hex("84"), throwsFormatException); + }); + + test("ocatal_to_hex rasies error when number is invalid", () { + expect(() => ocatal_to_hex("as23"), throwsFormatException); + }); + + test("ocatal_to_binary of empty string raises error", () { + expect(() => ocatal_to_binary(""), throwsFormatException); + }); +} From 818684ec009459c366216c005ad005715706cb0c Mon Sep 17 00:00:00 2001 From: Vishnu Date: Wed, 21 Oct 2020 09:12:37 +0530 Subject: [PATCH 281/443] test added --- conversions/octal_to_hexadecimal.dart | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/conversions/octal_to_hexadecimal.dart b/conversions/octal_to_hexadecimal.dart index 75c8d033..a7171c73 100644 --- a/conversions/octal_to_hexadecimal.dart +++ b/conversions/octal_to_hexadecimal.dart @@ -1,7 +1,7 @@ import "dart:math" show pow; import 'package:test/test.dart'; -// octal number to hex number +// octal number to hex number Map hex_table = { "10": "A", "11": "B", @@ -47,7 +47,7 @@ String ocatal_to_hex(String oct_val) { } // converting to decimal to hex - if (dec_val == 0) { + if (dec_val == 0) { return "0"; } String hex_string = ""; @@ -70,13 +70,15 @@ String ocatal_to_hex(String oct_val) { return hex_string; } +// driver function void main() { + // test input test("ocatal_to_hex 75", () { - expect(ocatal_to_hex("75"), equals("111101")); + expect(ocatal_to_hex("75"), equals("3D")); }); test("ocatal_to_hex -62", () { - expect(ocatal_to_hex("-62"), equals("-110010")); + expect(ocatal_to_hex("-62"), equals("-32")); }); test("ocatal_to_hex rasies error when number is invalid", () { @@ -87,7 +89,7 @@ void main() { expect(() => ocatal_to_hex("as23"), throwsFormatException); }); - test("ocatal_to_binary of empty string raises error", () { - expect(() => ocatal_to_binary(""), throwsFormatException); + test("ocatal_to_hex of empty string raises error", () { + expect(() => ocatal_to_hex(""), throwsFormatException); }); } From 1d19c3806b8a491e9f8af32cdc442614a451e173 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 21 Oct 2020 03:43:27 +0000 Subject: [PATCH 282/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e6e09edc..50b002a2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -12,6 +12,7 @@ * [Hexadecimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_octal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) * [Octal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_binary.dart) + * [Octal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_hexadecimal.dart) ## Data Structures * Binary Tree From 272f3e644b7812f7a8eab074a835f8571a17a996 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 21 Oct 2020 14:17:53 +0000 Subject: [PATCH 283/443] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 6156efb1..f8f9118e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -12,8 +12,8 @@ * [Hexadecimal To Octal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/hexadecimal_to_octal.dart) * [Integer To Roman](https://github.com/TheAlgorithms/Dart/blob/master/conversions/Integer_To_Roman.dart) * [Octal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_binary.dart) - * [Octal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_hexadecimal.dart) * [Octal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_decimal.dart) + * [Octal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_hexadecimal.dart) ## Data Structures * Binary Tree From 6947212312e6f49df3d39b1b0a84e8289fcc608b Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Wed, 21 Oct 2020 20:30:43 +0530 Subject: [PATCH 284/443] Update maths/Kynea_numbers.dart Co-authored-by: Parowicz --- maths/Kynea_numbers.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maths/Kynea_numbers.dart b/maths/Kynea_numbers.dart index 88de8224..f9ccb0a7 100644 --- a/maths/Kynea_numbers.dart +++ b/maths/Kynea_numbers.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + // Function to calculate nth kynea number int nthKyneaNumber(int n) { // Calculate nth kynea number From 168055049fd246bf0894de1a14653daa1708eaf5 Mon Sep 17 00:00:00 2001 From: Miracle <73017979+RimjhimGupta@users.noreply.github.com> Date: Wed, 21 Oct 2020 20:30:54 +0530 Subject: [PATCH 285/443] Update maths/Kynea_numbers.dart Co-authored-by: Parowicz --- maths/Kynea_numbers.dart | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/maths/Kynea_numbers.dart b/maths/Kynea_numbers.dart index f9ccb0a7..4e54ba35 100644 --- a/maths/Kynea_numbers.dart +++ b/maths/Kynea_numbers.dart @@ -19,11 +19,21 @@ int nthKyneaNumber(int n) { } // Driver Program -int main() { - int n = 8; - // print nth kynea number - print(nthKyneaNumber(n)); +void main() { + test("1th Kynea number equals to 7", () { + expect(nthKyneaNumber(1), equals(7)); + }); - return 0; + test("4th Kynea number equals to 287", () { + expect(nthKyneaNumber(4), equals(287)); + }); + + test("6th Kynea number equals to 4223", () { + expect(nthKyneaNumber(6), equals(4223)); + }); + + test("10th Kynea number equals to 1050623", () { + expect(nthKyneaNumber(10), equals(1050623)); + }); } From 3f413b5a1f3b9c2427a22562af690567aec709b8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 21 Oct 2020 16:00:39 +0000 Subject: [PATCH 286/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f8f9118e..58460a93 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -67,6 +67,7 @@ * [Find Min](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_min.dart) * [Find Min Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_min_recursion.dart) * [Hamming Distance](https://github.com/TheAlgorithms/Dart/blob/master/maths/hamming_distance.dart) + * [Kynea Numbers](https://github.com/TheAlgorithms/Dart/blob/master/maths/Kynea_numbers.dart) * [Lineardiophantineeqn](https://github.com/TheAlgorithms/Dart/blob/master/maths/LinearDiophantineEqn.dart) * [Lu Decomposition](https://github.com/TheAlgorithms/Dart/blob/master/maths/lu_decomposition.dart) * [Newton Method](https://github.com/TheAlgorithms/Dart/blob/master/maths/newton_method.dart) From 09e00f29d84ff0fd7f2463ae8d06a95664d1a313 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Thu, 22 Oct 2020 11:30:50 +0530 Subject: [PATCH 287/443] Adding minimum number of jumps DP in DART Added test cases DP problem for finding the minimum number of jumps --- dynamic_programming/min_number_of_jumps | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 dynamic_programming/min_number_of_jumps diff --git a/dynamic_programming/min_number_of_jumps b/dynamic_programming/min_number_of_jumps new file mode 100644 index 00000000..7280dd80 --- /dev/null +++ b/dynamic_programming/min_number_of_jumps @@ -0,0 +1,44 @@ +import 'dart:math'; +import 'package:test/test.dart'; + +int minimumNumberOfJumps(List array) { + List jumps = List.generate((array.length), (index) => 1000000000000); + jumps[0] = 0; + int length = array.length; + for (int i = 1; i < length; i++) { + for (int j = 0; j < i; j++) { + if (array[j] + j >= i) { + jumps[i] = min(jumps[j] + 1, jumps[i]); + } + } + } + return jumps[length - 1]; +} + +void main() { + List array; + test(('test 1'), () { + array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]; + expect(minimumNumberOfJumps(array), 4); + }); + test(('test 2'), () { + array = [1]; + expect(minimumNumberOfJumps(array), 0); + }); + test(('test 3'), () { + array = [1, 1]; + expect(minimumNumberOfJumps(array), 1); + }); + test(('test 4'), () { + array = [1, 1, 1]; + expect(minimumNumberOfJumps(array), 2); + }); + test(('test 5'), () { + array = [2, 1, 2, 3, 1, 1, 1]; + expect(minimumNumberOfJumps(array), 3); + }); + test(('test 6'), () { + array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3, 2, 3, 2, 1, 1, 1, 1]; + expect(minimumNumberOfJumps(array), 7); + }); +} From 23d0326f4c617326966f87bc69df30ef2615a830 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 22 Oct 2020 20:14:56 +0200 Subject: [PATCH 288/443] Rename min_number_of_jumps to min_number_of_jumps.dart --- .../{min_number_of_jumps => min_number_of_jumps.dart} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename dynamic_programming/{min_number_of_jumps => min_number_of_jumps.dart} (100%) diff --git a/dynamic_programming/min_number_of_jumps b/dynamic_programming/min_number_of_jumps.dart similarity index 100% rename from dynamic_programming/min_number_of_jumps rename to dynamic_programming/min_number_of_jumps.dart From e5a9c49c1f8ff3ba8b4de1ac94db50d695fe894c Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 23 Oct 2020 00:03:25 +0530 Subject: [PATCH 289/443] Update dynamic_programming/min_number_of_jumps.dart Co-authored-by: Parowicz --- dynamic_programming/min_number_of_jumps.dart | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dynamic_programming/min_number_of_jumps.dart b/dynamic_programming/min_number_of_jumps.dart index 7280dd80..117dadee 100644 --- a/dynamic_programming/min_number_of_jumps.dart +++ b/dynamic_programming/min_number_of_jumps.dart @@ -17,27 +17,27 @@ int minimumNumberOfJumps(List array) { void main() { List array; - test(('test 1'), () { + test('test 1', () { array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]; expect(minimumNumberOfJumps(array), 4); }); - test(('test 2'), () { + test('test 2', () { array = [1]; expect(minimumNumberOfJumps(array), 0); }); - test(('test 3'), () { + test('test 3', () { array = [1, 1]; expect(minimumNumberOfJumps(array), 1); }); - test(('test 4'), () { + test('test 4', () { array = [1, 1, 1]; expect(minimumNumberOfJumps(array), 2); }); - test(('test 5'), () { + test('test 5', () { array = [2, 1, 2, 3, 1, 1, 1]; expect(minimumNumberOfJumps(array), 3); }); - test(('test 6'), () { + test('test 6', () { array = [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3, 2, 3, 2, 1, 1, 1, 1]; expect(minimumNumberOfJumps(array), 7); }); From fb80972424a03bf044fe57061a7c13f1fedda2cc Mon Sep 17 00:00:00 2001 From: kjain1810 Date: Fri, 23 Oct 2020 00:07:33 +0530 Subject: [PATCH 290/443] Added circular queue --- data_structures/Queue/Circular_Queue.dart | 92 +++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 data_structures/Queue/Circular_Queue.dart diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart new file mode 100644 index 00000000..b51a1829 --- /dev/null +++ b/data_structures/Queue/Circular_Queue.dart @@ -0,0 +1,92 @@ +// author: kjain1810 +// reference: https://en.wikipedia.org/wiki/Circular_buffer +const int MAX_SIZE = 10; + +class CircularQueue{ + int start = -1, end = -1; + List queue = new List(MAX_SIZE); + + // insert elements into the queue + void enque(T element) + { + if(start == -1) + { + start = 0; + end = 0; + queue[0] = element; + return; + } + if(end == MAX_SIZE - 1 && start == 0) + { + print("The queue is full!!!"); + return; + } + if(end == start - 1) + { + print("The queue is full!!!"); + return; + } + end++; + end %= MAX_SIZE; + queue[end] = element; + } + + // remove elements from the queue + void deque() + { + if(start == -1) + { + print("The queue is empty!!!"); + return; + } + if(start == end) + { + start = -1; + end = -1; + return; + } + start++; + start %= MAX_SIZE; + } + + // get the size of the queue + int size() + { + if(start == -1) + return 0; + if(start < end) + return end - start + 1; + return (MAX_SIZE - (start - end)); + } + + // print all the elements of the queue + void printAll() + { + if(start == -1) + { + print("The queue is empty!!!"); + return; + } + int i = start; + while(i != end) + { + i++; + i %= MAX_SIZE; + print(queue[i]); + } + } +} + +void main(){ + CircularQueue Queue = new CircularQueue(); + Queue.enque(1); + Queue.enque(2); + Queue.enque(3); + Queue.enque(4); + Queue.printAll(); + Queue.deque(); + Queue.printAll(); + Queue.deque(); + print(Queue.size()); + return 0; +} \ No newline at end of file From 1b258042f32e7c716a4b7a699ecd42b83f112fc9 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 22 Oct 2020 19:23:11 +0000 Subject: [PATCH 291/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 58460a93..c7ab19b1 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -40,6 +40,7 @@ ## Dynamic Programming * [Coin Change](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/coin_change.dart) * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) + * [Min Number Of Jumps](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/min_number_of_jumps.dart) ## Graphs * [Breadth First Search](https://github.com/TheAlgorithms/Dart/blob/master/graphs/breadth_first_search.dart) From 6f2eb7947a79396f3aa202510a00b4f27dc36d31 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 22 Oct 2020 21:33:00 +0200 Subject: [PATCH 292/443] Update Circular_Queue.dart --- data_structures/Queue/Circular_Queue.dart | 48 ++++++++--------------- 1 file changed, 17 insertions(+), 31 deletions(-) diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart index b51a1829..13a35314 100644 --- a/data_structures/Queue/Circular_Queue.dart +++ b/data_structures/Queue/Circular_Queue.dart @@ -2,27 +2,23 @@ // reference: https://en.wikipedia.org/wiki/Circular_buffer const int MAX_SIZE = 10; -class CircularQueue{ +class CircularQueue { int start = -1, end = -1; List queue = new List(MAX_SIZE); // insert elements into the queue - void enque(T element) - { - if(start == -1) - { + void enque(T element) { + if (start == -1) { start = 0; end = 0; queue[0] = element; return; } - if(end == MAX_SIZE - 1 && start == 0) - { + if (end == MAX_SIZE - 1 && start == 0) { print("The queue is full!!!"); return; } - if(end == start - 1) - { + if (end == start - 1) { print("The queue is full!!!"); return; } @@ -32,15 +28,12 @@ class CircularQueue{ } // remove elements from the queue - void deque() - { - if(start == -1) - { + void deque() { + if (start == -1) { print("The queue is empty!!!"); return; } - if(start == end) - { + if (start == end) { start = -1; end = -1; return; @@ -48,28 +41,22 @@ class CircularQueue{ start++; start %= MAX_SIZE; } - + // get the size of the queue - int size() - { - if(start == -1) - return 0; - if(start < end) - return end - start + 1; + int size() { + if (start == -1) return 0; + if (start < end) return end - start + 1; return (MAX_SIZE - (start - end)); } // print all the elements of the queue - void printAll() - { - if(start == -1) - { + void printAll() { + if (start == -1) { print("The queue is empty!!!"); return; } int i = start; - while(i != end) - { + while (i != end) { i++; i %= MAX_SIZE; print(queue[i]); @@ -77,7 +64,7 @@ class CircularQueue{ } } -void main(){ +void main() { CircularQueue Queue = new CircularQueue(); Queue.enque(1); Queue.enque(2); @@ -88,5 +75,4 @@ void main(){ Queue.printAll(); Queue.deque(); print(Queue.size()); - return 0; -} \ No newline at end of file +} From 99ec64d8df29acaff9a90f29783cb5ad85855562 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 22 Oct 2020 21:37:59 +0200 Subject: [PATCH 293/443] Rename data_structures/linked_list.dart to data_structures/linked_list/linked_list.dart --- data_structures/{ => linked_list}/linked_list.dart | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data_structures/{ => linked_list}/linked_list.dart (100%) diff --git a/data_structures/linked_list.dart b/data_structures/linked_list/linked_list.dart similarity index 100% rename from data_structures/linked_list.dart rename to data_structures/linked_list/linked_list.dart From 0a08414a5bf85eba73ec56a06448506b699d71d8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 22 Oct 2020 19:38:15 +0000 Subject: [PATCH 294/443] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index c7ab19b1..1e8aa3a0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -26,9 +26,9 @@ * [Max Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Max_heap.dart) * [Min Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Min_Heap.dart) * [Min Heap Two](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/min_heap_two.dart) - * [Linked List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list.dart) * 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) * Queue * [List Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/List_Queue.dart) * [Priority Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Priority_Queue.dart) From fba13bf48c1461bcfadbe0fb0283aa1e52432127 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 23 Oct 2020 22:09:02 +0530 Subject: [PATCH 295/443] Added the validating array sub-sequence in dart Implemented the validating subsequence implementation in dart Added test cases. --- array/validate_subsequence.dart | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 array/validate_subsequence.dart diff --git a/array/validate_subsequence.dart b/array/validate_subsequence.dart new file mode 100644 index 00000000..b9063e92 --- /dev/null +++ b/array/validate_subsequence.dart @@ -0,0 +1,68 @@ +import 'package:test/test.dart'; + +bool checkIsSubSequence(List array, List sequence) { + if (array.isEmpty) { + return false; + } + + if (sequence.isEmpty) { + return true; + } + int arrayIndex = 0; + int sequenceIndex = 0; + + while (sequenceIndex < sequence.length && arrayIndex < array.length) { + if (sequence[sequenceIndex] == array[arrayIndex]) { + sequenceIndex += 1; + } + arrayIndex += 1; + } + return sequenceIndex == sequence.length; +} + +void main() { + List array; + List sequence; + + test('test 1', () { + array = [5, 1, 22, 25, 6, -1, 8, 10]; + sequence = [1, 6, -1, 10]; + expect(checkIsSubSequence(array, sequence), isTrue); + }); + + test('test 2', () { + array = [5, 1, 22, 25, 6, -1, 8, 10]; + sequence = [5, -1, 8, 10]; + expect(checkIsSubSequence(array, sequence), isTrue); + }); + + test('test 3', () { + array = [1, 1, 1, 1, 1]; + sequence = [0, 0, 0, 0]; + expect(checkIsSubSequence(array, sequence), isFalse); + }); + + test('test 4', () { + array = [1, 6, -1, 10]; + sequence = [1, 6, -1, 10]; + expect(checkIsSubSequence(array, sequence), isTrue); + }); + + test('test 5', () { + array = [1, 1, 6, 1]; + sequence = [0]; + expect(checkIsSubSequence(array, sequence), isFalse); + }); + + test('test 6', () { + array = []; + sequence = [0]; + expect(checkIsSubSequence(array, sequence), isFalse); + }); + + test('test 7', () { + array = [1, 1, 6, 1]; + sequence = []; + expect(checkIsSubSequence(array, sequence), isTrue); + }); +} From 9aba62e3a0fa29d1ac2a4d9535c1a5af6ebc7fbc Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 23 Oct 2020 16:56:03 +0000 Subject: [PATCH 296/443] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 1e8aa3a0..597b2cf0 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,4 +1,7 @@ +## Array + * [Validate Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/array/validate_subsequence.dart) + ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) * [Binary To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_hexadecimal.dart) From a1db309a7e75895384b90dcddbd5e7ba0e65e07b Mon Sep 17 00:00:00 2001 From: kjain1810 Date: Sat, 24 Oct 2020 05:46:37 +0530 Subject: [PATCH 297/443] Return value for deque added --- data_structures/Queue/Circular_Queue.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart index 13a35314..181a30c4 100644 --- a/data_structures/Queue/Circular_Queue.dart +++ b/data_structures/Queue/Circular_Queue.dart @@ -28,18 +28,20 @@ class CircularQueue { } // remove elements from the queue - void deque() { + T deque() { if (start == -1) { print("The queue is empty!!!"); - return; + return null; } + T here = queue[start]; if (start == end) { start = -1; end = -1; - return; + return here; } start++; start %= MAX_SIZE; + return here; } // get the size of the queue From b017bd27b767c223e4d3bbebc0d35318f5c40a81 Mon Sep 17 00:00:00 2001 From: Kunal Jain <30985312+kjain1810@users.noreply.github.com> Date: Sun, 25 Oct 2020 05:11:26 +0530 Subject: [PATCH 298/443] Update data_structures/Queue/Circular_Queue.dart Tests added Co-authored-by: Parowicz --- data_structures/Queue/Circular_Queue.dart | 46 ++++++++++++++++++----- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart index 181a30c4..74c639ff 100644 --- a/data_structures/Queue/Circular_Queue.dart +++ b/data_structures/Queue/Circular_Queue.dart @@ -67,14 +67,40 @@ class CircularQueue { } void main() { - CircularQueue Queue = new CircularQueue(); - Queue.enque(1); - Queue.enque(2); - Queue.enque(3); - Queue.enque(4); - Queue.printAll(); - Queue.deque(); - Queue.printAll(); - Queue.deque(); - print(Queue.size()); + test("Initial CircularQueue is empty", () { + CircularQueue queue = new CircularQueue(); + + expect(queue.deque(), isNull); + }); + + test("deque return first item put to CircularQueue", () { + CircularQueue queue = new CircularQueue(); + queue.enque(1); + + expect(queue.deque(), equals(1)); + }); + + test("CircularQueue act as fifo", () { + CircularQueue queue = new CircularQueue(); + queue.enque(1); + queue.enque(2); + queue.enque(3); + + expect(queue.deque(), equals(1)); + expect(queue.deque(), equals(2)); + expect(queue.deque(), equals(3)); + }); + + test("deque returns null after removing all items", () { + CircularQueue queue = new CircularQueue(); + queue.enque(1); + queue.enque(2); + queue.enque(3); + + queue.deque(); + queue.deque(); + queue.deque(); + + expect(queue.deque(), isNull); + }); } From 758857a4c5c699e6196cc84857d0f03db138f384 Mon Sep 17 00:00:00 2001 From: Kunal Jain <30985312+kjain1810@users.noreply.github.com> Date: Sun, 25 Oct 2020 05:11:42 +0530 Subject: [PATCH 299/443] Update data_structures/Queue/Circular_Queue.dart Co-authored-by: Parowicz --- data_structures/Queue/Circular_Queue.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/Queue/Circular_Queue.dart b/data_structures/Queue/Circular_Queue.dart index 74c639ff..6d870555 100644 --- a/data_structures/Queue/Circular_Queue.dart +++ b/data_structures/Queue/Circular_Queue.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + // author: kjain1810 // reference: https://en.wikipedia.org/wiki/Circular_buffer const int MAX_SIZE = 10; From d243bd2523a8a3317676dfe8980c368275ecee8e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 25 Oct 2020 20:20:15 +0000 Subject: [PATCH 300/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 597b2cf0..ab0e7c3a 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -33,6 +33,7 @@ * [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) * 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) * [Priority Queue](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Queue/Priority_Queue.dart) * Stack From ff37aa044300b6040663a27a84ee5e161b50f0ab Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sun, 25 Oct 2020 21:21:36 +0100 Subject: [PATCH 301/443] Update maths/fibonacci_dynamic_programming.dart --- maths/fibonacci_dynamic_programming.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maths/fibonacci_dynamic_programming.dart b/maths/fibonacci_dynamic_programming.dart index ecc092d3..81445a02 100644 --- a/maths/fibonacci_dynamic_programming.dart +++ b/maths/fibonacci_dynamic_programming.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Title: Nth Fibonacci Number using Dynamic Programming //Author: Richik Chanda //Email: richikchanda1999@gmail.com From 68689ade68f9c232ab99e8a13d21fb2ad3fbf51b Mon Sep 17 00:00:00 2001 From: Parowicz Date: Sun, 25 Oct 2020 21:21:43 +0100 Subject: [PATCH 302/443] Update maths/fibonacci_dynamic_programming.dart --- maths/fibonacci_dynamic_programming.dart | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/maths/fibonacci_dynamic_programming.dart b/maths/fibonacci_dynamic_programming.dart index 81445a02..570e3016 100644 --- a/maths/fibonacci_dynamic_programming.dart +++ b/maths/fibonacci_dynamic_programming.dart @@ -18,7 +18,20 @@ void main() { dp[0] = 0; dp[1] = 1; - getFib(100); - //Printing the first 100 fibonacci numbers - print("First 100 Fibonacci numbers: ${dp.sublist(1, 100)}"); + test("getFib 0 equals 0", () { + expect(getFib(0), equals(0)); + }); + + test("getFib 1 equals 1", () { + expect(getFib(1), equals(1)); + }); + + test("getFib 5 equals 5", () { + expect(getFib(5), equals(5)); + }); + + test("getFib(n) equals getFib(n - 1) + getFib(n - 2)", () { + expect(getFib(7), equals(getFib(6) + getFib(5))); + expect(getFib(14), equals(getFib(13) + getFib(12))); + }); } From 247968884dd997e7e13ac6bd02452ad95ba8a926 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 25 Oct 2020 20:25:44 +0000 Subject: [PATCH 303/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ab0e7c3a..9330bc3d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -66,6 +66,7 @@ * [Factorial Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/factorial_recursion.dart) * [Factors](https://github.com/TheAlgorithms/Dart/blob/master/maths/factors.dart) * [Fermats Little Theorem](https://github.com/TheAlgorithms/Dart/blob/master/maths/fermats_little_theorem.dart) + * [Fibonacci Dynamic Programming](https://github.com/TheAlgorithms/Dart/blob/master/maths/fibonacci_dynamic_programming.dart) * [Fibonacci Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/fibonacci_recursion.dart) * [Find Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_max.dart) * [Find Max Recursion](https://github.com/TheAlgorithms/Dart/blob/master/maths/find_max_recursion.dart) From 299e1d53a585dfdabe3581ffec4ea4b29d4584b5 Mon Sep 17 00:00:00 2001 From: Jerold Albertson Date: Sun, 25 Oct 2020 20:34:06 -0600 Subject: [PATCH 304/443] Create quad_tree.dart Added a QuadTree data structure. It's one of my favorite for orginizing a lot of objects in a 2D space when you'll be doing a lot of distance comparisons, but any given time you only need to search a local area. --- data_structures/quad_tree/quad_tree.dart | 209 +++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 data_structures/quad_tree/quad_tree.dart diff --git a/data_structures/quad_tree/quad_tree.dart b/data_structures/quad_tree/quad_tree.dart new file mode 100644 index 00000000..1061714f --- /dev/null +++ b/data_structures/quad_tree/quad_tree.dart @@ -0,0 +1,209 @@ +// Author: Jerold Albertson +// Profile: https://github.com/jerold + +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 +int _upperLeftIndex = 0; +int _upperRightIndex = 1; +int _lowerLeftIndex = 2; +int _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.insert("b", Point(100, 0)), isTrue); + expect(tree.insert("c", Point(0, 100)), isTrue); + 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"); + }); + }); +} From 05adb63bacb7d483ff636f429b998d25e8d5d4e0 Mon Sep 17 00:00:00 2001 From: Jerold Albertson Date: Sun, 25 Oct 2020 20:36:57 -0600 Subject: [PATCH 305/443] added a link to QuadTree on wikipedia --- data_structures/quad_tree/quad_tree.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structures/quad_tree/quad_tree.dart b/data_structures/quad_tree/quad_tree.dart index 1061714f..cfc23c9b 100644 --- a/data_structures/quad_tree/quad_tree.dart +++ b/data_structures/quad_tree/quad_tree.dart @@ -1,5 +1,6 @@ // Author: Jerold Albertson // Profile: https://github.com/jerold +// Algorithm: https://en.wikipedia.org/wiki/Quadtree import 'dart:math'; import 'package:test/test.dart'; From 8e25de097ec78e061d13d5bac30ca55e48ef5820 Mon Sep 17 00:00:00 2001 From: Jerold Albertson Date: Sun, 25 Oct 2020 20:49:31 -0600 Subject: [PATCH 306/443] fix item count bounds and add more tests --- data_structures/quad_tree/quad_tree.dart | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/data_structures/quad_tree/quad_tree.dart b/data_structures/quad_tree/quad_tree.dart index cfc23c9b..cf137e7a 100644 --- a/data_structures/quad_tree/quad_tree.dart +++ b/data_structures/quad_tree/quad_tree.dart @@ -40,7 +40,7 @@ class Node extends Rectangle { if (!containsPoint(atPoint)) return false; if (_children.isEmpty) { - if (_items.length + 1 < maxItems || _depth + 1 > maxDepth) { + if (_items.length + 1 <= maxItems || _depth + 1 > maxDepth) { _items.add(_ItemAtPoint(item, atPoint)); return true; } @@ -129,8 +129,17 @@ void main() { 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(), From ad6746e7389d108915d8281ccfd596fa15eb5efe Mon Sep 17 00:00:00 2001 From: Ganesh Agarwal <69008792+Ganesh-Agarwal-25@users.noreply.github.com> Date: Mon, 26 Oct 2020 11:38:13 +0530 Subject: [PATCH 307/443] Update roman_to_integer.dart --- conversions/roman_to_integer.dart | 50 ++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/conversions/roman_to_integer.dart b/conversions/roman_to_integer.dart index d8fb55c2..7b95e840 100644 --- a/conversions/roman_to_integer.dart +++ b/conversions/roman_to_integer.dart @@ -1,3 +1,22 @@ +int romanToInteger(var s) { + int ans = 0; + for (int i = 0; i < s.length; i++) { + int num1 = value(s[i]); + if (i + 1 < s.length) { + int num2 = value(s[i + 1]); + if (num1 < num2) { + ans = ans + num2 - num1; + i++; + } else { + ans = ans + num1; + } + } else { + ans = ans + num1; + } + } + return ans; +} + int value(var r) { if (r == 'I') return 1; @@ -16,21 +35,18 @@ int value(var r) { } void main() { - String s = 'newnewnew'; - - int ans = 0; - for (int i = 0; i < s.length; i++) { - int num1 = value(s[i]); - if (i + 1 < s.length) { - int num2 = value(s[i + 1]); - if (num1 < num2) { - ans = ans + num2 - num1; - i++; - } else { - ans = ans + num1; - } - } else { - ans = ans + num1; - } - } + String s = 'XII'; + print(romanToInteger(s)); + s = 'LII'; + print(romanToInteger(s)); + s = 'DLVII'; + print(romanToInteger(s)); + s = 'VI'; + print(romanToInteger(s)); + s = 'CLXV'; + print(romanToInteger(s)); + s = 'MDCI'; + print(romanToInteger(s)); + s = 'LVII'; + print(romanToInteger(s)); } From 6a9aafacd9a0fe43af468cdc69021ec51d407446 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 26 Oct 2020 17:30:47 +0000 Subject: [PATCH 308/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9330bc3d..b9edc0ed 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,6 +32,8 @@ * 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) * 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) From 82aecae58253cce995756ec21193818a0eea7ae7 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 26 Oct 2020 18:37:43 +0100 Subject: [PATCH 309/443] Convert `print`-s to tests --- conversions/roman_to_integer.dart | 43 +++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/conversions/roman_to_integer.dart b/conversions/roman_to_integer.dart index 7b95e840..27f8df7a 100644 --- a/conversions/roman_to_integer.dart +++ b/conversions/roman_to_integer.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + int romanToInteger(var s) { int ans = 0; for (int i = 0; i < s.length; i++) { @@ -35,18 +37,31 @@ int value(var r) { } void main() { - String s = 'XII'; - print(romanToInteger(s)); - s = 'LII'; - print(romanToInteger(s)); - s = 'DLVII'; - print(romanToInteger(s)); - s = 'VI'; - print(romanToInteger(s)); - s = 'CLXV'; - print(romanToInteger(s)); - s = 'MDCI'; - print(romanToInteger(s)); - s = 'LVII'; - print(romanToInteger(s)); + test("romanToInteger XII returns 12", () { + expect(romanToInteger('XII'), equals(12)); + }); + + test("romanToInteger LII returns 52", () { + expect(romanToInteger('LII'), equals(52)); + }); + + test("romanToInteger DLVII returns 557", () { + expect(romanToInteger('LII'), equals(52)); + }); + + test("romanToInteger VI returns 6", () { + expect(romanToInteger('VI'), equals(6)); + }); + + test("romanToInteger CLXV returns 165", () { + expect(romanToInteger('CLXV'), equals(165)); + }); + + test("romanToInteger MDCI returns 1601", () { + expect(romanToInteger('MDCI'), equals(1601)); + }); + + test("romanToInteger LVII returns 57", () { + expect(romanToInteger('LVII'), equals(57)); + }); } From c37f39941f5b25235a55958fd2358dea48c8c6a0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 26 Oct 2020 17:43:11 +0000 Subject: [PATCH 310/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b9edc0ed..5c149763 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -17,6 +17,7 @@ * [Octal To Binary](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_binary.dart) * [Octal To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_decimal.dart) * [Octal To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/octal_to_hexadecimal.dart) + * [Roman To Integer](https://github.com/TheAlgorithms/Dart/blob/master/conversions/roman_to_integer.dart) ## Data Structures * Binary Tree From ea7d162f605f37e9cf01e4ec7bc626cc599e79d8 Mon Sep 17 00:00:00 2001 From: Jerold Albertson Date: Mon, 26 Oct 2020 12:46:46 -0600 Subject: [PATCH 311/443] make private globals const addresses feedback from original quad tree pr. --- data_structures/quad_tree/quad_tree.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/data_structures/quad_tree/quad_tree.dart b/data_structures/quad_tree/quad_tree.dart index cf137e7a..b3628318 100644 --- a/data_structures/quad_tree/quad_tree.dart +++ b/data_structures/quad_tree/quad_tree.dart @@ -10,10 +10,10 @@ int default_max_depth = 1000; int default_max_items = 100; // names reflect a coordinate system where values increase as one goes left or down -int _upperLeftIndex = 0; -int _upperRightIndex = 1; -int _lowerLeftIndex = 2; -int _lowerRightIndex = 3; +const _upperLeftIndex = 0; +const _upperRightIndex = 1; +const _lowerLeftIndex = 2; +const _lowerRightIndex = 3; class Node extends Rectangle { final int maxDepth; From 12477928f462c25e06f1bfcf13dada4de8f6881f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 26 Oct 2020 21:32:37 +0000 Subject: [PATCH 312/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5c149763..d78a6883 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -163,5 +163,6 @@ ## Strings * [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) * [Reverse Words Of String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_words_of_string.dart) From da85859a2a8b7f5cab27a12c3c14b8e1ea134477 Mon Sep 17 00:00:00 2001 From: Roland Date: Tue, 27 Oct 2020 22:37:37 +0100 Subject: [PATCH 313/443] added euler project 10 --- project_euler/problem_10/sol10.dart | 68 +++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 project_euler/problem_10/sol10.dart diff --git a/project_euler/problem_10/sol10.dart b/project_euler/problem_10/sol10.dart new file mode 100644 index 00000000..ca0d1adf --- /dev/null +++ b/project_euler/problem_10/sol10.dart @@ -0,0 +1,68 @@ +/** + * Project Euler Problem 10: https://projecteuler.net/problem=10 + * Summation of primes + * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. + * Find the sum of all the primes below two million. + */ + +import 'dart:math'; +import 'package:test/test.dart'; + +void main() { + print("Solution 1 => ${solution1(2000000)}"); + print("Solution 2 => ${solution2(2000000)}"); + + test("Test isPrime", () { + expect(isPrime(-2), false); + expect(isPrime(0), false); + expect(isPrime(1), false); + expect(isPrime(2), true); + }); + + test("Test solution1", () { + expect(solution1(10), 17); + expect(solution1(20), 77); + }); + + test("Test solution2", () { + expect(solution2(10), 17); + expect(solution2(20), 77); + }); +} + +int solution1(int n) { + var sum = 0; + + for (int i = 2; i < n; i++) { + if (isPrime(i)) sum += i; + } + return sum; +} + +int solution2(int n) { + if (n <= 2) return 0; + if (n <= 3) return 2; + + var sum = 5; + var i = 5; + + while (i < n) { + if (isPrime(i)) sum += i; + i += 2; + if (i < n && isPrime(i)) sum += i; + i += 4; + } + return sum; +} + +bool isPrime(int number) { + if (number <= 1) return false; + + var root = sqrt(number).floor(); + + for (int div = 2; div <= root; div++) { + if (number % div == 0) return false; + } + + return true; +} From 28f1403408d42350b0c0715357c56383227c58d1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 27 Oct 2020 22:38:51 +0000 Subject: [PATCH 314/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d78a6883..9975258a 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -116,6 +116,8 @@ ## Project Euler * Problem 1 * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) + * Problem 10 + * [Sol10](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_10/sol10.dart) * Problem 13 * [Sol13](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_13/sol13.dart) * Problem 17 From e2a14b7bec46f6d6ad1f1247e287df4ade167201 Mon Sep 17 00:00:00 2001 From: richikchanda1999 Date: Thu, 29 Oct 2020 01:03:13 +0530 Subject: [PATCH 315/443] Added Project Euler 12 --- project_euler/problem_12/sol12.dart | 54 +++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 project_euler/problem_12/sol12.dart diff --git a/project_euler/problem_12/sol12.dart b/project_euler/problem_12/sol12.dart new file mode 100644 index 00000000..6c19002a --- /dev/null +++ b/project_euler/problem_12/sol12.dart @@ -0,0 +1,54 @@ +import 'dart:math'; + + +List prime_sieve(int limit){ + int sieve_bound = (limit - 1) ~/ 2; + int upper_sqrt = (sqrt(limit).toInt() - 1) ~/ 2; + List prime_bits = List.generate(sieve_bound + 1, (_) => true); + + for(int i = 1 ; i <= upper_sqrt ; ++i) + if (prime_bits[i]) + for(int j = i * (i + 1) * 2 ; j <= sieve_bound ; j += 2 * i + 1) + prime_bits[j] = false; + + List primes = [2]; + for(int i = 1 ; i <= sieve_bound ; ++i) + if (prime_bits[i]) + primes.add(2 * i + 1); + + return primes; +} + +int prime_factorisation_number_of_divisors(int n, List primes){ + int nod = 1; + int remain = n; + for(int i = 0 ; i < primes.length ; ++i){ + if (primes[i] * primes[i] > n) + return nod * 2; + int power = 1; + while (remain % primes[i] == 0){ + power += 1; + remain ~/= primes[i]; + } + nod *= power; + if (remain == 1) break; + } + return nod; +} + + +void main() { + int i = 2; + int count = 0; + int odd = 2; + int even = 2; + List primes = prime_sieve(500); + while (count < 500){ + even = i % 2 == 0 ? prime_factorisation_number_of_divisors(i + 1, primes) : even; + odd = i % 2 != 0 ? prime_factorisation_number_of_divisors((i + 1) ~/ 2, primes) : odd; + count = even * odd; + ++i; + } + int ans = (i * (i - 1) * 0.5).toInt(); + print("First Triangle Number with more than 500 divisors: $ans"); +} From 696e0bc3343a04b1f70cc311153162fe6105f21a Mon Sep 17 00:00:00 2001 From: Parowicz Date: Thu, 29 Oct 2020 18:01:31 +0100 Subject: [PATCH 316/443] Update sol12.dart --- project_euler/problem_12/sol12.dart | 86 ++++++++++++++--------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/project_euler/problem_12/sol12.dart b/project_euler/problem_12/sol12.dart index 6c19002a..380aa59a 100644 --- a/project_euler/problem_12/sol12.dart +++ b/project_euler/problem_12/sol12.dart @@ -1,54 +1,54 @@ import 'dart:math'; +List prime_sieve(int limit) { + int sieve_bound = (limit - 1) ~/ 2; + int upper_sqrt = (sqrt(limit).toInt() - 1) ~/ 2; + List prime_bits = List.generate(sieve_bound + 1, (_) => true); -List prime_sieve(int limit){ - int sieve_bound = (limit - 1) ~/ 2; - int upper_sqrt = (sqrt(limit).toInt() - 1) ~/ 2; - List prime_bits = List.generate(sieve_bound + 1, (_) => true); + for (int i = 1; i <= upper_sqrt; ++i) + if (prime_bits[i]) + for (int j = i * (i + 1) * 2; j <= sieve_bound; j += 2 * i + 1) + prime_bits[j] = false; - for(int i = 1 ; i <= upper_sqrt ; ++i) - if (prime_bits[i]) - for(int j = i * (i + 1) * 2 ; j <= sieve_bound ; j += 2 * i + 1) - prime_bits[j] = false; + List primes = [2]; + for (int i = 1; i <= sieve_bound; ++i) + if (prime_bits[i]) primes.add(2 * i + 1); - List primes = [2]; - for(int i = 1 ; i <= sieve_bound ; ++i) - if (prime_bits[i]) - primes.add(2 * i + 1); - - return primes; + return primes; } -int prime_factorisation_number_of_divisors(int n, List primes){ - int nod = 1; - int remain = n; - for(int i = 0 ; i < primes.length ; ++i){ - if (primes[i] * primes[i] > n) - return nod * 2; - int power = 1; - while (remain % primes[i] == 0){ - power += 1; - remain ~/= primes[i]; - } - nod *= power; - if (remain == 1) break; - } - return nod; +int prime_factorisation_number_of_divisors(int n, List primes) { + int nod = 1; + int remain = n; + for (int i = 0; i < primes.length; ++i) { + if (primes[i] * primes[i] > n) return nod * 2; + int power = 1; + while (remain % primes[i] == 0) { + power += 1; + remain ~/= primes[i]; + } + nod *= power; + if (remain == 1) break; + } + return nod; } - void main() { - int i = 2; - int count = 0; - int odd = 2; - int even = 2; - List primes = prime_sieve(500); - while (count < 500){ - even = i % 2 == 0 ? prime_factorisation_number_of_divisors(i + 1, primes) : even; - odd = i % 2 != 0 ? prime_factorisation_number_of_divisors((i + 1) ~/ 2, primes) : odd; - count = even * odd; - ++i; - } - int ans = (i * (i - 1) * 0.5).toInt(); - print("First Triangle Number with more than 500 divisors: $ans"); + int i = 2; + int count = 0; + int odd = 2; + int even = 2; + List primes = prime_sieve(500); + while (count < 500) { + even = i % 2 == 0 + ? prime_factorisation_number_of_divisors(i + 1, primes) + : even; + odd = i % 2 != 0 + ? prime_factorisation_number_of_divisors((i + 1) ~/ 2, primes) + : odd; + count = even * odd; + ++i; + } + int ans = (i * (i - 1) * 0.5).toInt(); + print("First Triangle Number with more than 500 divisors: $ans"); } From e9c134cfbc798e4422a59d6970900b0bf23c2d05 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 29 Oct 2020 17:11:08 +0000 Subject: [PATCH 317/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9975258a..f68d9f1c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -118,6 +118,8 @@ * [Sol1](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_1/sol1.dart) * Problem 10 * [Sol10](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_10/sol10.dart) + * Problem 12 + * [Sol12](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_12/sol12.dart) * Problem 13 * [Sol13](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_13/sol13.dart) * Problem 17 From eab9b8757be7c019f30c19c5a9429fa10b1a699e Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Wed, 4 Nov 2020 09:38:02 +0530 Subject: [PATCH 318/443] Added Knapsack Problem (recursive Solution) Added the recursive implementation of the 01 knapsack problem --- dynamic_programming/01knapsack_recursive.dart | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 dynamic_programming/01knapsack_recursive.dart diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart new file mode 100644 index 00000000..3f90255f --- /dev/null +++ b/dynamic_programming/01knapsack_recursive.dart @@ -0,0 +1,38 @@ +import 'dart:math'; +import 'package:test/test.dart'; + +int knapSackProblem( + int numberOfItems, int capacity, List values, List weights) { + if (numberOfItems == 0 || capacity == 0) { + return 0; + } + int currentValue = values[numberOfItems - 1]; + int currentWeight = weights[numberOfItems - 1]; + + if (weights[numberOfItems - 1] <= capacity) { + return max( + currentValue + + knapSackProblem( + numberOfItems - 1, capacity - currentWeight, values, weights), + knapSackProblem(numberOfItems - 1, capacity, values, weights)); + } else { + return knapSackProblem(numberOfItems - 1, capacity, values, weights); + } +} + +void main() { + int ans = knapSackProblem(4, 10, [1, 4, 5, 6], [2, 3, 6, 7]); + print(ans); + + test('TC: 1', () { + expect(knapSackProblem(4, 10, [1, 4, 5, 6], [2, 3, 6, 7]), 10); + }); + + ans = knapSackProblem(5, 100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]); + print(ans); + + test('TC: 2', () { + expect(knapSackProblem(5, 100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), + 101); + }); +} From 8aba885d3523bdd73b56c0e24216973a8369ad22 Mon Sep 17 00:00:00 2001 From: vipuluthaiah Date: Mon, 30 Nov 2020 13:48:05 +0530 Subject: [PATCH 319/443] Radix Sort --- sort/radix_sort.dart | 80 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 sort/radix_sort.dart diff --git a/sort/radix_sort.dart b/sort/radix_sort.dart new file mode 100644 index 00000000..d22723da --- /dev/null +++ b/sort/radix_sort.dart @@ -0,0 +1,80 @@ +//radix sort +/* + radix sort is a non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. + For elements with more than one significant digit, this bucketing process is repeated for each digit, + while preserving the ordering of the prior step, until all digits have been considered. For this reason, + radix sort has also been called bucket sort and digital sort. + */ +import 'dart:math' as Math; +import 'dart:math' show Random; +import 'package:test/test.dart'; + +main() { + + + test("Sorting of empty list returns empty list", () { + expect(radixSort([]), equals([])); + }); + test("Sorting one element list return same list", () { + expect(radixSort([1]), equals([1])); + }); + test("Sorting two times doesnt change input", () { + List lst = [5, 7, 1, 10, 54, -1]; + expect(radixSort(lst), equals(radixSort(radixSort(lst)))); + }); + test("Sorting already sorted list returns same list", () { + List lst = [1, 2, 3, 4, 10]; + 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])); + }); + + final seed = 10, rnd = Random(), length = 10; + var list = + List.generate(length, (i) => rnd.nextInt(seed), growable: false); + print('before sorting:'); + print(list); + print('----------------------------------------------'); + print('After sorting:'); + print(radixSort(list)); + +} + +getDigitNum(int n, int i) { + + var cal = (n.round().abs() / Math.pow(10, i)) % 10; + + return cal.round(); +} + +digitCount(int number) { + if (number == 0) { + return 1; + } + return (number.abs().toString().length); +} + +mostDigits(List number) { + var maxDigits = 0; + for (var i = 0; i < number.length; i++) { + maxDigits = Math.max(maxDigits, digitCount(number[i])); + } + return maxDigits; +} + +radixSort(List nums) { + var maxDightCount = mostDigits(nums); + for (var k = 0; k < maxDightCount; k++) { + var digitBuckets = List.generate(10, (_) => []); + // print(digitBuckets); + for (var i = 0; i < nums.length; i++) { + var digit = getDigitNum(nums[i], k); + digitBuckets[digit].add(nums[i]); + } + + nums = digitBuckets.expand((lst) => lst).toList(); + } + return nums; +} From 94e327744a00e9a07d754dff7ddc1d55838305b8 Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 30 Nov 2020 17:12:59 +0100 Subject: [PATCH 320/443] Update radix_sort.dart --- sort/radix_sort.dart | 4 ---- 1 file changed, 4 deletions(-) diff --git a/sort/radix_sort.dart b/sort/radix_sort.dart index d22723da..6919cc4a 100644 --- a/sort/radix_sort.dart +++ b/sort/radix_sort.dart @@ -10,8 +10,6 @@ import 'dart:math' show Random; import 'package:test/test.dart'; main() { - - test("Sorting of empty list returns empty list", () { expect(radixSort([]), equals([])); }); @@ -39,11 +37,9 @@ main() { print('----------------------------------------------'); print('After sorting:'); print(radixSort(list)); - } getDigitNum(int n, int i) { - var cal = (n.round().abs() / Math.pow(10, i)) % 10; return cal.round(); From bce157606ad697497e5e779268d406998e60a09a Mon Sep 17 00:00:00 2001 From: Parowicz Date: Mon, 30 Nov 2020 17:17:07 +0100 Subject: [PATCH 321/443] Remove debug print --- sort/radix_sort.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/sort/radix_sort.dart b/sort/radix_sort.dart index 6919cc4a..4dc393e1 100644 --- a/sort/radix_sort.dart +++ b/sort/radix_sort.dart @@ -64,7 +64,6 @@ radixSort(List nums) { var maxDightCount = mostDigits(nums); for (var k = 0; k < maxDightCount; k++) { var digitBuckets = List.generate(10, (_) => []); - // print(digitBuckets); for (var i = 0; i < nums.length; i++) { var digit = getDigitNum(nums[i], k); digitBuckets[digit].add(nums[i]); From ca4a5ab4113aaba3f90d12bf7e0b2c6cf58662b4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 30 Nov 2020 16:25:46 +0000 Subject: [PATCH 322/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f68d9f1c..ecd2af9b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -161,6 +161,7 @@ * [Merge Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/merge_sort.dart) * [Pigeonhole Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/pigeonhole_sort.dart) * [Quick Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/quick_Sort.dart) + * [Radix Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/radix_sort.dart) * [Select Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/select_Sort.dart) * [Shell Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/shell_Sort.dart) * [Tim Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/tim_Sort.dart) From b36cfa34a94b3bf8c296b7284210b27f32896d14 Mon Sep 17 00:00:00 2001 From: Tapajyoti Bose Date: Sun, 17 Jan 2021 09:10:27 +0530 Subject: [PATCH 323/443] feat: added open knight tour algorithm --- backtracking/open_knight_tour.dart | 163 +++++++++++++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 backtracking/open_knight_tour.dart diff --git a/backtracking/open_knight_tour.dart b/backtracking/open_knight_tour.dart new file mode 100644 index 00000000..9f74c601 --- /dev/null +++ b/backtracking/open_knight_tour.dart @@ -0,0 +1,163 @@ +import 'dart:io'; + +import 'package:test/test.dart'; + +List> getValidPos(List position, int n) { + final i = position[0]; + final j = position[1]; + final positions = [ + [i + 1, j + 2], + [i - 1, j + 2], + [i + 1, j - 2], + [i - 1, j - 2], + [i + 2, j + 1], + [i + 2, j - 1], + [i - 2, j + 1], + [i - 2, j - 1], + ]; + + final List> permissiblePositions = []; + for (final currPosition in positions) { + final iTest = currPosition[0]; + final jTest = currPosition[1]; + if (0 <= iTest && iTest < n && 0 <= jTest && jTest < n) { + permissiblePositions.add(currPosition); + } + } + return permissiblePositions; +} + +bool isComplete(List> board) { + for (final row in board) { + for (final elem in row) { + if (elem == 0) { + return false; + } + } + } + return true; +} + +bool openKnightTourHelper(List> board, List pos, int curr) { + if (isComplete(board)) { + return true; + } + + for (final position in getValidPos(pos, board.length)) { + final i = position[0]; + final j = position[1]; + + if (board[i][j] == 0) { + board[i][j] = curr + 1; + if (openKnightTourHelper(board, position, curr + 1)) { + return true; + } + board[i][j] = 0; + } + } + return false; +} + +List> openKnightTour(int n) { + // board creation + final List> board = []; + for (var i = 0; i < n; i++) { + final List row = []; + for (var j = 0; j < n; j++) { + row.add(0); + } + board.add(row); + } + // open knight tour with backtracking + for (var i = 0; i < n; i++) { + for (var j = 0; j < n; j++) { + board[i][j] = 1; + if (openKnightTourHelper(board, [i, j], 1)) { + return board; + } + board[i][j] = 0; + } + } + return board; +} + +void printBoard(List> board) { + for (final row in board) { + for (final elem in row) { + stdout.write(elem); + } + stdout.write("\n"); + } + stdout.write("\n"); +} + +void main() { + test(('getValidPos: testCase #1'), () { + expect( + 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] + ])); + }); + + test(('isComplete: testCase #1'), () { + expect( + isComplete([ + [1] + ]), + equals(true)); + }); + + test(('isComplete: testCase #2'), () { + expect( + isComplete([ + [1, 2], + [3, 0] + ]), + equals(false)); + }); + + test(('openKnightTour: testCase #1'), () { + expect( + openKnightTour(1), + equals([ + [1] + ])); + }); + + test(('openKnightTour: testCase #2'), () { + expect( + 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] + ])); + }); +} From d745a411d84c8e38cf2c6fbc5d1f63338aeba59a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 17 Jan 2021 08:25:18 +0000 Subject: [PATCH 324/443] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ecd2af9b..43d47f71 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -2,6 +2,9 @@ ## Array * [Validate Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/array/validate_subsequence.dart) +## Backtracking + * [Open Knight Tour](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/open_knight_tour.dart) + ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) * [Binary To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_hexadecimal.dart) From eb602655230d22ec064223fda2b4fa1ff9b6b5b6 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sun, 17 Jan 2021 16:26:13 +0800 Subject: [PATCH 325/443] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 3b795152..f6bcf04e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 The Algorithms +Copyright (c) 2021 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 From de10b7ac70039e26e933b8464231381b84afec23 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:17:17 +0000 Subject: [PATCH 326/443] Update dynamic_programming/01knapsack_recursive.dart Use of optional parameters is needed because the code checks for null values Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 3f90255f..07572cd0 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -2,7 +2,9 @@ import 'dart:math'; import 'package:test/test.dart'; int knapSackProblem( - int numberOfItems, int capacity, List values, List weights) { +int knapSackProblem(int capacity, List values, List weights, + [int numberOfItems]) { + numberOfItems ??= values.length; if (numberOfItems == 0 || capacity == 0) { return 0; } From 01de17876ffa1994ee02eb72056ab64b68fefbc5 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:18:06 +0000 Subject: [PATCH 327/443] Update dynamic_programming/01knapsack_recursive.dart Because numerOfItems is an optional parameter, it has to be the last value of the function Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 07572cd0..21f566f6 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -15,8 +15,8 @@ int knapSackProblem(int capacity, List values, List weights, return max( currentValue + knapSackProblem( - numberOfItems - 1, capacity - currentWeight, values, weights), - knapSackProblem(numberOfItems - 1, capacity, values, weights)); + capacity - currentWeight, values, weights, numberOfItems - 1), + knapSackProblem(capacity, values, weights, numberOfItems - 1)); } else { return knapSackProblem(numberOfItems - 1, capacity, values, weights); } From 71ab3fed9349365ed472044424a8e3cc320808d6 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:18:21 +0000 Subject: [PATCH 328/443] Update dynamic_programming/01knapsack_recursive.dart Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 21f566f6..8f2d8a95 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -18,7 +18,7 @@ int knapSackProblem(int capacity, List values, List weights, capacity - currentWeight, values, weights, numberOfItems - 1), knapSackProblem(capacity, values, weights, numberOfItems - 1)); } else { - return knapSackProblem(numberOfItems - 1, capacity, values, weights); + return knapSackProblem(capacity, values, weights, numberOfItems - 1); } } From 87833ad505dcc1b138c840bddd20c53b0dcc91c1 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:21:51 +0000 Subject: [PATCH 329/443] Update dynamic_programming/01knapsack_recursive.dart Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 8f2d8a95..8d88a91f 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -23,7 +23,7 @@ int knapSackProblem(int capacity, List values, List weights, } void main() { - int ans = knapSackProblem(4, 10, [1, 4, 5, 6], [2, 3, 6, 7]); + int ans = knapSackProblem(10, [1, 4, 5, 6], [2, 3, 6, 7]); print(ans); test('TC: 1', () { From f667431eb8ae376d993194198c74adcac2b64226 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:21:56 +0000 Subject: [PATCH 330/443] Update dynamic_programming/01knapsack_recursive.dart Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 8d88a91f..9d40d571 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -27,7 +27,7 @@ void main() { print(ans); test('TC: 1', () { - expect(knapSackProblem(4, 10, [1, 4, 5, 6], [2, 3, 6, 7]), 10); + expect(knapSackProblem(10, [1, 4, 5, 6], [2, 3, 6, 7]), 10); }); ans = knapSackProblem(5, 100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]); From b005f8776230c7f768f1325b6be01ac448deb4a7 Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:22:03 +0000 Subject: [PATCH 331/443] Update dynamic_programming/01knapsack_recursive.dart Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 9d40d571..0c9597b4 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -30,7 +30,7 @@ void main() { expect(knapSackProblem(10, [1, 4, 5, 6], [2, 3, 6, 7]), 10); }); - ans = knapSackProblem(5, 100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]); + ans = knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]); print(ans); test('TC: 2', () { From 293ff2d8325a24fe89c2ee8740fee035ca6cd65e Mon Sep 17 00:00:00 2001 From: mohammadreza490 <47437328+mohammadreza490@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:22:19 +0000 Subject: [PATCH 332/443] Update dynamic_programming/01knapsack_recursive.dart Co-authored-by: Parowicz --- dynamic_programming/01knapsack_recursive.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 0c9597b4..47b6a461 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -34,7 +34,7 @@ void main() { print(ans); test('TC: 2', () { - expect(knapSackProblem(5, 100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), - 101); + expect( + knapSackProblem(100, [2, 70, 30, 69, 100], [1, 70, 30, 69, 100]), 101); }); } From 61755a42bf84155bc3cca7ba5c78d9d5d635aece Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 9 Feb 2021 22:24:20 +0000 Subject: [PATCH 333/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 43d47f71..ea070a5f 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -48,6 +48,7 @@ * [Linked List Stack](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Stack/Linked_List_Stack.dart) ## Dynamic Programming + * [01Knapsack Recursive](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/01knapsack_recursive.dart) * [Coin Change](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/coin_change.dart) * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) * [Min Number Of Jumps](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/min_number_of_jumps.dart) From 7448be63f53b06a1797970e9fa1d1e2ef8785bc4 Mon Sep 17 00:00:00 2001 From: CrisesKhaos <76253854+CrisesKhaos@users.noreply.github.com> Date: Mon, 5 Apr 2021 12:46:47 +0530 Subject: [PATCH 334/443] Correcting typos (#151) * Update interpolation_Search.dart * Corrected typos discovered by codespell * Fixed typos * added sdK * Changed enqueue function to enque --- conversions/binary_to_decimal.dart | 2 +- conversions/hexadecimal_to_decimal.dart | 2 +- data_structures/Queue/List_Queue.dart | 12 ++++++------ dynamic_programming/01knapsack_recursive.dart | 1 - pubspec.yaml | 4 +++- search/interpolation_Search.dart | 2 +- sort/gnome_Sort.dart | 2 +- sort/heap_Sort.dart | 2 +- 8 files changed, 14 insertions(+), 13 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index e83ee4af..1e61c4af 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -20,7 +20,7 @@ int binary_to_decimal(String bin_string) { int decimal_val = 0; for (int i = 0; i < bin_string.length; i++) { if ("01".contains(bin_string[i]) == false) { - throw Exception("Non-binary value wass passed to the function"); + throw Exception("Non-binary value was passed to the function"); } else { decimal_val += pow(2, bin_string.length - i - 1) * int.parse((bin_string[i])); diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index 8c4a2536..9d12772c 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -30,7 +30,7 @@ int hexadecimal_to_decimal(String hex_string) { for (int i = 0; i < hex_string.length; i++) { if (int.parse(hex_string[i], onError: (e) => null) == null && hex_table.containsKey(hex_string[i]) == false) { - throw Exception("Non-hex value wass passed to the function"); + 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]]); diff --git a/data_structures/Queue/List_Queue.dart b/data_structures/Queue/List_Queue.dart index ed156c9a..6fb61bfb 100644 --- a/data_structures/Queue/List_Queue.dart +++ b/data_structures/Queue/List_Queue.dart @@ -16,12 +16,12 @@ class ListQueue { } } - //Add an elment to the queue - void enque(T elment) { + //Add an element to the queue + void enque(T element) { if (count == MAX_SIZE) { print("The queue is full!!!"); } else { - queue[count] = elment; + queue[count] = element; count++; } } @@ -47,13 +47,13 @@ void main() { Queue.enque(2); Queue.enque(7); print(Queue.queue); - print("Enque:"); + print("Enqueue:"); var returnData = Queue.deque(); print("$returnData\n"); - print("Enque:"); + print("Enqueue:"); returnData = Queue.deque(); print("$returnData\n"); - print("Enque:"); + print("Enqueue:"); returnData = Queue.deque(); print("$returnData\n"); print("Now the queue is: " + (Queue.queue).toString()); diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 47b6a461..bd28bfa7 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -1,7 +1,6 @@ import 'dart:math'; import 'package:test/test.dart'; -int knapSackProblem( int knapSackProblem(int capacity, List values, List weights, [int numberOfItems]) { numberOfItems ??= values.length; diff --git a/pubspec.yaml b/pubspec.yaml index 46a9860c..03f6fe12 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -5,7 +5,9 @@ repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 coverage: ^0.14.1 - + dev_dependencies: stack: ^0.0.1 +environment: + sdk: ">=2.10.0 <3.0.0" diff --git a/search/interpolation_Search.dart b/search/interpolation_Search.dart index 6b60727c..594dcc1c 100644 --- a/search/interpolation_Search.dart +++ b/search/interpolation_Search.dart @@ -15,7 +15,7 @@ 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 posible position of key */ + /* Calculate the nearest possible position of key */ int pos = low + (((key - arr[low]) * (high - low)) / (arr[high] - arr[low])).round(); if (key > arr[pos]) diff --git a/sort/gnome_Sort.dart b/sort/gnome_Sort.dart index 8613ec79..b6d1a9d3 100644 --- a/sort/gnome_Sort.dart +++ b/sort/gnome_Sort.dart @@ -32,7 +32,7 @@ void main() { //Get size of the array int n = arr.length; - //print the arrary + //print the array print(arr); //Sorting of array using gnome sort diff --git a/sort/heap_Sort.dart b/sort/heap_Sort.dart index 4e789551..e040f99c 100644 --- a/sort/heap_Sort.dart +++ b/sort/heap_Sort.dart @@ -2,7 +2,7 @@ void sort(List arr) { //The length of the list int n = arr.length; - //Build heap (rearrange arrary) + //Build heap (rearrange array) for (int i = (n / 2 - 1).round(); i >= 0; i--) { heapify(arr, n, i); } From ec06a4b925e47ec53551a2d89f3fed9d7a4bc721 Mon Sep 17 00:00:00 2001 From: StepfenShawn Date: Sat, 10 Jul 2021 18:46:14 +0800 Subject: [PATCH 335/443] Move N_bonacci.dart and magic_number.dart to other/ --- N_bonacci.dart => other/N_bonacci.dart | 0 magic_number.dart => other/magic_number.dart | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename N_bonacci.dart => other/N_bonacci.dart (100%) rename magic_number.dart => other/magic_number.dart (100%) diff --git a/N_bonacci.dart b/other/N_bonacci.dart similarity index 100% rename from N_bonacci.dart rename to other/N_bonacci.dart diff --git a/magic_number.dart b/other/magic_number.dart similarity index 100% rename from magic_number.dart rename to other/magic_number.dart From f7a3f8a69f554f532e923ccf28871e1e0cb3ab08 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Jul 2021 10:46:56 +0000 Subject: [PATCH 336/443] updating DIRECTORY.md --- DIRECTORY.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index ea070a5f..b22e141e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -58,8 +58,6 @@ * [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) -## [Magic Number](https://github.com/TheAlgorithms/Dart/blob/master//magic_number.dart) - ## Maths * [Abs](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs.dart) * [Abs Max](https://github.com/TheAlgorithms/Dart/blob/master/maths/abs_max.dart) @@ -100,8 +98,6 @@ * [Symmetric Derivative](https://github.com/TheAlgorithms/Dart/blob/master/maths/symmetric_derivative.dart) * [Ugly Numbers](https://github.com/TheAlgorithms/Dart/blob/master/maths/Ugly_numbers.dart) -## [N Bonacci](https://github.com/TheAlgorithms/Dart/blob/master//N_bonacci.dart) - ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) * [Binpow](https://github.com/TheAlgorithms/Dart/blob/master/other/binpow.dart) @@ -113,7 +109,9 @@ * [Heaps Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/heaps_algorithm.dart) * [Kadanealgo](https://github.com/TheAlgorithms/Dart/blob/master/other/kadaneAlgo.dart) * [Lcm](https://github.com/TheAlgorithms/Dart/blob/master/other/LCM.dart) + * [Magic Number](https://github.com/TheAlgorithms/Dart/blob/master/other/magic_number.dart) * [Moore Voting Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/other/Moore_voting_algorithm.dart) + * [N Bonacci](https://github.com/TheAlgorithms/Dart/blob/master/other/N_bonacci.dart) * [Swap All Odd And Even Bits](https://github.com/TheAlgorithms/Dart/blob/master/other/swap_all_odd_and_even_bits.dart) * [Tower Of Hanoi](https://github.com/TheAlgorithms/Dart/blob/master/other/tower_of_hanoi.dart) From a93a105493744b68510dba273351c60436188cc5 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sun, 10 Oct 2021 02:07:40 -0500 Subject: [PATCH 337/443] Add a dev_dependency on package:test We need to add a dev_dependency on package:test. --- .github/workflows/dart_test_analyze_format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 4ea76c5e..9ff5cdcf 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -10,6 +10,7 @@ jobs: - run: apt-get update - run: apt-get install --no-install-recommends -y -q lcov - run: dart pub get + - run: dart pub add --dev test - run: dart test --coverage . - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov - run: lcov -l coverage.lcov From dcd419ca3a405a8fa6725ad8c4155b2da655d79a Mon Sep 17 00:00:00 2001 From: Sahil Sharma <74351253+ys1113457623@users.noreply.github.com> Date: Thu, 26 May 2022 07:07:14 -0700 Subject: [PATCH 338/443] Create chinese_remainder_theorem.dart chinese_remainder_theorem --- .../chinese_remainder_theorem.dart | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 chinese_remainder_theorem/chinese_remainder_theorem.dart diff --git a/chinese_remainder_theorem/chinese_remainder_theorem.dart b/chinese_remainder_theorem/chinese_remainder_theorem.dart new file mode 100644 index 00000000..17189394 --- /dev/null +++ b/chinese_remainder_theorem/chinese_remainder_theorem.dart @@ -0,0 +1,72 @@ +// Importing required libraries. +import 'dart:io'; + +// Function to calculate modulo inverse. +int modular_inverse(int a, int m) { + // Temporary variable to store m to use later. + int temp = m; + + if (m == 1) { + return 0; + } + + int y = 0, x = 1, temp2, quotient, remainder; + + // Calculating x and y based on Euclid's algorithm + while (a > 1) { + quotient = (a / m).floor(); + remainder = a % m; + a = m; + m = remainder; + temp2 = y; + y = x - quotient * y; + x = temp2; + } + + // Making x positive if found negative + if (x < 0) { + x += temp; + } + + return x; +} + +// Driver function of the program +void main() { + // Taking input of the number array (num[i]). + print("Enter array of pairwise co-prime numbers:"); + + var input = stdin.readLineSync(); + var lis = input.split(' '); + List numbers = lis.map(int.parse).toList(); + + // Taking input of remainder array (rem[i]). + print("Enter remainders:"); + + input = stdin.readLineSync(); + lis = input.split(' '); + List remainders = lis.map(int.parse).toList(); + + int product = 1; + + // Length of the 'numbers' list. + int length = numbers.length; + + // Finding product of all the numbers. + for (int i = 0; i < length; i++) { + product *= numbers[i]; + } + + int temp, result = 0; + + // Summing the required values for all i according to the formula. + for (int i = 0; i < length; i++) { + temp = (product / numbers[i]).floor(); + result += temp * (remainders[i]) * modular_inverse(temp, numbers[i]); + } + + result = result % product; + + // Printing result + print("The value of 'x' by Chinese Remainder Theorem is $result."); +} From 71e4600a9aa7a38422952bcb961c83619be449d1 Mon Sep 17 00:00:00 2001 From: Sahil Sharma <74351253+ys1113457623@users.noreply.github.com> Date: Thu, 26 May 2022 07:25:41 -0700 Subject: [PATCH 339/443] Update chinese_remainder_theorem.dart --- chinese_remainder_theorem/chinese_remainder_theorem.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chinese_remainder_theorem/chinese_remainder_theorem.dart b/chinese_remainder_theorem/chinese_remainder_theorem.dart index 17189394..2dc4b008 100644 --- a/chinese_remainder_theorem/chinese_remainder_theorem.dart +++ b/chinese_remainder_theorem/chinese_remainder_theorem.dart @@ -38,14 +38,14 @@ void main() { var input = stdin.readLineSync(); var lis = input.split(' '); - List numbers = lis.map(int.parse).toList(); + List numbers = [9, 8, 5, 7, 1]; // Taking input of remainder array (rem[i]). print("Enter remainders:"); input = stdin.readLineSync(); lis = input.split(' '); - List remainders = lis.map(int.parse).toList(); + List remainders = [1, 2, 3, 4, 5]; int product = 1; From 38780cb25899ff1661da6ae94397a6c6406c753f Mon Sep 17 00:00:00 2001 From: Sahil Sharma <74351253+ys1113457623@users.noreply.github.com> Date: Thu, 26 May 2022 07:31:23 -0700 Subject: [PATCH 340/443] Update chinese_remainder_theorem.dart removal of dart:io --- .../chinese_remainder_theorem.dart | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/chinese_remainder_theorem/chinese_remainder_theorem.dart b/chinese_remainder_theorem/chinese_remainder_theorem.dart index 2dc4b008..39af8935 100644 --- a/chinese_remainder_theorem/chinese_remainder_theorem.dart +++ b/chinese_remainder_theorem/chinese_remainder_theorem.dart @@ -1,6 +1,3 @@ -// Importing required libraries. -import 'dart:io'; - // Function to calculate modulo inverse. int modular_inverse(int a, int m) { // Temporary variable to store m to use later. @@ -36,18 +33,14 @@ void main() { // Taking input of the number array (num[i]). print("Enter array of pairwise co-prime numbers:"); - var input = stdin.readLineSync(); - var lis = input.split(' '); List numbers = [9, 8, 5, 7, 1]; // Taking input of remainder array (rem[i]). print("Enter remainders:"); - input = stdin.readLineSync(); - lis = input.split(' '); List remainders = [1, 2, 3, 4, 5]; - int product = 1; + num product = 1; // Length of the 'numbers' list. int length = numbers.length; @@ -57,7 +50,8 @@ void main() { product *= numbers[i]; } - int temp, result = 0; + int temp; + num result = 0; // Summing the required values for all i according to the formula. for (int i = 0; i < length; i++) { From dd5e24fd0e44c1c8d6b057fc319f067d02774f9b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 7 Sep 2022 01:37:34 +0000 Subject: [PATCH 341/443] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b22e141e..5214b6c8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -5,6 +5,9 @@ ## Backtracking * [Open Knight Tour](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/open_knight_tour.dart) +## Chinese Remainder Theorem + * [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Dart/blob/master/chinese_remainder_theorem/chinese_remainder_theorem.dart) + ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) * [Binary To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_hexadecimal.dart) From 64058b5db76d482fab543bac2c536ef7261c63c9 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Mon, 12 Sep 2022 17:45:30 +0800 Subject: [PATCH 342/443] update the copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index f6bcf04e..5300ae48 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 The Algorithms +Copyright (c) 2022 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 From fb8c685b61e7071ab6d761e0f0c0eb565b5aa8f8 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Mon, 12 Sep 2022 17:47:31 +0800 Subject: [PATCH 343/443] Update dart_test_analyze_format.yml --- .github/workflows/dart_test_analyze_format.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 9ff5cdcf..4ea76c5e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -10,7 +10,6 @@ jobs: - run: apt-get update - run: apt-get install --no-install-recommends -y -q lcov - run: dart pub get - - run: dart pub add --dev test - run: dart test --coverage . - run: dart pub run coverage:format_coverage -i . -l > coverage.lcov - run: lcov -l coverage.lcov From 6cc3744e784b990b601f7afffcbcd8241414b8b4 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Sun, 18 Sep 2022 15:17:08 +0530 Subject: [PATCH 344/443] Sorted Squared Array --- array/sorted_squared_array.dart | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 array/sorted_squared_array.dart diff --git a/array/sorted_squared_array.dart b/array/sorted_squared_array.dart new file mode 100644 index 00000000..9ce5166c --- /dev/null +++ b/array/sorted_squared_array.dart @@ -0,0 +1,39 @@ +import 'package:test/test.dart'; + +List sortedSquaredArray(List array) { + int start = 0; + int end = array.length - 1; + int sortedIndex = array.length - 1; + List answer = List.filled(array.length, 0); + + while (end >= start) { + if (array[start].abs() > array[end].abs()) { + answer[sortedIndex] = array[start] * array[start]; + start += 1; + } else { + answer[sortedIndex] = array[end] * array[end]; + end -= 1; + } + sortedIndex -= 1; + } + + return answer; +} + +void main() { + test('test case 1', () { + expect(sortedSquaredArray([-1, -1, 2, 3, 3, 3, 4]), [1, 1, 4, 9, 9, 9, 16]); + }); + + test('test case 2', () { + expect(sortedSquaredArray([0]), [0]); + }); + + test('test case 2', () { + 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]); + }); +} From 766206eeaaaeee893dfce1091263f0d377180cc4 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Mon, 19 Sep 2022 21:05:20 +0530 Subject: [PATCH 345/443] Update pubspec.yaml --- pubspec.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pubspec.yaml b/pubspec.yaml index 03f6fe12..0ce0039e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,10 +4,10 @@ repository: https://github.com/TheAlgorithms/Dart dependencies: test: ^1.15.4 - coverage: ^0.14.1 + coverage: ^1.6.0 dev_dependencies: - stack: ^0.0.1 + stack: ^0.2.1 environment: sdk: ">=2.10.0 <3.0.0" From f651cfd2003843b8ba92d635ddd70ec7b78237a2 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 20 Sep 2022 10:22:36 +0530 Subject: [PATCH 346/443] fix formatting --- array/sorted_squared_array.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/array/sorted_squared_array.dart b/array/sorted_squared_array.dart index 9ce5166c..cc0c0407 100644 --- a/array/sorted_squared_array.dart +++ b/array/sorted_squared_array.dart @@ -30,10 +30,12 @@ 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]); }); } From 55498caf1d61ae7b3ebcc1e751cc0c19cbe5fb57 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 20 Sep 2022 05:07:34 +0000 Subject: [PATCH 347/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5214b6c8..f163582b 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,5 +1,6 @@ ## Array + * [Sorted Squared Array](https://github.com/TheAlgorithms/Dart/blob/master/array/sorted_squared_array.dart) * [Validate Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/array/validate_subsequence.dart) ## Backtracking From b0dcea5e8515d89628a8aba6b51db86f31e2ea55 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Wed, 21 Sep 2022 10:36:27 +0530 Subject: [PATCH 348/443] Two Sum Algorithm problem (#170) * Two Sum Algorithm problem Checks if there are two numbers in the array whose sum is equal to given number * Fix formatting --- array/two_sum.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 array/two_sum.dart diff --git a/array/two_sum.dart b/array/two_sum.dart new file mode 100644 index 00000000..29994eee --- /dev/null +++ b/array/two_sum.dart @@ -0,0 +1,26 @@ +import 'package:test/test.dart'; + +bool twoSum(List nums, int target) { + Map seen = {}; + for (int index = 0; index < nums.length; ++index) { + int number = nums[index]; + + int complement = target - number; + if (seen.containsKey(complement)) { + return true; + } else { + seen[number] = index; + } + } + return false; +} + +void main() { + test('test 1', () { + expect(twoSum([1, 2, 3, 4], 7), isTrue); + }); + + test('test 2', () { + expect(twoSum([1, 2, 3, 4], 12), isFalse); + }); +} From 5493c76da8a5524859a969b2c26adb7c64bd0a6c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 21 Sep 2022 05:06:44 +0000 Subject: [PATCH 349/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f163582b..afbf65d5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,6 +1,7 @@ ## Array * [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) ## Backtracking From b5d5863b4f6ffb3d203a3d27fa3d1e19164dc8be Mon Sep 17 00:00:00 2001 From: Jeevan Chandra Joshi Date: Fri, 7 Oct 2022 17:52:48 +0530 Subject: [PATCH 350/443] Implement solution 20 for project euler (#184) * Create sol20.dart * add test cases for sol20 * update test cases --- project_euler/problem_20/sol20.dart | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 project_euler/problem_20/sol20.dart diff --git a/project_euler/problem_20/sol20.dart b/project_euler/problem_20/sol20.dart new file mode 100644 index 00000000..7fa45988 --- /dev/null +++ b/project_euler/problem_20/sol20.dart @@ -0,0 +1,45 @@ +/* +Problem 20: Factorial digit sum + +n! means n × (n − 1) × ... × 3 × 2 × 1 +For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, +and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. +Find the sum of the digits in the number 100! +*/ + +import 'package:test/test.dart'; + +// To Calculate Factorial +int factorial(int number) { + int factorial = 1; + for (int i = number; i >= 1; i--) { + factorial *= i; + } + return factorial; +} + +// To Calculate Sum +int sum(int number) { + int sum = 0; + for (int i = factorial(number); i > 0; i = (i / 10).floor()) { + sum += (i % 10); + } + return sum; +} + +// Driver Code +void main() { + group("Solution 20", () { + test("Test 1", () { + expect(1, sum(1)); + }); + + test("Test 2", () { + expect(3, sum(5)); + }); + + test("Test 3", () { + expect(27, sum(10)); + }); + }); +} From 721f8060cab7d6af49bbd37ddc5375738642c0b3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 7 Oct 2022 12:23:10 +0000 Subject: [PATCH 351/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index afbf65d5..ac8ed2db 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -133,6 +133,8 @@ * [Sol17](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_17/sol17.dart) * Problem 2 * [Sol2](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_2/sol2.dart) + * Problem 20 + * [Sol20](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_20/sol20.dart) * Problem 3 * [Sol3](https://github.com/TheAlgorithms/Dart/blob/master/project_euler/problem_3/sol3.dart) * Problem 4 From cf9d6b1cf65e3abbf405a45ab8929bda475d0c0a Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 7 Oct 2022 19:20:20 +0530 Subject: [PATCH 352/443] Update CONTRIBUTING.md --- CONTRIBUTING.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f6beee79..7523068a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,7 +3,8 @@ Welcome to [TheAlgorithms/Dart](https://github.com/TheAlgorithms/Dart)! ## Contributing -* Fork this [repo](https://github.com/TheAlgorithms/Dart) +* Fork this [repo](https://github.com/TheAlgorithms/Dart). +* If Already Forked, Then make sure to sync your fork. * Make some changes and pull a request * Your algorithm must be able to run on [dartpad](https://dartpad.dev/) * [Automated tests are run](https://github.com/TheAlgorithms/Dart/actions) on all pull requests @@ -17,7 +18,7 @@ Welcome to [TheAlgorithms/Dart](https://github.com/TheAlgorithms/Dart)! ``` MyNewAlgorithm.dart is incorrect my_new_algorithm.dart is correct format -My_New_Algorithm.dart is correct format ``` Writer [@StepfenShawn](https://github.com/StepfenShawn), Feb 2020. +Updated [@akashgk](https://github.com/akashgk), Oct 2022. From f2213eaf1ad71ce6853b80728f31e423a9ac3c8e Mon Sep 17 00:00:00 2001 From: AwsmAsim <63421684+AwsmAsim@users.noreply.github.com> Date: Fri, 7 Oct 2022 19:34:52 +0530 Subject: [PATCH 353/443] added count_sort.dart (#159) * added count_sort.dart * added tests --- sort/count_sort.dart | 71 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 sort/count_sort.dart diff --git a/sort/count_sort.dart b/sort/count_sort.dart new file mode 100644 index 00000000..38575c87 --- /dev/null +++ b/sort/count_sort.dart @@ -0,0 +1,71 @@ +import 'package:test/test.dart'; + +List countSort(List arr) { + // In case the list is empty, return an empty list + if (arr.length == 0) return []; + + int min = arr[0], max = arr[0], i; + List outputArr = [], countArr = []; + for (int i in arr) { + if (i > max) max = i; + if (i < min) min = i; + } + + int range = max - min + 1; + + // INITIALISING countArr with 0's + for (i = 0; i < range; i++) { + countArr.add(0); + } + for (i = 0; i < arr.length; i++) { + outputArr.add(0); + } + + for (i in arr) { + countArr[i - min] += 1; + } + + // PREFIX SUM OF countArr + for (i = 1; i < countArr.length; i++) { + countArr[i] += countArr[i - 1]; + } + + // PUTING VALUES IN SORTED ARRAY + for (i in arr) { + int index = countArr[i - min]; + outputArr[index - 1] = i; + countArr[i - min] -= 1; + } + + // COPYING VALUES OF SORTED ARRAY INTO ORIGINAL ARRAY + for (i = 0; i < outputArr.length; i++) { + arr[i] = outputArr[i]; + } + + return arr; +} + +int main() { + test("Sorting of empty list returns empty list", () { + expect(countSort([]), equals([])); + }); + test("Sorting one element list return same list", () { + expect(countSort([1]), equals([1])); + }); + test("Sorting two times doesnt change input", () { + List lst = [5, 7, 1, 10, 54, -1]; + expect(countSort(lst), equals(countSort(countSort(lst)))); + }); + test("Sorting already sorted list returns same list", () { + List lst = [1, 2, 3, 4, 10]; + 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])); + }); + + print(countSort([-10, -4, 1, 5, 2, -2])); + + return 0; +} From 9b0f1db536e2e8e45e41f2695e8af4bdfe44a275 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 7 Oct 2022 14:05:09 +0000 Subject: [PATCH 354/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ac8ed2db..5af253f8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -164,6 +164,7 @@ * [Bubble Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/bubble_Sort.dart) * [Cocktail Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/cocktail_sort.dart) * [Comb Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/comb_sort.dart) + * [Count Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/count_sort.dart) * [Gnome Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/gnome_Sort.dart) * [Heap Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/heap_Sort.dart) * [Insert Sort](https://github.com/TheAlgorithms/Dart/blob/master/sort/insert_Sort.dart) From 11d4bc0356d42104f8450a8d089ca2cc2f4e67e1 Mon Sep 17 00:00:00 2001 From: MD Mobin <74850678+Djsmk123@users.noreply.github.com> Date: Mon, 10 Oct 2022 13:24:05 +0530 Subject: [PATCH 355/443] N-Queen Problem (#185) * added n queen problem solution * resolve requested changes * resolve requested changes * add more test case and fix test failing * add more test case and fix test failing * fix requested changes * change 20*20 list to n*n --- backtracking/n-queen.dart | 140 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 backtracking/n-queen.dart diff --git a/backtracking/n-queen.dart b/backtracking/n-queen.dart new file mode 100644 index 00000000..38c2552b --- /dev/null +++ b/backtracking/n-queen.dart @@ -0,0 +1,140 @@ +import 'package:test/test.dart'; + +/*N-Queens Problem + +N - Queens problem is to place n - queens in such a manner +on an n x n chessboard that no queens attack each other by being in the same row, column or diagonal +We have to find maximum no of solutions that are possible. +You can learn more about from the following link :https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/ +.*/ + +// Chess board, A 2d List of integers + +List> board = []; + +// checking is it safe place for a queen ? + +/*size : no of rows or columns of the given chess board + for e.g if there is a 3*3 chessboard then size = 3*/ + +bool isSafe(int size, int row, int col) { + //checking column safe + for (int k = 0; k < row; k++) { + if (board[k][col] == 1) { + return false; + } + } + int i = row; + int j = col; + + //checking left diagonal safe + while (i >= 0 && j >= 0) { + if (board[i][j] == 1) { + return false; + } + j--; + i--; + } + //checking right diagonal safe + i = row; + j = col; + while (i >= 0 && j < size) { + if (board[i][j] == 1) { + return false; + } + j++; + i--; + } + return true; +} + +int solveNQueen(int row, int size) { + //base case + if (size == row) { + return 1; + } + //recursive case + int ways = 0; + for (int col = 0; col < size; col++) { + //whether the current i,j is safe or not + if (isSafe(size, row, col)) { + board[row][col] = 1; + ways += solveNQueen(row + 1, size); + + //backtrack + board[row][col] = 0; + } + } + return ways; +} + +//This Function is used to refilled board with default value for testing purpose only. +// You can remove it, if you are using single test case. +void resetBoard(int boardSize) { + board = List.generate(boardSize, (i) => List.generate(boardSize, (j) => 0)); +} + +void main() { + /* + Test Cases + Size Expected Values + 1 : 1 + 2 : 0 + 3 : 0 + 4 : 2 + 5 : 10 + 6 : 4 + 7 : 40 + 8 : 92 + 9 : 352 + 10 : 724 + + */ + test("N Queen #testcase 1", () { + resetBoard(1); + expect(solveNQueen(0, 1), equals(1)); + }); + + test("N Queen #testcase 2", () { + resetBoard(2); + expect(solveNQueen(0, 2), equals(0)); + }); + + test("N Queen #testcase 3", () { + resetBoard(3); + expect(solveNQueen(0, 3), equals(0)); + }); + + test("N Queen #testcase 4", () { + resetBoard(4); + expect(solveNQueen(0, 4), equals(2)); + }); + + test("N Queen #testcase 5", () { + resetBoard(5); + expect(solveNQueen(0, 5), equals(10)); + }); + + test("N Queen #testcase 6", () { + resetBoard(6); + expect(solveNQueen(0, 6), equals(4)); + }); + + test("N Queen #testcase 7", () { + resetBoard(7); + expect(solveNQueen(0, 7), equals(40)); + }); + + test("N Queen #testcase 8", () { + resetBoard(8); + expect(solveNQueen(0, 8), equals(92)); + }); + test("N Queen #testcase 9", () { + resetBoard(9); + expect(solveNQueen(0, 9), equals(352)); + }); + test("N Queen #testcase 10", () { + resetBoard(10); + expect(solveNQueen(0, 10), equals(724)); + }); +} From 4a2af653de995d7cda1243d76f1e58b0d5407144 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 10 Oct 2022 07:54:21 +0000 Subject: [PATCH 356/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5af253f8..ecdc5de2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -5,6 +5,7 @@ * [Validate Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/array/validate_subsequence.dart) ## Backtracking + * [N-Queen](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/n-queen.dart) * [Open Knight Tour](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/open_knight_tour.dart) ## Chinese Remainder Theorem From 2678893081cf6a79274efd301512807c469fed41 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Wed, 12 Oct 2022 15:55:30 +0530 Subject: [PATCH 357/443] Fix test cases for array stack --- data_structures/Stack/Array_Stack.dart | 117 ++++++++++++++++--------- 1 file changed, 74 insertions(+), 43 deletions(-) diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index 809ca624..ddcdba28 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -1,63 +1,94 @@ -//Author: Shawn -//Email: stepfencurryxiao@gmail.com +import 'package:test/expect.dart'; +import 'package:test/scaffolding.dart'; class ArrayStack { - //stack - List stack; - //element of the stack - int count; - //size of stack - int n; + /// [stack] + List _stack; + + /// [_count] is the number of element in the stack + int _count; + + /// [_size] of stack + int _size; //Init the array stack - ArrayStack(var n) { - this.n = n; - this.stack = new List(n); - this.count = 0; + ArrayStack(int size) { + this._size = size; + this._stack = List.filled(_size, null); + this._count = 0; } - //Push a item to the stack + /// Push a item to the stack of type [T] to the [_stack] + /// if the size is exceeded the element wont be added. void push(T item) { - if (count == n) { - print("The stack is full\n"); + if (_count == _size) { + return null; } - stack[count] = item; - count++; + _stack[_count] = item; + _count++; } - //Pop a item from the stack + /// Pop the last element inserted from the [_stack]. T pop() { - if (count == 0) { - print("No data in the stack!\n"); + if (_count == 0) { + return null; } - T pop_data = stack[count - 1]; - stack[count - 1] = null; - count--; + T pop_data = _stack[_count - 1]; + _stack[_count - 1] = null; + _count--; return pop_data; } - void Display() { - print("ArrayStack: $stack\n"); + List get stack { + return _stack; } } void main() { - ArrayStack array_stack = new ArrayStack(6); - - array_stack.push('1'); - array_stack.push("2"); - array_stack.push('3'); - array_stack.push("4"); - array_stack.push('5'); - array_stack.push("6"); - - array_stack.Display(); - - var pop_data; - pop_data = array_stack.pop(); - print("Pop $pop_data from stack\n"); - pop_data = array_stack.pop(); - print("Pop $pop_data from stack\n"); - print("Now the stock:"); - array_stack.Display(); + ArrayStack arrayStack = new ArrayStack(6); + + arrayStack.push('1'); + arrayStack.push("2"); + arrayStack.push('3'); + arrayStack.push("4"); + arrayStack.push('5'); + arrayStack.push("6"); + + test('test case 1', () { + expect(arrayStack.stack, ['1', '2', '3', '4', '5', '6']); + }); + + test('test case 2: pop stack', () { + expect('6', arrayStack.pop()); + }); + + test('test case 3: pop stack', () { + expect('5', arrayStack.pop()); + }); + + test('test case 4: pop stack', () { + expect('4', arrayStack.pop()); + }); + + test('test case 5: pop stack', () { + expect('3', arrayStack.pop()); + }); + + test('test case 6: pop stack', () { + expect('2', arrayStack.pop()); + }); + + test('test case 7: pop stack', () { + expect('1', arrayStack.pop()); + }); + + test('test case 8: pop stack', () { + expect(null, arrayStack.pop()); + }); + + ArrayStack arrayStack2 = new ArrayStack(3); + + test('test case 9', () { + expect(arrayStack2.stack, [null, null, null]); + }); } From 10a933338722b8c6613f83d57b86e402de140cd2 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Wed, 12 Oct 2022 16:13:03 +0530 Subject: [PATCH 358/443] Fix test cases for array stack (#188) --- data_structures/Stack/Array_Stack.dart | 117 ++++++++++++++++--------- 1 file changed, 74 insertions(+), 43 deletions(-) diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index 809ca624..ddcdba28 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -1,63 +1,94 @@ -//Author: Shawn -//Email: stepfencurryxiao@gmail.com +import 'package:test/expect.dart'; +import 'package:test/scaffolding.dart'; class ArrayStack { - //stack - List stack; - //element of the stack - int count; - //size of stack - int n; + /// [stack] + List _stack; + + /// [_count] is the number of element in the stack + int _count; + + /// [_size] of stack + int _size; //Init the array stack - ArrayStack(var n) { - this.n = n; - this.stack = new List(n); - this.count = 0; + ArrayStack(int size) { + this._size = size; + this._stack = List.filled(_size, null); + this._count = 0; } - //Push a item to the stack + /// Push a item to the stack of type [T] to the [_stack] + /// if the size is exceeded the element wont be added. void push(T item) { - if (count == n) { - print("The stack is full\n"); + if (_count == _size) { + return null; } - stack[count] = item; - count++; + _stack[_count] = item; + _count++; } - //Pop a item from the stack + /// Pop the last element inserted from the [_stack]. T pop() { - if (count == 0) { - print("No data in the stack!\n"); + if (_count == 0) { + return null; } - T pop_data = stack[count - 1]; - stack[count - 1] = null; - count--; + T pop_data = _stack[_count - 1]; + _stack[_count - 1] = null; + _count--; return pop_data; } - void Display() { - print("ArrayStack: $stack\n"); + List get stack { + return _stack; } } void main() { - ArrayStack array_stack = new ArrayStack(6); - - array_stack.push('1'); - array_stack.push("2"); - array_stack.push('3'); - array_stack.push("4"); - array_stack.push('5'); - array_stack.push("6"); - - array_stack.Display(); - - var pop_data; - pop_data = array_stack.pop(); - print("Pop $pop_data from stack\n"); - pop_data = array_stack.pop(); - print("Pop $pop_data from stack\n"); - print("Now the stock:"); - array_stack.Display(); + ArrayStack arrayStack = new ArrayStack(6); + + arrayStack.push('1'); + arrayStack.push("2"); + arrayStack.push('3'); + arrayStack.push("4"); + arrayStack.push('5'); + arrayStack.push("6"); + + test('test case 1', () { + expect(arrayStack.stack, ['1', '2', '3', '4', '5', '6']); + }); + + test('test case 2: pop stack', () { + expect('6', arrayStack.pop()); + }); + + test('test case 3: pop stack', () { + expect('5', arrayStack.pop()); + }); + + test('test case 4: pop stack', () { + expect('4', arrayStack.pop()); + }); + + test('test case 5: pop stack', () { + expect('3', arrayStack.pop()); + }); + + test('test case 6: pop stack', () { + expect('2', arrayStack.pop()); + }); + + test('test case 7: pop stack', () { + expect('1', arrayStack.pop()); + }); + + test('test case 8: pop stack', () { + expect(null, arrayStack.pop()); + }); + + ArrayStack arrayStack2 = new ArrayStack(3); + + test('test case 9', () { + expect(arrayStack2.stack, [null, null, null]); + }); } From a968df75ea6b0f16268577731a283bad6c99d6ee Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 13 Oct 2022 18:21:27 +0530 Subject: [PATCH 359/443] Dart lint fixes --- conversions/binary_to_decimal.dart | 41 +++++++++++++++--------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 1e61c4af..d23a8e36 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -1,30 +1,29 @@ import "dart:math" show pow; -void main() { - print(binary_to_decimal("-111")); // -7 - print(binary_to_decimal(" 101011 ")); // 43 - try { - print(binary_to_decimal("1a1")); //error - } catch (ex) { - print(ex); - } -} - -int binary_to_decimal(String bin_string) { - bin_string = bin_string.trim(); - if (bin_string == null || bin_string == "") { +int binaryToDecimal(String binaryString) { + binaryString = binaryString.trim(); + if (binaryString == null || binaryString == "") { throw Exception("An empty value was passed to the function"); } - bool is_negative = bin_string[0] == "-"; - if (is_negative) bin_string = bin_string.substring(1); - int decimal_val = 0; - for (int i = 0; i < bin_string.length; i++) { - if ("01".contains(bin_string[i]) == false) { + bool isNegative = binaryString[0] == "-"; + if (isNegative) binaryString = binaryString.substring(1); + int decimalValue = 0; + for (int i = 0; i < binaryString.length; i++) { + if ("01".contains(binaryString[i]) == false) { throw Exception("Non-binary value was passed to the function"); } else { - decimal_val += - pow(2, bin_string.length - i - 1) * int.parse((bin_string[i])); + decimalValue += pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); } } - return is_negative ? -1 * decimal_val : decimal_val; + return isNegative ? -1 * decimalValue : decimalValue; +} + +void main() { + print(binaryToDecimal("-111")); // -7 + print(binaryToDecimal(" 101011 ")); // 43 + try { + print(binaryToDecimal("1a1")); //error + } catch (ex) { + print(ex); + } } From a2de1eb7f8fabab20c11d8bc90e1a368d406591d Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 13 Oct 2022 18:23:44 +0530 Subject: [PATCH 360/443] Add test cases --- conversions/binary_to_decimal.dart | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index d23a8e36..470c93f4 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -1,5 +1,7 @@ import "dart:math" show pow; +import 'package:test/test.dart'; + int binaryToDecimal(String binaryString) { binaryString = binaryString.trim(); if (binaryString == null || binaryString == "") { @@ -19,11 +21,18 @@ int binaryToDecimal(String binaryString) { } void main() { - print(binaryToDecimal("-111")); // -7 - print(binaryToDecimal(" 101011 ")); // 43 - try { - print(binaryToDecimal("1a1")); //error - } catch (ex) { - print(ex); - } + test('test case 1', () { + expect(binaryToDecimal("-111"), -7); + }); + test('test case 2', () { + expect(binaryToDecimal("101011"), 43); + }); + + test('test case 3', () { + try { + binaryToDecimal("1a1"); + } catch (e) { + expect('Exception: Non-binary value was passed to the function', e.toString()); + } + }); } From 8909fa8704748651cb5a466c8751bfd0b31621c5 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 13 Oct 2022 18:34:37 +0530 Subject: [PATCH 361/443] fix: dart format --- conversions/binary_to_decimal.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 470c93f4..bf5a3927 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -14,7 +14,8 @@ int binaryToDecimal(String binaryString) { if ("01".contains(binaryString[i]) == false) { throw Exception("Non-binary value was passed to the function"); } else { - decimalValue += pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); + decimalValue += + pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); } } return isNegative ? -1 * decimalValue : decimalValue; @@ -32,7 +33,8 @@ void main() { try { binaryToDecimal("1a1"); } catch (e) { - expect('Exception: Non-binary value was passed to the function', e.toString()); + expect('Exception: Non-binary value was passed to the function', + e.toString()); } }); } From 9849f46ba339bcbbbb7b5e51a86608d6407c050e Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:20:34 +0530 Subject: [PATCH 362/443] Update variable naming as per new linter --- conversions/binary_to_hexadecimal.dart | 42 +++++++++++++------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/conversions/binary_to_hexadecimal.dart b/conversions/binary_to_hexadecimal.dart index 40aa70be..bbdd5227 100644 --- a/conversions/binary_to_hexadecimal.dart +++ b/conversions/binary_to_hexadecimal.dart @@ -1,7 +1,7 @@ import 'package:test/test.dart'; //Binary number to hexadecimal number conversion -Map hex_table = { +Map hexTable = { "0000": '0', "0001": '1', "0010": '2', @@ -21,58 +21,58 @@ Map hex_table = { }; // function to take a binary string and to return hex value -String binary_to_hexadecimal(String bin_string) { +String binaryToHexadecimal(String binaryString) { // checking for unexpected values - bin_string = bin_string.trim(); - if (bin_string == null || bin_string == "") { + binaryString = binaryString.trim(); + if (binaryString == null || binaryString == "") { throw new FormatException("An empty value was passed to the function"); } try { - int.parse(bin_string); + int.parse(binaryString); } catch (e) { throw new FormatException("An invalid value was passed to the function"); } // negative number check - bool is_negative = bin_string[0] == "-"; - if (is_negative) bin_string = bin_string.substring(1); + bool isNegative = binaryString[0] == "-"; + if (isNegative) binaryString = binaryString.substring(1); // add min 0's in the end to make right substring length divisible by 4 - var len_bin = bin_string.length; - for (int i = 1; i <= (4 - len_bin % 4) % 4; i++) - bin_string = '0' + bin_string; + var binaryStringLength = binaryString.length; + for (int i = 1; i <= (4 - binaryStringLength % 4) % 4; i++) + binaryString = '0' + binaryString; // coverting the binary values to hex by diving into substring - String hex_val = ""; + String hexValue = ""; int i = 0; - while (i != bin_string.length) { - String bin_curr = bin_string.substring(i, i + 4); - hex_val += hex_table[bin_curr]; + while (i != binaryString.length) { + String bin_curr = binaryString.substring(i, i + 4); + hexValue += hexTable[bin_curr]; i += 4; } // returning the value - if (is_negative) { - return "-" + hex_val; + if (isNegative) { + return "-" + hexValue; } - return hex_val; + return hexValue; } // driver function void main() { test("binary_to_hexadecimal -1111", () { - expect(binary_to_hexadecimal("-1111"), equals("-F")); + expect(binaryToHexadecimal("-1111"), equals("-F")); }); test("binary_to_hexadecimal 101011", () { - expect(binary_to_hexadecimal("101011"), equals("2B")); + expect(binaryToHexadecimal("101011"), equals("2B")); }); test("binary_to_hexadecimal rasies error when number is invalid", () { - expect(() => binary_to_hexadecimal("-1011a01"), throwsFormatException); + expect(() => binaryToHexadecimal("-1011a01"), throwsFormatException); }); test("binary_to_hexadecimal of empty string raises error", () { - expect(() => binary_to_hexadecimal(""), throwsFormatException); + expect(() => binaryToHexadecimal(""), throwsFormatException); }); } From 3025e9a7ee97156c1de1acc831b64a9acd6204b6 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Mon, 17 Oct 2022 00:22:08 +0530 Subject: [PATCH 363/443] Update variable naming as per dart linter --- conversions/binary_to_octal.dart | 38 ++++++++++++++++---------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/conversions/binary_to_octal.dart b/conversions/binary_to_octal.dart index 90126459..7553a4d5 100644 --- a/conversions/binary_to_octal.dart +++ b/conversions/binary_to_octal.dart @@ -3,52 +3,52 @@ import 'package:test/test.dart'; //Binary number to octal number conversion void main() { test("binary_to_octal -1111", () { - expect(binary_to_octal("-1111"), equals("-17")); + expect(binaryToOctal("-1111"), equals("-17")); }); test("binary_to_octal 101011", () { - expect(binary_to_octal("101011"), equals("53")); + expect(binaryToOctal("101011"), equals("53")); }); test("binary_to_octal rasies error when number is invalid", () { - expect(() => binary_to_octal("-1011a01"), throwsFormatException); + expect(() => binaryToOctal("-1011a01"), throwsFormatException); }); test("binary_to_octal of empty string raises error", () { - expect(() => binary_to_octal(""), throwsFormatException); + expect(() => binaryToOctal(""), throwsFormatException); }); } -String binary_to_octal(String bin_string) { - bin_string = bin_string.trim(); - if (bin_string == null || bin_string == "") { +String binaryToOctal(String binaryString) { + binaryString = binaryString.trim(); + if (binaryString == null || binaryString == "") { throw new FormatException("An empty value was passed to the function"); } - bool is_negative = bin_string[0] == "-"; - if (is_negative) bin_string = bin_string.substring(1); + bool isNegative = binaryString[0] == "-"; + if (isNegative) binaryString = binaryString.substring(1); - String octal_val = ""; + String octalValue = ""; int binary; try { - binary = int.parse(bin_string); + binary = int.parse(binaryString); } catch (e) { throw new FormatException("An invalid value was passed to the function"); } - int curr_bit; + int currentBit; int j = 1; while (binary > 0) { - int code_3 = 0; + int code3 = 0; for (int i = 0; i < 3; i++) { - curr_bit = binary % 10; + currentBit = binary % 10; binary = binary ~/ 10; - code_3 += curr_bit * j; + code3 += currentBit * j; j *= 2; } - octal_val = code_3.toString() + octal_val; + octalValue = code3.toString() + octalValue; j = 1; } - if (is_negative) { - return "-" + octal_val; + if (isNegative) { + return "-" + octalValue; } - return octal_val; + return octalValue; } From 9b5455362f99107627881364648cf66abce28d97 Mon Sep 17 00:00:00 2001 From: prakhargupta-jan <75901535+prakhargupta-jan@users.noreply.github.com> Date: Wed, 19 Oct 2022 12:56:09 +0530 Subject: [PATCH 364/443] Implemented Level Order traversal and fixed:List.List deprecation warnings in binary_tree_traversal.dart --- .../binary_tree/binary_tree_traversal.dart | 48 ++++++++++++++++--- 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index 5712453c..0a1306c3 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -1,3 +1,5 @@ +import 'dart:collection'; + import 'package:test/test.dart'; class TreeNode { @@ -55,6 +57,27 @@ List postOrder(TreeNode root, List result) { return result; } +List levelOrder(TreeNode root, List result) { + Queue q = Queue(); + if (root != null) { + q.add(root); + } + + while (!q.isEmpty) { + TreeNode curr = q.first; + q.removeFirst(); + result.add(curr.data); + if (curr.left != null) { + q.addLast(curr.left); + } + if (curr.right != null) { + q.addLast(curr.right); + } + } + + return result; +} + void main() { var root = TreeNode(1); root.left = TreeNode(2); @@ -67,38 +90,49 @@ void main() { root.right.left.left.right = TreeNode(9); List result; - result = List(); + result = List.empty(growable: true); test(('inOrder traversal'), () { - result = List(); + result = List.empty(growable: true); expect(inOrder(root, result), equals([4, 2, 6, 5, 1, 8, 9, 7, 3])); }); test(('preOrder traversal'), () { - result = List(); + result = List.empty(growable: true); expect(preOrder(root, result), equals([1, 2, 4, 5, 6, 3, 7, 8, 9])); }); test(('postOrder traversal'), () { - result = List(); + result = List.empty(growable: true); expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); }); + test(('levelOrder traversal'), () { + result = List.empty(growable: true); + expect(levelOrder(root, result), equals([1, 2, 3, 4, 5, 7, 6, 8, 9])); + }); + test(('postOrder traversal'), () { - result = List(); + result = List.empty(growable: true); root = null; expect(postOrder(root, result), equals([])); }); test(('inOrder traversal'), () { - result = List(); + result = List.empty(growable: true); root = null; expect(inOrder(root, result), equals([])); }); test(('preOrder traversal'), () { - result = List(); + result = List.empty(growable: true); root = null; expect(preOrder(root, result), equals([])); }); + + test(('levelOrder traversal'), () { + result = List.empty(growable: true); + root = null; + expect(levelOrder(root, result), equals([])); + }); } From 3152a4df8cfaf32081b5dea9a0fd67662a49c5ca Mon Sep 17 00:00:00 2001 From: prakhargupta-jan <75901535+prakhargupta-jan@users.noreply.github.com> Date: Wed, 19 Oct 2022 13:07:26 +0530 Subject: [PATCH 365/443] added documentation link in comments for level order traversal --- data_structures/binary_tree/binary_tree_traversal.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index 0a1306c3..7a8d2722 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -107,7 +107,7 @@ void main() { expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); }); - test(('levelOrder traversal'), () { + test(('levelOrder traversal'), () { // https://www.geeksforgeeks.org/level-order-tree-traversal/ result = List.empty(growable: true); expect(levelOrder(root, result), equals([1, 2, 3, 4, 5, 7, 6, 8, 9])); }); From 25782e6e8fc91f3ac3582f5759d65c771204de70 Mon Sep 17 00:00:00 2001 From: RohitSingh107 <64142943+RohitSingh107@users.noreply.github.com> Date: Thu, 20 Oct 2022 11:35:21 +0530 Subject: [PATCH 366/443] added dp alogorithm longest common subsequence in dart (#203) * added dp alogorithm longest common subsequence in dart * added dp alogorithm longest common subsequence in dart --- .../longest_common_subsequence.dart | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 dynamic_programming/longest_common_subsequence.dart diff --git a/dynamic_programming/longest_common_subsequence.dart b/dynamic_programming/longest_common_subsequence.dart new file mode 100644 index 00000000..8f6ed250 --- /dev/null +++ b/dynamic_programming/longest_common_subsequence.dart @@ -0,0 +1,56 @@ +// Longest Common Subsequence Editorial: https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/ +//Longest Common Subsequence Wiki: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem +import 'dart:math'; +import 'package:test/test.dart'; + +int longestCommonSubsequence(String text1, String text2) { + int m = text1.length; + int n = text2.length; + + // BottomUp Tabulation + List> dp = List.generate(m + 1, (_) => List.filled(n + 1, 0)); + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + continue; + } + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m][n]; +} + +void main() { + test(('testCase #1'), () { + expect(longestCommonSubsequence("", ""), equals(0)); + }); + + test(('testCase #2'), () { + expect(longestCommonSubsequence("", "abcd"), equals(0)); + }); + test(('testCase #3'), () { + expect(longestCommonSubsequence("abcd", ""), equals(0)); + }); + test(('testCase #4'), () { + expect(longestCommonSubsequence("abcd", "c"), equals(1)); + }); + test(('testCase #5'), () { + expect(longestCommonSubsequence("abcd", "d"), equals(1)); + }); + test(('testCase #6'), () { + expect(longestCommonSubsequence("abcd", "e"), equals(0)); + }); + test(('testCase #7'), () { + expect(longestCommonSubsequence("abcdefghi", "acegi"), equals(5)); + }); + test(('testCase #8'), () { + expect(longestCommonSubsequence("abcdgh", "aedfhr"), equals(3)); + }); + test(('testCase #9'), () { + expect(longestCommonSubsequence("aggtab", "gxtxayb"), equals(4)); + }); + test(('testCase #10'), () { + expect(longestCommonSubsequence("ggg", "g"), equals(1)); + }); +} From 7fa9f4507f6f845c98c3ad4e2314912996d8d610 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 20 Oct 2022 06:05:34 +0000 Subject: [PATCH 367/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index ecdc5de2..f6596525 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -57,6 +57,7 @@ * [01Knapsack Recursive](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/01knapsack_recursive.dart) * [Coin Change](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/coin_change.dart) * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) + * [Longest Common Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/longest_common_subsequence.dart) * [Min Number Of Jumps](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/min_number_of_jumps.dart) ## Graphs From f1db5f651e5c73e9a772dad49bfef4a7c84da31b Mon Sep 17 00:00:00 2001 From: Vinod Khadka <40072637+skdotv@users.noreply.github.com> Date: Wed, 26 Oct 2022 11:47:22 +0530 Subject: [PATCH 368/443] Fixes: #198 (#199) --- graphs/breadth_first_search.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/graphs/breadth_first_search.dart b/graphs/breadth_first_search.dart index fdd9546c..4a7406f7 100644 --- a/graphs/breadth_first_search.dart +++ b/graphs/breadth_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) { @@ -42,7 +42,7 @@ class Graph { List breadthFirstSearch(Graph graph, int numberOfNodes, int startNode) { Queue queue = new Queue(); - List answer = List(); + List answer = []; queue.add(startNode); while (queue.isNotEmpty) { int node = queue.removeFirst(); From 4dff060fed848f8963e93e99dd92678d1f07ddbe Mon Sep 17 00:00:00 2001 From: RohitSingh107 <64142943+RohitSingh107@users.noreply.github.com> Date: Mon, 31 Oct 2022 02:21:09 +0530 Subject: [PATCH 369/443] added longest common substring (#206) --- .../longest_common_substring.dart | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 dynamic_programming/longest_common_substring.dart diff --git a/dynamic_programming/longest_common_substring.dart b/dynamic_programming/longest_common_substring.dart new file mode 100644 index 00000000..3662c60d --- /dev/null +++ b/dynamic_programming/longest_common_substring.dart @@ -0,0 +1,60 @@ +// Longest Common Substring Editorial: https://www.geeksforgeeks.org/longest-common-substring-dp-29/ +//Longest Common Substring Wiki: https://en.wikipedia.org/wiki/Longest_common_substring_problem + +import 'dart:math'; +import 'package:test/test.dart'; + +int longestCommonSubstring(String text1, String text2) { + int m = text1.length; + int n = text2.length; + + // BottomUp Tabulation + List> dp = List.generate(m + 1, (_) => List.filled(n + 1, 0)); + int ans = 0; + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + ans = max(ans, dp[i][j]); + } + } + } + return ans; +} + +void main() { + test(('testCase #1'), () { + expect(longestCommonSubstring("", ""), equals(0)); + }); + + test(('testCase #2'), () { + expect(longestCommonSubstring("a", ""), equals(0)); + }); + test(('testCase #3'), () { + expect(longestCommonSubstring("", "a"), equals(0)); + }); + test(('testCase #4'), () { + expect(longestCommonSubstring("c", "c"), equals(1)); + }); + test(('testCase #5'), () { + expect(longestCommonSubstring("abcdef", "bcd"), equals(3)); + }); + test(('testCase #6'), () { + expect(longestCommonSubstring("abcdef", "xabded"), equals(2)); + }); + test(('testCase #7'), () { + expect(longestCommonSubstring("GeeksforGeeks", "GeeksQuiz"), equals(5)); + }); + test(('testCase #8'), () { + expect(longestCommonSubstring("abcdxyz", "xyzabcd"), equals(4)); + }); + test(('testCase #9'), () { + expect(longestCommonSubstring("zxabcdezy", "yzabcdezx"), equals(6)); + }); + test(('testCase #10'), () { + expect( + longestCommonSubstring( + "OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com"), + equals(10)); + }); +} From 619a383308adf1fe2948715e25258a9418576d73 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 30 Oct 2022 20:51:26 +0000 Subject: [PATCH 370/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index f6596525..b3a72f17 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -58,6 +58,7 @@ * [Coin Change](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/coin_change.dart) * [Kadanes Algorithm](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/kadanes_algorithm.dart) * [Longest Common Subsequence](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/longest_common_subsequence.dart) + * [Longest Common Substring](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/longest_common_substring.dart) * [Min Number Of Jumps](https://github.com/TheAlgorithms/Dart/blob/master/dynamic_programming/min_number_of_jumps.dart) ## Graphs From af6c81c040d0ce0fe72167e45d39965c843b1365 Mon Sep 17 00:00:00 2001 From: prakhargupta-jan <75901535+prakhargupta-jan@users.noreply.github.com> Date: Fri, 11 Nov 2022 23:55:35 +0530 Subject: [PATCH 371/443] fixed: ran dart format --- data_structures/binary_tree/binary_tree_traversal.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data_structures/binary_tree/binary_tree_traversal.dart b/data_structures/binary_tree/binary_tree_traversal.dart index 7a8d2722..0576aa77 100644 --- a/data_structures/binary_tree/binary_tree_traversal.dart +++ b/data_structures/binary_tree/binary_tree_traversal.dart @@ -107,7 +107,8 @@ void main() { expect(postOrder(root, result), equals([4, 6, 5, 2, 9, 8, 7, 3, 1])); }); - test(('levelOrder traversal'), () { // https://www.geeksforgeeks.org/level-order-tree-traversal/ + test(('levelOrder traversal'), () { + // https://www.geeksforgeeks.org/level-order-tree-traversal/ result = List.empty(growable: true); expect(levelOrder(root, result), equals([1, 2, 3, 4, 5, 7, 6, 8, 9])); }); From 4c9fb3d5f163c390333f4e15578bcb86fa53690e Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:07:24 +0530 Subject: [PATCH 372/443] Add tim sort test cases. --- sort/tim_Sort.dart | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/sort/tim_Sort.dart b/sort/tim_Sort.dart index 8a4b16d5..89447363 100644 --- a/sort/tim_Sort.dart +++ b/sort/tim_Sort.dart @@ -1,5 +1,8 @@ import 'dart:math'; +import 'package:test/expect.dart'; +import 'package:test/scaffolding.dart'; + const int RUN = 32; void insertionSort(List list, int left, int right) { for (int i = left + 1; i <= right; i++) { @@ -65,9 +68,21 @@ void timSort(List list, int n) { } void main() { - //Get the array - List arr = [12, 213, 45, 9, 107]; - print("Before sorting: $arr\n"); - timSort(arr, arr.length); - print("After sorting: $arr"); + test('test case 1', () { + List arr = [12, 213, 45, 9, 107]; + timSort(arr, arr.length); + expect(arr, [9, 12, 45, 107, 213]); + }); + + test('test case 2', () { + List arr = []; + timSort(arr, arr.length); + expect(arr, []); + }); + + test('test case 3', () { + List arr = [-1, 0, 1]; + timSort(arr, arr.length); + expect(arr, [-1, 0, 1]); + }); } From ff3556af5931c2bb30701a16d9c2d55d747e698b Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:10:12 +0530 Subject: [PATCH 373/443] ran dart format --- sort/tim_Sort.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sort/tim_Sort.dart b/sort/tim_Sort.dart index 89447363..d2593d81 100644 --- a/sort/tim_Sort.dart +++ b/sort/tim_Sort.dart @@ -18,7 +18,8 @@ void insertionSort(List list, int left, int right) { void merge(List list, int left, int middle, int right) { int length1 = middle - left + 1, length2 = right - middle; - List leftList = new List(length1), rightList = new List(length2); + List leftList = List.filled(length1, null), + rightList = new List.filled(length2, null); for (int i = 0; i < length1; i++) { leftList[i] = list[left + i]; From 9d73735a553b864adf38ab34938ef835230ac600 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:18:29 +0530 Subject: [PATCH 374/443] Update binary_to_decimal.dart --- conversions/binary_to_decimal.dart | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index bf5a3927..f4c33147 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -5,17 +5,16 @@ import 'package:test/test.dart'; int binaryToDecimal(String binaryString) { binaryString = binaryString.trim(); if (binaryString == null || binaryString == "") { - throw Exception("An empty value was passed to the function"); + throw FormatException("An empty value was passed to the function"); } bool isNegative = binaryString[0] == "-"; if (isNegative) binaryString = binaryString.substring(1); int decimalValue = 0; for (int i = 0; i < binaryString.length; i++) { if ("01".contains(binaryString[i]) == false) { - throw Exception("Non-binary value was passed to the function"); + throw FormatException("Non-binary value was passed to the function"); } else { - decimalValue += - pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); + decimalValue += pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); } } return isNegative ? -1 * decimalValue : decimalValue; @@ -30,11 +29,6 @@ void main() { }); test('test case 3', () { - try { - binaryToDecimal("1a1"); - } catch (e) { - expect('Exception: Non-binary value was passed to the function', - e.toString()); - } + expect(() => binaryToDecimal("1a1"), throwsFormatException); }); } From 0cd85cea7cd7204747a37c689c3149b4e54a6e2b Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:18:54 +0530 Subject: [PATCH 375/443] ran dart format --- conversions/binary_to_decimal.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index f4c33147..1ee739c4 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -14,7 +14,8 @@ int binaryToDecimal(String binaryString) { if ("01".contains(binaryString[i]) == false) { throw FormatException("Non-binary value was passed to the function"); } else { - decimalValue += pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); + decimalValue += + pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); } } return isNegative ? -1 * decimalValue : decimalValue; From d591c30caeefd315ec7bcb89a5e1d54779288f69 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:34:00 +0530 Subject: [PATCH 376/443] Update Decimal_To_Any.dart --- conversions/Decimal_To_Any.dart | 36 +++++++++++++++------------------ 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index 4c396f6e..582b4afb 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -1,25 +1,10 @@ //Convert a Decimal Number to Any Other Representation //https://en.wikipedia.org/wiki/Positional_notation#Base_conversion -void main() { - print(decimal_to_any(0, 2)); //Expected '0' - print(decimal_to_any(5, 4)); //Expected '11' - print(decimal_to_any(20, 3)); //Expected '202' - print(decimal_to_any(-58, 16)); //Expected '-3A' - print(decimal_to_any(243, 17)); //Expected 'E5' - print(decimal_to_any(34923, 36)); //Expected 'QY3' - print(decimal_to_any(10, 11)); //Expected 'A' - print(decimal_to_any(-16, 16)); //Expected '-10' - print(decimal_to_any(36, 36)); //Expected '10' - - try { - print(decimal_to_any(10, 37)); //Expected Error - } on FormatException { - print("Base value is not supported"); - } -} +import 'package:test/expect.dart'; +import 'package:test/scaffolding.dart'; -String decimal_to_any(int value, int base) { +String decimalToAny(int value, int base) { var ALPHABET_VALUES = { 10: 'A', 11: 'B', @@ -64,9 +49,20 @@ String decimal_to_any(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]) + output; } return negative ? '-' + output : output; } + +void main() { + test('test case 1', () => expect(decimalToAny(0, 2), '0')); + test('test case 2', () => expect(decimalToAny(5, 4), '11')); + test('test case 3', () => expect(decimalToAny(20, 3), '202')); + test('test case 4', () => expect(decimalToAny(-58, 16), '-3A')); + test('test case 5', () => expect(decimalToAny(243, 17), 'E5')); + test('test case 6', () => expect(decimalToAny(34923, 36), 'QY3')); + test('test case 7', () => expect(decimalToAny(10, 11), 'A')); + test('test case 8', () => expect(decimalToAny(-16, 16), '-10')); + test('test case 9', () => expect(decimalToAny(36, 36), '10')); +} From c6b4e51d322b4c706e6b8890f98e3a7deb731ed7 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 21:43:08 +0530 Subject: [PATCH 377/443] Update Decimal_To_Any.dart --- conversions/Decimal_To_Any.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index 582b4afb..8d44bd55 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -49,7 +49,8 @@ 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]) + + output; } return negative ? '-' + output : output; From 5f6e4d529dc34da3a73c31bcbbbb49c4b325b501 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 15 Dec 2022 22:09:17 +0530 Subject: [PATCH 378/443] Update pull_request_template.md --- .github/pull_request_template.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 314b9b78..e6ced89f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,6 +5,7 @@ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? +* [ ] Add/Update/Fix test cases. ### **Checklist:** From 7ab792c1e6ccc38a274a53b55176fbabfda238e7 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Thu, 22 Dec 2022 22:44:11 +0800 Subject: [PATCH 379/443] Update CONTRIBUTING.md Remove this because `dart test` is recommended :) --- CONTRIBUTING.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7523068a..fe26c3e3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,6 @@ Welcome to [TheAlgorithms/Dart](https://github.com/TheAlgorithms/Dart)! * Fork this [repo](https://github.com/TheAlgorithms/Dart). * If Already Forked, Then make sure to sync your fork. * Make some changes and pull a request -* Your algorithm must be able to run on [dartpad](https://dartpad.dev/) * [Automated tests are run](https://github.com/TheAlgorithms/Dart/actions) on all pull requests * `dart analyze` is mandatory * `dart format` is mandatory From e6b5ee91527cdf3ef0f60db7dc128ab5969e80e4 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 29 Dec 2022 17:43:17 +0530 Subject: [PATCH 380/443] Create path_sum.dart --- trees/path_sum.dart | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 trees/path_sum.dart diff --git a/trees/path_sum.dart b/trees/path_sum.dart new file mode 100644 index 00000000..fbd80ead --- /dev/null +++ b/trees/path_sum.dart @@ -0,0 +1,63 @@ +import 'package:test/test.dart'; + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode([this.val = 0, this.left, this.right]); +} + +bool isLeaf(TreeNode node) { + if (node.left == null && node.right == null) { + return true; + } + return false; +} + +bool traverse(TreeNode node, int targetSum, int runningSum) { + if (node == null) { + return false; + } + runningSum += node.val; + if (isLeaf(node) && runningSum == targetSum) { + return true; + } + + bool hasPathSumInLeftTree = traverse(node.left, targetSum, runningSum); + bool hasPathSumInRightTree = traverse(node.right, targetSum, runningSum); + return hasPathSumInLeftTree || hasPathSumInRightTree; +} + +bool hasPathSum(TreeNode root, int targetSum) { + return traverse(root, targetSum, 0); +} + +void main(List args) { + TreeNode root = TreeNode( + 5, + TreeNode( + 4, + TreeNode( + 11, + TreeNode(7), + TreeNode(2), + ), + ), + TreeNode( + 8, + TreeNode(13), + TreeNode( + 4, + null, + TreeNode(1), + ), + ), + ); + + test('Test Case 1: true case', () { + expect(hasPathSum(root, 22), true); + }); + test('Test Case 2: false case', () { + expect(hasPathSum(root, 222), false); + }); +} From 717c695450bcb3bd0f373e6a7862ee0e70aba4f7 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 29 Dec 2022 17:46:12 +0530 Subject: [PATCH 381/443] Update path_sum.dart --- trees/path_sum.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/trees/path_sum.dart b/trees/path_sum.dart index fbd80ead..f64ee67f 100644 --- a/trees/path_sum.dart +++ b/trees/path_sum.dart @@ -1,5 +1,6 @@ import 'package:test/test.dart'; +// Question URL: https://leetcode.com/problems/path-sum/description/ class TreeNode { int val; TreeNode left; From da5ff469b6de0c5d02c48a98a16cc9523a074d51 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 29 Dec 2022 17:59:53 +0530 Subject: [PATCH 382/443] Update path_sum.dart --- trees/path_sum.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/trees/path_sum.dart b/trees/path_sum.dart index f64ee67f..acfab1ed 100644 --- a/trees/path_sum.dart +++ b/trees/path_sum.dart @@ -33,7 +33,7 @@ bool hasPathSum(TreeNode root, int targetSum) { return traverse(root, targetSum, 0); } -void main(List args) { +void main() { TreeNode root = TreeNode( 5, TreeNode( From 504b166d030fa9d95406b26ee750ada19ac6cc2f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 29 Dec 2022 12:35:44 +0000 Subject: [PATCH 383/443] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index b3a72f17..a8c1a987 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -184,3 +184,6 @@ * [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) * [Reverse Words Of String](https://github.com/TheAlgorithms/Dart/blob/master/strings/reverse_words_of_string.dart) + +## Trees + * [Path Sum](https://github.com/TheAlgorithms/Dart/blob/master/trees/path_sum.dart) From d185ade9751f941e92512a69f5a006baa56abe0a Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sat, 31 Dec 2022 22:45:49 +0800 Subject: [PATCH 384/443] Rename chinese_remainder_theorem/chinese_remainder_theorem.dart to other/chinese_remainder_theorem.dart --- .../chinese_remainder_theorem.dart | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {chinese_remainder_theorem => other}/chinese_remainder_theorem.dart (100%) diff --git a/chinese_remainder_theorem/chinese_remainder_theorem.dart b/other/chinese_remainder_theorem.dart similarity index 100% rename from chinese_remainder_theorem/chinese_remainder_theorem.dart rename to other/chinese_remainder_theorem.dart From 754bb7ca86fc5f2053cfb3cd9663f51c1075302b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 31 Dec 2022 14:46:03 +0000 Subject: [PATCH 385/443] updating DIRECTORY.md --- DIRECTORY.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index a8c1a987..bc7e16a8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -8,9 +8,6 @@ * [N-Queen](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/n-queen.dart) * [Open Knight Tour](https://github.com/TheAlgorithms/Dart/blob/master/backtracking/open_knight_tour.dart) -## Chinese Remainder Theorem - * [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Dart/blob/master/chinese_remainder_theorem/chinese_remainder_theorem.dart) - ## Conversions * [Binary To Decimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_decimal.dart) * [Binary To Hexadecimal](https://github.com/TheAlgorithms/Dart/blob/master/conversions/binary_to_hexadecimal.dart) @@ -109,6 +106,7 @@ ## Other * [Ackermann](https://github.com/TheAlgorithms/Dart/blob/master/other/ackermann.dart) * [Binpow](https://github.com/TheAlgorithms/Dart/blob/master/other/binpow.dart) + * [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Dart/blob/master/other/chinese_remainder_theorem.dart) * [Collatz](https://github.com/TheAlgorithms/Dart/blob/master/other/collatz.dart) * [Fisher Yates Shuffle](https://github.com/TheAlgorithms/Dart/blob/master/other/fisher_yates_shuffle.dart) * [Fizzbuzz](https://github.com/TheAlgorithms/Dart/blob/master/other/FizzBuzz.dart) From 96dea068acf95bfc8e0de9489f47fabc8b4edc19 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Sun, 29 Jan 2023 12:43:35 +0800 Subject: [PATCH 386/443] Update copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 5300ae48..6d7f310d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 The Algorithms +Copyright (c) 2023 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 From b1c422e7b2b59316f37ddd9d67ff00f628b4c7dd Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:18:58 +0530 Subject: [PATCH 387/443] Move Zeroes --- array/move_zeroes.dart | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 array/move_zeroes.dart diff --git a/array/move_zeroes.dart b/array/move_zeroes.dart new file mode 100644 index 00000000..c09aa79c --- /dev/null +++ b/array/move_zeroes.dart @@ -0,0 +1,32 @@ +import 'package:test/test.dart'; + +List moveZeroes(List nums) { + int lastNonZeroFoundAt = 0; + + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != 0) { + nums[lastNonZeroFoundAt] = nums[i]; + lastNonZeroFoundAt += 1; + } + } + + for (int i = lastNonZeroFoundAt; i < nums.length; ++i) { + nums[i] = 0; + } + return nums; +} + +void main() { + test('test case 1', () { + return expect(moveZeroes([1, 0, 2, 0, 0]), [1, 2, 0, 0, 0]); + }); + test('test case 2', () { + return expect(moveZeroes([1, 2, 2, 3, 5]), [1, 2, 2, 3, 5]); + }); + test('test case 3', () { + return expect(moveZeroes([0, 0, 0, 0, 0]), [0, 0, 0, 0, 0]); + }); + test('test case 4', () { + return expect(moveZeroes([]), []); + }); +} From 7b974baaa92850c0060311442429b2687f389669 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 23 Feb 2023 18:00:38 +0000 Subject: [PATCH 388/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index bc7e16a8..573ab668 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,5 +1,6 @@ ## Array + * [Move Zeroes](https://github.com/TheAlgorithms/Dart/blob/master/array/move_zeroes.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) From 79309d06c93af5321ccdf99c72735c16b191546f Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:48:24 +0530 Subject: [PATCH 389/443] Add Test cases to merge sort --- sort/merge_sort.dart | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 9da909e3..b8a72835 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -1,11 +1,11 @@ -import 'dart:math' show Random; +import 'package:test/test.dart'; void merge(List list, int lIndex, int mIndex, int rIndex) { int lSize = mIndex - lIndex + 1; int rSize = rIndex - mIndex; - List lList = new List(lSize); - List rList = new List(rSize); + List lList = new List.filled(lSize, () => 0); + List rList = new List.filled(rSize, () => 0); for (int i = 0; i < lSize; i++) lList[i] = list[lIndex + i]; for (int j = 0; j < rSize; j++) rList[j] = list[mIndex + j + 1]; @@ -37,7 +37,7 @@ void merge(List list, int lIndex, int mIndex, int rIndex) { } } -void mergeSort(List list, int lIndex, int rIndex) { +List mergeSort(List list, int lIndex, int rIndex) { if (lIndex < rIndex) { int mIndex = (rIndex + lIndex) ~/ 2; // finds the middle index @@ -46,16 +46,27 @@ void mergeSort(List list, int lIndex, int rIndex) { merge(list, lIndex, mIndex, rIndex); } + return list; } void main() { - final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); - print('before sorting:'); - print(list); - print('--------------------------------------'); - print('After sorting:'); - mergeSort(list, 0, list.length - 1); - print(list); + List list = [5, 4, 3, 2, 1]; + 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])); + + List list3 = [-1, -11, -1221, -123121, -1111111]; + test( + '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])); } From 05ec3886cd23702746bfb24ad7911c390cd896ee Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:49:34 +0530 Subject: [PATCH 390/443] fix formatting --- sort/merge_sort.dart | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index b8a72835..5bd9355f 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -51,7 +51,8 @@ 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), [])); @@ -63,10 +64,12 @@ void main() { List list3 = [-1, -11, -1221, -123121, -1111111]; test( 'test case 4', - () => expect( - mergeSort(list3, 0, list3.length - 1), [-1111111, -123121, -1221, -11, -1])); + () => 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( + 'test case 1', + () => + expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200])); } From 51655198694ca803fa321a24887b82dd4bbd1ac3 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:50:49 +0530 Subject: [PATCH 391/443] Fix formatting --- sort/merge_sort.dart | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 5bd9355f..b8a72835 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -51,8 +51,7 @@ 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), [])); @@ -64,12 +63,10 @@ void main() { List list3 = [-1, -11, -1221, -123121, -1111111]; test( 'test case 4', - () => expect(mergeSort(list3, 0, list3.length - 1), - [-1111111, -123121, -1221, -11, -1])); + () => 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('test case 1', + () => expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200])); } From f2a6a655c3f3f2b29bef4c6e474e83cf775f7858 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:51:13 +0530 Subject: [PATCH 392/443] fix format --- sort/merge_sort.dart | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index b8a72835..5bd9355f 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -51,7 +51,8 @@ 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), [])); @@ -63,10 +64,12 @@ void main() { List list3 = [-1, -11, -1221, -123121, -1111111]; test( 'test case 4', - () => expect( - mergeSort(list3, 0, list3.length - 1), [-1111111, -123121, -1221, -11, -1])); + () => 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( + 'test case 1', + () => + expect(mergeSort(list4, 0, list4.length - 1), [-1, 1, 5, 11, 1200])); } From 049d98eb5c7ec9b87edd8868d66ec0526282e55c Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 23 Feb 2023 23:53:51 +0530 Subject: [PATCH 393/443] Revert "Add test case to merge sort" --- sort/merge_sort.dart | 40 +++++++++++++--------------------------- 1 file changed, 13 insertions(+), 27 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 5bd9355f..9da909e3 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -1,11 +1,11 @@ -import 'package:test/test.dart'; +import 'dart:math' show Random; void merge(List list, int lIndex, int mIndex, int rIndex) { int lSize = mIndex - lIndex + 1; int rSize = rIndex - mIndex; - List lList = new List.filled(lSize, () => 0); - List rList = new List.filled(rSize, () => 0); + List lList = new List(lSize); + List rList = new List(rSize); for (int i = 0; i < lSize; i++) lList[i] = list[lIndex + i]; for (int j = 0; j < rSize; j++) rList[j] = list[mIndex + j + 1]; @@ -37,7 +37,7 @@ void merge(List list, int lIndex, int mIndex, int rIndex) { } } -List mergeSort(List list, int lIndex, int rIndex) { +void mergeSort(List list, int lIndex, int rIndex) { if (lIndex < rIndex) { int mIndex = (rIndex + lIndex) ~/ 2; // finds the middle index @@ -46,30 +46,16 @@ List mergeSort(List list, int lIndex, int rIndex) { merge(list, lIndex, mIndex, rIndex); } - return list; } 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])); - - 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])); - - List list3 = [-1, -11, -1221, -123121, -1111111]; - test( - '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])); + final seed = 100, rnd = Random(), length = 100; + var list = + List.generate(length, (i) => rnd.nextInt(seed), growable: false); + print('before sorting:'); + print(list); + print('--------------------------------------'); + print('After sorting:'); + mergeSort(list, 0, list.length - 1); + print(list); } From b6ba6fc759b785010271e6ba40fbbeb4cbea857c Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 24 Feb 2023 00:04:08 +0530 Subject: [PATCH 394/443] Add test cases to merge sort --- sort/merge_sort.dart | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/sort/merge_sort.dart b/sort/merge_sort.dart index 9da909e3..5bd9355f 100644 --- a/sort/merge_sort.dart +++ b/sort/merge_sort.dart @@ -1,11 +1,11 @@ -import 'dart:math' show Random; +import 'package:test/test.dart'; void merge(List list, int lIndex, int mIndex, int rIndex) { int lSize = mIndex - lIndex + 1; int rSize = rIndex - mIndex; - List lList = new List(lSize); - List rList = new List(rSize); + List lList = new List.filled(lSize, () => 0); + List rList = new List.filled(rSize, () => 0); for (int i = 0; i < lSize; i++) lList[i] = list[lIndex + i]; for (int j = 0; j < rSize; j++) rList[j] = list[mIndex + j + 1]; @@ -37,7 +37,7 @@ void merge(List list, int lIndex, int mIndex, int rIndex) { } } -void mergeSort(List list, int lIndex, int rIndex) { +List mergeSort(List list, int lIndex, int rIndex) { if (lIndex < rIndex) { int mIndex = (rIndex + lIndex) ~/ 2; // finds the middle index @@ -46,16 +46,30 @@ void mergeSort(List list, int lIndex, int rIndex) { merge(list, lIndex, mIndex, rIndex); } + return list; } void main() { - final seed = 100, rnd = Random(), length = 100; - var list = - List.generate(length, (i) => rnd.nextInt(seed), growable: false); - print('before sorting:'); - print(list); - print('--------------------------------------'); - print('After sorting:'); - mergeSort(list, 0, list.length - 1); - print(list); + List list = [5, 4, 3, 2, 1]; + 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])); + + List list3 = [-1, -11, -1221, -123121, -1111111]; + test( + '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])); } From a33b4fcafe90c47166027206dbe1cf1df96b6cc7 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 3 Mar 2023 21:45:30 +0530 Subject: [PATCH 395/443] Create car_pool.dart --- array/car_pool.dart | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 array/car_pool.dart diff --git a/array/car_pool.dart b/array/car_pool.dart new file mode 100644 index 00000000..ce2b6ac9 --- /dev/null +++ b/array/car_pool.dart @@ -0,0 +1,59 @@ +import 'dart:math'; + +import 'package:test/test.dart'; + +bool carPooling(List> trips, int capacity) { + List passengerTimelineCount = List.filled(1001, 0); + int lastPoint = 0; + + for (List trip in trips) { + int count = trip[0]; + int from = trip[1]; + int to = trip[2]; + if (count > capacity) { + return false; + } + + lastPoint = max(lastPoint, to); + passengerTimelineCount[from] += count; + passengerTimelineCount[to] -= count; + } + + for (int i = 1; i < lastPoint; ++i) { + passengerTimelineCount[i] += passengerTimelineCount[i - 1]; + if (passengerTimelineCount[i] > capacity) { + return false; + } + } + return true; +} + +void main() { + List> trips = [ + [2, 1, 5], + [3, 3, 7] + ]; + + List> trips1 = [ + [2, 1, 5], + [3, 5, 7] + ]; + + List> trips2 = [ + [2, 2, 6], + [2, 4, 7], + [8, 6, 7] + ]; + + List> trips3 = [ + [7, 5, 6], + [6, 7, 8], + [10, 1, 6] + ]; + + test('test case 1', () => expect(carPooling(trips, 4), false)); + test('test case 2', () => expect(carPooling(trips, 5), true)); + test('test case 3', () => expect(carPooling(trips1, 3), true)); + test('test case 4', () => expect(carPooling(trips2, 11), true)); + test('test case 5', () => expect(carPooling(trips3, 16), false)); +} From 4cf1f94d065836f702a59151cf3776c98b56c3da Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 3 Mar 2023 21:47:21 +0530 Subject: [PATCH 396/443] Update car_pool.dart --- array/car_pool.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/array/car_pool.dart b/array/car_pool.dart index ce2b6ac9..2d5adc64 100644 --- a/array/car_pool.dart +++ b/array/car_pool.dart @@ -1,5 +1,7 @@ -import 'dart:math'; +// Leetcode problem: https://leetcode.com/problems/car-pooling/ +// 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'; bool carPooling(List> trips, int capacity) { From 2ce9cc649907728355f36579da5bfb4f86aa0143 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 3 Mar 2023 16:27:07 +0000 Subject: [PATCH 397/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 573ab668..4eb63e92 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,5 +1,6 @@ ## 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) * [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) From 6cc96cfeea2fab8bb97ac3d5a48a6a6aa9ba93e8 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:11:45 +0530 Subject: [PATCH 398/443] Create hash_map_impl.dart --- data_structures/HashMap/hash_map_impl.dart | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 data_structures/HashMap/hash_map_impl.dart diff --git a/data_structures/HashMap/hash_map_impl.dart b/data_structures/HashMap/hash_map_impl.dart new file mode 100644 index 00000000..53ea7205 --- /dev/null +++ b/data_structures/HashMap/hash_map_impl.dart @@ -0,0 +1,73 @@ +import 'package:test/test.dart'; + +// Internal class to store each key-value pair and its next node +class Entry { + final K key; + V value; + Entry next; + + Entry(this.key, this.value, [this.next]); +} + +class HashMap { + // Internal list to store the keys and values + List> _table; + + HashMap() { + _table = List>.filled(256, null); + } + + // Helper function to generate a hash code for a key + int _hashCode(K key) { + return key.hashCode % _table.length; + } + + // Insert a new key-value pair into the hash map + void insert(K key, V value) { + final int index = _hashCode(key); + if (_table[index] == null) { + _table[index] = Entry(key, value); + } else { + Entry entry = _table[index]; + while (entry.next != null && entry.key != key) { + entry = entry.next; + } + if (entry.key == key) { + entry.value = value; + } else { + entry.next = Entry(key, value); + } + } + } + + // Get the value associated with a key in the hash map + V get(K key) { + final int index = _hashCode(key); + if (_table[index] == null) { + return null; + } else { + Entry entry = _table[index]; + while (entry != null && entry.key != key) { + entry = entry.next; + } + return entry?.value; + } + } +} + +void main() { + test('adding a key to a map', () { + HashMap map = HashMap(); + expect(map.get(1), null); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + }); + + test('updating a key in a map', () { + HashMap map = HashMap(); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + map.insert(1, 'IronMan'); + expect(map.get(1), 'IronMan'); + }); +} From 51c69618771afd79a4d57482d623335d074d2306 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:12:41 +0530 Subject: [PATCH 399/443] Revert "Create hash_map_impl.dart" This reverts commit 6cc96cfeea2fab8bb97ac3d5a48a6a6aa9ba93e8. --- data_structures/HashMap/hash_map_impl.dart | 73 ---------------------- 1 file changed, 73 deletions(-) delete mode 100644 data_structures/HashMap/hash_map_impl.dart diff --git a/data_structures/HashMap/hash_map_impl.dart b/data_structures/HashMap/hash_map_impl.dart deleted file mode 100644 index 53ea7205..00000000 --- a/data_structures/HashMap/hash_map_impl.dart +++ /dev/null @@ -1,73 +0,0 @@ -import 'package:test/test.dart'; - -// Internal class to store each key-value pair and its next node -class Entry { - final K key; - V value; - Entry next; - - Entry(this.key, this.value, [this.next]); -} - -class HashMap { - // Internal list to store the keys and values - List> _table; - - HashMap() { - _table = List>.filled(256, null); - } - - // Helper function to generate a hash code for a key - int _hashCode(K key) { - return key.hashCode % _table.length; - } - - // Insert a new key-value pair into the hash map - void insert(K key, V value) { - final int index = _hashCode(key); - if (_table[index] == null) { - _table[index] = Entry(key, value); - } else { - Entry entry = _table[index]; - while (entry.next != null && entry.key != key) { - entry = entry.next; - } - if (entry.key == key) { - entry.value = value; - } else { - entry.next = Entry(key, value); - } - } - } - - // Get the value associated with a key in the hash map - V get(K key) { - final int index = _hashCode(key); - if (_table[index] == null) { - return null; - } else { - Entry entry = _table[index]; - while (entry != null && entry.key != key) { - entry = entry.next; - } - return entry?.value; - } - } -} - -void main() { - test('adding a key to a map', () { - HashMap map = HashMap(); - expect(map.get(1), null); - map.insert(1, 'Akash'); - expect(map.get(1), 'Akash'); - }); - - test('updating a key in a map', () { - HashMap map = HashMap(); - map.insert(1, 'Akash'); - expect(map.get(1), 'Akash'); - map.insert(1, 'IronMan'); - expect(map.get(1), 'IronMan'); - }); -} From a62507c0aae9836b95d7ee984b8d7a34bbf0fc47 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:14:20 +0530 Subject: [PATCH 400/443] Create hashmap_impl.dart --- data_structures/HashMap/hashmap_impl.dart | 73 +++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 data_structures/HashMap/hashmap_impl.dart diff --git a/data_structures/HashMap/hashmap_impl.dart b/data_structures/HashMap/hashmap_impl.dart new file mode 100644 index 00000000..53ea7205 --- /dev/null +++ b/data_structures/HashMap/hashmap_impl.dart @@ -0,0 +1,73 @@ +import 'package:test/test.dart'; + +// Internal class to store each key-value pair and its next node +class Entry { + final K key; + V value; + Entry next; + + Entry(this.key, this.value, [this.next]); +} + +class HashMap { + // Internal list to store the keys and values + List> _table; + + HashMap() { + _table = List>.filled(256, null); + } + + // Helper function to generate a hash code for a key + int _hashCode(K key) { + return key.hashCode % _table.length; + } + + // Insert a new key-value pair into the hash map + void insert(K key, V value) { + final int index = _hashCode(key); + if (_table[index] == null) { + _table[index] = Entry(key, value); + } else { + Entry entry = _table[index]; + while (entry.next != null && entry.key != key) { + entry = entry.next; + } + if (entry.key == key) { + entry.value = value; + } else { + entry.next = Entry(key, value); + } + } + } + + // Get the value associated with a key in the hash map + V get(K key) { + final int index = _hashCode(key); + if (_table[index] == null) { + return null; + } else { + Entry entry = _table[index]; + while (entry != null && entry.key != key) { + entry = entry.next; + } + return entry?.value; + } + } +} + +void main() { + test('adding a key to a map', () { + HashMap map = HashMap(); + expect(map.get(1), null); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + }); + + test('updating a key in a map', () { + HashMap map = HashMap(); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + map.insert(1, 'IronMan'); + expect(map.get(1), 'IronMan'); + }); +} From 058ad3c68127521e14f659717e445da2cc5be281 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 10 Mar 2023 07:44:37 +0000 Subject: [PATCH 401/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4eb63e92..360560c8 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -33,6 +33,7 @@ * [Binary Tree Traversal](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/binary_tree/binary_tree_traversal.dart) * Hashmap * [Hashing](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/Hashing.dart) + * [Hashmap Impl](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/hashmap_impl.dart) * Heap * Binary Heap * [Max Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Max_heap.dart) From 08f4e5848f9e6a6fe8499163d0e0a56c8c0f1664 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:15:20 +0530 Subject: [PATCH 402/443] Delete hashmap_impl.dart --- data_structures/HashMap/hashmap_impl.dart | 73 ----------------------- 1 file changed, 73 deletions(-) delete mode 100644 data_structures/HashMap/hashmap_impl.dart diff --git a/data_structures/HashMap/hashmap_impl.dart b/data_structures/HashMap/hashmap_impl.dart deleted file mode 100644 index 53ea7205..00000000 --- a/data_structures/HashMap/hashmap_impl.dart +++ /dev/null @@ -1,73 +0,0 @@ -import 'package:test/test.dart'; - -// Internal class to store each key-value pair and its next node -class Entry { - final K key; - V value; - Entry next; - - Entry(this.key, this.value, [this.next]); -} - -class HashMap { - // Internal list to store the keys and values - List> _table; - - HashMap() { - _table = List>.filled(256, null); - } - - // Helper function to generate a hash code for a key - int _hashCode(K key) { - return key.hashCode % _table.length; - } - - // Insert a new key-value pair into the hash map - void insert(K key, V value) { - final int index = _hashCode(key); - if (_table[index] == null) { - _table[index] = Entry(key, value); - } else { - Entry entry = _table[index]; - while (entry.next != null && entry.key != key) { - entry = entry.next; - } - if (entry.key == key) { - entry.value = value; - } else { - entry.next = Entry(key, value); - } - } - } - - // Get the value associated with a key in the hash map - V get(K key) { - final int index = _hashCode(key); - if (_table[index] == null) { - return null; - } else { - Entry entry = _table[index]; - while (entry != null && entry.key != key) { - entry = entry.next; - } - return entry?.value; - } - } -} - -void main() { - test('adding a key to a map', () { - HashMap map = HashMap(); - expect(map.get(1), null); - map.insert(1, 'Akash'); - expect(map.get(1), 'Akash'); - }); - - test('updating a key in a map', () { - HashMap map = HashMap(); - map.insert(1, 'Akash'); - expect(map.get(1), 'Akash'); - map.insert(1, 'IronMan'); - expect(map.get(1), 'IronMan'); - }); -} From 8b9795dd4f21546966b00e1aa38bd75ce101d781 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 10 Mar 2023 07:45:35 +0000 Subject: [PATCH 403/443] updating DIRECTORY.md --- DIRECTORY.md | 1 - 1 file changed, 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 360560c8..4eb63e92 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -33,7 +33,6 @@ * [Binary Tree Traversal](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/binary_tree/binary_tree_traversal.dart) * Hashmap * [Hashing](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/Hashing.dart) - * [Hashmap Impl](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/HashMap/hashmap_impl.dart) * Heap * Binary Heap * [Max Heap](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/Heap/Binary_Heap/Max_heap.dart) From e81218f8d7443aa69ff42507d344f9c473a3d3a9 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:17:15 +0530 Subject: [PATCH 404/443] Create hashmap_implementation --- .../HashMap/hashmap_implementation | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 data_structures/HashMap/hashmap_implementation diff --git a/data_structures/HashMap/hashmap_implementation b/data_structures/HashMap/hashmap_implementation new file mode 100644 index 00000000..53ea7205 --- /dev/null +++ b/data_structures/HashMap/hashmap_implementation @@ -0,0 +1,73 @@ +import 'package:test/test.dart'; + +// Internal class to store each key-value pair and its next node +class Entry { + final K key; + V value; + Entry next; + + Entry(this.key, this.value, [this.next]); +} + +class HashMap { + // Internal list to store the keys and values + List> _table; + + HashMap() { + _table = List>.filled(256, null); + } + + // Helper function to generate a hash code for a key + int _hashCode(K key) { + return key.hashCode % _table.length; + } + + // Insert a new key-value pair into the hash map + void insert(K key, V value) { + final int index = _hashCode(key); + if (_table[index] == null) { + _table[index] = Entry(key, value); + } else { + Entry entry = _table[index]; + while (entry.next != null && entry.key != key) { + entry = entry.next; + } + if (entry.key == key) { + entry.value = value; + } else { + entry.next = Entry(key, value); + } + } + } + + // Get the value associated with a key in the hash map + V get(K key) { + final int index = _hashCode(key); + if (_table[index] == null) { + return null; + } else { + Entry entry = _table[index]; + while (entry != null && entry.key != key) { + entry = entry.next; + } + return entry?.value; + } + } +} + +void main() { + test('adding a key to a map', () { + HashMap map = HashMap(); + expect(map.get(1), null); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + }); + + test('updating a key in a map', () { + HashMap map = HashMap(); + map.insert(1, 'Akash'); + expect(map.get(1), 'Akash'); + map.insert(1, 'IronMan'); + expect(map.get(1), 'IronMan'); + }); +} From 2dbaf33938165604fcdea156c3bb359e824a07e0 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 18 Apr 2023 19:11:39 +0530 Subject: [PATCH 405/443] Add pivot index --- array/pivot_index.dart | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 array/pivot_index.dart diff --git a/array/pivot_index.dart b/array/pivot_index.dart new file mode 100644 index 00000000..b6c77bae --- /dev/null +++ b/array/pivot_index.dart @@ -0,0 +1,29 @@ +import 'package:test/test.dart'; + +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)); +} From 6584053c0e3b4d2adb464be002e17d061e73f219 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 18 Apr 2023 19:13:53 +0530 Subject: [PATCH 406/443] Add Problem URL --- array/pivot_index.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/array/pivot_index.dart b/array/pivot_index.dart index b6c77bae..b73e74ef 100644 --- a/array/pivot_index.dart +++ b/array/pivot_index.dart @@ -1,5 +1,6 @@ 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++) { From 4bfc1f1fcfdc6dc31ae28b2cdee5af2ab567bde4 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 18 Apr 2023 14:05:48 +0000 Subject: [PATCH 407/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4eb63e92..baaf5a55 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) From c23c7a413a0acd4343ee2a5580eff8911ddff054 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 20 Apr 2023 22:26:32 +0530 Subject: [PATCH 408/443] Add isomorphic string --- strings/isomorphic_strings.dart | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 strings/isomorphic_strings.dart diff --git a/strings/isomorphic_strings.dart b/strings/isomorphic_strings.dart new file mode 100644 index 00000000..8e0b9ad6 --- /dev/null +++ b/strings/isomorphic_strings.dart @@ -0,0 +1,32 @@ +import 'package:test/test.dart'; + +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)); +} From b7ed354f9f1f8aaca46e2109a2b6466a5cd48365 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Thu, 20 Apr 2023 22:27:14 +0530 Subject: [PATCH 409/443] Add isomorphic string --- strings/isomorphic_strings.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/strings/isomorphic_strings.dart b/strings/isomorphic_strings.dart index 8e0b9ad6..7c33c51c 100644 --- a/strings/isomorphic_strings.dart +++ b/strings/isomorphic_strings.dart @@ -1,5 +1,6 @@ import 'package:test/test.dart'; +// Leetcode problem url: https://leetcode.com/problems/isomorphic-strings/ bool isIsomorphic(String string1, String string2) { Map sMap = {}; Map tMap = {}; From a360ea693bb9f5ce106c60f2666396b6197bfbd8 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 20 Apr 2023 19:08:05 +0000 Subject: [PATCH 410/443] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index baaf5a55..9fd8d943 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -181,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) From ae2319b0cb99b3dcf89c2e92f3492c8d7f7372f6 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Fri, 21 Apr 2023 20:56:59 +0530 Subject: [PATCH 411/443] Merge sorted linked list --- .../linked_list/merge_sorted_list.dart | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 data_structures/linked_list/merge_sorted_list.dart 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..705b0b23 --- /dev/null +++ b/data_structures/linked_list/merge_sorted_list.dart @@ -0,0 +1,86 @@ +// 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 < list2.val) { + 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 < list2.val) { + 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]); + }); +} From 037e550260f13e15be5ce3c64ff2d4ceffcef9f6 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Sun, 23 Apr 2023 16:14:26 +0530 Subject: [PATCH 412/443] Breadth first search --- graphs/area_of_island.dart | 116 +++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 graphs/area_of_island.dart diff --git a/graphs/area_of_island.dart b/graphs/area_of_island.dart new file mode 100644 index 00000000..1cac46a0 --- /dev/null +++ b/graphs/area_of_island.dart @@ -0,0 +1,116 @@ +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); + }); +} From aba494d5287814c24e6c55e3ff120c828b676049 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 23 Apr 2023 10:51:43 +0000 Subject: [PATCH 413/443] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 9fd8d943..63e3f768 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -42,6 +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) + * [Merge Sorted List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/merge_sorted_list.dart) * Quad Tree * [Quad Tree](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/quad_tree/quad_tree.dart) * Queue @@ -62,6 +63,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) From 9b7724a73afe9a89620952108ef56b464b12cd8a Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Sat, 27 May 2023 13:32:03 +0530 Subject: [PATCH 414/443] Run dart format before test Running dart format before test will stop the workflow before executing the complete test --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 4ea76c5e..6f086ddc 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -10,8 +10,8 @@ jobs: - run: apt-get update - run: apt-get install --no-install-recommends -y -q lcov - 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 analyze - - run: dart format --set-exit-if-changed . From d8c4c7ff84d9d3b7fac18500840e3ac81f0db1dc Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Fri, 23 Jun 2023 14:48:10 +0800 Subject: [PATCH 415/443] Update README.md Fix #226 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c49f19f2..d9d40b18 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![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/)   ### All algorithms implemented in Dart (for education) From 11eabaebc00954bd53060f93962761ace7223ad3 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Fri, 23 Jun 2023 21:33:29 +0800 Subject: [PATCH 416/443] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d9d40b18..079f7631 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![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)   [![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) From 67ff979393ce219327ab92d5423f00a2ba397db0 Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Thu, 11 Jan 2024 12:03:53 +0800 Subject: [PATCH 417/443] Update copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 6d7f310d..eb813ea4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 The Algorithms +Copyright (c) 2024 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 From 002630685141584aea383e317a0fbf05e6f70b47 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:26:01 +0300 Subject: [PATCH 418/443] Update flutter --- .gitignore | 1 + pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) 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/pubspec.yaml b/pubspec.yaml index 0ce0039e..ddc6d722 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: ">=2.12.0 <3.0.0" From 79fdcd654c886509ece7cf7b242eff856b762808 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:26:19 +0300 Subject: [PATCH 419/443] Update Directory --- DIRECTORY.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 63e3f768..48986dc4 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -43,8 +43,6 @@ * [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) * [Merge Sorted List](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/linked_list/merge_sorted_list.dart) - * Quad Tree - * [Quad Tree](https://github.com/TheAlgorithms/Dart/blob/master/data_structures/quad_tree/quad_tree.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) From fa59267e7fde4f3cbc1f34c5483e8e6bef1b371d Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:26:53 +0300 Subject: [PATCH 420/443] Null Safe: Car Pool --- array/car_pool.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/array/car_pool.dart b/array/car_pool.dart index 2d5adc64..7c8d7e79 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); From 62457b083a8f0ad8ca1856aef0fe581aabc8c78a Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:28:41 +0300 Subject: [PATCH 421/443] Null Safe: Conversions --- conversions/Decimal_To_Any.dart | 7 ++++--- conversions/Decimal_to_Hexadecimal.dart | 2 +- conversions/Integer_To_Roman.dart | 2 +- conversions/binary_to_decimal.dart | 6 +++--- conversions/binary_to_hexadecimal.dart | 4 ++-- conversions/binary_to_octal.dart | 2 +- conversions/hexadecimal_to_binary.dart | 4 ++-- conversions/hexadecimal_to_decimal.dart | 8 ++++---- conversions/hexadecimal_to_octal.dart | 17 ++++++++--------- 9 files changed, 26 insertions(+), 26 deletions(-) diff --git a/conversions/Decimal_To_Any.dart b/conversions/Decimal_To_Any.dart index 8d44bd55..d9f6c3e8 100644 --- a/conversions/Decimal_To_Any.dart +++ b/conversions/Decimal_To_Any.dart @@ -48,9 +48,10 @@ String decimalToAny(int value, int base) { while (value > 0) { int remainder = value % base; value = value ~/ base; - output = - (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder]) + - output; + 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..29f4a7fd 100644 --- a/conversions/Integer_To_Roman.dart +++ b/conversions/Integer_To_Roman.dart @@ -41,7 +41,7 @@ List RomanNumbers = [ 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..963275d2 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] == "-"; @@ -14,8 +14,8 @@ int binaryToDecimal(String binaryString) { if ("01".contains(binaryString[i]) == false) { throw FormatException("Non-binary value was passed to the function"); } else { - decimalValue += - pow(2, binaryString.length - i - 1) * int.parse((binaryString[i])); + decimalValue += (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..1049b20b 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -21,19 +21,19 @@ 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..44294606 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,42 @@ 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; } } From 34faff10e464ee9b659127ff00e29f507d4026c9 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:29:20 +0300 Subject: [PATCH 422/443] Null Safe: datastructures --- data_structures/HashMap/Hashing.dart | 29 ++- .../Heap/Binary_Heap/Max_heap.dart | 6 +- .../Heap/Binary_Heap/min_heap_two.dart | 6 +- data_structures/Queue/Circular_Queue.dart | 6 +- data_structures/Queue/List_Queue.dart | 6 +- data_structures/Queue/Priority_Queue.dart | 8 +- data_structures/Stack/Array_Stack.dart | 14 +- data_structures/Stack/Linked_List_Stack.dart | 20 +- .../binary_tree/binary_tree_traversal.dart | 52 ++--- .../linked_list/cycle_in_linked_list.dart | 64 ++--- data_structures/linked_list/linked_list.dart | 44 ++-- .../linked_list/merge_sorted_list.dart | 34 +-- data_structures/quad_tree/quad_tree.dart | 219 ------------------ 13 files changed, 144 insertions(+), 364 deletions(-) delete mode 100644 data_structures/quad_tree/quad_tree.dart 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..37457b7c 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]; } @@ -65,7 +65,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..5672cccd 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]; } @@ -65,7 +65,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/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..54a7b504 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 extends 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 index 705b0b23..575667f9 100644 --- a/data_structures/linked_list/merge_sorted_list.dart +++ b/data_structures/linked_list/merge_sorted_list.dart @@ -2,23 +2,23 @@ import 'package:test/test.dart'; class ListNode { - int val; - ListNode next; + int? val; + ListNode? next; ListNode({this.val = 0, this.next}); } -extension PrintLinkedList on ListNode { +extension PrintLinkedList on ListNode? { void printLinkedList() { - ListNode node = this; + ListNode? node = this; while (node != null) { print(node.val); node = node.next; } } - List listValues() { - List values = []; - ListNode node = this; + List listValues() { + List values = []; + ListNode? node = this; while (node != null) { values.add(node.val); node = node.next; @@ -27,7 +27,7 @@ extension PrintLinkedList on ListNode { } } -ListNode mergeTwoLists(ListNode list1, ListNode list2) { +ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { if (list1 == null) { return list2; } else if (list2 == null) { @@ -35,7 +35,7 @@ ListNode mergeTwoLists(ListNode list1, ListNode list2) { } ListNode head = list1; - if (list1.val < list2.val) { + if ((list1.val ?? 0) < (list2.val ?? 0)) { head = list1; list1 = list1.next; } else { @@ -43,26 +43,26 @@ ListNode mergeTwoLists(ListNode list1, ListNode list2) { list2 = list2.next; } - ListNode node = head; + ListNode? node = head; while (list1 != null || list2 != null) { if (list1 != null && list2 != null) { - if (list1.val < list2.val) { - node.next = list1; + if ((list1.val ?? 0) < (list2.val ?? 0)) { + node?.next = list1; list1 = list1.next; } else { - node.next = list2; + node?.next = list2; list2 = list2.next; } } else if (list1 != null) { - node.next = list1; + node?.next = list1; list1 = list1.next; } else { - node.next = list2; - list2 = list2.next; + node?.next = list2; + list2 = list2?.next; } - node = node.next; + node = node?.next; } return head; } 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"); - }); - }); -} From 53df54e320fb718db801828fa8e9dc541a1bde2c Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:29:37 +0300 Subject: [PATCH 423/443] Null Safe: graphs --- graphs/depth_first_search.dart | 6 +++--- graphs/nearest_neighbour_algorithm.dart | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/graphs/depth_first_search.dart b/graphs/depth_first_search.dart index c60ca4fc..ac85cffd 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) { @@ -59,7 +59,7 @@ List depthFirstSearch(Graph graph, int numberOfNodes, int startNode) { List visitedNodes = new List.generate(numberOfNodes, (index) => false); - List answer = List(); + List answer = []; depthFirstSearchHelper(graph.graph, visitedNodes, startNode, answer); return answer; } diff --git a/graphs/nearest_neighbour_algorithm.dart b/graphs/nearest_neighbour_algorithm.dart index c4675f73..3a72664d 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; From 5a24465926c5356f2cda300a3317e8b4c1cbaabf Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:29:57 +0300 Subject: [PATCH 424/443] Null Safe: project euler --- project_euler/problem_17/sol17.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/project_euler/problem_17/sol17.dart b/project_euler/problem_17/sol17.dart index a9ae1a1c..d212e1ea 100644 --- a/project_euler/problem_17/sol17.dart +++ b/project_euler/problem_17/sol17.dart @@ -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"; From 8f846075abfe740fa2a80b2dfba66a8f85211366 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:30:23 +0300 Subject: [PATCH 425/443] Null Safe: Conversions --- conversions/octal_to_binary.dart | 4 ++-- conversions/octal_to_decimal.dart | 4 ++-- conversions/octal_to_hexadecimal.dart | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) 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(); } From a5d9e183e367b1653cf754292b9c63f1022283ed Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:30:38 +0300 Subject: [PATCH 426/443] Null Safe: Maths --- maths/Armstrong_number.dart | 2 +- maths/average.dart | 4 +-- maths/fibonacci_dynamic_programming.dart | 2 +- maths/hamming_distance.dart | 2 +- maths/lu_decomposition.dart | 40 ++++++++++++------------ 5 files changed, 25 insertions(+), 25 deletions(-) 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/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/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/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..7980fcd5 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,7 +280,7 @@ double f(double x, double y) { } void main() { - Matrix a = new Matrix([ + Matrix a = new Matrix(values: [ [3, 2, -1], [2, -2, 4], [-1, 0.5, -1] From a61f1e8ff17ca69daab9db4db2a5e449ea68186a Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:30:53 +0300 Subject: [PATCH 427/443] Null Safe: sort --- sort/gnome_Sort.dart | 2 +- sort/heap_Sort.dart | 4 ++-- sort/pigeonhole_sort.dart | 5 +---- sort/quick_Sort.dart | 2 +- 4 files changed, 5 insertions(+), 8 deletions(-) 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/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)); From 373aacf41ccaebdd09d978ce882c9b5d932668df Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:31:12 +0300 Subject: [PATCH 428/443] Null Safe: trees --- dynamic_programming/01knapsack_recursive.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index bd28bfa7..7a9c28c7 100644 --- a/dynamic_programming/01knapsack_recursive.dart +++ b/dynamic_programming/01knapsack_recursive.dart @@ -2,7 +2,7 @@ import 'dart:math'; import 'package:test/test.dart'; int knapSackProblem(int capacity, List values, List weights, - [int numberOfItems]) { + [int? numberOfItems]) { numberOfItems ??= values.length; if (numberOfItems == 0 || capacity == 0) { return 0; From 563c55eb6b1ba0ef74be3fe9f768edef237ef1f4 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:31:33 +0300 Subject: [PATCH 429/443] Null Safe: trees --- other/N_bonacci.dart | 2 +- other/haversine_formula.dart | 2 +- other/kadaneAlgo.dart | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) 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..8be48ca8 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; 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()); From a132f20218360aec6044228f7c4876246051108e Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:31:52 +0300 Subject: [PATCH 430/443] Null Safe: trees --- trees/path_sum.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/trees/path_sum.dart b/trees/path_sum.dart index acfab1ed..f5282866 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; } From cd0e7f05d8ab85547ae25de9364f55b92608f45e Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:42:54 +0300 Subject: [PATCH 431/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 6f086ddc..a73d39a6 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -3,12 +3,12 @@ on: [push, pull_request] jobs: dart_test_analyze_format: runs-on: ubuntu-latest - container: google/dart + container: + image: google/dart:2.17 # Specify Dart SDK version 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 + - run: apt-get update && apt-get install --no-install-recommends -y -q lcov - run: dart pub get - run: dart format --set-exit-if-changed . - run: dart test --coverage . From 7394e76ff112280a177845d6006a5e10731c6015 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:49:19 +0300 Subject: [PATCH 432/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index a73d39a6..9602b3e9 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -4,7 +4,7 @@ jobs: dart_test_analyze_format: runs-on: ubuntu-latest container: - image: google/dart:2.17 # Specify Dart SDK version + image: google/dart:2.18.0-271.0.dev 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 From b9441eac0ea546c0f49f6d188d8efd90d8cb5387 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:50:30 +0300 Subject: [PATCH 433/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 9602b3e9..9ed9a0c9 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -4,7 +4,7 @@ jobs: dart_test_analyze_format: runs-on: ubuntu-latest container: - image: google/dart:2.18.0-271.0.dev + image: google/dart:2.18 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 From e8712efa3eea359532ea9f92a33258d1075a0092 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:52:03 +0300 Subject: [PATCH 434/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 9ed9a0c9..6b1ba821 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -4,7 +4,7 @@ jobs: dart_test_analyze_format: runs-on: ubuntu-latest container: - image: google/dart:2.18 + image: google/dart 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 From 97a2ac095001966d0491263dfd1df846d0c5b0b9 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:54:48 +0300 Subject: [PATCH 435/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 6b1ba821..6877bf33 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,8 +7,6 @@ jobs: image: google/dart 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 && apt-get install --no-install-recommends -y -q lcov - run: dart pub get - run: dart format --set-exit-if-changed . - run: dart test --coverage . From a7031415680c577ee30854eab4eaa8bc9b6ee5de Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:58:53 +0300 Subject: [PATCH 436/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 6877bf33..81ee9feb 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -7,6 +7,8 @@ jobs: image: google/dart 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 && apt-get install --no-install-recommends -y -q lcov - run: dart pub get - run: dart format --set-exit-if-changed . - run: dart test --coverage . From 375057e8f68935f815514e582adea718edf1b73f Mon Sep 17 00:00:00 2001 From: Akash G Krishnan <78728996+akashgk@users.noreply.github.com> Date: Tue, 2 Apr 2024 23:59:54 +0300 Subject: [PATCH 437/443] Fix Pipeline --- .github/workflows/dart_test_analyze_format.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index 81ee9feb..ce138056 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -8,10 +8,8 @@ jobs: 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 && apt-get install --no-install-recommends -y -q lcov - 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 analyze From 94b7930db11baf8968ff35b94a8d7645bb0931ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=8D=8CShawn?= Date: Sat, 4 Jan 2025 16:55:35 +0800 Subject: [PATCH 438/443] Update copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index eb813ea4..3b57d694 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2024 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 From cb414a6e096de5164006896023537311ca1c8854 Mon Sep 17 00:00:00 2001 From: Musaddiq Ahmed Khan <37911054+Musaddiq625@users.noreply.github.com> Date: Wed, 15 Oct 2025 16:11:00 +0500 Subject: [PATCH 439/443] Embed image directly in Time Complexity Graph section Replaced the text link to the complexity graph with a direct image embed. This makes the graph visible without needing to click the link. --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 079f7631..309e9c8d 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,9 @@ __Properties__ ### Time-Complexity Graphs -Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) +Comparing the complexity of sorting algorithms (Bubble Sort, Selection Sort and Insertion Sort) -[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) +![alt text][complexity-graph] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort @@ -157,6 +157,8 @@ Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Sel [binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm [binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png +[complexity-graph]: https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png + ---------------------------------------------------------------------------------- ## Community Channel From 827be3c59d714aa577fc096b8319c2ceff4628c7 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Fri, 27 Feb 2026 21:37:15 +0300 Subject: [PATCH 440/443] Update to latest dart version --- .../workflows/dart_test_analyze_format.yml | 6 +- array/car_pool.dart | 8 +- array/sorted_squared_array.dart | 22 ++++- backtracking/open_knight_tour.dart | 89 ++++++++++--------- conversions/Decimal_To_Any.dart | 5 +- conversions/Integer_To_Roman.dart | 4 +- conversions/binary_to_decimal.dart | 3 +- conversions/hexadecimal_to_decimal.dart | 3 +- conversions/hexadecimal_to_octal.dart | 3 +- conversions/roman_to_integer.dart | 3 +- .../Heap/Binary_Heap/Max_heap.dart | 9 +- .../Heap/Binary_Heap/min_heap_two.dart | 9 +- data_structures/Stack/balanced_brackets.dart | 8 +- data_structures/linked_list/linked_list.dart | 2 +- .../linked_list/merge_sorted_list.dart | 24 +++-- dynamic_programming/01knapsack_recursive.dart | 25 ++++-- dynamic_programming/coin_change.dart | 6 +- .../longest_common_substring.dart | 9 +- graphs/area_of_island.dart | 27 ++++-- graphs/breadth_first_search.dart | 18 ++-- graphs/depth_first_search.dart | 24 +++-- graphs/nearest_neighbour_algorithm.dart | 25 +++--- maths/Ugly_numbers.dart | 2 +- maths/factors.dart | 5 +- maths/fermats_little_theorem.dart | 1 - maths/find_max_recursion.dart | 12 ++- maths/find_min_recursion.dart | 12 ++- maths/lu_decomposition.dart | 12 +-- maths/newton_method.dart | 8 +- maths/sigmoid.dart | 4 +- maths/symmetric_derivative.dart | 3 +- other/LCM.dart | 28 +++--- other/haversine_formula.dart | 3 +- project_euler/problem_17/sol17.dart | 6 +- project_euler/problem_8/sol8.dart | 3 +- pubspec.yaml | 2 +- search/binary_search_recursion.dart | 12 ++- search/fibonacci_Search.dart | 2 - search/interpolation_Search.dart | 3 +- sort/bubble_Sort.dart | 7 +- sort/count_sort.dart | 6 +- sort/insert_Sort.dart | 7 +- sort/merge_sort.dart | 30 ++++--- sort/radix_sort.dart | 13 ++- sort/select_Sort.dart | 7 +- sort/shell_Sort.dart | 7 +- strings/knuth_morris_prat.dart | 6 +- strings/reverse_words_of_string.dart | 6 +- trees/path_sum.dart | 19 +--- 49 files changed, 343 insertions(+), 215 deletions(-) diff --git a/.github/workflows/dart_test_analyze_format.yml b/.github/workflows/dart_test_analyze_format.yml index ce138056..a0911f2e 100644 --- a/.github/workflows/dart_test_analyze_format.yml +++ b/.github/workflows/dart_test_analyze_format.yml @@ -4,12 +4,12 @@ jobs: dart_test_analyze_format: runs-on: ubuntu-latest container: - image: google/dart + image: dart:stable steps: - - uses: actions/checkout@v2 + - 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: dart run coverage:format_coverage -i . -l > coverage.lcov - run: dart analyze diff --git a/array/car_pool.dart b/array/car_pool.dart index 7c8d7e79..b5cbb401 100644 --- a/array/car_pool.dart +++ b/array/car_pool.dart @@ -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/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 d9f6c3e8..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"; @@ -48,7 +48,8 @@ String decimalToAny(int value, int base) { while (value > 0) { int remainder = value % base; value = value ~/ base; - output = (remainder < 10 + output = + (remainder < 10 ? remainder.toString() : ALPHABET_VALUES[remainder] ?? '0') + output; diff --git a/conversions/Integer_To_Roman.dart b/conversions/Integer_To_Roman.dart index 29f4a7fd..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,7 +36,7 @@ List RomanNumbers = [ "IX", "V", "IV", - "I" + "I", ]; List integer_to_roman(int num) { diff --git a/conversions/binary_to_decimal.dart b/conversions/binary_to_decimal.dart index 963275d2..e39bcaf9 100644 --- a/conversions/binary_to_decimal.dart +++ b/conversions/binary_to_decimal.dart @@ -14,7 +14,8 @@ int binaryToDecimal(String binaryString) { if ("01".contains(binaryString[i]) == false) { throw FormatException("Non-binary value was passed to the function"); } else { - decimalValue += (pow(2, binaryString.length - i - 1).toInt() * + decimalValue += + (pow(2, binaryString.length - i - 1).toInt() * (int.tryParse(binaryString[i]) ?? 0)); } } diff --git a/conversions/hexadecimal_to_decimal.dart b/conversions/hexadecimal_to_decimal.dart index 1049b20b..416a8585 100644 --- a/conversions/hexadecimal_to_decimal.dart +++ b/conversions/hexadecimal_to_decimal.dart @@ -32,7 +32,8 @@ int hexadecimal_to_decimal(String hex_string) { 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).toInt() * + decimal_val += + pow(16, hex_string.length - i - 1).toInt() * (int.tryParse(hex_string[i]) ?? hex_table[hex_string[i]] ?? 0); } } diff --git a/conversions/hexadecimal_to_octal.dart b/conversions/hexadecimal_to_octal.dart index 44294606..c72e29c2 100644 --- a/conversions/hexadecimal_to_octal.dart +++ b/conversions/hexadecimal_to_octal.dart @@ -64,7 +64,8 @@ String hexadecimal_to_octal(String hex_val) { break; default: throw new FormatException( - "An invalid value was passed to the function"); + "An invalid value was passed to the function", + ); } } 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/Heap/Binary_Heap/Max_heap.dart b/data_structures/Heap/Binary_Heap/Max_heap.dart index 37457b7c..752d399a 100644 --- a/data_structures/Heap/Binary_Heap/Max_heap.dart +++ b/data_structures/Heap/Binary_Heap/Max_heap.dart @@ -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; diff --git a/data_structures/Heap/Binary_Heap/min_heap_two.dart b/data_structures/Heap/Binary_Heap/min_heap_two.dart index 5672cccd..6627b3c1 100644 --- a/data_structures/Heap/Binary_Heap/min_heap_two.dart +++ b/data_structures/Heap/Binary_Heap/min_heap_two.dart @@ -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; 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/linked_list/linked_list.dart b/data_structures/linked_list/linked_list.dart index 54a7b504..a0eda717 100644 --- a/data_structures/linked_list/linked_list.dart +++ b/data_structures/linked_list/linked_list.dart @@ -8,7 +8,7 @@ class Node { Node.before(this.next, this.value); } -class LinkedListIterator extends Iterator { +class LinkedListIterator implements Iterator { Node? _current; @override diff --git a/data_structures/linked_list/merge_sorted_list.dart b/data_structures/linked_list/merge_sorted_list.dart index 575667f9..c31c26c7 100644 --- a/data_structures/linked_list/merge_sorted_list.dart +++ b/data_structures/linked_list/merge_sorted_list.dart @@ -69,18 +69,26 @@ ListNode? mergeTwoLists(ListNode? list1, ListNode? list2) { 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))); + 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))); + 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/dynamic_programming/01knapsack_recursive.dart b/dynamic_programming/01knapsack_recursive.dart index 7a9c28c7..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 index 1cac46a0..688dc037 100644 --- a/graphs/area_of_island.dart +++ b/graphs/area_of_island.dart @@ -19,14 +19,16 @@ const List> deltas = [ [-1, 0], // top neighbour [0, 1], // right neighbour [1, 0], // bottom neighbour - [0, -1] // left 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> visited = List.generate( + numRows, + (int index) => List.filled(numCols, false), + ); List areas = []; for (int i = 0; i < numRows; ++i) { @@ -43,7 +45,11 @@ bool isInvalidIndex(int i, int j, int rowCount, int colCount) { } List> adjacentNodes( - List> grid, List> visited, int x, int y) { + List> grid, + List> visited, + int x, + int y, +) { List> nodes = []; for (int i = 0; i < deltas.length; ++i) { int dx = x + deltas[i][0]; @@ -57,11 +63,16 @@ List> adjacentNodes( return nodes; } -void traverseNode(int i, int j, List> grid, List> visited, - List areas) { +void traverseNode( + int i, + int j, + List> grid, + List> visited, + List areas, +) { int area = 0; List> nodesToExplore = [ - [i, j] + [i, j], ]; while (nodesToExplore.isNotEmpty) { List node = nodesToExplore.removeLast(); @@ -91,7 +102,7 @@ void main() { [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] + [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], ]; expect(maxAreaOfIsland(island), 6); }); 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 ac85cffd..4903e584 100644 --- a/graphs/depth_first_search.dart +++ b/graphs/depth_first_search.dart @@ -56,8 +56,10 @@ 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 = []; depthFirstSearchHelper(graph.graph, visitedNodes, startNode, 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 3a72664d..50dc2dcd 100644 --- a/graphs/nearest_neighbour_algorithm.dart +++ b/graphs/nearest_neighbour_algorithm.dart @@ -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/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/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/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/lu_decomposition.dart b/maths/lu_decomposition.dart index 7980fcd5..d0350a7e 100644 --- a/maths/lu_decomposition.dart +++ b/maths/lu_decomposition.dart @@ -280,11 +280,13 @@ double f(double x, double y) { } void main() { - Matrix a = new Matrix(values: [ - [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/haversine_formula.dart b/other/haversine_formula.dart index 8be48ca8..caee0b3b 100644 --- a/other/haversine_formula.dart +++ b/other/haversine_formula.dart @@ -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/project_euler/problem_17/sol17.dart b/project_euler/problem_17/sol17.dart index d212e1ea..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'; 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 ddc6d722..5f2cab02 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,4 +10,4 @@ dev_dependencies: stack: ^0.2.1 environment: - sdk: ">=2.12.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/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/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/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 f5282866..a601ff0e 100644 --- a/trees/path_sum.dart +++ b/trees/path_sum.dart @@ -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', () { From b18ce0e9b18543a67c28b67541d55732733113d5 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 25 Apr 2026 17:50:17 +0300 Subject: [PATCH 441/443] test: standardize data structures tests using package:test --- data_structures/HashMap/Hashing.dart | 34 +++++---- .../Heap/Binary_Heap/Min_Heap.dart | 10 ++- data_structures/Queue/List_Queue.dart | 38 ++++++---- data_structures/Queue/Priority_Queue.dart | 28 +++++--- data_structures/Stack/Array_Stack.dart | 72 ++++++++----------- data_structures/Stack/Linked_List_Stack.dart | 41 ++++++----- .../binary_tree/basic_binary_tree.dart | 35 +++++---- 7 files changed, 141 insertions(+), 117 deletions(-) diff --git a/data_structures/HashMap/Hashing.dart b/data_structures/HashMap/Hashing.dart index 3a6ad40a..59c5b6d7 100644 --- a/data_structures/HashMap/Hashing.dart +++ b/data_structures/HashMap/Hashing.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author:Shawn //Email:stepfencurryxiao@gmail.com @@ -103,26 +105,22 @@ class HashMap { } void main() { - HashMap h = new HashMap(hsize: 7); - - print("Add key 5"); - h.insertHash(5); - - print("Add key 28"); - h.insertHash(28); - - print("Add key 1"); - h.insertHash(1); + test("Insert and Delete from HashMap", () { + HashMap h = new HashMap(hsize: 7); - print("Delete Key 28"); - h.deleteHash(28); + h.insertHash(5); + h.insertHash(28); + h.insertHash(1); - print("Print Table:\n"); - h.displayHashtable(); + expect(h.buckets[5].head?.data, equals(5)); + // 28 % 7 = 0 + expect(h.buckets[0].head?.data, equals(28)); + expect(h.buckets[1].head?.data, equals(1)); - print("Delete Key 1"); - h.deleteHash(1); + h.deleteHash(28); + expect(h.buckets[0].head, isNull); - print("Print Table:\n"); - h.displayHashtable(); + h.deleteHash(1); + expect(h.buckets[1].head, isNull); + }); } diff --git a/data_structures/Heap/Binary_Heap/Min_Heap.dart b/data_structures/Heap/Binary_Heap/Min_Heap.dart index ca6962af..3b56f6ca 100644 --- a/data_structures/Heap/Binary_Heap/Min_Heap.dart +++ b/data_structures/Heap/Binary_Heap/Min_Heap.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author:Shawn //Email:stepfencurryxiao@gmail.com @@ -72,7 +74,9 @@ List buildHead(List arr, int length) { } void main() { - List arr = [1, 3, 0, 5, 4, 6, 7, 8, 9]; - List BinaryHeap = buildHead(arr, arr.length); - print(BinaryHeap); + test("buildHead creates a min heap", () { + List arr = [1, 3, 0, 5, 4, 6, 7, 8, 9]; + List binaryHeap = buildHead(arr, arr.length); + expect(binaryHeap, equals([0, 3, 1, 5, 4, 6, 7, 8, 9])); + }); } diff --git a/data_structures/Queue/List_Queue.dart b/data_structures/Queue/List_Queue.dart index ca7d8d50..576136d1 100644 --- a/data_structures/Queue/List_Queue.dart +++ b/data_structures/Queue/List_Queue.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author:Shawn //Email:stepfencurryxiao@gmail.com @@ -36,25 +38,31 @@ class ListQueue { for (int i = 0; i < queue.length - 1; i++) { queue[i] = queue[i + 1]; } + count--; } return result; } } void main() { - ListQueue Queue = new ListQueue(); - Queue.enque(12); - Queue.enque(2); - Queue.enque(7); - print(Queue.queue); - print("Enqueue:"); - var returnData = Queue.deque(); - print("$returnData\n"); - print("Enqueue:"); - returnData = Queue.deque(); - print("$returnData\n"); - print("Enqueue:"); - returnData = Queue.deque(); - print("$returnData\n"); - print("Now the queue is: " + (Queue.queue).toString()); + test("Enqueue and deque elements", () { + ListQueue queue = new ListQueue(); + + // Note: The original hasElements returns true if queue.length > 0, + // but queue is initialized with length MAX_SIZE (10), so it always returns true. + expect(queue.hasElements(), isTrue); + + queue.enque(12); + queue.enque(2); + queue.enque(7); + + expect(queue.queue.sublist(0, 3), equals([12, 2, 7])); + + expect(queue.deque(), equals(12)); + expect(queue.deque(), equals(2)); + expect(queue.deque(), equals(7)); + + // Deque on empty + expect(queue.deque(), isNull); + }); } diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart index 94ceffe2..3a8a32ff 100644 --- a/data_structures/Queue/Priority_Queue.dart +++ b/data_structures/Queue/Priority_Queue.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + class PriorityQueue { List> _dataStore = >[]; @@ -62,14 +64,22 @@ class QueueItem { } void main() { - PriorityQueue queue = new PriorityQueue(); - queue.enqueue(1, 2); - queue.enqueue(2, 1); - queue.enqueue(3, 3); - queue.enqueue(4, 2); + test("Enqueue and dequeue based on priority", () { + PriorityQueue queue = new PriorityQueue(); + queue.enqueue(1, 2); + queue.enqueue(2, 1); + queue.enqueue(3, 3); + queue.enqueue(4, 2); - print(queue.dequeue()); - print(queue.dequeue()); - print(queue.dequeue()); - print(queue.dequeue()); + expect(queue.size, equals(4)); + expect(queue.front, equals(2)); // priority 1 + + expect(queue.dequeue(), equals(2)); + expect(queue.dequeue(), equals(1)); // priority 2, enqueued first + expect(queue.dequeue(), equals(4)); // priority 2 + expect(queue.dequeue(), equals(3)); // priority 3 + + expect(queue.isEmpty, isTrue); + expect(queue.dequeue(), isNull); + }); } diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index 09d218e0..710496db 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -1,5 +1,4 @@ -import 'package:test/expect.dart'; -import 'package:test/scaffolding.dart'; +import 'package:test/test.dart'; class ArrayStack { /// [stack] @@ -45,50 +44,37 @@ class ArrayStack { } void main() { - ArrayStack arrayStack = new ArrayStack(6); - - arrayStack.push('1'); - arrayStack.push("2"); - arrayStack.push('3'); - arrayStack.push("4"); - arrayStack.push('5'); - arrayStack.push("6"); - - test('test case 1', () { - expect(arrayStack.stack, ['1', '2', '3', '4', '5', '6']); - }); - - test('test case 2: pop stack', () { - expect('6', arrayStack.pop()); - }); - - test('test case 3: pop stack', () { - expect('5', arrayStack.pop()); - }); - - test('test case 4: pop stack', () { - expect('4', arrayStack.pop()); + test('test case 1: push and get stack', () { + ArrayStack arrayStack = new ArrayStack(6); + arrayStack.push('1'); + arrayStack.push("2"); + arrayStack.push('3'); + arrayStack.push("4"); + arrayStack.push('5'); + arrayStack.push("6"); + expect(arrayStack.stack, equals(['1', '2', '3', '4', '5', '6'])); }); - test('test case 5: pop stack', () { - expect('3', arrayStack.pop()); + test('test case 2: pop stack items', () { + ArrayStack arrayStack = new ArrayStack(6); + arrayStack.push('1'); + arrayStack.push("2"); + arrayStack.push('3'); + arrayStack.push("4"); + arrayStack.push('5'); + arrayStack.push("6"); + + expect(arrayStack.pop(), equals('6')); + expect(arrayStack.pop(), equals('5')); + expect(arrayStack.pop(), equals('4')); + expect(arrayStack.pop(), equals('3')); + expect(arrayStack.pop(), equals('2')); + expect(arrayStack.pop(), equals('1')); + expect(arrayStack.pop(), isNull); }); - test('test case 6: pop stack', () { - expect('2', arrayStack.pop()); - }); - - test('test case 7: pop stack', () { - expect('1', arrayStack.pop()); - }); - - test('test case 8: pop stack', () { - expect(null, arrayStack.pop()); - }); - - ArrayStack arrayStack2 = new ArrayStack(3); - - test('test case 9', () { - expect(arrayStack2.stack, [null, null, null]); + test('test case 9: empty stack', () { + ArrayStack arrayStack2 = new ArrayStack(3); + expect(arrayStack2.stack, equals([null, null, null])); }); } diff --git a/data_structures/Stack/Linked_List_Stack.dart b/data_structures/Stack/Linked_List_Stack.dart index 1ce58440..0ac7a1e0 100644 --- a/data_structures/Stack/Linked_List_Stack.dart +++ b/data_structures/Stack/Linked_List_Stack.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author: Shawn //Email: stepfencurryxiao@gmail.com @@ -57,20 +59,27 @@ class LinkedListStack { } } -int main() { - LinkedListStack Stack = new LinkedListStack(); - var returnData; - print("Push 2 5 9 7 to the stack\n"); - Stack.push("2"); - Stack.push("5"); - Stack.push("9"); - Stack.push("7"); - print("Successful push!\n"); - returnData = Stack.pop(); - print("Pop a data: $returnData\n"); - returnData = Stack.pop(); - print("Pop a data: $returnData\n"); - returnData = Stack.pop(); - print("Pop a data: $returnData\n"); - return 0; +void main() { + test("Push and Pop elements from LinkedListStack", () { + LinkedListStack stack = new LinkedListStack(); + + expect(stack.isEmpty(), isTrue); + expect(stack.getSize(), equals(0)); + + stack.push("2"); + stack.push("5"); + stack.push("9"); + stack.push("7"); + + expect(stack.isEmpty(), isFalse); + expect(stack.getSize(), equals(4)); + + expect(stack.pop(), equals("7")); + expect(stack.pop(), equals("9")); + expect(stack.pop(), equals("5")); + expect(stack.pop(), equals("2")); + + expect(stack.isEmpty(), isTrue); + expect(stack.pop(), isNull); + }); } diff --git a/data_structures/binary_tree/basic_binary_tree.dart b/data_structures/binary_tree/basic_binary_tree.dart index e89398be..7eb5540c 100644 --- a/data_structures/binary_tree/basic_binary_tree.dart +++ b/data_structures/binary_tree/basic_binary_tree.dart @@ -1,3 +1,5 @@ +import 'package:test/test.dart'; + //Author:Shawn //Email:stepfencurryxiao@gmail.com @@ -71,18 +73,25 @@ bool is_full_binary_tree(var tree) { //Main function for testing void main() { - var tree = Node(1); - tree.left = Node(2); - tree.right = Node(3); - tree.left.left = Node(4); - tree.left.right = Node(5); - tree.left.right.left = Node(6); - tree.right.left = Node(7); - tree.right.left.left = Node(8); - tree.right.left.left.right = Node(9); + test("Tree operations", () { + var tree = Node(1); + tree.left = Node(2); + tree.right = Node(3); + tree.left.left = Node(4); + tree.left.right = Node(5); + tree.left.right.left = Node(6); + tree.right.left = Node(7); + tree.right.left.left = Node(8); + tree.right.left.left.right = Node(9); + + expect(is_full_binary_tree(tree), isFalse); + expect(depth_of_tree(tree), equals(5.0)); + }); - print(is_full_binary_tree(tree)); - print(depth_of_tree(tree)); - print("Tree is:\n"); - display(tree); + test("is_full_binary_tree on full tree", () { + var fullTree = Node(1); + fullTree.left = Node(2); + fullTree.right = Node(3); + expect(is_full_binary_tree(fullTree), isTrue); + }); } From 73d13294af53e41d795660f4757748b435eeec1d Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 25 Apr 2026 17:52:16 +0300 Subject: [PATCH 442/443] Dart format --- data_structures/Queue/List_Queue.dart | 14 +++++++------- data_structures/Queue/Priority_Queue.dart | 4 ++-- data_structures/Stack/Array_Stack.dart | 2 +- data_structures/Stack/Linked_List_Stack.dart | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/data_structures/Queue/List_Queue.dart b/data_structures/Queue/List_Queue.dart index 576136d1..60153757 100644 --- a/data_structures/Queue/List_Queue.dart +++ b/data_structures/Queue/List_Queue.dart @@ -47,21 +47,21 @@ class ListQueue { void main() { test("Enqueue and deque elements", () { ListQueue queue = new ListQueue(); - - // Note: The original hasElements returns true if queue.length > 0, + + // Note: The original hasElements returns true if queue.length > 0, // but queue is initialized with length MAX_SIZE (10), so it always returns true. - expect(queue.hasElements(), isTrue); - + expect(queue.hasElements(), isTrue); + queue.enque(12); queue.enque(2); queue.enque(7); - + expect(queue.queue.sublist(0, 3), equals([12, 2, 7])); - + expect(queue.deque(), equals(12)); expect(queue.deque(), equals(2)); expect(queue.deque(), equals(7)); - + // Deque on empty expect(queue.deque(), isNull); }); diff --git a/data_structures/Queue/Priority_Queue.dart b/data_structures/Queue/Priority_Queue.dart index 3a8a32ff..30a89789 100644 --- a/data_structures/Queue/Priority_Queue.dart +++ b/data_structures/Queue/Priority_Queue.dart @@ -73,12 +73,12 @@ void main() { expect(queue.size, equals(4)); expect(queue.front, equals(2)); // priority 1 - + expect(queue.dequeue(), equals(2)); expect(queue.dequeue(), equals(1)); // priority 2, enqueued first expect(queue.dequeue(), equals(4)); // priority 2 expect(queue.dequeue(), equals(3)); // priority 3 - + expect(queue.isEmpty, isTrue); expect(queue.dequeue(), isNull); }); diff --git a/data_structures/Stack/Array_Stack.dart b/data_structures/Stack/Array_Stack.dart index 710496db..2d7136cd 100644 --- a/data_structures/Stack/Array_Stack.dart +++ b/data_structures/Stack/Array_Stack.dart @@ -63,7 +63,7 @@ void main() { arrayStack.push("4"); arrayStack.push('5'); arrayStack.push("6"); - + expect(arrayStack.pop(), equals('6')); expect(arrayStack.pop(), equals('5')); expect(arrayStack.pop(), equals('4')); diff --git a/data_structures/Stack/Linked_List_Stack.dart b/data_structures/Stack/Linked_List_Stack.dart index 0ac7a1e0..69ac400b 100644 --- a/data_structures/Stack/Linked_List_Stack.dart +++ b/data_structures/Stack/Linked_List_Stack.dart @@ -62,7 +62,7 @@ class LinkedListStack { void main() { test("Push and Pop elements from LinkedListStack", () { LinkedListStack stack = new LinkedListStack(); - + expect(stack.isEmpty(), isTrue); expect(stack.getSize(), equals(0)); @@ -78,7 +78,7 @@ void main() { expect(stack.pop(), equals("9")); expect(stack.pop(), equals("5")); expect(stack.pop(), equals("2")); - + expect(stack.isEmpty(), isTrue); expect(stack.pop(), isNull); }); From 73da8ab4ea413eee9bf29aa2263157d86060f871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=8D=8CShawn?= Date: Sun, 28 Jun 2026 21:36:25 +0800 Subject: [PATCH 443/443] Update copyright year in LICENSE file --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 3b57d694..76ef0691 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 The Algorithms +Copyright (c) 2026 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