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 01/13] 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 02/13] 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 03/13] 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 04/13] 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 05/13] 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 06/13] 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 07/13] 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 08/13] 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 09/13] 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 10/13] 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 11/13] 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 12/13] 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 13/13] 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; }