├── .gitignore ├── .travis.yml ├── 01_array ├── class_data.dart ├── high_array.dart ├── low_array.dart ├── ordered_array.dart ├── tasks │ ├── task_1.dart │ ├── task_2.dart │ ├── task_3.dart │ ├── task_4.dart │ ├── task_5.dart │ ├── task_6.dart │ └── test │ │ ├── task_1_test.dart │ │ ├── task_2_test.dart │ │ ├── task_3_test.dart │ │ ├── task_4_test.dart │ │ ├── task_5_test.dart │ │ └── task_6_test.dart └── test │ ├── class_data_test.dart │ ├── high_array_test.dart │ ├── low_array_test.dart │ └── ordered_array_test.dart ├── 02_simple_sorting ├── buble_sort.dart ├── insert_sort.dart ├── object_sort.dart ├── select_sort.dart └── test │ ├── buble_sort_test.dart │ ├── insert_sort_test.dart │ ├── object_sort_test.dart │ └── select_sort_test.dart ├── 03_stack_queue ├── infix.dart ├── postfix.dart ├── priority_queue.dart ├── queue.dart └── stack │ ├── brackets.dart │ ├── reverse.dart │ └── stack.dart ├── 04_linked_list ├── double_linked_list.dart ├── first_last_list.dart ├── link_insertion_sort.dart ├── link_queue_list.dart ├── link_stack_list.dart ├── linked_list │ ├── linked_list.dart │ └── simple_linked_list.dart ├── list_iterator.dart └── sorted_list.dart ├── 05_recursion ├── anagram.dart ├── binary_search.dart ├── merge.dart ├── merge_sort.dart ├── power.dart ├── stack_triangle.dart ├── stack_triangle2.dart ├── towers.dart └── triangle.dart ├── 06_sorting ├── partion.dart ├── quick_sort1.dart ├── quick_sort2.dart └── shell_sort.dart ├── 07_binary_tree └── binary_tree.dart ├── 09_tree_2_3_4 └── tree_2_3_4.dart ├── 10_hash ├── hash.dart ├── hash_chain.dart └── hash_double.dart ├── 11_heap ├── heap.dart └── heap_sort.dart ├── 12_graph ├── bfs.dart ├── dfs.dart ├── mst.dart ├── topo.dart └── until │ └── graph.dart ├── 13_weighted_graph ├── mstw.dart └── path.dart ├── LICENSE ├── README.md ├── analysis_options.yaml ├── dart_test.yaml ├── doc ├── graph-mst.jpg ├── graph-not-optimized.jpg ├── graph.jpg ├── graph_shortest_path.jpg ├── weighted-graph-mstw-input.jpg └── weighted-graph-mstw-output.jpg └── pubspec.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | # Files and directories created by pub 2 | .packages 3 | .pub/ 4 | .dart_tool/ 5 | build/ 6 | # Remove the following pattern if you wish to check in your lock file 7 | pubspec.lock 8 | 9 | # Directory created by dartdoc 10 | doc/api/ 11 | 12 | .idea 13 | .vscode/ 14 | 15 | .DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: dart 2 | dart: 3 | - stable 4 | dart_task: 5 | - test 6 | -------------------------------------------------------------------------------- /01_array/class_data.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Person { 4 | String firstName; 5 | String lastName; 6 | int age; 7 | 8 | // Constructor shorthand 9 | Person(this.lastName, this.firstName, this.age) {} 10 | 11 | void displayPerson() { 12 | stdout.write('Last Name $lastName, '); 13 | stdout.write('First Name $firstName, '); 14 | stdout.writeln('Age $age'); 15 | } 16 | 17 | String getLastName() { 18 | return lastName; 19 | } 20 | } 21 | 22 | class DataArray { 23 | List a; // reference to array 24 | int nElems; // number of data items 25 | 26 | // Constructor 27 | DataArray(int max) { 28 | a = new List(max); // create array (List in Dart) 29 | nElems = 0; // initialize items count 30 | } 31 | 32 | /// Find specified value (Liner search) 33 | Person find(String searchName) { 34 | int j; 35 | // for each element 36 | for(j = 0; j < nElems; j++) { 37 | if(a[j].getLastName() == searchName) { 38 | break; // exit loop before end 39 | } 40 | } 41 | if(j == nElems) { 42 | return null; // can't find it 43 | } else { 44 | return a[j]; // found it 45 | } 46 | } 47 | 48 | /// Insert Data to Array 49 | void insert(String lastName, String firstName, int age) { 50 | a[nElems] = new Person(lastName, firstName, age); 51 | nElems ++; // increment size 52 | } 53 | 54 | /// Delete person from array 55 | bool delete(String searchName) { 56 | int j; 57 | for(j = 0; j < nElems; j++) { 58 | if (a[j].getLastName() == searchName) { 59 | break; 60 | } 61 | } 62 | if (j == nElems) { 63 | return false; 64 | } else { 65 | // shift down 66 | for (int k = j; k < nElems; k ++) { 67 | a[k] = a[k + 1]; 68 | } 69 | } 70 | nElems --; // decrement size 71 | return true; 72 | } 73 | 74 | /// Display array contents 75 | void display() { 76 | for(int j = 0; j < nElems; j++) { 77 | a[j].displayPerson(); 78 | } 79 | } 80 | } 81 | 82 | void main() { 83 | int maxSize = 100; // array size 84 | DataArray array = new DataArray(maxSize); // create instance of DataArray 85 | 86 | // Insert 10 items 87 | array.insert('Evans', 'Patty', 24); 88 | array.insert('Smith', 'Lorraine', 37); 89 | array.insert('Yee', 'Tom', 43); 90 | array.insert('Adams', 'Henry', 63); 91 | array.insert('Hashimoto', 'Sato', 21); 92 | array.insert('Stimson', 'Henry', 29); 93 | array.insert('Velasquez', 'Jose', 72); 94 | array.insert('Lamarque', 'Henry', 54); 95 | array.insert('Vang', 'Minh', 22); 96 | array.insert('Creswell', 'Lucinda', 18); 97 | 98 | // Display items 99 | array.display(); 100 | 101 | // Search item 102 | String searchKey = 'Stimson'; 103 | Person found = array.find(searchKey); 104 | 105 | if (found != null) { 106 | stdout.write('Found'); 107 | found.displayPerson(); 108 | } else { 109 | stdout.writeln("Can't find Person with key = $searchKey"); 110 | } 111 | 112 | // Delete 3 items 113 | stdout.writeln('Deleting Smith, Yee, and Creswell'); 114 | array.delete('Smith'); 115 | array.delete('Yee'); 116 | array.delete('Creswell'); 117 | 118 | // Display 119 | array.display(); 120 | } 121 | -------------------------------------------------------------------------------- /01_array/high_array.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class HighArray { 4 | List a; // ref to array a 5 | int nElems; // number of data items 6 | 7 | // Constructor 8 | HighArray(int max) { 9 | a = new List(max); // create array (List in Dart) 10 | nElems = 0; // initialize items count 11 | } 12 | 13 | /// Find specified value 14 | bool find(int searchKey) { 15 | int j; 16 | // for each element 17 | for(j = 0; j < nElems; j++) { 18 | // found item? 19 | if (a[j] == searchKey) { 20 | break; // exit loop before end 21 | } 22 | } 23 | // is end of array 24 | if (j == nElems) { 25 | return false; 26 | } else { 27 | return true; 28 | } 29 | } 30 | 31 | /// Insert element into array 32 | void insert(int value) { 33 | a[nElems] = value; // insert it 34 | nElems ++; // increment size 35 | } 36 | 37 | /// Delete element from array 38 | bool delete(int value) { 39 | int j; 40 | for(j = 0; j < nElems; j++) { 41 | if (value == a[j]) { 42 | break; 43 | } 44 | } 45 | 46 | if(j == nElems) { 47 | return false; 48 | } else { 49 | for (int k = j; k < nElems - 1; k++) { 50 | a[k] = a[k + 1]; 51 | } 52 | nElems --; 53 | return true; 54 | } 55 | } 56 | 57 | /// Display Array contents 58 | void display() { 59 | // for each element 60 | for(int j = 0; j < nElems; j++) { 61 | stdout.write('${a[j]} '); // display it 62 | } 63 | stdout.writeln(''); // add new line on the end 64 | } 65 | } 66 | 67 | 68 | void main() { 69 | int maxSize = 10; // array size 70 | HighArray array = new HighArray(maxSize); // create instance of HighArray 71 | 72 | // Insert 10 items 73 | array.insert(77); 74 | array.insert(99); 75 | array.insert(44); 76 | array.insert(55); 77 | array.insert(22); 78 | array.insert(88); 79 | array.insert(11); 80 | array.insert(0); 81 | array.insert(66); 82 | array.insert(33); 83 | 84 | // Display items 85 | array.display(); 86 | 87 | // Search Element 88 | int searchKey = 35; 89 | if(array.find(searchKey)) { 90 | stdout.writeln('Found $searchKey'); 91 | } else { 92 | stdout.writeln("Can't find $searchKey"); 93 | } 94 | 95 | // Delete 3 items 96 | array.delete(0); 97 | array.delete(55); 98 | array.delete(99); 99 | 100 | // Display items again 101 | array.display(); 102 | } 103 | -------------------------------------------------------------------------------- /01_array/low_array.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class LowArray { 4 | List a; // ref to array a 5 | 6 | // Constructor 7 | LowArray(int size) { 8 | a = new List(size); // create array (List in Dart) 9 | } 10 | 11 | // set value 12 | void setElement(int index, int value) { 13 | a[index] = value; 14 | } 15 | 16 | // get value 17 | int getElement(int index) { 18 | return a[index]; 19 | } 20 | } 21 | 22 | void main(List arguments) { 23 | LowArray array = new LowArray(100); // create LowArray instance 24 | int nElement = 0; // number of items in array 25 | int j; // loop variable 26 | 27 | // Insert 10 items 28 | array.setElement(0, 77); 29 | array.setElement(1, 99); 30 | array.setElement(2, 44); 31 | array.setElement(3, 55); 32 | array.setElement(4, 22); 33 | array.setElement(5, 88); 34 | array.setElement(6, 11); 35 | array.setElement(7, 00); 36 | array.setElement(8, 66); 37 | array.setElement(9, 33); 38 | 39 | // update number of items in array 40 | nElement = 10; 41 | 42 | // Display items 43 | for(j = 0; j < nElement; j++) { 44 | stdout.write('${array.getElement(j)} '); 45 | } 46 | stdout.writeln(''); 47 | 48 | // Element Search 49 | int searchKey = 26; 50 | 51 | // for each element 52 | for(j = 0; j < nElement; j++) { 53 | // found item? 54 | if (array.getElement(j) == searchKey) { 55 | break; 56 | } 57 | } 58 | 59 | if(j == nElement) { 60 | stdout.writeln("Can't find $searchKey"); 61 | } else { 62 | stdout.writeln('Found $searchKey'); 63 | } 64 | 65 | // Delete Element with key 55 66 | for(j = 0; j < nElement; j++) { 67 | if (array.getElement(j) == 55) { 68 | break; 69 | } 70 | } 71 | // Higher ones down 72 | for(int k = j; k < nElement; k++) { 73 | array.setElement(k, array.getElement(k + 1)); 74 | } 75 | nElement --; // decrement size 76 | 77 | 78 | // Display items 79 | for(int j = 0; j < nElement; j++) { 80 | stdout.write('${array.getElement(j)} '); 81 | } 82 | stdout.writeln(''); 83 | 84 | } 85 | -------------------------------------------------------------------------------- /01_array/ordered_array.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class OrderedArray { 4 | List a; // ref to array a 5 | int nElems; // // number of data items 6 | 7 | // Constructor 8 | OrderedArray(int max) { 9 | a = new List(max); // create array (List in Dart) 10 | nElems = 0; // initialize items count 11 | } 12 | 13 | int size() { 14 | return nElems; 15 | } 16 | 17 | /// Binary search 18 | int find(int searchKey) { 19 | int lowerBound = 0; 20 | int upperBound = nElems - 1; 21 | int curIn; 22 | 23 | while(true) { 24 | curIn = (lowerBound + upperBound) ~/ 2; 25 | if(a[curIn] == searchKey) { 26 | return curIn; // found It 27 | } else if (lowerBound > upperBound) { 28 | return nElems; // can't find it 29 | } else { // divide range 30 | if(a[curIn] < searchKey) { 31 | lowerBound = curIn + 1; // it's in upper half; 32 | } else { 33 | upperBound = curIn - 1; // it's in lower half; 34 | } 35 | } 36 | } 37 | } 38 | 39 | /// Insert element into ordered array 40 | void insert(int value) { 41 | int j; 42 | for(j = 0; j < nElems; j++) { // find where it goes 43 | if (a[j] > value) { // liner search 44 | break; 45 | } 46 | } 47 | for(int k = nElems; k > j; k--) { // move bigger ones up 48 | a[k] = a[k - 1]; 49 | } 50 | a[j] = value; // insert it 51 | nElems++; // increment size 52 | } 53 | 54 | /// Delete element from array 55 | bool delete(int value) { 56 | int j = find(value); 57 | if (j == nElems) { // can't find it 58 | return false; 59 | } else { // found it 60 | for(int k = j; k > j; k++) { // move bigger ones down 61 | a[k] = a[k + 1]; 62 | } 63 | nElems--; // decrement size 64 | return true; 65 | } 66 | } 67 | 68 | /// Display array contents 69 | void display() { 70 | for(int j = 0; j < nElems; j ++) { // for each element 71 | stdout.write('${a[j]} '); // display it 72 | } 73 | stdout.writeln(''); 74 | } 75 | } 76 | 77 | void main() { 78 | int maxSize = 100; // array size 79 | OrderedArray array = new OrderedArray(maxSize); // // create instance of OrderedArray 80 | 81 | // Insert 10 items 82 | array.insert(77); 83 | array.insert(99); 84 | array.insert(44); 85 | array.insert(55); 86 | array.insert(22); 87 | array.insert(88); 88 | array.insert(11); 89 | array.insert(00); 90 | array.insert(66); 91 | array.insert(33); 92 | 93 | // Search item 94 | int searchKey = 55; 95 | 96 | if(array.find(searchKey) != array.size()) { 97 | stdout.writeln('Found $searchKey'); 98 | } else { 99 | stdout.writeln("Can't find $searchKey"); 100 | } 101 | 102 | // Display items 103 | array.display(); 104 | 105 | // Delete 3 items 106 | array.delete(00); 107 | array.delete(55); 108 | array.delete(99); 109 | 110 | // Display items again 111 | array.display(); 112 | } 113 | -------------------------------------------------------------------------------- /01_array/tasks/task_1.dart: -------------------------------------------------------------------------------- 1 | /// To the HighArray class in the `high_array.dart` program 2 | /// add a method called `getMax()` that returns the value of the highest key in the array, or –1 if the array is empty. 3 | /// You can assume all the keys are positive numbers. 4 | 5 | import 'dart:io'; 6 | 7 | import '../high_array.dart'; 8 | 9 | class HighArrayTask1 extends HighArray { 10 | 11 | /// Inheritance tha super class 12 | HighArrayTask1(int max) 13 | : super(max); 14 | 15 | /// Find Max value 16 | int getMax() { 17 | if (nElems == 0) { 18 | return -1; 19 | } 20 | int max = a[0]; 21 | for(int i = 0; i < nElems; i++) { 22 | if(a[i] > max) { 23 | max = a[i]; 24 | } 25 | } 26 | return max; 27 | } 28 | } 29 | 30 | 31 | void main() { 32 | int maxSize = 10; // array size 33 | HighArrayTask1 array = new HighArrayTask1(maxSize); 34 | 35 | // Insert 10 items 36 | array.insert(77); 37 | array.insert(99); 38 | array.insert(44); 39 | array.insert(55); 40 | array.insert(22); 41 | array.insert(88); 42 | array.insert(11); 43 | array.insert(00); 44 | array.insert(66); 45 | array.insert(33); 46 | 47 | // Display items 48 | array.display(); 49 | stdout.writeln('Max value is ${array.getMax()}'); 50 | 51 | } 52 | -------------------------------------------------------------------------------- /01_array/tasks/task_2.dart: -------------------------------------------------------------------------------- 1 | /// Modify the method from `task_1.dart` so that the item with the highest key is not only returned by the method, 2 | /// but also removed from the array. 3 | /// Call the method `removeMax()`. 4 | 5 | import 'dart:io'; 6 | 7 | import '../high_array.dart'; 8 | 9 | class HighArrayTask2 extends HighArray { 10 | HighArrayTask2(int max) 11 | : super(max); 12 | 13 | /// Remove Max value 14 | int removeMax() { 15 | int max = a[0]; 16 | int maxIndex; 17 | 18 | for(int i = 0; i < nElems; i++) { 19 | if(a[i] > max) { 20 | max = a[i]; 21 | maxIndex = i; 22 | } 23 | } 24 | 25 | for(int k = maxIndex; k < nElems - 1; k ++) { 26 | a[k] = a[k + 1]; 27 | } 28 | nElems --; 29 | 30 | return max; 31 | } 32 | } 33 | 34 | 35 | void main() { 36 | int maxSize = 10; // array size 37 | HighArrayTask2 array = new HighArrayTask2(maxSize); 38 | 39 | // Insert 10 items 40 | array.insert(77); 41 | array.insert(44); 42 | array.insert(55); 43 | array.insert(22); 44 | array.insert(88); 45 | array.insert(11); 46 | array.insert(00); 47 | array.insert(66); 48 | array.insert(99); 49 | array.insert(33); 50 | 51 | // Display items 52 | array.display(); 53 | 54 | stdout.writeln('Max value is ${array.removeMax()}'); 55 | 56 | array.display(); 57 | } 58 | -------------------------------------------------------------------------------- /01_array/tasks/task_3.dart: -------------------------------------------------------------------------------- 1 | /// The removeMax() method in `task_2.dart` suggests a way to sort the contents of an array by key value. 2 | /// Implement a sorting scheme that does not require modifying the HighArray class, but only the code in main(). 3 | /// You’ll need a second array, which will end up inversely sorted. 4 | /// (This scheme is a rather crude variant of the selection sort in Chap03, 'Simple Sorting.) 5 | 6 | import 'dart:io'; 7 | 8 | import '../high_array.dart'; 9 | 10 | class HighArrayTask3 extends HighArray { 11 | 12 | HighArrayTask3(int max): super(max); 13 | 14 | /// Remove Max value 15 | int removeMax() { 16 | int max = a[0]; 17 | int maxIndex = 0; 18 | 19 | for(int i = 0; i < nElems; i++) { 20 | if(a[i] > max) { 21 | max = a[i]; 22 | maxIndex = i; 23 | } 24 | } 25 | 26 | for(int k = maxIndex; k < nElems - 1; k ++) { 27 | a[k] = a[k + 1]; 28 | } 29 | nElems --; 30 | 31 | return max; 32 | } 33 | } 34 | 35 | 36 | void main() { 37 | int maxSize = 11; // array size 38 | HighArrayTask3 array = new HighArrayTask3(maxSize); 39 | 40 | // Insert 10 items 41 | array.insert(77); 42 | array.insert(99); 43 | array.insert(44); 44 | array.insert(55); 45 | array.insert(22); 46 | array.insert(88); 47 | array.insert(11); 48 | array.insert(00); 49 | array.insert(66); 50 | array.insert(33); 51 | 52 | // Display items 53 | array.display(); 54 | 55 | int length = array.nElems; 56 | HighArray orderedArray = new HighArray(maxSize); 57 | for(int i = 0; i < length; i++) { 58 | int item = array.removeMax(); 59 | orderedArray.insert(item); 60 | } 61 | 62 | orderedArray.display(); 63 | } 64 | -------------------------------------------------------------------------------- /01_array/tasks/task_4.dart: -------------------------------------------------------------------------------- 1 | /// Modify the `ordered_array.dart` so that the insert() and delete() 2 | /// routines, as well as find(), use a binary search, as suggested in the text. 3 | 4 | import 'dart:io'; 5 | 6 | import '../ordered_array.dart'; 7 | 8 | class OrderedArrayTask4 extends OrderedArray { 9 | List a; 10 | int nElems; 11 | 12 | // Constructor 13 | OrderedArrayTask4(int max) 14 | : super(max); 15 | 16 | /// Put element into ordered array using Binary Search 17 | @override 18 | void insert(int value) { 19 | int lowerBound = 0; 20 | int upperBound = nElems - 1; 21 | int j = 0; 22 | 23 | while(true) { 24 | if(lowerBound > upperBound) break; 25 | j = (lowerBound + upperBound) ~/ 2; 26 | if(a[j] < value) { 27 | lowerBound = j + 1; 28 | j ++; 29 | } else { 30 | upperBound = j -1; 31 | } 32 | } 33 | 34 | for(int k = nElems; k > j; k--) { 35 | a[k] = a[k - 1]; 36 | } 37 | a[j] = value; 38 | nElems++; 39 | } 40 | 41 | /// Delete Element from array 42 | @override 43 | bool delete(int value) { 44 | int j = find(value); 45 | if (j == nElems) { 46 | return false; 47 | } 48 | else { 49 | for(int k = j; k > j; k++) { 50 | a[k] = a[k + 1]; 51 | } 52 | nElems--; 53 | return true; 54 | } 55 | } 56 | } 57 | 58 | void main() { 59 | int maxSize = 100; 60 | OrderedArrayTask4 array = new OrderedArrayTask4(maxSize); 61 | 62 | // Insert 10 items 63 | array.insert(77); 64 | array.insert(99); 65 | array.insert(44); 66 | array.insert(55); 67 | array.insert(22); 68 | array.insert(88); 69 | array.insert(11); 70 | array.insert(00); 71 | array.insert(66); 72 | array.insert(33); 73 | 74 | 75 | // Display items 76 | array.display(); 77 | } 78 | -------------------------------------------------------------------------------- /01_array/tasks/task_5.dart: -------------------------------------------------------------------------------- 1 | /// Add a merge() method to the `OrderedArray` class in the `ordered_array.dart` 2 | /// program so that you can merge two ordered source arrays into an ordered destination array. 3 | /// Write code in main() that inserts some random 4 | /// numbers into the two source arrays, invokes merge(), and displays the contents of the resulting destination array. 5 | /// The source arrays may hold different numbers of data items. 6 | /// In your algorithm you will need to compare the keys of 7 | /// the source arrays, picking the smallest one to copy to the destination. 8 | /// You’ll also need to handle the situation when one source array exhausts its contents before the other. 9 | 10 | import 'dart:io'; 11 | import 'dart:math'; 12 | 13 | import '../ordered_array.dart'; 14 | 15 | class OrderedArrayTask5 extends OrderedArray { 16 | 17 | OrderedArrayTask5(int max) 18 | : super(max); 19 | 20 | int getValueAt(int index) { 21 | return a[index]; 22 | } 23 | 24 | void setValueAt(int index, int value) { 25 | a[index] = value; 26 | } 27 | 28 | static OrderedArrayTask5 merge(OrderedArrayTask5 source_one, OrderedArrayTask5 source_two) { 29 | final int length = source_one.size() + source_two.size(); 30 | 31 | OrderedArrayTask5 destination = new OrderedArrayTask5(length); 32 | 33 | // initialize indexes for source_one, source_two and destination 34 | int i = 0, j = 0, k = 0; 35 | while (i < source_one.size() && j < source_two.size()) { 36 | if (source_one.getValueAt(i) <= source_two.getValueAt(j)) { 37 | destination.setValueAt(k, source_one.getValueAt(i)); 38 | i ++; 39 | } else { 40 | destination.setValueAt(k, source_two.getValueAt(j)); 41 | j ++; 42 | } 43 | destination.nElems ++; 44 | k ++; 45 | } 46 | 47 | while (i < source_one.size()) { 48 | destination.setValueAt(k, source_one.getValueAt(i)); 49 | destination.nElems ++; 50 | k ++; 51 | j ++; 52 | i ++; 53 | } 54 | 55 | while (j < source_two.size()) { 56 | destination.setValueAt(k, source_two.getValueAt(j)); 57 | destination.nElems ++; 58 | k ++; 59 | j ++; 60 | i ++; 61 | } 62 | return destination; 63 | } 64 | } 65 | 66 | void main() { 67 | Random random = new Random(); 68 | 69 | final int maxArraySize = 10; 70 | OrderedArrayTask5 source_one = new OrderedArrayTask5(maxArraySize); 71 | OrderedArrayTask5 source_two = new OrderedArrayTask5(maxArraySize); 72 | 73 | for(int i = 0; i < maxArraySize - 1; i ++) { 74 | source_one.insert(random.nextInt(100)); 75 | source_two.insert(random.nextInt(100)); 76 | } 77 | 78 | stdout.write('source_one = '); 79 | source_one.display(); 80 | stdout.write('source_two = '); 81 | source_two.display(); 82 | 83 | OrderedArrayTask5 destination = OrderedArrayTask5.merge(source_one, source_two); 84 | 85 | stdout.write('destination = '); 86 | destination.display(); 87 | } 88 | -------------------------------------------------------------------------------- /01_array/tasks/task_6.dart: -------------------------------------------------------------------------------- 1 | /// Write a `noDups()` method for the `HighArray` class of the `high_array.dart` program. 2 | /// This method should remove all duplicates from the array. 3 | /// That is, if three items with the key 17 appear in the array, `noDups()` should remove two of them. 4 | /// Don’t worry about maintaining the order of the items. 5 | /// One approach is to first compare every item with all the other items and 6 | /// overwrite any duplicates with a null (or a distinctive value that isn’t used for real keys). 7 | /// Then remove all the nulls. Of course, the array size will be reduced. 8 | 9 | 10 | import 'dart:io'; 11 | 12 | import '../high_array.dart'; 13 | 14 | class HighArrayTask6 extends HighArray { 15 | 16 | HighArrayTask6(int max) 17 | : super(max); 18 | 19 | @override 20 | String toString() { 21 | String string = ''; 22 | for(int j = 0; j < nElems; j++) { 23 | string += '${a[j]} '; 24 | } 25 | return string.trim(); 26 | } 27 | 28 | void noDups() { 29 | int size = nElems - 1; 30 | int value = null; 31 | 32 | for(int i = 0; i <= size; i ++) { 33 | value = a[i]; 34 | for (int j = i + 1; j <= size; j ++) { 35 | if (a[j] == value) { 36 | for(int k = j; k < size; k ++) { 37 | a[k] = a[k + 1]; 38 | } 39 | nElems --; 40 | j --; 41 | size --; 42 | } 43 | } 44 | } 45 | } 46 | } 47 | 48 | 49 | void main() { 50 | int maxArraySize = 10; 51 | HighArrayTask6 highArrayTask6 = new HighArrayTask6(maxArraySize); 52 | 53 | highArrayTask6.insert(10); 54 | highArrayTask6.insert(15); 55 | highArrayTask6.insert(3); 56 | highArrayTask6.insert(15); 57 | highArrayTask6.insert(19); 58 | highArrayTask6.insert(18); 59 | highArrayTask6.insert(3); 60 | highArrayTask6.insert(8); 61 | highArrayTask6.insert(10); 62 | highArrayTask6.insert(65); 63 | 64 | stdout.write('With Duplicates highArrayTask6 = '); 65 | highArrayTask6.display(); 66 | 67 | stdout.write('Without Duplicates highArrayTask6 = '); 68 | highArrayTask6.noDups(); 69 | highArrayTask6.display(); 70 | } 71 | -------------------------------------------------------------------------------- /01_array/tasks/test/task_1_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_1.dart'; 4 | 5 | void main() { 6 | HighArrayTask1 array; 7 | setUp(() { 8 | array = new HighArrayTask1(10); 9 | 10 | array.insert(10); 11 | array.insert(44); 12 | array.insert(30); 13 | array.insert(22); 14 | array.insert(88); 15 | array.insert(99); 16 | array.insert(94); 17 | array.insert(2); 18 | array.insert(66); 19 | array.insert(3); 20 | }); 21 | 22 | group('HightArrayTask1', () { 23 | test('.getMax() return max element of array', () { 24 | expect(array.getMax(), equals(99)); 25 | }); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /01_array/tasks/test/task_2_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_2.dart'; 4 | 5 | void main() { 6 | HighArrayTask2 array; 7 | setUp(() { 8 | array = new HighArrayTask2(10); 9 | 10 | array.insert(10); 11 | array.insert(44); 12 | array.insert(30); 13 | array.insert(22); 14 | array.insert(88); 15 | array.insert(94); 16 | array.insert(2); 17 | array.insert(66); 18 | array.insert(3); 19 | array.insert(99); 20 | }); 21 | 22 | group('HightArrayTask2', () { 23 | test('.removeMax() return and remove max element of array', () { 24 | expect(array.removeMax(), equals(99)); 25 | expect(array.find(99), equals(false)); 26 | expect(array.nElems, equals(9)); 27 | }); 28 | }); 29 | } 30 | -------------------------------------------------------------------------------- /01_array/tasks/test/task_3_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_3.dart'; 4 | 5 | void main() { 6 | HighArrayTask3 array; 7 | HighArrayTask3 orderedArray; 8 | setUp(() { 9 | int maxArraySize = 10; 10 | 11 | array = new HighArrayTask3(maxArraySize); 12 | 13 | array.insert(10); 14 | array.insert(44); 15 | array.insert(30); 16 | array.insert(22); 17 | array.insert(88); 18 | array.insert(94); 19 | array.insert(2); 20 | array.insert(66); 21 | array.insert(3); 22 | array.insert(99); 23 | 24 | 25 | orderedArray = new HighArrayTask3(maxArraySize); 26 | }); 27 | 28 | group('HightArrayTask3', () { 29 | test('.removeMax() for build new array sorted array', () { 30 | 31 | int length = array.nElems; 32 | for(int i = 0; i < length; i++) { 33 | int item = array.removeMax(); 34 | orderedArray.insert(item); 35 | } 36 | 37 | expect(orderedArray.a, equals([99, 94, 88, 66, 44, 30, 22, 10, 3, 2])); 38 | }); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /01_array/tasks/test/task_4_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_4.dart'; 4 | 5 | void main() { 6 | OrderedArrayTask4 orderedArray; 7 | setUp(() { 8 | int maxArraySize = 10; 9 | 10 | orderedArray = new OrderedArrayTask4(maxArraySize); 11 | 12 | // insert 10 elements 13 | orderedArray.insert(8); 14 | orderedArray.insert(4); 15 | orderedArray.insert(10); 16 | orderedArray.insert(55); 17 | orderedArray.insert(32); 18 | orderedArray.insert(18); 19 | orderedArray.insert(50); 20 | orderedArray.insert(90); 21 | orderedArray.insert(14); 22 | orderedArray.insert(0); 23 | }); 24 | 25 | group('OrderedArrayTask4', () { 26 | test('.insert() put element in right position', () { 27 | expect(orderedArray.a, equals([0, 4, 8, 10, 14, 18, 32, 50, 55, 90])); 28 | expect(orderedArray.nElems, 10); 29 | }); 30 | test('.delete() remove element by key and return true', () { 31 | expect(orderedArray.delete(14), equals(true)); 32 | expect(orderedArray.nElems, equals(9)); 33 | }); 34 | test('.delete() return false if element not found', () { 35 | expect(orderedArray.delete(105), equals(false)); 36 | expect(orderedArray.nElems, equals(10)); 37 | }); 38 | }); 39 | } -------------------------------------------------------------------------------- /01_array/tasks/test/task_5_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_5.dart'; 4 | 5 | void main() { 6 | OrderedArrayTask5 source_one; 7 | OrderedArrayTask5 source_two; 8 | 9 | setUp(() { 10 | int maxArraySize = 5; 11 | source_one = new OrderedArrayTask5(maxArraySize); 12 | source_two = new OrderedArrayTask5(maxArraySize); 13 | 14 | source_one.insert(59); 15 | source_one.insert(12); 16 | source_one.insert(90); 17 | source_one.insert(45); 18 | source_one.insert(3); 19 | 20 | source_two.insert(100); 21 | source_two.insert(7); 22 | source_two.insert(46); 23 | source_two.insert(14); 24 | source_two.insert(17); 25 | }); 26 | 27 | group('OrderedArrayTask5', () { 28 | test('.merge() should merge two equal length array withoud duplicates', () { 29 | OrderedArrayTask5 result = OrderedArrayTask5.merge(source_one, source_two); 30 | 31 | expect(result.a, equals([3, 7, 12, 14, 17, 45, 46, 59, 90, 100])); 32 | expect(result.nElems, equals(10)); 33 | }); 34 | 35 | test('.merge() should merge two different lenght array withoud duplicates', () { 36 | source_one = new OrderedArrayTask5(8); 37 | 38 | source_one.insert(59); 39 | source_one.insert(12); 40 | source_one.insert(90); 41 | source_one.insert(45); 42 | source_one.insert(3); 43 | source_one.insert(10); 44 | source_one.insert(67); 45 | source_one.insert(38); 46 | 47 | OrderedArrayTask5 result = OrderedArrayTask5.merge(source_one, source_two); 48 | 49 | expect(result.a, equals([3, 7, 10, 12, 14, 17, 38, 45, 46, 59, 67, 90, 100])); 50 | expect(result.nElems, equals(13)); 51 | }); 52 | 53 | test('.merge() should merge two different lenght array with duplicated', () { 54 | source_one = new OrderedArrayTask5(8); 55 | 56 | source_one.insert(59); 57 | source_one.insert(12); 58 | source_one.insert(90); 59 | source_one.insert(46); 60 | source_one.insert(7); 61 | source_one.insert(10); 62 | source_one.insert(17); 63 | source_one.insert(38); 64 | 65 | OrderedArrayTask5 result = OrderedArrayTask5.merge(source_one, source_two); 66 | expect(result.a, equals([7, 7, 10, 12, 14, 17, 17, 38, 46, 46, 59, 90, 100])); 67 | expect(result.nElems, equals(13)); 68 | }); 69 | 70 | }); 71 | } 72 | -------------------------------------------------------------------------------- /01_array/tasks/test/task_6_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../task_6.dart'; 4 | 5 | void main() { 6 | HighArrayTask6 highArrayTask6; 7 | 8 | setUp(() { 9 | int maxArraySize = 10; 10 | highArrayTask6 = new HighArrayTask6(maxArraySize); 11 | 12 | highArrayTask6.insert(89); 13 | highArrayTask6.insert(10); 14 | highArrayTask6.insert(15); 15 | highArrayTask6.insert(17); 16 | highArrayTask6.insert(35); 17 | highArrayTask6.insert(10); 18 | highArrayTask6.insert(38); 19 | highArrayTask6.insert(15); 20 | highArrayTask6.insert(38); 21 | highArrayTask6.insert(90); 22 | }); 23 | 24 | group('HighArrayTask6', () { 25 | test('.noDups() should remove 3 element', () { 26 | highArrayTask6.noDups(); 27 | expect(highArrayTask6.toString(), equals('89 10 15 17 35 38 90')); 28 | expect(highArrayTask6.nElems, equals(7)); 29 | }); 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /01_array/test/class_data_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../class_data.dart'; 4 | 5 | void main() { 6 | DataArray dataArray; 7 | setUp(() { 8 | dataArray = new DataArray(5); 9 | 10 | dataArray.insert('Borvo', 'the Hutt', 24); 11 | dataArray.insert('Darth', 'Vader', 47); 12 | dataArray.insert('Bail', 'Organa', 32); 13 | dataArray.insert('Sheev', 'Palpatine', 90); 14 | }); 15 | 16 | group('DataArray', () { 17 | test('.find() return Peson by lastName', () { 18 | expect(dataArray.find('Darth'), equals(isNotNull)); 19 | }); 20 | 21 | test('.find() return null if Person was not found', () { 22 | expect(dataArray.find('Yoda'), equals(isNull)); 23 | }); 24 | 25 | test('.insert() put new element to array', () { 26 | dataArray.insert('Bobba', 'Fett', 32); 27 | expect(dataArray.nElems, equals(5)); 28 | }); 29 | 30 | test('.delete() remove and return true if element was found', () { 31 | expect(dataArray.delete('Darth'), equals(isTrue)); 32 | expect(dataArray.nElems, equals(3)); 33 | }); 34 | 35 | test('.delete() remove and return false if element was not found', () { 36 | expect(dataArray.delete('Yoda'), equals(isFalse)); 37 | expect(dataArray.nElems, equals(4)); 38 | }); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /01_array/test/high_array_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../high_array.dart'; 4 | 5 | void main() { 6 | HighArray highArray; 7 | setUp(() { 8 | highArray = new HighArray(10); 9 | highArray.insert(10); 10 | highArray.insert(30); 11 | highArray.insert(25); 12 | highArray.insert(5); 13 | highArray.insert(8); 14 | highArray.insert(90); 15 | highArray.insert(13); 16 | highArray.insert(14); 17 | highArray.insert(7); 18 | }); 19 | 20 | group('HighArray', () { 21 | test('.find() should return true if element was found', () { 22 | expect(highArray.find(90), equals(true)); 23 | }); 24 | 25 | test('.find() should return false if element was not found', () { 26 | expect(highArray.find(99), equals(false)); 27 | }); 28 | 29 | test('.insert() should insert element and increase array size', () { 30 | highArray.insert(17); 31 | expect(highArray.nElems, equals(10)); 32 | expect(highArray.find(17), equals(true)); 33 | }); 34 | 35 | test('.delete() should remove element and decreate the array size', () { 36 | expect(highArray.delete(10), equals(true)); 37 | expect(highArray.nElems, equals(8)); 38 | }); 39 | 40 | test('.delete() should return false if element was not find', () { 41 | expect(highArray.delete(99), equals(false)); 42 | expect(highArray.nElems, equals(9)); 43 | }); 44 | }); 45 | } 46 | -------------------------------------------------------------------------------- /01_array/test/low_array_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../low_array.dart'; 4 | 5 | void main() { 6 | LowArray lowArray; 7 | setUp(() { 8 | lowArray = new LowArray(10); 9 | }); 10 | 11 | group('LowArray', () { 12 | test('.setElement() should create element on index', () { 13 | lowArray.setElement(0, 5); 14 | expect(lowArray.a[0], equals(5)); 15 | }); 16 | 17 | test('.getElement() should return element by index', () { 18 | lowArray.a[0] = 5; 19 | expect(lowArray.getElement(0), equals(5)); 20 | }); 21 | }); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /01_array/test/ordered_array_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../ordered_array.dart'; 4 | 5 | void main() { 6 | OrderedArray orderedArray; 7 | setUp(() { 8 | orderedArray = new OrderedArray(10); 9 | 10 | orderedArray.insert(10); 11 | orderedArray.insert(30); 12 | orderedArray.insert(3); 13 | orderedArray.insert(15); 14 | orderedArray.insert(24); 15 | orderedArray.insert(99); 16 | orderedArray.insert(8); 17 | orderedArray.insert(19); 18 | orderedArray.insert(70); 19 | }); 20 | 21 | group('OrderedArray', () { 22 | test('.size() return number of elements in array', () { 23 | expect(orderedArray.size(), equals(9)); 24 | }); 25 | 26 | test('.find() return element index if element was found', () { 27 | expect(orderedArray.find(15), equals(3)); 28 | }); 29 | 30 | test('.find() return nElems if element was not found', () { 31 | expect(orderedArray.find(99), equals(8)); 32 | }); 33 | 34 | test('.insert() put element in right position', () { 35 | orderedArray.insert(18); 36 | expect(orderedArray.a, equals([3, 8, 10, 15, 18, 19, 24, 30, 70, 99])); 37 | expect(orderedArray.nElems, 10); 38 | }); 39 | 40 | test('.delete() remove element by key and return true', () { 41 | expect(orderedArray.delete(15), equals(true)); 42 | expect(orderedArray.nElems, equals(8)); 43 | }); 44 | 45 | test('.delete() return false if element not found', () { 46 | expect(orderedArray.delete(105), equals(false)); 47 | expect(orderedArray.nElems, equals(9)); 48 | }); 49 | }); 50 | } 51 | -------------------------------------------------------------------------------- /02_simple_sorting/buble_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class ArrayBub { 4 | List a; 5 | int nElems; 6 | 7 | ArrayBub(int max) { 8 | a = new List(max); 9 | nElems = 0; 10 | } 11 | 12 | /// Insert Data 13 | void insert(int value) { 14 | a[nElems] = value; 15 | nElems ++; 16 | } 17 | 18 | /// Display Data 19 | void display() { 20 | for(int i = 0; i < nElems; i++) { 21 | stdout.write('${a[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | /// Bubble Array Sort 27 | void bubbleSort() { 28 | for(int out = nElems - 1; out > 1; out --) { 29 | for(int _in = 0; _in < out; _in ++) { 30 | if(a[_in] > a[_in +1 ]) { 31 | swap(_in, _in + 1); 32 | } 33 | } 34 | } 35 | } 36 | 37 | /// Swap elements 38 | void swap(int one, int two) { 39 | int temp = a[one]; 40 | a[one] = a[two]; 41 | a[two] = temp; 42 | } 43 | } 44 | 45 | void main() { 46 | int maxSize = 100; 47 | ArrayBub array = new ArrayBub(maxSize); 48 | 49 | // Insert 10 items 50 | array.insert(77); 51 | array.insert(99); 52 | array.insert(44); 53 | array.insert(55); 54 | array.insert(22); 55 | array.insert(88); 56 | array.insert(11); 57 | array.insert(00); 58 | array.insert(66); 59 | array.insert(33); 60 | 61 | array.display(); 62 | 63 | array.bubbleSort(); 64 | 65 | array.display(); 66 | } 67 | -------------------------------------------------------------------------------- /02_simple_sorting/insert_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class ArrayInsert { 4 | List a; 5 | int nElems; 6 | 7 | ArrayInsert(int max) { 8 | a = new List(max); 9 | nElems = 0; 10 | } 11 | 12 | /// Insert Item to array 13 | void insert(int value) { 14 | a[nElems] = value; 15 | nElems ++; 16 | } 17 | 18 | /// Display Array contents 19 | void display() { 20 | for(int i = 0; i < nElems; i++) { 21 | stdout.write('${a[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | /// Insert Sort Array 27 | void insertSort() { 28 | int _in, out; 29 | for(out = 0; out < nElems; out ++) { 30 | int temp = a[out]; 31 | _in = out; 32 | while(_in > 0 && a[_in - 1] >= temp) { 33 | a[_in] = a[_in - 1]; 34 | _in --; 35 | } 36 | a[_in] = temp; 37 | } 38 | } 39 | } 40 | 41 | void main() { 42 | int maxSize = 100; 43 | ArrayInsert array = new ArrayInsert(maxSize); 44 | 45 | // Insert 10 items 46 | array.insert(77); 47 | array.insert(99); 48 | array.insert(44); 49 | array.insert(55); 50 | array.insert(22); 51 | array.insert(88); 52 | array.insert(11); 53 | array.insert(00); 54 | array.insert(66); 55 | array.insert(33); 56 | 57 | array.display(); 58 | 59 | array.insertSort(); 60 | 61 | array.display(); 62 | } 63 | -------------------------------------------------------------------------------- /02_simple_sorting/object_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Person { 4 | String firstName; 5 | String lastName; 6 | int age; 7 | 8 | // Constructor shorthand 9 | Person(this.lastName, this.firstName, this.age) {} 10 | 11 | /// Display Person Data 12 | void displayPerson() { 13 | stdout.write('Last Name $lastName, '); 14 | stdout.write('First Name $firstName, '); 15 | stdout.writeln('Age $age'); 16 | } 17 | 18 | String getLastName() { 19 | return lastName; 20 | } 21 | } 22 | 23 | class ArrayInObject { 24 | List a; 25 | int nElems; 26 | 27 | ArrayInObject(int max) { 28 | a = new List(max); 29 | nElems = 0; 30 | } 31 | 32 | /// Insert Data to Array 33 | void insert(String lastName, String firstName, int age) { 34 | a[nElems] = new Person(lastName, firstName, age); 35 | nElems ++; // increment size 36 | } 37 | 38 | /// Display array contents 39 | void display() { 40 | for(int j = 0; j < nElems; j++) { 41 | a[j].displayPerson(); 42 | } 43 | } 44 | 45 | /// Insertion Sort array 46 | void insertionSort() { 47 | int _in, out; 48 | for(out = 1; out < nElems; out ++) { 49 | Person temp = a[out]; 50 | _in = out; 51 | while(_in > 0 && (a[_in - 1].getLastName().compareTo(temp.getLastName()) > 0)) { 52 | a[_in] = a[_in - 1]; 53 | _in --; 54 | } 55 | a[_in] = temp; 56 | } 57 | } 58 | } 59 | 60 | void main() { 61 | int maxSize = 100; // array size 62 | ArrayInObject array = new ArrayInObject (maxSize); // create instance of ArrayInObject 63 | 64 | // Insert 10 items 65 | array.insert('Evans', 'Patty', 24); 66 | array.insert('Smith', 'Lorraine', 37); 67 | array.insert('Yee', 'Tom', 43); 68 | array.insert('Adams', 'Henry', 63); 69 | array.insert('Hashimoto', 'Sato', 21); 70 | array.insert('Stimson', 'Henry', 29); 71 | array.insert('Velasquez', 'Jose', 72); 72 | array.insert('Lamarque', 'Henry', 54); 73 | array.insert('Vang', 'Minh', 22); 74 | array.insert('Creswell', 'Lucinda', 18); 75 | 76 | stdout.writeln('Before Sorting'); 77 | array.display(); 78 | 79 | array.insertionSort(); 80 | 81 | stdout.writeln('After Sorting'); 82 | array.display(); 83 | } 84 | -------------------------------------------------------------------------------- /02_simple_sorting/select_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class ArraySelect { 4 | List a; 5 | int nElems; 6 | 7 | ArraySelect(int max) { 8 | a = new List(max); 9 | nElems = 0; 10 | } 11 | 12 | /// Insert new element 13 | void insert(int value) { 14 | a[nElems] = value; 15 | nElems ++; 16 | } 17 | 18 | /// Display Array contents 19 | void display() { 20 | for(int i = 0; i < nElems; i++) { 21 | stdout.write('${a[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | /// Select Sort Array 27 | void selectSort() { 28 | int min; 29 | for(int out = 0; out < nElems - 1; out ++) { 30 | min = out; 31 | for(int _in = out + 1; _in < nElems; _in ++) { 32 | if(a[_in] < a[min]) { 33 | min = _in; 34 | } 35 | } 36 | swap(out, min); 37 | } 38 | } 39 | 40 | /// Swap elements 41 | void swap(int one, int two) { 42 | int temp = a[one]; 43 | a[one] = a[two]; 44 | a[two] = temp; 45 | } 46 | } 47 | 48 | void main() { 49 | int maxSize = 100; 50 | ArraySelect array = new ArraySelect(maxSize); 51 | 52 | // Insert 10 items 53 | array.insert(77); 54 | array.insert(99); 55 | array.insert(44); 56 | array.insert(55); 57 | array.insert(22); 58 | array.insert(88); 59 | array.insert(11); 60 | array.insert(00); 61 | array.insert(66); 62 | array.insert(33); 63 | 64 | array.display(); 65 | 66 | array.selectSort(); 67 | 68 | array.display(); 69 | } 70 | -------------------------------------------------------------------------------- /02_simple_sorting/test/buble_sort_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../buble_sort.dart'; 4 | 5 | void main() { 6 | ArrayBub arrayBub; 7 | 8 | setUp(() { 9 | arrayBub = ArrayBub(5); 10 | }); 11 | 12 | group('ArrayBub', () { 13 | group('.insert', () { 14 | test('should add new element', () { 15 | arrayBub.insert(4); 16 | 17 | expect(arrayBub.nElems, equals(1)); 18 | }); 19 | }); 20 | 21 | group('.bubleSort', () { 22 | setUp(() { 23 | arrayBub.insert(4); 24 | arrayBub.insert(6); 25 | arrayBub.insert(2); 26 | arrayBub.insert(3); 27 | arrayBub.insert(9); 28 | }); 29 | test('should sort array', () { 30 | arrayBub.bubbleSort(); 31 | 32 | expect(arrayBub.a, equals([2, 3, 4, 6, 9])); 33 | }); 34 | 35 | test('.swap should swap items', () { 36 | arrayBub.swap(0, 1); 37 | 38 | expect(arrayBub.a, equals([6, 4, 2, 3, 9])); 39 | }); 40 | }); 41 | }); 42 | } -------------------------------------------------------------------------------- /02_simple_sorting/test/insert_sort_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../insert_sort.dart'; 4 | 5 | void main() { 6 | ArrayInsert arrayInsert; 7 | 8 | group('ArrayInsert', () { 9 | setUp(() { 10 | arrayInsert = ArrayInsert(5); 11 | }); 12 | 13 | group('.insert', () { 14 | test('should add new element', () { 15 | arrayInsert.insert(4); 16 | 17 | expect(arrayInsert.nElems, equals(1)); 18 | }); 19 | }); 20 | 21 | group('.insertSort', () { 22 | setUp(() { 23 | arrayInsert.insert(4); 24 | arrayInsert.insert(6); 25 | arrayInsert.insert(2); 26 | arrayInsert.insert(3); 27 | arrayInsert.insert(9); 28 | }); 29 | 30 | test('should sort elements', () { 31 | arrayInsert.insertSort(); 32 | 33 | expect(arrayInsert.a, equals([2, 3, 4, 6, 9])); 34 | }); 35 | }); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /02_simple_sorting/test/object_sort_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../object_sort.dart'; 4 | 5 | void main() { 6 | Person person; 7 | ArrayInObject arrayInObject; 8 | 9 | group('Peson', () { 10 | test('Person()', () { 11 | person = Person('lastName', 'firstName', 25); 12 | 13 | expect(person.firstName, 'firstName'); 14 | expect(person.lastName, 'lastName'); 15 | expect(person.age, 25); 16 | }); 17 | 18 | test('.getLastName', () { 19 | person = Person('lastName', 'firstName', 25); 20 | 21 | expect(person.getLastName(), 'lastName'); 22 | }); 23 | }); 24 | 25 | group('ArrayInObject', () { 26 | setUp(() { 27 | arrayInObject = ArrayInObject(5); 28 | }); 29 | 30 | group('.insert', () { 31 | test('should add new element', () { 32 | arrayInObject.insert('lastName', 'firstName', 25); 33 | 34 | expect(arrayInObject.nElems, equals(1)); 35 | expect(arrayInObject.a[0] is Person, equals(true)); 36 | }); 37 | }); 38 | 39 | group('.insertionSort', () { 40 | setUp(() { 41 | arrayInObject.insert('Evans', 'Patty', 24); 42 | arrayInObject.insert('Smith', 'Lorraine', 37); 43 | arrayInObject.insert('Yee', 'Tom', 43); 44 | arrayInObject.insert('Adams', 'Henry', 63); 45 | 46 | arrayInObject.insertionSort(); 47 | 48 | expect(arrayInObject.a[0].getLastName(), equals('Adams')); 49 | expect(arrayInObject.a[1].getLastName(), equals('Evans')); 50 | expect(arrayInObject.a[2].getLastName(), equals('Yee')); 51 | expect(arrayInObject.a[3].getLastName(), equals('Smith')); 52 | }); 53 | }); 54 | }); 55 | } 56 | -------------------------------------------------------------------------------- /02_simple_sorting/test/select_sort_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import '../select_sort.dart'; 4 | 5 | void main() { 6 | ArraySelect arraySelect; 7 | 8 | setUp(() { 9 | arraySelect = ArraySelect(5); 10 | }); 11 | 12 | group(('ArraySelect'), () { 13 | group('.insert', () { 14 | test('should add new element', () { 15 | arraySelect.insert(4); 16 | 17 | expect(arraySelect.nElems, equals(1)); 18 | }); 19 | }); 20 | 21 | group('.selectSort', () { 22 | setUp(() { 23 | arraySelect.insert(4); 24 | arraySelect.insert(6); 25 | arraySelect.insert(2); 26 | arraySelect.insert(3); 27 | arraySelect.insert(9); 28 | }); 29 | 30 | test('should sort array', () { 31 | arraySelect.selectSort(); 32 | 33 | expect(arraySelect.a, equals([2, 3, 4, 6, 9])); 34 | }); 35 | 36 | test('.swap should swap items', () { 37 | arraySelect.swap(0, 1); 38 | 39 | expect(arraySelect.a, equals([6, 4, 2, 3, 9])); 40 | }); 41 | }); 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /03_stack_queue/infix.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackX { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackX(int size) { 9 | maxSize = size; 10 | stackArray = new List(maxSize); 11 | top = -1; 12 | } 13 | 14 | /// Put item on top of stack 15 | void push(String item) { 16 | stackArray[++top] = item; 17 | } 18 | 19 | /// Take item from top of stack 20 | String pop() { 21 | return stackArray[top--]; 22 | } 23 | 24 | /// Peek at top of stack 25 | String peek() { 26 | return stackArray[top]; 27 | } 28 | 29 | bool isEmpty() { 30 | return top == -1; 31 | } 32 | 33 | int size() { 34 | return top + 1; 35 | } 36 | 37 | String peekN(int n) { 38 | return stackArray[n]; 39 | } 40 | 41 | /// Display Stack Data 42 | void displayStack(String s) { 43 | stdout.write(s); 44 | stdout.write('Stack (bottom -> top): '); 45 | for(int i = 0; i < size(); i ++) { 46 | stdout.write('${peekN(i)} '); 47 | } 48 | stdout.writeln(); 49 | } 50 | } 51 | 52 | class InfixToPostfix { 53 | StackX stackX; 54 | String input; 55 | String output = ''; 56 | 57 | InfixToPostfix(String _input) { 58 | input = _input; 59 | int stackSize = input.length; 60 | stackX = new StackX(stackSize); 61 | } 62 | 63 | /// Do translation to postfix 64 | String doTranslation() { 65 | // for each char 66 | for(int i = 0; i < input.length; i++) { 67 | String char = input[i]; // get it 68 | stackX.displayStack('For $char '); 69 | switch(char) { 70 | case '+': 71 | case '-': 72 | gotOperator(char, 1); 73 | break; 74 | case '*': 75 | case '/': 76 | gotOperator(char, 2); 77 | break; 78 | case '(': 79 | stackX.push(char); 80 | break; 81 | case ')': 82 | gotParent(char); 83 | break; 84 | default: 85 | output = output + char; 86 | break; 87 | } 88 | } 89 | 90 | while(!stackX.isEmpty()) { 91 | stackX.displayStack('While '); 92 | output = output + stackX.pop(); 93 | } 94 | stackX.displayStack('End '); 95 | return output; 96 | } 97 | 98 | void gotOperator(String opThis, int priority) { 99 | while(!stackX.isEmpty()) { 100 | String opTop = stackX.pop(); 101 | if(opTop == '(') { 102 | stackX.push(opTop); 103 | break; 104 | } else { 105 | int prior; 106 | if(opTop == '+' || opTop == '-') { 107 | prior = 1; 108 | } else { 109 | prior = 2; 110 | } 111 | if(prior < priority) { 112 | stackX.push(opTop); 113 | break; 114 | } else { 115 | output = output + opTop; 116 | } 117 | } 118 | } 119 | stackX.push(opThis); 120 | } 121 | 122 | void gotParent(String char) { 123 | while(!stackX.isEmpty()) { 124 | String charX = stackX.pop(); 125 | if(charX == '(') { 126 | break; 127 | } 128 | else { 129 | output = output + charX; 130 | } 131 | } 132 | } 133 | } 134 | 135 | void main() { 136 | String input, output; 137 | 138 | stdout.writeln('Enter infix:'); 139 | input = stdin.readLineSync(); 140 | 141 | InfixToPostfix infixToPostfix = new InfixToPostfix(input); 142 | 143 | output = infixToPostfix.doTranslation(); 144 | 145 | stdout.writeln('Postfix is $output'); 146 | } 147 | -------------------------------------------------------------------------------- /03_stack_queue/postfix.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackX { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackX(int size) { 9 | maxSize = size; 10 | stackArray = new List(maxSize); 11 | top = -1; 12 | } 13 | 14 | /// Put item on top of stack 15 | void push(int item) { 16 | stackArray[++top] = item; 17 | } 18 | 19 | /// Take item from top of stack 20 | int pop() { 21 | return stackArray[top--]; 22 | } 23 | 24 | /// Peek at top of stack 25 | int peek() { 26 | return stackArray[top]; 27 | } 28 | 29 | bool isEmpty() { 30 | return top == -1; 31 | } 32 | 33 | int size() { 34 | return top + 1; 35 | } 36 | 37 | int peekN(int n) { 38 | return stackArray[n]; 39 | } 40 | 41 | /// Display Stack Data 42 | void displayStack(String s) { 43 | stdout.write(s); 44 | stdout.write('Stack (bottom -> top): '); 45 | for(int i = 0; i < size(); i ++) { 46 | stdout.write('${peekN(i)} '); 47 | } 48 | stdout.writeln(); 49 | } 50 | } 51 | 52 | class ParsePost { 53 | StackX stackX; 54 | String input; 55 | 56 | ParsePost(String s) { 57 | input = s; 58 | } 59 | 60 | int doParse() { 61 | stackX = new StackX(20); 62 | String char; 63 | int i; 64 | int num1, num2; 65 | int interAns; 66 | 67 | for(i = 0; i < input.length; i++) { 68 | char = input[i]; 69 | stackX.displayStack('$char '); 70 | try { 71 | stackX.push(int.parse(char)); 72 | } catch(error) { 73 | num2 = stackX.pop(); 74 | num1 = stackX.pop(); 75 | switch(char) { 76 | case '+': 77 | interAns = num1 + num2; 78 | break; 79 | case '-': 80 | interAns = num1 - num2; 81 | break; 82 | case '*': 83 | interAns = num1 * num2; 84 | break; 85 | case '/': 86 | interAns = num1 ~/ num2; 87 | break; 88 | default: 89 | interAns = 0; 90 | } 91 | stackX.push(interAns); 92 | } 93 | } 94 | interAns = stackX.pop(); 95 | return interAns; 96 | } 97 | } 98 | 99 | void main() { 100 | stdout.writeln('Enter postfix'); 101 | String input = stdin.readLineSync(); 102 | num output; 103 | 104 | ParsePost parsePost = new ParsePost(input); 105 | output = parsePost.doParse(); 106 | stdout.writeln('Evalutes to $output'); 107 | } 108 | -------------------------------------------------------------------------------- /03_stack_queue/priority_queue.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class PriorityQueue { 4 | int maxSize; 5 | List queueArray; 6 | int nItems; 7 | 8 | PriorityQueue(int s) { 9 | maxSize = s; 10 | queueArray = new List(maxSize); 11 | nItems = 0; 12 | } 13 | 14 | /// Insert Data to Queue 15 | void insert(int item) { 16 | int j; 17 | if (nItems == 0) { 18 | queueArray[nItems++] = item; 19 | } else { 20 | for(j = nItems - 1; j >= 0; j --) { 21 | if(item > queueArray[j]) { 22 | queueArray[j + 1] = queueArray[j]; 23 | } else { 24 | break; 25 | } 26 | } 27 | queueArray[j+1] = item; 28 | nItems ++; 29 | } 30 | } 31 | 32 | /// Remove data 33 | int remove() { 34 | return queueArray[--nItems]; 35 | } 36 | 37 | int peekMin() { 38 | return queueArray[nItems - 1]; 39 | } 40 | 41 | bool isEmpty() { 42 | return nItems == 0; 43 | } 44 | 45 | bool isFull() { 46 | return nItems == maxSize; 47 | } 48 | } 49 | 50 | void main() { 51 | PriorityQueue priorityQueue = new PriorityQueue(5); 52 | priorityQueue.insert(30); 53 | priorityQueue.insert(50); 54 | priorityQueue.insert(10); 55 | priorityQueue.insert(40); 56 | priorityQueue.insert(20); 57 | 58 | while(!priorityQueue.isEmpty()) { 59 | int item = priorityQueue.remove(); 60 | stdout.write('$item '); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /03_stack_queue/queue.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Queue { 4 | int maxSize; 5 | List queueArray; 6 | int front; 7 | int rear; 8 | int nItems; 9 | 10 | Queue(int s) { 11 | maxSize = s; 12 | queueArray = new List(maxSize); 13 | front = 0; 14 | rear = -1; 15 | nItems = 0; 16 | } 17 | 18 | /// Put item at rear of queue 19 | void insert(int item) { 20 | // Deal with wraparound 21 | if (rear == maxSize - 1) { 22 | rear = -1; 23 | } 24 | queueArray[++rear] = item; // increment rear and insert 25 | nItems ++; // one more item 26 | } 27 | 28 | /// Take item from front of queue 29 | int remove() { 30 | // get value and increment front 31 | int temp = queueArray[front++]; 32 | if(front == maxSize) { 33 | front = 0; 34 | } 35 | nItems --; 36 | return temp; 37 | } 38 | 39 | /// Peek at front of queue 40 | int peekFront() { 41 | return queueArray[front]; 42 | } 43 | 44 | bool isEmpty() { 45 | return nItems == 0; 46 | } 47 | 48 | bool isFull() { 49 | return nItems == maxSize; 50 | } 51 | } 52 | 53 | void main() { 54 | Queue queue = new Queue(5); 55 | 56 | queue.insert(10); 57 | queue.insert(20); 58 | queue.insert(30); 59 | queue.insert(40); 60 | 61 | queue.remove(); 62 | queue.remove(); 63 | queue.remove(); 64 | 65 | queue.insert(50); 66 | queue.insert(60); 67 | queue.insert(70); 68 | queue.insert(80); 69 | 70 | while(!queue.isEmpty()) { 71 | int n = queue.remove(); 72 | stdout.write('$n '); 73 | } 74 | stdout.writeln(); 75 | } 76 | -------------------------------------------------------------------------------- /03_stack_queue/stack/brackets.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackString { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackString(int s) { 9 | maxSize = s; 10 | stackArray = new List(s); 11 | top = -1; 12 | } 13 | 14 | void push(String j) { 15 | stackArray[++top] = j; 16 | } 17 | 18 | String pop() { 19 | return stackArray[top--]; 20 | } 21 | 22 | String peek() { 23 | return stackArray[top]; 24 | } 25 | 26 | bool isEmpty() { 27 | return (top == -1); 28 | } 29 | 30 | bool isFull() { 31 | return (top == maxSize - 1); 32 | } 33 | } 34 | 35 | class BracketChecker { 36 | String input; 37 | 38 | BracketChecker(String _input) { 39 | input = _input; 40 | } 41 | 42 | /// Check if all brackets are closed 43 | void check() { 44 | int stackSize = input.length; 45 | StackString stack = new StackString(stackSize); 46 | 47 | for(int i = 0; i < stackSize; i ++) { 48 | String char = input[i]; 49 | switch(char) { 50 | case '{': 51 | case '[': 52 | case '(': 53 | stack.push(char); 54 | break; 55 | case '}': 56 | case ']': 57 | case ')': 58 | if(!stack.isEmpty()) { 59 | String charx = stack.pop(); 60 | if((charx != '{' && char == '}') || 61 | (charx != '[' && char == ']') || 62 | (charx != '(' && char == ')')) { 63 | stdout.writeln('Error $char at $i'); 64 | } 65 | } else { 66 | stdout.writeln('Error $char at $i'); 67 | } 68 | break; 69 | default: 70 | break; 71 | } 72 | } 73 | if(!stack.isEmpty()) { 74 | stdout.writeln('Error: missing right delimeter'); 75 | } 76 | } 77 | } 78 | 79 | void main() { 80 | stdout.writeln('Enter a string: '); 81 | String input = stdin.readLineSync(); 82 | 83 | BracketChecker bracketChecker = new BracketChecker(input); 84 | bracketChecker.check(); 85 | 86 | } 87 | -------------------------------------------------------------------------------- /03_stack_queue/stack/reverse.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackString { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackString(int s) { 9 | maxSize = s; 10 | stackArray = new List(s); 11 | top = -1; 12 | } 13 | 14 | void push(String j) { 15 | stackArray[++top] = j; 16 | } 17 | 18 | String pop() { 19 | return stackArray[top--]; 20 | } 21 | 22 | String peek() { 23 | return stackArray[top]; 24 | } 25 | 26 | bool isEmpty() { 27 | return (top == -1); 28 | } 29 | 30 | bool isFull() { 31 | return (top == maxSize - 1); 32 | } 33 | } 34 | 35 | class Reverser { 36 | String input; 37 | String output; 38 | 39 | Reverser(String _input) { 40 | input = _input; 41 | } 42 | 43 | String doReverse() { 44 | int stackSize = input.length; 45 | StackString stack = new StackString(stackSize); 46 | 47 | for(int i = 0; i < stackSize; i++) { 48 | String char = input[i]; 49 | stack.push(char); 50 | } 51 | output = ''; 52 | while(!stack.isEmpty()) { 53 | String char = stack.pop(); 54 | output = output + char; 55 | } 56 | return output; 57 | } 58 | } 59 | 60 | void main() { 61 | String input, output; 62 | 63 | stdout.writeln('Enter a string: '); 64 | input = stdin.readLineSync(); 65 | 66 | Reverser reverser = new Reverser(input); 67 | output = reverser.doReverse(); 68 | 69 | stdout.writeln('Reversed: $output'); 70 | } 71 | -------------------------------------------------------------------------------- /03_stack_queue/stack/stack.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackX { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackX(int s) { 9 | maxSize = s; 10 | stackArray = new List(s); 11 | top = -1; 12 | } 13 | 14 | void push(int j) { 15 | stackArray[++top] = j; 16 | } 17 | 18 | int pop() { 19 | return stackArray[top--]; 20 | } 21 | 22 | int peek() { 23 | return stackArray[top]; 24 | } 25 | 26 | bool isEmpty() { 27 | return (top == -1); 28 | } 29 | 30 | bool isFull() { 31 | return (top == maxSize - 1); 32 | } 33 | } 34 | 35 | void main() { 36 | StackX stack = new StackX(10); 37 | stack.push(20); 38 | stack.push(40); 39 | stack.push(60); 40 | stack.push(80); 41 | 42 | while(!stack.isEmpty()) { 43 | int value = stack.pop(); 44 | stdout.write('$value '); 45 | } 46 | stdout.writeln(); 47 | } 48 | -------------------------------------------------------------------------------- /04_linked_list/double_linked_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int data; 5 | Link next; 6 | Link previous; 7 | 8 | Link(this.data){} 9 | 10 | void displayLink() { 11 | stdout.write('$data '); 12 | } 13 | } 14 | 15 | class DoublLinkedList { 16 | Link first; 17 | Link last; 18 | 19 | DoublLinkedList() { 20 | first = null; 21 | last = null; 22 | } 23 | 24 | bool isEmpty() { 25 | return first == null; 26 | } 27 | 28 | void insertFirst(int data) { 29 | Link newLink = new Link(data); 30 | if (isEmpty()) { 31 | last = newLink; 32 | } else { 33 | first.previous = newLink; 34 | } 35 | newLink.next = first; 36 | first = newLink; 37 | } 38 | 39 | void insertLast(int data) { 40 | Link newLink = new Link(data); 41 | if (isEmpty()) { 42 | first = newLink; 43 | } else { 44 | last.next = newLink; 45 | newLink.previous = last; 46 | } 47 | last = newLink; 48 | } 49 | 50 | Link deleteFirst() { 51 | Link temp = first; 52 | if (first.next == null) { 53 | last = null; 54 | } else { 55 | first.next.previous = null; 56 | } 57 | first = first.next; 58 | return temp; 59 | } 60 | 61 | Link deleteLast() { 62 | Link temp = last; 63 | if (first.next == null) { 64 | first = null; 65 | } else { 66 | last.previous.next = null; 67 | } 68 | last = last.previous; 69 | return temp; 70 | } 71 | 72 | bool insertAfter(int key, int data) { 73 | Link current = first; 74 | while (current.data != key) { 75 | current = current.next; 76 | if (current == null) { 77 | return false; 78 | } 79 | } 80 | Link newLink = new Link(data); 81 | if (current == last) { 82 | newLink.next = null; 83 | last = newLink; 84 | } else { 85 | newLink.next = current.next; 86 | current.next.previous = newLink; 87 | } 88 | newLink.previous = current; 89 | current.next = newLink; 90 | return true; 91 | } 92 | 93 | Link deleteKey(int key) { 94 | Link current = first; 95 | while(current.data != key) { 96 | current = current.next; 97 | if (current == null) { 98 | return null; 99 | } 100 | } 101 | if (current == first) { 102 | first = current.next; 103 | } else { 104 | current.previous.next = current.next; 105 | } 106 | 107 | if (current == last) { 108 | last = current.previous; 109 | } else { 110 | current.next.previous = current.previous; 111 | } 112 | return current; 113 | } 114 | 115 | void displayForward() { 116 | stdout.write('List (first -> last): '); 117 | Link current = first; 118 | while (current != null) { 119 | current.displayLink(); 120 | current = current.next; 121 | } 122 | stdout.writeln(); 123 | } 124 | 125 | void displayBackward() { 126 | stdout.write('List (last -> first): '); 127 | Link current = last; 128 | while (current != null) { 129 | current.displayLink(); 130 | current = current.previous; 131 | } 132 | stdout.writeln(); 133 | } 134 | } 135 | 136 | void main(List args) { 137 | DoublLinkedList doublLinkedList = new DoublLinkedList(); 138 | doublLinkedList.insertFirst(22); 139 | doublLinkedList.insertFirst(44); 140 | doublLinkedList.insertFirst(66); 141 | 142 | doublLinkedList.insertLast(11); 143 | doublLinkedList.insertLast(33); 144 | doublLinkedList.insertLast(55); 145 | 146 | doublLinkedList.displayForward(); 147 | doublLinkedList.displayBackward(); 148 | 149 | doublLinkedList.deleteFirst(); 150 | doublLinkedList.deleteLast(); 151 | doublLinkedList.deleteKey(11); 152 | 153 | doublLinkedList.displayForward(); 154 | 155 | doublLinkedList.insertAfter(22, 77); 156 | doublLinkedList.insertAfter(33, 88); 157 | 158 | doublLinkedList.displayForward(); 159 | } 160 | -------------------------------------------------------------------------------- /04_linked_list/first_last_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int intData; 5 | Link next; 6 | 7 | Link(this.intData) {} 8 | 9 | void displayLink() { 10 | stdout.write('$intData '); 11 | } 12 | } 13 | 14 | class FirstLastList { 15 | Link first; 16 | Link last; 17 | 18 | FirstLastList() { 19 | first = null; 20 | last = null; 21 | } 22 | 23 | bool isEmpty() { 24 | return first == null; 25 | } 26 | 27 | void insertFirst(int item) { 28 | Link newLink = new Link(item); 29 | if (isEmpty()) { 30 | last = newLink; 31 | } 32 | newLink.next = first; 33 | first = newLink; 34 | } 35 | 36 | void insertLast(int item) { 37 | Link newLink = new Link(item); 38 | if (isEmpty()) { 39 | first = newLink; 40 | } else { 41 | last.next = newLink; 42 | } 43 | last = newLink; 44 | } 45 | 46 | int deleteFirst() { 47 | int temp = first.intData; 48 | if (first.next == null) { 49 | last = null; 50 | } 51 | first = first.next; 52 | return temp; 53 | } 54 | 55 | void displayList() { 56 | stdout.write('List (first -> last): '); 57 | Link current = first; 58 | while (current != null) { 59 | current.displayLink(); 60 | current = current.next; 61 | } 62 | stdout.writeln(); 63 | } 64 | } 65 | 66 | void main(List args) { 67 | FirstLastList firstLastList = new FirstLastList(); 68 | 69 | firstLastList.insertFirst(22); 70 | firstLastList.insertFirst(44); 71 | firstLastList.insertFirst(66); 72 | 73 | firstLastList.insertLast(11); 74 | firstLastList.insertLast(33); 75 | firstLastList.insertLast(55); 76 | 77 | firstLastList.displayList(); 78 | 79 | firstLastList.deleteFirst(); 80 | firstLastList.deleteFirst(); 81 | 82 | firstLastList.displayList(); 83 | } 84 | -------------------------------------------------------------------------------- /04_linked_list/link_insertion_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class Link { 5 | int data; 6 | Link next; 7 | 8 | Link(this.data){} 9 | } 10 | 11 | class SortedList { 12 | Link first; 13 | 14 | SortedList() { 15 | first = null; 16 | } 17 | 18 | SortedList.fromArray(List linkArray) { 19 | first = null; 20 | for(int i = 0; i < linkArray.length; i++) { 21 | insert(linkArray[i]); 22 | } 23 | } 24 | 25 | void insert(Link item) { 26 | Link previous = null; 27 | Link current = first; 28 | 29 | while(current != null && item.data > current.data) { 30 | previous = current; 31 | current = current.next; 32 | } 33 | if (previous == null) { 34 | first = item; 35 | } else { 36 | previous.next = item; 37 | } 38 | item.next = current; 39 | } 40 | 41 | Link remove() { 42 | Link temp = first; 43 | first = first.next; 44 | return temp; 45 | } 46 | } 47 | 48 | void displayArray(List array) { 49 | for(int i = 0; i < array.length; i ++) { 50 | stdout.write('${array[i].data} '); 51 | } 52 | stdout.writeln(); 53 | } 54 | 55 | void main(List args) { 56 | int size = 10; 57 | Random random = new Random(); 58 | List linkArray = new List(size); 59 | 60 | for(int i = 0; i < linkArray.length; i ++) { 61 | int n = random.nextInt(100); 62 | Link newLink = new Link(n); 63 | linkArray[i] = newLink; 64 | } 65 | 66 | stdout.write('Unsorted Array: '); 67 | displayArray(linkArray); 68 | 69 | SortedList sortedList = new SortedList.fromArray(linkArray); 70 | for (int i = 0; i < size; i++) { 71 | linkArray[i] = sortedList.remove(); 72 | } 73 | 74 | stdout.write('Sorted Array: '); 75 | displayArray(linkArray); 76 | } -------------------------------------------------------------------------------- /04_linked_list/link_queue_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int data; 5 | Link next; 6 | 7 | Link(this.data) {} 8 | 9 | void displayLink() { 10 | stdout.write('$data '); 11 | } 12 | } 13 | 14 | class FirstLastList { 15 | Link first; 16 | Link last; 17 | 18 | FirstLastList() { 19 | first = null; 20 | last = null; 21 | } 22 | 23 | bool isEmpty() { 24 | return first == null; 25 | } 26 | 27 | void insertLast(int item) { 28 | Link newLink = new Link(item); 29 | if (isEmpty()) { 30 | first = newLink; 31 | } else { 32 | last.next = newLink; 33 | } 34 | last = newLink; 35 | } 36 | 37 | int deleteFirst() { 38 | int temp = first.data; 39 | if (first.next == null) { 40 | last = null; 41 | } 42 | first = first.next; 43 | return temp; 44 | } 45 | 46 | void displayList() { 47 | Link current = first; 48 | while (current != null) { 49 | current.displayLink(); 50 | current = current.next; 51 | } 52 | stdout.writeln(); 53 | } 54 | } 55 | 56 | class LinkQueue { 57 | FirstLastList list; 58 | 59 | LinkQueue() { 60 | list = new FirstLastList(); 61 | } 62 | 63 | bool isEmpty() { 64 | return list.isEmpty(); 65 | } 66 | 67 | void insert(int item) { 68 | list.insertLast(item); 69 | } 70 | 71 | int remove() { 72 | return list.deleteFirst(); 73 | } 74 | 75 | void displayQueue() { 76 | stdout.write('Queue (front -> rear): '); 77 | list.displayList(); 78 | } 79 | } 80 | 81 | void main(List args) { 82 | LinkQueue linkQueue = new LinkQueue(); 83 | 84 | linkQueue.insert(20); 85 | linkQueue.insert(40); 86 | 87 | linkQueue.displayQueue(); 88 | 89 | linkQueue.insert(60); 90 | linkQueue.insert(80); 91 | 92 | linkQueue.displayQueue(); 93 | 94 | linkQueue.remove(); 95 | linkQueue.remove(); 96 | 97 | linkQueue.displayQueue(); 98 | } -------------------------------------------------------------------------------- /04_linked_list/link_stack_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int data; 5 | Link next; 6 | 7 | Link(this.data) {} 8 | 9 | void displayLink() { 10 | stdout.write('$data '); 11 | } 12 | } 13 | 14 | class LinkList { 15 | Link first; 16 | 17 | LinkList() { 18 | first = null; 19 | } 20 | 21 | bool isEmpty() { 22 | return first == null; 23 | } 24 | 25 | void insertFirst(int data) { 26 | Link newLink = new Link(data); 27 | newLink.next = first; 28 | first = newLink; 29 | } 30 | 31 | int deleteFirst() { 32 | Link temp = first; 33 | first = first.next; 34 | return temp.data; 35 | } 36 | 37 | void displayList() { 38 | Link current = first; 39 | while(current != null) { 40 | current.displayLink(); 41 | current = current.next; 42 | } 43 | stdout.writeln(); 44 | } 45 | } 46 | 47 | class LinkStack { 48 | LinkList list; 49 | 50 | LinkStack() { 51 | list = new LinkList(); 52 | } 53 | 54 | void push(int item) { 55 | list.insertFirst(item); 56 | } 57 | 58 | int pop() { 59 | return list.deleteFirst(); 60 | } 61 | 62 | void displayStack() { 63 | stdout.write('Stack (top -> bottom): '); 64 | list.displayList(); 65 | } 66 | } 67 | 68 | void main(List args) { 69 | LinkStack linkStack = new LinkStack(); 70 | 71 | linkStack.push(20); 72 | linkStack.push(40); 73 | 74 | linkStack.displayStack(); 75 | 76 | linkStack.push(60); 77 | linkStack.push(80); 78 | 79 | linkStack.displayStack(); 80 | 81 | linkStack.pop(); 82 | linkStack.pop(); 83 | 84 | linkStack.displayStack(); 85 | } -------------------------------------------------------------------------------- /04_linked_list/linked_list/linked_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int intData; 5 | double doubleData; 6 | Link next; 7 | 8 | Link(int id, double dd) { 9 | intData = id; 10 | doubleData = dd; 11 | next = null; 12 | } 13 | 14 | void displayLink() { 15 | stdout.write('{ $intData, $doubleData } '); 16 | } 17 | } 18 | 19 | class LinkList { 20 | Link first; 21 | 22 | LinkList() { 23 | first = null; 24 | } 25 | 26 | bool isEmpty() { 27 | return first == null; 28 | } 29 | 30 | void insertFirst(int id, double dd) { 31 | Link newLink = new Link(id, dd); 32 | newLink.next = first; 33 | first = newLink; 34 | } 35 | 36 | Link find(int key) { 37 | Link current = first; 38 | while (current.intData != key) { 39 | if (current.next == null) { 40 | return null; 41 | } else { 42 | current = current.next; 43 | } 44 | } 45 | return current; 46 | } 47 | 48 | Link delete(int key) { 49 | Link current = first; 50 | Link prevous = first; 51 | 52 | while (current.intData != key) { 53 | if (current.next == null) { 54 | return null; 55 | } else { 56 | prevous = current; 57 | current = current.next; 58 | } 59 | } 60 | if (current == first) { 61 | first = first.next; 62 | } else { 63 | prevous.next = current.next; 64 | } 65 | return current; 66 | } 67 | 68 | Link deleteFirst() { 69 | Link temp = first; 70 | first = first.next; 71 | return temp; 72 | } 73 | 74 | void displayList() { 75 | stdout.write('List frist -> last '); 76 | Link curent = first; 77 | while (curent != null) { 78 | curent.displayLink(); 79 | curent = curent.next; 80 | } 81 | stdout.writeln(); 82 | } 83 | } 84 | 85 | void main() { 86 | LinkList linkList = new LinkList(); 87 | linkList.insertFirst(22, 2.99); 88 | linkList.insertFirst(44, 4.99); 89 | linkList.insertFirst(66, 6.99); 90 | linkList.insertFirst(88, 8.99); 91 | 92 | linkList.displayList(); 93 | 94 | Link findElement = linkList.find(44); 95 | if (findElement != null) { 96 | stdout.writeln('Found link with key ${findElement.intData}'); 97 | } else { 98 | stdout.writeln("Can't find link"); 99 | } 100 | 101 | Link deletetElement = linkList.delete(66); 102 | if (deletetElement != null) { 103 | stdout.writeln('Delete link with key ${deletetElement.intData}'); 104 | } else { 105 | stdout.writeln("Can't delete link"); 106 | } 107 | 108 | linkList.displayList(); 109 | } 110 | -------------------------------------------------------------------------------- /04_linked_list/linked_list/simple_linked_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int intData; 5 | double doubleData; 6 | Link next; 7 | 8 | Link(int id, double dd) { 9 | intData = id; 10 | doubleData = dd; 11 | next = null; 12 | } 13 | 14 | void displayLink() { 15 | stdout.write('{ $intData, $doubleData } '); 16 | } 17 | } 18 | 19 | class LinkList { 20 | Link first; 21 | 22 | LinkList() { 23 | first = null; 24 | } 25 | 26 | bool isEmpty() { 27 | return first == null; 28 | } 29 | 30 | void insertFirst(int id, double dd) { 31 | Link newLink = new Link(id, dd); 32 | newLink.next = first; 33 | first = newLink; 34 | } 35 | 36 | Link deleteFirst() { 37 | Link temp = first; 38 | first = first.next; 39 | return temp; 40 | } 41 | 42 | void displayList() { 43 | stdout.write('List frist -> last '); 44 | Link curent = first; 45 | while(curent != null) { 46 | curent.displayLink(); 47 | curent = curent.next; 48 | } 49 | stdout.writeln(); 50 | } 51 | } 52 | 53 | void main() { 54 | LinkList linkList = new LinkList(); // Создание нового списка 55 | linkList.insertFirst(22, 2.99); 56 | linkList.insertFirst(44, 4.99); 57 | linkList.insertFirst(66, 6.99); 58 | linkList.insertFirst(88, 8.99); 59 | 60 | linkList.displayList(); 61 | 62 | while(!linkList.isEmpty()) { 63 | Link tempLink = linkList.deleteFirst(); 64 | stdout.write('Deleted'); 65 | tempLink.displayLink(); 66 | stdout.writeln(); 67 | } 68 | linkList.displayList(); 69 | } 70 | -------------------------------------------------------------------------------- /04_linked_list/list_iterator.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int data; 5 | Link next; 6 | 7 | Link(this.data){} 8 | 9 | void displayLink() { 10 | stdout.write('$data '); 11 | } 12 | } 13 | 14 | class LinkList { 15 | Link first; 16 | 17 | LinkList() { 18 | first = null; 19 | } 20 | 21 | Link getFirst() { 22 | return first; 23 | } 24 | 25 | void setFirst(Link item) { 26 | first = item; 27 | } 28 | 29 | bool isEmpty() { 30 | return first == null; 31 | } 32 | 33 | ListIterator getIterator() { 34 | return new ListIterator(this); 35 | } 36 | 37 | void displayList() { 38 | Link current = first; 39 | while (current != null) { 40 | current.displayLink(); 41 | current = current.next; 42 | } 43 | stdout.writeln(); 44 | } 45 | } 46 | 47 | class ListIterator { 48 | Link current; 49 | Link previous; 50 | LinkList ourList; 51 | 52 | ListIterator(LinkList list) { 53 | ourList = list; 54 | reset(); 55 | } 56 | 57 | void reset() { 58 | current = ourList.getFirst(); 59 | previous = null; 60 | } 61 | 62 | bool atEnd() { 63 | return current.next == null; 64 | } 65 | 66 | void nextLink() { 67 | previous = current; 68 | current = current.next; 69 | } 70 | 71 | Link getCurrent() { 72 | return current; 73 | } 74 | 75 | void insertAfter(int data) { 76 | Link newLink = new Link(data); 77 | if (ourList.isEmpty()) { 78 | ourList.setFirst(newLink); 79 | current = newLink; 80 | } else { 81 | newLink.next = current.next; 82 | current.next = newLink; 83 | nextLink(); 84 | } 85 | } 86 | 87 | void insertBefore(int data) { 88 | Link newLink = new Link(data); 89 | if (previous == null) { 90 | newLink.next = ourList.getFirst(); 91 | ourList.setFirst(newLink); 92 | reset(); 93 | } else { 94 | newLink.next = previous.next; 95 | previous.next = newLink; 96 | current = newLink; 97 | } 98 | } 99 | 100 | int deleteCurrent() { 101 | int value = current.data; 102 | if (previous == null) { 103 | ourList.setFirst(current.next); 104 | reset(); 105 | } else { 106 | previous.next = current.next; 107 | if (atEnd()) { 108 | reset(); 109 | } else { 110 | current = current.next; 111 | } 112 | } 113 | return value; 114 | } 115 | } 116 | 117 | void main(List args) { 118 | LinkList linkList = new LinkList(); 119 | ListIterator iterator1 = linkList.getIterator(); 120 | int value; 121 | 122 | iterator1.insertAfter(20); 123 | iterator1.insertAfter(40); 124 | iterator1.insertAfter(80); 125 | iterator1.insertBefore(60); 126 | 127 | while (true) { 128 | stdout.writeln('Enter first letter of: show, reset, next before, after, delete'); 129 | String choise = stdin.readLineSync(); 130 | switch(choise) { 131 | case 's': 132 | if(!linkList.isEmpty()) { 133 | linkList.displayList(); 134 | } else { 135 | stdout.writeln('List is empty'); 136 | } 137 | break; 138 | case 'r': 139 | iterator1.reset(); 140 | break; 141 | case 'n': 142 | if (!linkList.isEmpty() && !iterator1.atEnd()) { 143 | iterator1.nextLink(); 144 | } else { 145 | stdout.writeln("Can't go to next link"); 146 | } 147 | break; 148 | case 'g': 149 | if (!linkList.isEmpty()) { 150 | value = iterator1.getCurrent().data; 151 | stdout.writeln('Retruned $value'); 152 | } else { 153 | stdout.writeln('List is empty'); 154 | } 155 | break; 156 | case 'b': 157 | stdout.write('Enter value to insert: '); 158 | String userInput = stdin.readLineSync(); 159 | value = int.parse(userInput); 160 | iterator1.insertBefore(value); 161 | break; 162 | case 'a': 163 | stdout.write('Enter value to insert: '); 164 | String userInput = stdin.readLineSync(); 165 | value = int.parse(userInput); 166 | iterator1.insertAfter(value); 167 | break; 168 | case 'd': 169 | if (!linkList.isEmpty()) { 170 | value = iterator1.deleteCurrent(); 171 | stdout.writeln('Deletet $value'); 172 | } else { 173 | stdout.writeln("Can't delete"); 174 | } 175 | break; 176 | default: 177 | stdout.writeln('Invalud command'); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /04_linked_list/sorted_list.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Link { 4 | int data; 5 | Link next; 6 | 7 | Link(this.data) {} 8 | 9 | void displayLink() { 10 | stdout.write('$data '); 11 | } 12 | } 13 | 14 | class SortedList { 15 | Link first; 16 | 17 | SortedList() { 18 | first = null; 19 | } 20 | 21 | bool isEmpty() { 22 | return first == null; 23 | } 24 | 25 | void insert(int key) { 26 | Link newLink = new Link(key); 27 | Link previous = null; 28 | Link current = first; 29 | 30 | while(current != null && key > current.data) { 31 | previous = current; 32 | current = current.next; 33 | } 34 | if (previous == null) { 35 | first = newLink; 36 | } else { 37 | previous.next = newLink; 38 | } 39 | newLink.next = current; 40 | } 41 | 42 | Link remove() { 43 | Link temp = first; 44 | first = first.next; 45 | return temp; 46 | } 47 | 48 | void diaplayList() { 49 | stdout.write('List (first -> last): '); 50 | Link current = first; 51 | 52 | while (current != null) { 53 | current.displayLink(); 54 | current = current.next; 55 | } 56 | stdout.writeln(); 57 | } 58 | } 59 | 60 | void main(List args) { 61 | SortedList sortedList = new SortedList(); 62 | 63 | sortedList.insert(20); 64 | sortedList.insert(40); 65 | 66 | sortedList.diaplayList(); 67 | 68 | sortedList.insert(10); 69 | sortedList.insert(30); 70 | sortedList.insert(50); 71 | 72 | sortedList.diaplayList(); 73 | 74 | sortedList.remove(); 75 | 76 | sortedList.diaplayList(); 77 | } 78 | -------------------------------------------------------------------------------- /05_recursion/anagram.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class AnagramApp { 4 | int size; 5 | int count; 6 | List arrayChar = new List(100); 7 | 8 | void displayWord() { 9 | if (count < 99) { 10 | stdout.write(' '); 11 | } 12 | if (count < 9) { 13 | stdout.write(' '); 14 | } 15 | stdout.write('${++count} '); 16 | 17 | for (int i = 0; i < size; i ++) { 18 | stdout.write(' ${arrayChar[i]}'); 19 | } 20 | stdout.writeln(' '); 21 | if (count %6 == 0) { 22 | stdout.writeln(); 23 | } 24 | } 25 | 26 | void rotate(int newSize) { 27 | int i; 28 | int position = size - newSize; 29 | String temp = arrayChar[position]; 30 | for (i = position + 1; i < size; i ++) { 31 | arrayChar[i - 1] = arrayChar[i]; 32 | } 33 | arrayChar[i - 1] = temp; 34 | } 35 | 36 | void doAnagram(int newSize) { 37 | if (newSize == 1) { 38 | return; 39 | } else { 40 | for (int i = 0; i < newSize; i ++) { 41 | doAnagram(newSize - 1); 42 | if (newSize == 2) { 43 | displayWord(); 44 | } 45 | rotate(newSize); 46 | } 47 | } 48 | } 49 | } 50 | 51 | void main(List args) { 52 | stdout.writeln('Enter a word: '); 53 | String word = stdin.readLineSync(); 54 | 55 | AnagramApp anagramApp = new AnagramApp(); 56 | 57 | anagramApp.size = word.length; 58 | anagramApp.count = 0; 59 | for (int i = 0; i < anagramApp.size; i ++) { 60 | anagramApp.arrayChar[i] = word[i]; 61 | } 62 | 63 | anagramApp.doAnagram(anagramApp.size); 64 | } 65 | -------------------------------------------------------------------------------- /05_recursion/binary_search.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class OrderedArray { 4 | List a; 5 | int nElems; 6 | 7 | OrderedArray(int max) { 8 | a = new List(max); 9 | nElems = 0; 10 | } 11 | 12 | int size() { 13 | return nElems; 14 | } 15 | 16 | int find(int searchKey) { 17 | return _recursionFind(searchKey, 0, nElems - 1); 18 | } 19 | 20 | int _recursionFind(int searchKey, int lowerBound, int upperBound) { 21 | int curIn; 22 | curIn = (lowerBound + upperBound) ~/ 2; 23 | if (a[curIn] == searchKey){ 24 | return curIn; 25 | } else if (lowerBound > upperBound) { 26 | return nElems; 27 | } else { 28 | if (a[curIn] < searchKey) { 29 | return _recursionFind(searchKey, curIn + 1, upperBound); 30 | } else { 31 | return _recursionFind(searchKey, lowerBound, curIn - 1 ); 32 | } 33 | } 34 | } 35 | 36 | void insert(int value) { 37 | int j; 38 | for (j = 0; j < nElems; j ++) { 39 | if (a[j] > value) { 40 | break; 41 | } 42 | } 43 | for (int k = nElems; k > j; k --) { 44 | a[k] = a[k - 1]; 45 | } 46 | a[j] = value; 47 | nElems ++; 48 | } 49 | 50 | void display() { 51 | for (int i = 0; i < nElems; i ++){ 52 | stdout.write('${a[i]} '); 53 | } 54 | stdout.writeln(); 55 | } 56 | } 57 | 58 | void main(List args) { 59 | int maxSize = 100; 60 | OrderedArray orderedArray = new OrderedArray(maxSize); 61 | orderedArray.insert(72); 62 | orderedArray.insert(90); 63 | orderedArray.insert(45); 64 | orderedArray.insert(126); 65 | orderedArray.insert(54); 66 | orderedArray.insert(99); 67 | orderedArray.insert(144); 68 | orderedArray.insert(27); 69 | orderedArray.insert(135); 70 | orderedArray.insert(81); 71 | orderedArray.insert(18); 72 | orderedArray.insert(108); 73 | orderedArray.insert(9); 74 | orderedArray.insert(117); 75 | orderedArray.insert(63); 76 | orderedArray.insert(36); 77 | 78 | orderedArray.display(); 79 | 80 | int searchKey = 27; 81 | 82 | if (orderedArray.find(searchKey) != orderedArray.size()) { 83 | stdout.writeln('Found $searchKey'); 84 | } else { 85 | stdout.writeln("Can't find $searchKey"); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /05_recursion/merge.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class MergeApp { 4 | static void merge(List arrayA, int sizeA, List arrayB, int sizeB, List arrayC ) { 5 | int aDex = 0, bDex = 0, cDex = 0; 6 | while (aDex < sizeA && bDex < sizeB) { 7 | if (arrayA[aDex] < arrayB[bDex]) { 8 | arrayC[cDex ++] = arrayA[aDex ++]; 9 | } else { 10 | arrayC[cDex ++] = arrayB[bDex ++]; 11 | } 12 | } 13 | while (aDex < sizeA) { 14 | arrayC[cDex ++] = arrayA[aDex ++]; 15 | } 16 | while (bDex < sizeB) { 17 | arrayC[cDex ++] = arrayB[bDex ++]; 18 | } 19 | } 20 | static void display(List array, int size) { 21 | for (int i = 0; i < size; i ++) { 22 | stdout.write('${array[i]} '); 23 | } 24 | stdout.writeln(); 25 | } 26 | } 27 | 28 | void main(List args) { 29 | List arrayA = [23, 47, 81, 95]; 30 | List arrayB = [7, 14, 39, 55, 62, 74]; 31 | List arrayC = new List(10); 32 | 33 | MergeApp.merge(arrayA, arrayA.length, arrayB, arrayB.length, arrayC); 34 | MergeApp.display(arrayC, 10); 35 | } 36 | -------------------------------------------------------------------------------- /05_recursion/merge_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Array { 4 | List array; 5 | int numberOfElements; 6 | 7 | Array(int max) { 8 | array = new List(max); 9 | numberOfElements = 0; 10 | } 11 | 12 | void insert(int value) { 13 | array[numberOfElements] = value; 14 | numberOfElements ++; 15 | } 16 | 17 | void display() { 18 | for (int i = 0; i < numberOfElements; i ++) { 19 | stdout.write('${array[i]} '); 20 | } 21 | stdout.writeln(); 22 | } 23 | 24 | void mergeSort() { 25 | List workSpace = new List(numberOfElements); 26 | _recursiveMergeSort(workSpace, 0, numberOfElements - 1); 27 | } 28 | 29 | void _recursiveMergeSort(List workSpace, int lowerBound, int upperBound) { 30 | if (lowerBound == upperBound) { 31 | return; 32 | } else { 33 | int mid = (lowerBound + upperBound) ~/ 2; 34 | _recursiveMergeSort(workSpace, lowerBound, mid); 35 | _recursiveMergeSort(workSpace, mid + 1, upperBound); 36 | _merge(workSpace, lowerBound, mid + 1, upperBound); 37 | } 38 | } 39 | 40 | void _merge(List workSpace, int lowPtr, int highPtr, int upperBound) { 41 | int i = 0; 42 | int lowerBound = lowPtr; 43 | int mid = highPtr - 1; 44 | int n = upperBound - lowerBound + 1; 45 | 46 | while (lowPtr <= mid && highPtr <= upperBound) { 47 | if (array[lowPtr] < array[highPtr]) { 48 | workSpace[i++] = array[lowPtr++]; 49 | } else { 50 | workSpace[i++] = array[highPtr++]; 51 | } 52 | } 53 | 54 | while (lowPtr <= mid) { 55 | workSpace[i++] = array[lowPtr++]; 56 | } 57 | while (highPtr <= upperBound) { 58 | workSpace[i++] = array[highPtr++]; 59 | } 60 | 61 | for (i=0; i < n; i ++) { 62 | array[lowerBound + i] = workSpace[i]; 63 | } 64 | } 65 | } 66 | 67 | void main() { 68 | int maxSize = 100; 69 | Array array = new Array(maxSize); 70 | array.insert(64); 71 | array.insert(21); 72 | array.insert(33); 73 | array.insert(70); 74 | array.insert(12); 75 | array.insert(85); 76 | array.insert(44); 77 | array.insert(3); 78 | array.insert(99); 79 | array.insert(0); 80 | array.insert(108); 81 | array.insert(36); 82 | 83 | array.display(); 84 | 85 | array.mergeSort(); 86 | array.display(); 87 | } 88 | -------------------------------------------------------------------------------- /05_recursion/power.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class PowerApp { 4 | static int power(int x, int y) { 5 | stdout.writeln('X = $x; Y = $y'); 6 | if (y != 1) { 7 | x = power(x*x, y~/2); 8 | } 9 | return x; 10 | } 11 | } 12 | 13 | void main() { 14 | stdout.write('Enter X '); 15 | int x = int.parse(stdin.readLineSync()); 16 | stdout.write('Enter Y '); 17 | int y = int.parse(stdin.readLineSync()); 18 | int answer = PowerApp.power(x, y); 19 | stdout.writeln(answer); 20 | } -------------------------------------------------------------------------------- /05_recursion/stack_triangle.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Params { 4 | int n; 5 | int returnAddress; 6 | 7 | Params(this.n, this.returnAddress){} 8 | } 9 | 10 | class StackX { 11 | int maxSize; 12 | List stackArray; 13 | int top; 14 | 15 | StackX(int s) { 16 | maxSize = s; 17 | stackArray = new List(maxSize); 18 | top = -1; 19 | } 20 | 21 | void push(Params p) { 22 | stackArray[++top] = p; 23 | } 24 | 25 | Params pop() { 26 | return stackArray[top--]; 27 | } 28 | 29 | Params peek() { 30 | return stackArray[top]; 31 | } 32 | } 33 | 34 | class StackTriangleApp { 35 | static int number; 36 | static int answer; 37 | static StackX stackX; 38 | static int codePart; 39 | static Params params; 40 | 41 | static void recTriangle() { 42 | stackX = new StackX(10000); 43 | codePart = 1; 44 | while (step() == false) { 45 | 46 | } 47 | } 48 | 49 | static bool step() { 50 | switch (codePart) { 51 | case 1: 52 | params = new Params(number, 6); 53 | stackX.push(params); 54 | codePart = 2; 55 | break; 56 | case 2: 57 | params = stackX.peek(); 58 | if (params.n == 1) { 59 | answer = 1; 60 | codePart = 5; 61 | } else { 62 | codePart = 3; 63 | } 64 | break; 65 | case 3: 66 | params = new Params(params.n - 1, 4); 67 | stackX.push(params); 68 | codePart = 2; 69 | break; 70 | case 4: 71 | params = stackX.peek(); 72 | answer = answer + params.n; 73 | codePart = 5; 74 | break; 75 | case 5: 76 | params = stackX.peek(); 77 | codePart = params.returnAddress; 78 | stackX.pop(); 79 | break; 80 | case 6: 81 | return true; 82 | } 83 | return false; 84 | } 85 | 86 | } 87 | 88 | 89 | void main() { 90 | stdout.write('Enter a number: '); 91 | StackTriangleApp.number = int.parse(stdin.readLineSync()); 92 | StackTriangleApp.recTriangle(); 93 | stdout.writeln('Triangle = ${StackTriangleApp.answer}'); 94 | } 95 | 96 | -------------------------------------------------------------------------------- /05_recursion/stack_triangle2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class StackX { 4 | int maxSize; 5 | List stackArray; 6 | int top; 7 | 8 | StackX(int s) { 9 | maxSize = s; 10 | stackArray = new List(maxSize); 11 | top = -1; 12 | } 13 | 14 | void push(int p) { 15 | stackArray[++top] = p; 16 | } 17 | 18 | int pop() { 19 | return stackArray[top--]; 20 | } 21 | 22 | int peek() { 23 | return stackArray[top]; 24 | } 25 | 26 | bool isEmpty() { 27 | return top == -1; 28 | } 29 | } 30 | 31 | class StackTriangleApp { 32 | static int number; 33 | static int answer; 34 | static StackX stackX; 35 | 36 | static void stackTriangle() { 37 | stackX = new StackX(10000); 38 | answer = 0; 39 | while (number > 0) { 40 | stackX.push(number); 41 | -- number; 42 | } 43 | while (!stackX.isEmpty()) { 44 | int newN = stackX.pop(); 45 | answer += newN; 46 | } 47 | } 48 | } 49 | 50 | 51 | void main() { 52 | stdout.write('Enter a number: '); 53 | StackTriangleApp.number = int.parse(stdin.readLineSync()); 54 | StackTriangleApp.stackTriangle(); 55 | stdout.writeln('Triangle = ${StackTriangleApp.answer}'); 56 | } 57 | 58 | -------------------------------------------------------------------------------- /05_recursion/towers.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class TowerApp { 4 | static int nDisk = 3; 5 | 6 | static void doTowers(int topN, String from, String inter, String to) { 7 | if (topN == 1) { 8 | stdout.writeln('Disk 1 from $from to $to'); 9 | } else { 10 | doTowers(topN - 1, from, to, inter); 11 | stdout.writeln('Disk $topN from $from to $to'); 12 | doTowers(topN - 1, inter, from, to); 13 | } 14 | } 15 | } 16 | 17 | void main(List args) { 18 | TowerApp.doTowers(TowerApp.nDisk, 'A', 'B', 'C'); 19 | } 20 | -------------------------------------------------------------------------------- /05_recursion/triangle.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | int triangle(int number) { 4 | if (number == 1) { 5 | return 1; 6 | } else { 7 | return (number + triangle(number - 1)); 8 | } 9 | } 10 | 11 | void main(List args) { 12 | stdout.writeln('Enter a number:'); 13 | int number = int.parse(stdin.readLineSync()); 14 | int answer = triangle(number); 15 | 16 | stdout.writeln(answer); 17 | } 18 | -------------------------------------------------------------------------------- /06_sorting/partion.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class ArrayPart { 5 | List array; 6 | int nElems; 7 | 8 | ArrayPart(int max) { 9 | array = new List(max); 10 | nElems = 0; 11 | } 12 | 13 | void insert(int value) { 14 | array[nElems] = value; 15 | nElems++; 16 | } 17 | 18 | int size() { 19 | return nElems; 20 | } 21 | 22 | void display() { 23 | stdout.write('A = '); 24 | for (int i = 0; i < nElems; i++) { 25 | stdout.write('${array[i]} '); 26 | } 27 | stdout.writeln(); 28 | } 29 | 30 | int partion(int left, int right, int pivot) { 31 | int leftPtr = left - 1; 32 | int rightPtr = right + 1; 33 | 34 | while (true) { 35 | while (leftPtr < right && array[++leftPtr] < pivot) {}; 36 | while (rightPtr > left && array[--rightPtr] > pivot) {}; 37 | 38 | if (leftPtr >= rightPtr) { 39 | break; 40 | } else { 41 | swap(leftPtr, rightPtr); 42 | } 43 | } 44 | return leftPtr; 45 | } 46 | 47 | void swap(int dex1, int dex2) { 48 | int temp; 49 | temp = array[dex1]; 50 | array[dex1] = array[dex2]; 51 | array[dex2] = temp; 52 | } 53 | } 54 | 55 | void main() { 56 | int maxSize = 16; 57 | ArrayPart arrayPart = new ArrayPart(maxSize); 58 | Random random = new Random(); 59 | for (int i = 0; i < maxSize; i++) { 60 | int n = random.nextInt(200); 61 | arrayPart.insert(n); 62 | } 63 | arrayPart.display(); 64 | 65 | int pivot = 99; 66 | stdout.write('Pivot is $pivot'); 67 | int size = arrayPart.size(); 68 | 69 | int partDex = arrayPart.partion(0, size - 1, pivot); 70 | 71 | stdout.writeln(', Partion is at index $partDex'); 72 | arrayPart.display(); 73 | } -------------------------------------------------------------------------------- /06_sorting/quick_sort1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class ArrayIns { 5 | List array; 6 | int numberOfElements; 7 | 8 | ArrayIns(int max) { 9 | array = new List(max); 10 | numberOfElements = 0; 11 | } 12 | 13 | void insert(int value) { 14 | array[numberOfElements] = value; 15 | numberOfElements++; 16 | } 17 | 18 | void display() { 19 | stdout.write('A = '); 20 | for (int i = 0; i < numberOfElements; i++) { 21 | stdout.write('${array[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | void quickSort() { 27 | recQuickSort(0, numberOfElements - 1); 28 | } 29 | 30 | void recQuickSort(int left, int right) { 31 | if (right - left <= 0) { 32 | return; 33 | } else { 34 | int pivot = array[right]; 35 | int partion = partionIt(left, right, pivot); 36 | recQuickSort(left, partion - 1); 37 | recQuickSort(partion + 1, right); 38 | } 39 | } 40 | 41 | int partionIt(int left, int right, int pivot) { 42 | int leftPtr = left - 1; 43 | int rightPtr = right; 44 | 45 | while (true) { 46 | while (array[++leftPtr] < pivot) {}; 47 | while (rightPtr > 0 && array[--rightPtr] > pivot) {}; 48 | 49 | if (leftPtr >= rightPtr) { 50 | break; 51 | } else { 52 | swap(leftPtr, rightPtr); 53 | } 54 | } 55 | swap(leftPtr, right); 56 | return leftPtr; 57 | } 58 | 59 | void swap(int dex1, int dex2) { 60 | int temp; 61 | temp = array[dex1]; 62 | array[dex1] = array[dex2]; 63 | array[dex2] = temp; 64 | } 65 | } 66 | 67 | void main() { 68 | int maxSize = 16; 69 | Random random = new Random(); 70 | ArrayIns arrayIns = new ArrayIns(maxSize); 71 | for (int i = 0; i < maxSize; i++) { 72 | int value = random.nextInt(100); 73 | arrayIns.insert(value); 74 | } 75 | 76 | arrayIns.display(); 77 | arrayIns.quickSort(); 78 | arrayIns.display(); 79 | } 80 | -------------------------------------------------------------------------------- /06_sorting/quick_sort2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class ArrayIns { 5 | List array; 6 | int numberOfElements; 7 | 8 | ArrayIns(int max) { 9 | array = new List(max); 10 | numberOfElements = 0; 11 | } 12 | 13 | void insert(int value) { 14 | array[numberOfElements] = value; 15 | numberOfElements++; 16 | } 17 | 18 | void display() { 19 | stdout.write('A = '); 20 | for (int i = 0; i < numberOfElements; i++) { 21 | stdout.write('${array[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | void quickSort() { 27 | recQuickSort(0, numberOfElements - 1); 28 | } 29 | 30 | void recQuickSort(int left, int right) { 31 | int size = right - left + 1; 32 | if (size <= 3) { 33 | manualSort(left, right); 34 | } else { 35 | int median = medianOf3(left, right); 36 | int partion = partionIt(left, right, median); 37 | recQuickSort(left, partion - 1); 38 | recQuickSort(partion + 1, right); 39 | } 40 | } 41 | 42 | int medianOf3(int left, int right) { 43 | int center = (left + right) ~/2; 44 | if (array[left] > array[center]) { 45 | swap(left, center); 46 | } 47 | if (array[left] > array[right]) { 48 | swap(left, right); 49 | } 50 | if (array[center] > array[right]) { 51 | swap(center, right); 52 | } 53 | 54 | swap(center, right - 1); 55 | return array[right - 1]; 56 | } 57 | 58 | int partionIt(int left, int right, int pivot) { 59 | int leftPtr = left; 60 | int rightPtr = right - 1; 61 | 62 | while (true) { 63 | while (array[++leftPtr] < pivot) {}; 64 | while (array[--rightPtr] > pivot) {}; 65 | 66 | if (leftPtr >= rightPtr) { 67 | break; 68 | } else { 69 | swap(leftPtr, rightPtr); 70 | } 71 | } 72 | swap(leftPtr, right - 1); 73 | return leftPtr; 74 | } 75 | 76 | void manualSort(int left, int right) { 77 | int size = right - left + 1; 78 | if (size <= 1) { 79 | return; 80 | } 81 | if (size == 2 ) { 82 | if (array[left] > array[right]) { 83 | swap(left, right); 84 | } 85 | return; 86 | } else { 87 | if (array[left] > array[right - 1]) { 88 | swap(left, right - 1); 89 | } 90 | if (array[left] > array[right]) { 91 | swap(left, right); 92 | } 93 | if (array[right - 1 ]> array[right]) { 94 | swap(right - 1, right); 95 | } 96 | } 97 | } 98 | 99 | void swap(int dex1, int dex2) { 100 | int temp; 101 | temp = array[dex1]; 102 | array[dex1] = array[dex2]; 103 | array[dex2] = temp; 104 | } 105 | } 106 | 107 | void main() { 108 | int maxSize = 16; 109 | Random random = new Random(); 110 | ArrayIns arrayIns = new ArrayIns(maxSize); 111 | for (int i = 0; i < maxSize; i++) { 112 | int value = random.nextInt(100); 113 | arrayIns.insert(value); 114 | } 115 | 116 | arrayIns.display(); 117 | arrayIns.quickSort(); 118 | arrayIns.display(); 119 | } 120 | -------------------------------------------------------------------------------- /06_sorting/shell_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class ArraySh { 5 | List array; 6 | int nElems; 7 | 8 | ArraySh(int max) { 9 | array = new List(max); 10 | nElems = 0; 11 | } 12 | 13 | void insert(int value) { 14 | array[nElems] = value; 15 | nElems++; 16 | } 17 | 18 | void display() { 19 | stdout.write('A = '); 20 | for (int i = 0; i < nElems; i++) { 21 | stdout.write('${array[i]} '); 22 | } 23 | stdout.writeln(); 24 | } 25 | 26 | void shellSort() { 27 | int inner, outer; 28 | int temp; 29 | int h = 1; 30 | while (h <= nElems / 3) { 31 | h = h * 3 + 1; 32 | } 33 | 34 | while (h > 0) { 35 | for (outer = h; outer < nElems; outer++) { 36 | temp = array[outer]; 37 | inner = outer; 38 | while (inner > h - 1 && array[inner - h] >= temp) { 39 | array[inner] = array[inner - h]; 40 | inner -= h; 41 | } 42 | array[inner] = temp; 43 | } 44 | h = (h - 1) ~/ 3; 45 | } 46 | } 47 | } 48 | 49 | void main() { 50 | int maxSize = 10; 51 | ArraySh arraySh = new ArraySh(maxSize); 52 | Random random = new Random(); 53 | for (int i = 0; i < maxSize; i++) { 54 | int n = random.nextInt(100); 55 | arraySh.insert(n); 56 | } 57 | arraySh.display(); 58 | arraySh.shellSort(); 59 | arraySh.display(); 60 | } 61 | -------------------------------------------------------------------------------- /07_binary_tree/binary_tree.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:collection'; 3 | 4 | class Node { 5 | int iData; 6 | double dData; 7 | Node leftChild; 8 | Node rightChild; 9 | 10 | void displayNode() { 11 | stdout.write('{'); 12 | stdout.write(iData); 13 | stdout.write(', '); 14 | stdout.write(dData); 15 | stdout.write('}'); 16 | } 17 | } 18 | 19 | class Tree { 20 | Node root; 21 | 22 | Tree() { 23 | root = null; 24 | } 25 | 26 | Node find(int key) { 27 | Node current = root; 28 | while (current.iData != key) { 29 | if (key < current.iData) { 30 | current = current.leftChild; 31 | } else { 32 | current = current.rightChild; 33 | } 34 | if (current == null) { 35 | return null; 36 | } 37 | } 38 | return current; 39 | } 40 | 41 | void insert(int key, double dd) { 42 | Node newNode = new Node(); 43 | newNode.iData = key; 44 | newNode.dData = dd; 45 | if (root == null) { 46 | root = newNode; 47 | } else { 48 | Node current = root; 49 | Node parent; 50 | while (true) { 51 | parent = current; 52 | if (key < current.iData) { 53 | current = current.leftChild; 54 | if (current == null) { 55 | parent.leftChild = newNode; 56 | return; 57 | } 58 | } else { 59 | current = current.rightChild; 60 | if (current == null) { 61 | parent.rightChild = newNode; 62 | return; 63 | } 64 | } 65 | } 66 | } 67 | } 68 | 69 | Node minimum() { 70 | Node current = root; 71 | Node last; 72 | while (current != null) { 73 | last = current; 74 | current = current.leftChild; 75 | } 76 | return last; 77 | } 78 | 79 | bool delete(int key) { 80 | Node current = root; 81 | Node parent = root; 82 | bool isLeftChild = true; 83 | 84 | while (current.iData != key) { 85 | parent = current; 86 | if (key < current.iData) { 87 | isLeftChild = true; 88 | current = current.leftChild; 89 | } else { 90 | isLeftChild = false; 91 | current = current.rightChild; 92 | } 93 | if (current == null) { 94 | return false; 95 | } 96 | if (current.leftChild == null && current.rightChild == null) { 97 | if (current == root) { 98 | root = null; 99 | } else if (isLeftChild) { 100 | parent.leftChild = null; 101 | } else { 102 | parent.rightChild = null; 103 | } 104 | } else if (current.rightChild == null) { 105 | if (current == root) { 106 | root = current.leftChild; 107 | } else if (isLeftChild) { 108 | parent.leftChild = current.leftChild; 109 | } else { 110 | parent.rightChild = current.leftChild; 111 | } 112 | } else if (current.leftChild == null) { 113 | if (current == root) { 114 | root = current.rightChild; 115 | } else if (isLeftChild) { 116 | parent.leftChild = current.rightChild; 117 | } else { 118 | parent.rightChild = current.rightChild; 119 | } 120 | } else { 121 | Node successor = getSuccessor(current); 122 | if (current == root) { 123 | root = successor; 124 | } else if (isLeftChild) { 125 | parent.leftChild = successor; 126 | } else { 127 | parent.rightChild = successor; 128 | // successor.leftChild = current.leftChild; 129 | } 130 | } 131 | } 132 | return true; 133 | } 134 | 135 | Node getSuccessor(Node delNode) { 136 | Node successorParent = delNode; 137 | Node successor = delNode; 138 | Node current = delNode.rightChild; 139 | 140 | while (current != null) { 141 | successorParent = successor; 142 | successor = current; 143 | current = current.leftChild; 144 | } 145 | if (successor != delNode.rightChild) { 146 | successorParent.leftChild = successor.rightChild; 147 | successor.rightChild = delNode.rightChild; 148 | } 149 | return successor; 150 | } 151 | 152 | void traverse (int traverseType) { 153 | switch (traverseType) { 154 | case 1: 155 | stdout.write('Preorder traveral: '); 156 | preOrder(root); 157 | break; 158 | case 2: 159 | stdout.write('Inorder traveral: '); 160 | inOrder(root); 161 | break; 162 | case 3: 163 | stdout.write('Postorder traveral: '); 164 | postOrder(root); 165 | break; 166 | } 167 | stdout.writeln(); 168 | } 169 | 170 | void preOrder(Node localRoot) { 171 | if (localRoot != null) { 172 | stdout.write('${localRoot.iData} '); 173 | preOrder(localRoot.leftChild); 174 | preOrder(localRoot.rightChild); 175 | } 176 | } 177 | 178 | void inOrder(Node localRoot) { 179 | if (localRoot != null) { 180 | inOrder(localRoot.leftChild); 181 | stdout.write('${localRoot.iData} '); 182 | inOrder(localRoot.rightChild); 183 | } 184 | } 185 | 186 | void postOrder(Node localRoot) { 187 | if (localRoot != null) { 188 | postOrder(localRoot.leftChild); 189 | postOrder(localRoot.rightChild); 190 | stdout.write('${localRoot.iData} '); 191 | } 192 | } 193 | 194 | void displayTree() { 195 | Queue globalQueue = new Queue(); 196 | globalQueue.addLast(root); 197 | int nBlanks = 32; 198 | bool isRowEmpty = false; 199 | stdout.writeln( 200 | "............................................." 201 | ); 202 | while (isRowEmpty == false) { 203 | Queue localQueue = new Queue(); 204 | isRowEmpty = true; 205 | for (int i = 0; i < nBlanks; i ++) { 206 | stdout.write(' '); 207 | } 208 | while (globalQueue.isEmpty == false) { 209 | Node temp = globalQueue.removeLast(); 210 | if (temp != null) { 211 | stdout.write(temp.iData); 212 | localQueue.addLast(temp.leftChild); 213 | localQueue.addLast(temp.rightChild); 214 | 215 | if (temp.leftChild != null || temp.rightChild != null) { 216 | isRowEmpty = false; 217 | } 218 | } else { 219 | stdout.write('--'); 220 | localQueue.addLast(null); 221 | localQueue.addLast(null); 222 | } 223 | for (int i = 0; i < nBlanks * 2 - 2; i ++) { 224 | stdout.write(' '); 225 | } 226 | } 227 | stdout.writeln(); 228 | nBlanks = nBlanks ~/ 2; 229 | while (localQueue.isEmpty == false) { 230 | globalQueue.addLast(localQueue.removeLast()); 231 | } 232 | } 233 | stdout.writeln( 234 | "............................................." 235 | ); 236 | } 237 | 238 | } 239 | 240 | void main(List args) { 241 | Tree tree = new Tree(); 242 | 243 | tree.insert(50, 1.5); 244 | tree.insert(25, 1.7); 245 | tree.insert(75, 1.9); 246 | tree.insert(12, 1.5); 247 | tree.insert(37, 1.2); 248 | tree.insert(43, 1.7); 249 | tree.insert(30, 1.5); 250 | tree.insert(33, 1.2); 251 | tree.insert(87, 1.7); 252 | tree.insert(93, 1.5); 253 | tree.insert(97, 1.5); 254 | 255 | while(true) { 256 | stdout.write('Enter first letter of show, insert, find, delete, traverse: '); 257 | String choise = stdin.readLineSync(); 258 | 259 | switch(choise) { 260 | case 's': 261 | tree.displayTree(); 262 | break; 263 | case 'i': 264 | stdout.write('Enter value to insert: '); 265 | int value = int.parse(stdin.readLineSync()); 266 | tree.insert(value, value + 0.9); 267 | break; 268 | case 'f': 269 | stdout.write('Enter value to find: '); 270 | int value = int.parse(stdin.readLineSync()); 271 | Node found = tree.find(value); 272 | if (found != null) { 273 | stdout.write('Found: '); 274 | found.displayNode(); 275 | stdout.writeln(); 276 | } else { 277 | stdout.write('Value not Found'); 278 | } 279 | break; 280 | case 'd': 281 | stdout.write('Enter value to delete: '); 282 | int value = int.parse(stdin.readLineSync()); 283 | bool isDeleted = tree.delete(value); 284 | if (isDeleted) { 285 | tree.displayTree(); 286 | } else { 287 | stdout.write('Value not Found'); 288 | } 289 | break; 290 | case 't': 291 | stdout.write('Please write type of traverse; Pre Order - 1, In Order - 2, Post Order - 3: '); 292 | int value = int.parse(stdin.readLineSync()); 293 | tree.traverse(value); 294 | break; 295 | } 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /09_tree_2_3_4/tree_2_3_4.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | /// DataItem class represented a data in Tree 4 | class DataItem { 5 | int data; 6 | 7 | DataItem(this.data) {} 8 | 9 | void displayItem() { 10 | stdout.write('/$data'); 11 | } 12 | } 13 | 14 | class Node { 15 | static final int ORDER = 4; 16 | int numItems = 0; 17 | Node parent; 18 | List childArray = new List(ORDER); 19 | List itemArray = new List(ORDER - 1); 20 | 21 | /// Connect Child to Parent 22 | void connectChild(int childNum, Node child) { 23 | childArray[childNum] = child; 24 | if (child != null) { 25 | child.parent = this; 26 | } 27 | } 28 | 29 | /// Disconnect Child from Node and return it 30 | Node disconnectChild(int childNum) { 31 | Node temp = childArray[childNum]; 32 | childArray[childNum] = null; 33 | 34 | return temp; 35 | } 36 | 37 | Node getChild(int childNum) { 38 | return childArray[childNum]; 39 | } 40 | 41 | Node getParent() { 42 | return parent; 43 | } 44 | 45 | bool isLeaf() { 46 | return (childArray[0] == null); 47 | } 48 | 49 | int getNumItems() { 50 | return numItems; 51 | } 52 | 53 | /// Get DataItem by index 54 | DataItem getItem(int index) { 55 | return itemArray[index]; 56 | } 57 | 58 | bool isFull() { 59 | return (numItems == ORDER - 1); 60 | } 61 | 62 | /// Find Element index in NODE or return -1 63 | int findItem(int key) { 64 | for(int i = 0; i < ORDER - 1; i ++) { 65 | if(itemArray[i] == null) { 66 | break; 67 | } else if (itemArray[i].data == key ) { 68 | return i; 69 | } 70 | } 71 | return -1; 72 | } 73 | 74 | /// Insert new Item to Node 75 | /// 76 | /// Return new element index 77 | int insertItem(DataItem newItem) { 78 | numItems ++; 79 | int newKey = newItem.data; 80 | 81 | for(int i = ORDER - 2; i >= 0; i --) { 82 | if (itemArray[i] == null) { 83 | continue; 84 | } else { 85 | int itsKey = itemArray[i].data; 86 | if(newKey < itsKey) { 87 | itemArray[i + 1] = itemArray[i]; 88 | } else { 89 | itemArray[i + 1] = newItem; 90 | return i + 1; 91 | } 92 | } 93 | } 94 | itemArray[0] = newItem; 95 | return 0; 96 | } 97 | 98 | /// Delete max item 99 | DataItem removeItem() { 100 | DataItem temp = itemArray[numItems - 1]; 101 | itemArray[numItems - 1] = null; 102 | numItems --; 103 | return temp; 104 | } 105 | 106 | void displayNode() { 107 | for(int i = 0; i < numItems; i ++) { 108 | itemArray[i].displayItem(); 109 | } 110 | stdout.writeln(); 111 | } 112 | } 113 | 114 | class Tree234 { 115 | Node root = new Node(); 116 | 117 | int find(int key) { 118 | Node curNode = root; 119 | int childNumber = curNode.findItem(key); 120 | 121 | while(true) { 122 | if (childNumber != -1) { 123 | return childNumber; 124 | } else if (curNode.isLeaf()) { 125 | return -1; 126 | } else { 127 | curNode = getNextChild(curNode, key); 128 | } 129 | } 130 | } 131 | 132 | /// Insert data element 133 | void insert(int data) { 134 | Node curNode = root; 135 | DataItem temItem = new DataItem(data); 136 | 137 | while(true) { 138 | if(curNode.isFull()) { 139 | split(curNode); 140 | curNode = curNode.getParent(); 141 | 142 | curNode = getNextChild(curNode, data); 143 | } else if (curNode.isLeaf()) { 144 | break; 145 | } else { 146 | curNode = getNextChild(curNode, data); 147 | } 148 | } 149 | curNode.insertItem(temItem); 150 | } 151 | 152 | /// Split Node 153 | void split(Node thisNode) { 154 | DataItem itemB, itemC; 155 | Node parent, child2, child3; 156 | int itemIndex; 157 | 158 | itemC = thisNode.removeItem(); 159 | itemB = thisNode.removeItem(); 160 | child2 = thisNode.disconnectChild(2); 161 | child3 = thisNode.disconnectChild(3); 162 | Node newRight = new Node(); 163 | 164 | /// If Node is Root -> create a new Root 165 | if(thisNode == root) { 166 | root = new Node(); 167 | parent = root; 168 | root.connectChild(0, thisNode); 169 | } else { 170 | parent = thisNode.getParent(); 171 | } 172 | 173 | itemIndex = parent.insertItem(itemB); 174 | int n = parent.getNumItems(); 175 | 176 | for(int i = n - 1; i > itemIndex; i --) { 177 | Node temp = parent.disconnectChild(i); 178 | parent.connectChild(i + 1, temp); 179 | } 180 | 181 | parent.connectChild(itemIndex + 1, newRight); 182 | 183 | newRight.insertItem(itemC); 184 | newRight.connectChild(0, child2); 185 | newRight.connectChild(1, child3); 186 | } 187 | 188 | Node getNextChild(Node node, int value) { 189 | int i; 190 | int numItems = node.getNumItems(); 191 | 192 | for(i = 0; i < numItems; i ++) { 193 | if(value < node.getItem(i).data) { 194 | return node.getChild(i); 195 | } 196 | } 197 | return node.getChild(i); 198 | } 199 | 200 | void displayTree() { 201 | recursionDisplayTree(root, 0, 0); 202 | } 203 | 204 | void recursionDisplayTree(Node node, int level, int childNumber) { 205 | stdout.write('Level = $level child = $childNumber '); 206 | node.displayNode(); 207 | 208 | int numItems = node.getNumItems(); 209 | for(int i = 0; i < numItems + 1; i ++) { 210 | Node nextNode = node.getChild(i); 211 | 212 | if(nextNode != null) { 213 | recursionDisplayTree(nextNode, level + 1, i); 214 | } else { 215 | return; 216 | } 217 | } 218 | } 219 | } 220 | 221 | void main(List args) { 222 | int value; 223 | Tree234 tree234 = new Tree234(); 224 | 225 | tree234.insert(50); 226 | tree234.insert(40); 227 | tree234.insert(60); 228 | tree234.insert(30); 229 | tree234.insert(70); 230 | 231 | while(true) { 232 | stdout.write('Enter first letter of show, insert, find: '); 233 | String choice = stdin.readLineSync(); 234 | 235 | switch(choice) { 236 | case 's': 237 | tree234.displayTree(); 238 | break; 239 | case 'i': 240 | stdout.write('Enter value to insert: '); 241 | value = int.parse(stdin.readLineSync()); 242 | tree234.insert(value); 243 | break; 244 | case 'f': 245 | stdout.write('Enter value to find: '); 246 | value = int.parse(stdin.readLineSync()); 247 | int found = tree234.find(value); 248 | if (found != -1) { 249 | stdout.writeln('Found $value'); 250 | } else { 251 | stdout.writeln('Could now find $value'); 252 | } 253 | break; 254 | default: 255 | stdout.writeln('Invalud entry'); 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /10_hash/hash.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class DataItem { 5 | int data; 6 | 7 | DataItem(this.data) {} 8 | 9 | int getKey() { 10 | return data; 11 | } 12 | } 13 | 14 | class HashTable { 15 | int arraySize; 16 | List hashArray; 17 | DataItem nonItem; 18 | 19 | HashTable(int size) { 20 | this.arraySize = size; 21 | hashArray = new List(size); 22 | nonItem = new DataItem(-1); 23 | } 24 | 25 | void displayTable() { 26 | stdout.write('HashTable: '); 27 | 28 | for(int i = 0; i < arraySize; i++) { 29 | if(hashArray[i] != null) { 30 | stdout.write('${hashArray[i].getKey()} '); 31 | } else { 32 | stdout.write('** '); 33 | } 34 | } 35 | stdout.writeln(); 36 | } 37 | 38 | /// Hash Function 39 | int hashFunc(int key) { 40 | return key % arraySize; 41 | } 42 | 43 | /// Insert a DataItem 44 | void insert(DataItem item) { 45 | int key = item.getKey(); 46 | int hashVal = hashFunc(key); 47 | 48 | // until empty cell or -1 49 | while(hashArray[hashVal] != null && hashArray[hashVal].getKey() != -1) { 50 | ++ hashVal; // go to next cell 51 | hashVal %= arraySize; 52 | } 53 | // insert item 54 | hashArray[hashVal] = item; 55 | } 56 | 57 | /// Delete a DataItem 58 | DataItem delete(int key) { 59 | int hashVal = hashFunc(key); 60 | 61 | // until empty cell 62 | while(hashArray[hashVal] != null) { 63 | if (hashArray[hashVal].getKey() == key) { 64 | DataItem temp = hashArray[hashVal]; 65 | hashArray[hashVal] = nonItem; 66 | return temp; 67 | } 68 | ++ hashVal; 69 | hashVal %= arraySize; 70 | } 71 | return null; 72 | } 73 | 74 | /// Find Element by key 75 | DataItem find(int key) { 76 | int hashVal = hashFunc(key); 77 | 78 | // until empty cell 79 | while (hashArray[hashVal] != null) { 80 | if (hashArray[hashVal].getKey() == key) { 81 | return hashArray[hashVal]; 82 | } 83 | ++ hashVal; 84 | hashVal %= arraySize; 85 | } 86 | return null; 87 | } 88 | } 89 | 90 | void main() { 91 | DataItem dataItem; 92 | int key, size, n; 93 | 94 | Random random = new Random(); 95 | 96 | // get size 97 | stdout.write('Enter size of hash table: '); 98 | size = int.parse(stdin.readLineSync()); 99 | 100 | stdout.write('Enter initial number of items: '); 101 | n = int.parse(stdin.readLineSync()); 102 | 103 | // make table 104 | HashTable hashTable = new HashTable(size); 105 | 106 | // insert data 107 | for (int i = 0; i < n; i ++) { 108 | key = random.nextInt(200); 109 | dataItem = new DataItem(key); 110 | hashTable.insert(dataItem); 111 | } 112 | 113 | // interact with user 114 | while(true) { 115 | stdout.writeln('Enter first leter of show, insert, delete, find: '); 116 | String choice = stdin.readLineSync(); 117 | switch (choice) { 118 | case 's': 119 | hashTable.displayTable(); 120 | break; 121 | case 'i': 122 | stdout.write('Enter key value to insert: '); 123 | key = int.parse(stdin.readLineSync()); 124 | dataItem = new DataItem(key); 125 | hashTable.insert(dataItem); 126 | break; 127 | case 'd': 128 | stdout.write('Enter key value to delete: '); 129 | key = int.parse(stdin.readLineSync()); 130 | hashTable.delete(key); 131 | break; 132 | case 'f': 133 | stdout.write('Enter key value to find: '); 134 | key = int.parse(stdin.readLineSync()); 135 | dataItem = hashTable.find(key); 136 | if (dataItem != null) { 137 | stdout.writeln('Found $key'); 138 | } else { 139 | stdout.writeln('Could NOT found $key'); 140 | } 141 | break; 142 | default: 143 | stdout.writeln('Invalid command'); 144 | } 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /10_hash/hash_chain.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class Link { 5 | int data; 6 | Link next; 7 | 8 | Link(int this.data){} 9 | 10 | int getKey() { 11 | return data; 12 | } 13 | 14 | void displayLink() { 15 | stdout.write('$data '); 16 | } 17 | } 18 | 19 | class SortedList { 20 | Link first; 21 | 22 | SortedList() { 23 | first = null; 24 | } 25 | 26 | /// Insert in ordered 27 | void insert(Link link) { 28 | int key = link.getKey(); 29 | Link previous = null; 30 | Link current = first; 31 | 32 | while (current != null && key > current.getKey()) { 33 | previous = current; 34 | current = current.next; 35 | } 36 | if(previous == null) { 37 | first = link; 38 | } else { 39 | previous.next = link; 40 | } 41 | link.next = current; 42 | } 43 | 44 | /// Remove element 45 | void delete(int key) { 46 | Link previous = null; 47 | Link current = first; 48 | 49 | while (current != null && key != current.getKey()) { 50 | previous = current; 51 | current = current.next; 52 | } 53 | 54 | if (previous == null) { 55 | first = first.next; 56 | } else { 57 | previous.next = current.next; 58 | } 59 | } 60 | 61 | Link find(int key) { 62 | Link current = first; 63 | 64 | while(current != null && current.getKey() <= key) { 65 | if (current.getKey() == key) { 66 | return current; 67 | } 68 | current = current.next; 69 | } 70 | return null; 71 | } 72 | 73 | void displayList() { 74 | stdout.write('List (first -> last): '); 75 | Link current = first; 76 | while(current != null) { 77 | current.displayLink(); 78 | current = current.next; 79 | } 80 | stdout.writeln(); 81 | } 82 | } 83 | 84 | class HashTable { 85 | List hashArray; 86 | int arraySize; 87 | 88 | HashTable(int size) { 89 | arraySize = size; 90 | hashArray = new List(arraySize); 91 | 92 | for(int i = 0; i < arraySize; i ++) { 93 | hashArray[i] = new SortedList(); 94 | } 95 | } 96 | 97 | void displayTable() { 98 | for(int i = 0; i < arraySize; i ++) { 99 | stdout.write('$i. '); 100 | hashArray[i].displayList(); 101 | } 102 | } 103 | 104 | int hashFunc(int key) { 105 | return key % arraySize; 106 | } 107 | 108 | void insert(Link link) { 109 | int key = link.getKey(); 110 | int hashVal = hashFunc(key); 111 | hashArray[hashVal].insert(link); 112 | } 113 | 114 | void delete(int key) { 115 | int hashVal = hashFunc(key); 116 | hashArray[hashVal].delete(key); 117 | } 118 | 119 | Link find(int key) { 120 | int hashVal = hashFunc(key); 121 | Link link = hashArray[hashVal].find(key); 122 | return link; 123 | } 124 | } 125 | 126 | void main() { 127 | int key; 128 | Link dataItem; 129 | int size, n; 130 | 131 | Random random = new Random(); 132 | 133 | stdout.write('Enter size of hash table: '); 134 | size = int.parse(stdin.readLineSync()); 135 | 136 | stdout.write('Enter initial number of items: '); 137 | n = int.parse(stdin.readLineSync()); 138 | 139 | HashTable hashTable = new HashTable(size); 140 | 141 | for(int i = 0; i < n; i ++) { 142 | key = random.nextInt(100); 143 | dataItem = new Link(key); 144 | hashTable.insert(dataItem); 145 | } 146 | 147 | while(true) { 148 | stdout.writeln('Enter first leter of show, insert, delete, find'); 149 | String choice = stdin.readLineSync(); 150 | 151 | switch(choice) { 152 | case 's': 153 | hashTable.displayTable(); 154 | break; 155 | case 'i': 156 | stdout.write('Enter key value to insert: '); 157 | key = int.parse(stdin.readLineSync()); 158 | dataItem = new Link(key); 159 | hashTable.insert(dataItem); 160 | break; 161 | case 'd': 162 | stdout.write('Enter key value to deleete: '); 163 | key = int.parse(stdin.readLineSync()); 164 | hashTable.delete(key); 165 | break; 166 | case 'f': 167 | stdout.write('Enter key value to deleete: '); 168 | key = int.parse(stdin.readLineSync()); 169 | dataItem = hashTable.find(key); 170 | if (dataItem != null) { 171 | stdout.writeln('Found $key'); 172 | } else { 173 | stdout.writeln('Could not find $key'); 174 | } 175 | break; 176 | default: 177 | stdout.writeln('Invalid entry'); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /10_hash/hash_double.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | 5 | class DataItem { 6 | int data; 7 | 8 | DataItem(this.data) {} 9 | 10 | int getKey() { 11 | return data; 12 | } 13 | } 14 | 15 | class HashTable { 16 | int arraySize; 17 | List hashArray; 18 | DataItem nonItem; 19 | 20 | HashTable(int size) { 21 | this.arraySize = size; 22 | hashArray = new List(size); 23 | nonItem = new DataItem(-1); 24 | } 25 | 26 | void displayTable() { 27 | stdout.write('HashTable: '); 28 | 29 | for(int i = 0; i < arraySize; i++) { 30 | if(hashArray[i] != null) { 31 | stdout.write('${hashArray[i].getKey()} '); 32 | } else { 33 | stdout.write('** '); 34 | } 35 | } 36 | stdout.writeln(); 37 | } 38 | 39 | /// Hash Function 40 | int hashFunc(int key) { 41 | return key % arraySize; 42 | } 43 | 44 | /// Second Hash Function 45 | /// return value should be: 46 | /// - non-zero, 47 | /// - less than array size 48 | /// - different from [hashFunc] 49 | int secondHashFunc(int key) { 50 | return 5 - key % 5; 51 | } 52 | 53 | /// Insert a DataItem 54 | void insert(DataItem item) { 55 | int key = item.getKey(); 56 | int hashVal = hashFunc(key); 57 | int stepSize = secondHashFunc(hashVal); 58 | 59 | // until empty cell or -1 60 | while(hashArray[hashVal] != null && hashArray[hashVal].getKey() != -1) { 61 | hashVal += stepSize; // add the step 62 | hashVal %= arraySize; 63 | } 64 | // insert item 65 | hashArray[hashVal] = item; 66 | } 67 | 68 | /// Delete a DataItem 69 | DataItem delete(int key) { 70 | int hashVal = hashFunc(key); 71 | int stepSize = secondHashFunc(hashVal); 72 | 73 | // until empty cell 74 | while(hashArray[hashVal] != null) { 75 | if (hashArray[hashVal].getKey() == key) { 76 | DataItem temp = hashArray[hashVal]; 77 | hashArray[hashVal] = nonItem; 78 | return temp; 79 | } 80 | hashVal += stepSize; // add the step 81 | hashVal %= arraySize; 82 | } 83 | return null; 84 | } 85 | 86 | /// Find Element by key 87 | DataItem find(int key) { 88 | int hashVal = hashFunc(key); 89 | int stepSize = secondHashFunc(hashVal); 90 | 91 | // until empty cell 92 | while (hashArray[hashVal] != null) { 93 | if (hashArray[hashVal].getKey() == key) { 94 | return hashArray[hashVal]; 95 | } 96 | hashVal += stepSize; 97 | hashVal %= arraySize; 98 | } 99 | return null; 100 | } 101 | } 102 | 103 | void main() { 104 | DataItem dataItem; 105 | int key, size, n; 106 | 107 | Random random = new Random(); 108 | 109 | // get size 110 | stdout.write('Enter size of hash table: '); 111 | size = int.parse(stdin.readLineSync()); 112 | 113 | stdout.write('Enter initial number of items: '); 114 | n = int.parse(stdin.readLineSync()); 115 | 116 | // make table 117 | HashTable hashTable = new HashTable(size); 118 | 119 | // insert data 120 | for (int i = 0; i < n; i ++) { 121 | key = random.nextInt(200); 122 | dataItem = new DataItem(key); 123 | hashTable.insert(dataItem); 124 | } 125 | 126 | // interact with user 127 | while(true) { 128 | stdout.writeln('Enter first leter of show, insert, delete, find: '); 129 | String choice = stdin.readLineSync(); 130 | switch (choice) { 131 | case 's': 132 | hashTable.displayTable(); 133 | break; 134 | case 'i': 135 | stdout.write('Enter key value to insert: '); 136 | key = int.parse(stdin.readLineSync()); 137 | dataItem = new DataItem(key); 138 | hashTable.insert(dataItem); 139 | break; 140 | case 'd': 141 | stdout.write('Enter key value to delete: '); 142 | key = int.parse(stdin.readLineSync()); 143 | hashTable.delete(key); 144 | break; 145 | case 'f': 146 | stdout.write('Enter key value to find: '); 147 | key = int.parse(stdin.readLineSync()); 148 | dataItem = hashTable.find(key); 149 | if (dataItem != null) { 150 | stdout.writeln('Found $key'); 151 | } else { 152 | stdout.writeln('Could NOT found $key'); 153 | } 154 | break; 155 | default: 156 | stdout.writeln('Invalid command'); 157 | } 158 | } 159 | } 160 | 161 | -------------------------------------------------------------------------------- /11_heap/heap.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Node { 4 | int _data; 5 | 6 | Node(int this._data) {} 7 | 8 | int get data_key => _data; 9 | set data_key(int id) => _data = id; 10 | } 11 | 12 | class Heap { 13 | List heapArray; 14 | int maxSize; 15 | int currentSize; 16 | 17 | Heap(int this.maxSize) { 18 | currentSize = 0; 19 | heapArray = new List(maxSize); 20 | } 21 | 22 | bool isEmpty() => currentSize == 0; 23 | 24 | bool insert(int key) { 25 | if(currentSize == maxSize) { 26 | return false; 27 | } 28 | Node newNode = new Node(key); 29 | heapArray[currentSize] = newNode; 30 | trickleUp(currentSize ++); 31 | return true; 32 | } 33 | 34 | void trickleUp(int index) { 35 | int parent = (index - 1 ) ~/ 2; 36 | Node bottom = heapArray[index]; 37 | 38 | while(index > 0 && heapArray[parent].data_key < bottom.data_key) { 39 | heapArray[index] = heapArray[parent]; 40 | index = parent; 41 | parent = (parent - 1) ~/ 2; 42 | } 43 | heapArray[index] = bottom; 44 | } 45 | 46 | Node remove() { 47 | Node root = heapArray[0]; 48 | heapArray[0] = heapArray[--currentSize]; 49 | trickleDown(0); 50 | return root; 51 | } 52 | 53 | void trickleDown(int index) { 54 | int largerChild; 55 | Node top = heapArray[index]; 56 | while(index < currentSize ~/ 2) { 57 | int leftChild = 2 * index + 1; 58 | int rightChild = leftChild + 1; 59 | 60 | if(rightChild < currentSize && heapArray[leftChild].data_key < heapArray[rightChild].data_key) { 61 | largerChild = rightChild; 62 | } else { 63 | largerChild = leftChild; 64 | } 65 | 66 | if(top.data_key >= heapArray[largerChild].data_key) { 67 | break; 68 | } 69 | 70 | heapArray[index] = heapArray[largerChild]; 71 | index = largerChild; 72 | } 73 | heapArray[index] = top; 74 | } 75 | 76 | bool change(int index, int newValue) { 77 | if(index < 0 || index >= currentSize) { 78 | return false; 79 | } 80 | 81 | int oldValue = heapArray[index].data_key; 82 | heapArray[index].data_key = newValue; 83 | 84 | if(oldValue < newValue) { 85 | trickleUp(index); 86 | } else { 87 | trickleDown(index); 88 | } 89 | return true; 90 | } 91 | 92 | void displayHeap() { 93 | stdout.write('Heap Array: '); 94 | for(int i = 0; i < currentSize; i ++) { 95 | if (heapArray[i] != null) { 96 | stdout.write('${heapArray[i].data_key} '); 97 | } else { 98 | stdout.write('--'); 99 | } 100 | } 101 | stdout.writeln(); 102 | 103 | int nBlanks = 32; 104 | int itemsPerRow = 1; 105 | int column = 0; 106 | int j = 0; 107 | String dots = '............................'; 108 | stdout.writeln(dots + dots); 109 | 110 | while(currentSize > 0) { 111 | if (column == 0) { 112 | for (int k = 0; k < nBlanks; k ++) { 113 | stdout.write(' '); 114 | } 115 | } 116 | stdout.write(heapArray[j].data_key); 117 | 118 | if(++j == currentSize) { 119 | break; 120 | } 121 | 122 | if (++column == itemsPerRow) { 123 | nBlanks ~/= 2; 124 | itemsPerRow *= 2; 125 | column = 0; 126 | stdout.writeln(); 127 | } else { 128 | for(int k = 0; k < nBlanks * 2 - 2; k ++) { 129 | stdout.write(' '); 130 | } 131 | } 132 | } 133 | stdout.writeln("\n ${dots + dots}"); 134 | } 135 | } 136 | 137 | void main() { 138 | int value, value2; 139 | Heap heap = new Heap(31); 140 | bool success; 141 | 142 | heap.insert(70); 143 | heap.insert(40); 144 | heap.insert(50); 145 | heap.insert(20); 146 | heap.insert(60); 147 | heap.insert(100); 148 | heap.insert(80); 149 | heap.insert(30); 150 | heap.insert(10); 151 | heap.insert(90); 152 | 153 | while(true) { 154 | stdout.writeln('Enter first letter of show, insert, remove, change: '); 155 | 156 | String choice = stdin.readLineSync(); 157 | 158 | switch(choice) { 159 | case 's': 160 | heap.displayHeap(); 161 | break; 162 | case 'i': 163 | stdout.write('Enter value to insert: '); 164 | value = int.parse(stdin.readLineSync()); 165 | success = heap.insert(value); 166 | 167 | if(!success) { 168 | stdout.writeln("Can't insert; heap full"); 169 | } 170 | break; 171 | case 'r': 172 | if(!heap.isEmpty()) { 173 | heap.remove(); 174 | } else { 175 | stdout.writeln("Can't remove; heap is empty"); 176 | } 177 | break; 178 | case 'c': 179 | stdout.write('Enter current index of item: '); 180 | value = int.parse(stdin.readLineSync()); 181 | stdout.write('Enter new key: '); 182 | value2 = int.parse(stdin.readLineSync()); 183 | success = heap.change(value, value2); 184 | 185 | if(!success) { 186 | stdout.writeln('Invalid index'); 187 | } 188 | break; 189 | default: 190 | stdout.writeln('Invalid entry \n'); 191 | } 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /11_heap/heap_sort.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | class Node { 5 | int _data; 6 | 7 | Node(int this._data) {} 8 | 9 | int get data_key => _data; 10 | set data_key(int id) => _data = id; 11 | } 12 | class Heap { 13 | List heapArray; 14 | int maxSize; 15 | int currentSize; 16 | 17 | Heap(int this.maxSize) { 18 | currentSize = 0; 19 | heapArray = new List(maxSize); 20 | } 21 | 22 | bool isEmpty() => currentSize == 0; 23 | 24 | Node remove() { 25 | Node root = heapArray[0]; 26 | heapArray[0] = heapArray[--currentSize]; 27 | trickleDown(0); 28 | return root; 29 | } 30 | 31 | void trickleDown(int index) { 32 | int largerChild; 33 | Node top = heapArray[index]; 34 | while(index < currentSize ~/ 2) { 35 | int leftChild = 2 * index + 1; 36 | int rightChild = leftChild + 1; 37 | 38 | if(rightChild < currentSize && heapArray[leftChild].data_key < heapArray[rightChild].data_key) { 39 | largerChild = rightChild; 40 | } else { 41 | largerChild = leftChild; 42 | } 43 | 44 | if(top.data_key >= heapArray[largerChild].data_key) { 45 | break; 46 | } 47 | 48 | heapArray[index] = heapArray[largerChild]; 49 | index = largerChild; 50 | } 51 | heapArray[index] = top; 52 | } 53 | 54 | void displayHeap() { 55 | int nBlanks = 32; 56 | int itemsPerRow = 1; 57 | int column = 0; 58 | int j = 0; 59 | String dots = '............................'; 60 | stdout.writeln(dots + dots); 61 | 62 | while(currentSize > 0) { 63 | if (column == 0) { 64 | for (int k = 0; k < nBlanks; k ++) { 65 | stdout.write(' '); 66 | } 67 | } 68 | stdout.write(heapArray[j].data_key); 69 | 70 | if(++j == currentSize) { 71 | break; 72 | } 73 | 74 | if (++column == itemsPerRow) { 75 | nBlanks ~/= 2; 76 | itemsPerRow *= 2; 77 | column = 0; 78 | stdout.writeln(); 79 | } else { 80 | for(int k = 0; k < nBlanks * 2 - 2; k ++) { 81 | stdout.write(' '); 82 | } 83 | } 84 | } 85 | stdout.writeln("\n ${dots + dots}"); 86 | } 87 | 88 | void displayArray() { 89 | for(int i = 0; i < maxSize; i ++) { 90 | stdout.write('${heapArray[i].data_key} '); 91 | } 92 | stdout.writeln(); 93 | } 94 | 95 | void insertAt(int index, Node newNode) { 96 | heapArray[index] = newNode; 97 | } 98 | 99 | void incrementSize() { 100 | currentSize ++; 101 | } 102 | } 103 | 104 | void main() { 105 | int size, i; 106 | Random random = new Random(); 107 | 108 | stdout.write('Enter number of items: '); 109 | size = int.parse(stdin.readLineSync()); 110 | 111 | Heap heap = new Heap(size); 112 | for(i = 0; i < size; i ++) { 113 | Node newNode = new Node(random.nextInt(100)); 114 | heap.insertAt(i, newNode); 115 | heap.incrementSize(); 116 | } 117 | 118 | stdout.write('Random Array: '); 119 | heap.displayArray(); 120 | 121 | for(i = size ~/ 2 - 1; i >= 0; i --) { 122 | heap.trickleDown(i); 123 | } 124 | 125 | stdout.write('Heap: '); 126 | heap.displayArray(); 127 | heap.displayHeap(); 128 | 129 | for(i = size - 1; i >= 0; i --) { 130 | Node biggestNode = heap.remove(); 131 | heap.insertAt(i, biggestNode); 132 | } 133 | 134 | stdout.write('Sorted: '); 135 | heap.displayArray(); 136 | } 137 | -------------------------------------------------------------------------------- /12_graph/bfs.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import '../03_stack_queue/queue.dart'; 4 | import './until/graph.dart'; 5 | 6 | class GraphBfs extends Graph { 7 | Queue queue; 8 | 9 | GraphBfs(): super() { 10 | queue = new Queue(maxVerts); 11 | } 12 | 13 | void bfs() { 14 | vertexList[0].wasVisited = true; 15 | displayVertex(0); 16 | queue.insert(0); 17 | int v2; 18 | 19 | while (!queue.isEmpty()) { 20 | int v1 = queue.remove(); 21 | while( (v2 = getAdjUnvisitedVertex(v1)) != -1) { 22 | vertexList[v2].wasVisited = true; 23 | displayVertex(v2); 24 | queue.insert(v2); 25 | } 26 | } 27 | for(int i = 0; i < nVerts; i ++) { 28 | vertexList[i].wasVisited = false; 29 | } 30 | } 31 | } 32 | 33 | 34 | void main() { 35 | GraphBfs graph = new GraphBfs(); 36 | graph.addVertex('A'); 37 | graph.addVertex('B'); 38 | graph.addVertex('C'); 39 | graph.addVertex('D'); 40 | graph.addVertex('E'); 41 | 42 | graph.addEdge(0, 1); 43 | graph.addEdge(1, 2); 44 | graph.addEdge(0, 3); 45 | graph.addEdge(3, 4); 46 | 47 | stdout.write('Visits: '); 48 | graph.bfs(); 49 | stdout.writeln(); 50 | } 51 | -------------------------------------------------------------------------------- /12_graph/dfs.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import '../03_stack_queue/stack/stack.dart'; 4 | import './until/graph.dart'; 5 | 6 | class GraphDfs extends Graph { 7 | StackX stack; 8 | 9 | GraphDfs(): super() { 10 | stack = new StackX(maxVerts); 11 | } 12 | 13 | void dfs() { 14 | vertexList[0].wasVisited = true; 15 | displayVertex(0); 16 | stack.push(0); 17 | 18 | while(!stack.isEmpty()) { 19 | int v = getAdjUnvisitedVertex(stack.peek()); 20 | if (v == -1) { 21 | stack.pop(); 22 | } else { 23 | vertexList[v].wasVisited = true; 24 | displayVertex(v); 25 | stack.push(v); 26 | } 27 | } 28 | 29 | for(int i = 0; i < nVerts; i ++) { 30 | vertexList[i].wasVisited = false; 31 | } 32 | } 33 | } 34 | 35 | void main() { 36 | GraphDfs graph = new GraphDfs(); 37 | graph.addVertex('A'); 38 | graph.addVertex('B'); 39 | graph.addVertex('C'); 40 | graph.addVertex('D'); 41 | graph.addVertex('E'); 42 | 43 | graph.addEdge(0, 1); 44 | graph.addEdge(1, 2); 45 | graph.addEdge(0, 3); 46 | graph.addEdge(3, 4); 47 | 48 | stdout.write('Visits: '); 49 | graph.dfs(); 50 | stdout.writeln(); 51 | } 52 | -------------------------------------------------------------------------------- /12_graph/mst.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import '../03_stack_queue/stack/stack.dart'; 4 | import './until/graph.dart'; 5 | 6 | class GraphMst extends Graph { 7 | StackX stack; 8 | 9 | GraphMst(): super() { 10 | stack = new StackX(maxVerts); 11 | } 12 | 13 | void mst() { 14 | vertexList[0].wasVisited = true; 15 | stack.push(0); 16 | 17 | while(!stack.isEmpty()) { 18 | int currentVertex = stack.peek(); 19 | int v = getAdjUnvisitedVertex(currentVertex); 20 | if (v == -1) { 21 | stack.pop(); 22 | } else { 23 | vertexList[v].wasVisited = true; 24 | stack.push(v); 25 | 26 | displayVertex(currentVertex); 27 | displayVertex(v); 28 | stdout.write(' '); 29 | } 30 | } 31 | for(int i = 0; i < nVerts; i ++) { 32 | vertexList[i].wasVisited = false; 33 | } 34 | } 35 | } 36 | 37 | void main() { 38 | GraphMst graph = new GraphMst(); 39 | graph.addVertex('A'); 40 | graph.addVertex('B'); 41 | graph.addVertex('C'); 42 | graph.addVertex('D'); 43 | graph.addVertex('E'); 44 | 45 | graph.addEdge(0, 1); 46 | graph.addEdge(0, 2); 47 | graph.addEdge(0, 3); 48 | graph.addEdge(0, 4); 49 | graph.addEdge(1, 2); 50 | graph.addEdge(1, 3); 51 | graph.addEdge(1, 4); 52 | graph.addEdge(2, 3); 53 | graph.addEdge(2, 4); 54 | graph.addEdge(3, 4); 55 | 56 | stdout.write('Minimum spanning tree: '); 57 | graph.mst(); 58 | stdout.writeln(); 59 | } 60 | -------------------------------------------------------------------------------- /12_graph/topo.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'until/graph.dart'; 4 | 5 | class GraphTopo extends Graph { 6 | List sortedArray; 7 | 8 | GraphTopo(): super() { 9 | sortedArray = new List(maxVerts); 10 | } 11 | 12 | @override 13 | void addEdge(int start, int end) { 14 | adjMat[start][end] = 1; 15 | } 16 | 17 | int noSuccessors() { 18 | bool isEdge; 19 | 20 | for(int row = 0; row < nVerts; row ++) { 21 | isEdge = false; 22 | for(int col = 0; col < nVerts; col ++) { 23 | if(adjMat[row][col] > 0) { 24 | isEdge = true; 25 | break; 26 | } 27 | } 28 | if (!isEdge) { 29 | return row; 30 | } 31 | } 32 | return -1; 33 | } 34 | 35 | void topo() { 36 | int originNumberVerts = nVerts; 37 | 38 | while(nVerts > 0) { 39 | int currentVertex = noSuccessors(); 40 | if(currentVertex == -1) { 41 | stdout.write('Error: Graph has cycles'); 42 | return; 43 | } 44 | sortedArray[nVerts -1] = vertexList[currentVertex].label; 45 | 46 | deleteVertex(currentVertex); 47 | } 48 | 49 | stdout.write('Topologically sorted order: '); 50 | for(int i = 0; i < originNumberVerts; i ++) { 51 | stdout.write(sortedArray[i]); 52 | } 53 | stdout.writeln(); 54 | } 55 | 56 | void deleteVertex(int delVertex) { 57 | if(delVertex != nVerts - 1) { 58 | for(int i = delVertex; i < nVerts - 1; i ++) { 59 | vertexList[i] = vertexList[i + 1]; 60 | } 61 | 62 | for(int row = delVertex; row < nVerts - 1; row ++) { 63 | moveRowUp(row, nVerts); 64 | } 65 | 66 | for(int col = delVertex; col < nVerts - 1; col ++) { 67 | moveColLeft(col, nVerts - 1); 68 | } 69 | } 70 | nVerts -- ; 71 | } 72 | 73 | void moveRowUp(int row, int length) { 74 | for(int col = 0; col < length; col ++ ) { 75 | adjMat[row][col] = adjMat[row + 1][col]; 76 | } 77 | } 78 | 79 | void moveColLeft(int col, int length) { 80 | for(int row = 0; row < length; row ++ ) { 81 | adjMat[row][col] = adjMat[row][col + 1]; 82 | } 83 | } 84 | } 85 | 86 | void main() { 87 | GraphTopo graphTopo = new GraphTopo(); 88 | graphTopo.addVertex('A'); // 0 89 | graphTopo.addVertex('B'); // 1 90 | graphTopo.addVertex('C'); // 2 91 | graphTopo.addVertex('D'); // 3 92 | graphTopo.addVertex('E'); // 4 93 | graphTopo.addVertex('F'); // 5 94 | graphTopo.addVertex('G'); // 6 95 | graphTopo.addVertex('H'); // 7 96 | 97 | graphTopo.addEdge(0, 3); // AD 98 | graphTopo.addEdge(0, 4); // AE 99 | graphTopo.addEdge(1, 4); // BE 100 | graphTopo.addEdge(2, 5); // CF 101 | graphTopo.addEdge(3, 6); // DG 102 | graphTopo.addEdge(4, 6); // EG 103 | graphTopo.addEdge(5, 7); // FH 104 | graphTopo.addEdge(6, 7); // GH 105 | 106 | graphTopo.topo(); 107 | } 108 | -------------------------------------------------------------------------------- /12_graph/until/graph.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Vertex { 4 | String label; 5 | bool wasVisited; 6 | 7 | Vertex(this.label) { 8 | this.wasVisited = false; 9 | } 10 | } 11 | 12 | class Graph { 13 | final int maxVerts = 20; 14 | List vertexList; 15 | List> adjMat; 16 | int nVerts; 17 | 18 | Graph() { 19 | vertexList = new List(maxVerts); 20 | adjMat = new List.generate(maxVerts, (int i) => new List(maxVerts)); 21 | nVerts = 0; 22 | for(int i = 0; i < maxVerts; i ++) { 23 | for(int j = 0; j < maxVerts; j ++) { 24 | adjMat[i][j] = 0; 25 | } 26 | } 27 | } 28 | 29 | void addVertex(String label) { 30 | vertexList[nVerts++] = new Vertex(label); 31 | } 32 | 33 | void addEdge(int start, int end) { 34 | adjMat[start][end] = 1; 35 | adjMat[end][start] = 1; 36 | } 37 | 38 | void displayVertex(int v) { 39 | stdout.write(vertexList[v].label); 40 | } 41 | 42 | int getAdjUnvisitedVertex(int v) { 43 | for(int i = 0; i < nVerts; i++) { 44 | if(adjMat[v][i] == 1 && vertexList[i].wasVisited == false) { 45 | return i; 46 | } 47 | } 48 | return -1; 49 | } 50 | } -------------------------------------------------------------------------------- /13_weighted_graph/mstw.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Edge { 4 | int srcVert; 5 | int destVert; 6 | int distance; 7 | 8 | Edge(this.srcVert, this.destVert, this.distance); 9 | } 10 | 11 | class PriorityQueue { 12 | int maxSize = 20; 13 | List queueArray; 14 | int size; 15 | 16 | PriorityQueue() { 17 | queueArray = new List(this.maxSize); 18 | size = 0; 19 | } 20 | 21 | void insert(Edge item) { 22 | int i; 23 | for(i = 0; i < size; i ++ ) { 24 | if(item.distance >= queueArray[i].distance) { 25 | break; 26 | } 27 | } 28 | 29 | for(int j = size - 1; j >= i; j --) { 30 | queueArray[j + 1] = queueArray[j]; 31 | } 32 | 33 | queueArray[i] = item; 34 | size ++; 35 | } 36 | 37 | Edge removeMin() { 38 | return queueArray[--size]; 39 | } 40 | 41 | void removeN(int n) { 42 | for(int i = n; i < size - 1; i ++) { 43 | queueArray[i] = queueArray[i + 1]; 44 | } 45 | size --; 46 | } 47 | 48 | Edge peekMin() { 49 | return queueArray[size - 1]; 50 | } 51 | 52 | bool isEmpty() { 53 | return size == 0; 54 | } 55 | 56 | Edge peekN(int n) { 57 | return queueArray[n]; 58 | } 59 | 60 | int find(int findDex) { 61 | for(int i = 0; i < size; i ++) { 62 | if(queueArray[i].destVert == findDex) { 63 | return i; 64 | } 65 | } 66 | 67 | return -1; 68 | } 69 | } 70 | 71 | class Vertex { 72 | String label; 73 | bool isInTree; 74 | 75 | Vertex(this.label) { 76 | isInTree = false; 77 | } 78 | } 79 | class GraphMstw { 80 | final int maxVerts = 20; 81 | final int INFINITY = 1000000; 82 | List vertexList; 83 | List> adjMat; 84 | int nVerts; 85 | int currentVert; 86 | PriorityQueue priorityQueue; 87 | int nTree; 88 | 89 | GraphMstw() { 90 | nTree = 0; 91 | currentVert = 0; 92 | vertexList = new List(maxVerts); 93 | adjMat = new List.generate(maxVerts, (int i) => new List(maxVerts)); 94 | nVerts = 0; 95 | for(int i = 0; i < maxVerts; i ++) { 96 | for(int j = 0; j < maxVerts; j ++) { 97 | adjMat[i][j] = INFINITY; 98 | } 99 | } 100 | 101 | priorityQueue = new PriorityQueue(); 102 | } 103 | 104 | void addVertex(String label) { 105 | vertexList[nVerts++] = new Vertex(label); 106 | } 107 | 108 | void addEdge(int start, int end, int weight) { 109 | adjMat[start][end] = weight; 110 | adjMat[end][start] = weight; 111 | } 112 | 113 | void displayVertex(int v) { 114 | stdout.write(vertexList[v].label); 115 | } 116 | 117 | void mstw() { 118 | currentVert = 0; 119 | 120 | while(nTree < nVerts - 1) { 121 | vertexList[currentVert].isInTree = true; 122 | nTree ++; 123 | 124 | for(int i = 0; i < nVerts; i ++) { 125 | if (i == currentVert) { 126 | continue; 127 | } 128 | if (vertexList[i].isInTree) { 129 | continue; 130 | } 131 | int distance = adjMat[currentVert][i]; 132 | 133 | if(distance == INFINITY) { 134 | continue; 135 | } 136 | 137 | putInPriorityQueue(i, distance); 138 | } 139 | 140 | if(priorityQueue.size == 0) { 141 | stdout.writeln(' GRAPH NOT CONNECTED'); 142 | return; 143 | } 144 | 145 | Edge edge = priorityQueue.removeMin(); 146 | int sourceVert = edge.srcVert; 147 | currentVert = edge.destVert; 148 | 149 | stdout.write(vertexList[sourceVert].label); 150 | stdout.write(vertexList[currentVert].label); 151 | stdout.write(' '); 152 | } 153 | 154 | for(int i = 0; i < nVerts; i ++) { 155 | vertexList[i].isInTree = false; 156 | } 157 | } 158 | 159 | void putInPriorityQueue(int newVert, int newDist) { 160 | int queueIndex = priorityQueue.find(newVert); 161 | if(queueIndex != -1) { 162 | Edge tempEdge = priorityQueue.peekN(queueIndex); 163 | int oldDist = tempEdge.distance; 164 | if(oldDist > newDist) { 165 | priorityQueue.removeN(queueIndex); 166 | Edge edge = new Edge(currentVert, newVert, newDist); 167 | priorityQueue.insert(edge); 168 | } 169 | } else { 170 | Edge edge = new Edge(currentVert, newVert, newDist); 171 | priorityQueue.insert(edge); 172 | } 173 | } 174 | } 175 | 176 | void main() { 177 | GraphMstw graph = new GraphMstw(); 178 | 179 | graph.addVertex('A'); 180 | graph.addVertex('B'); 181 | graph.addVertex('C'); 182 | graph.addVertex('D'); 183 | graph.addVertex('E'); 184 | graph.addVertex('F'); 185 | 186 | graph.addEdge(0, 1, 6); // AB 6 187 | graph.addEdge(0, 3, 4); // AD 4 188 | graph.addEdge(1, 2, 10); // BC 10 189 | graph.addEdge(1, 3, 7); // BD 7 190 | graph.addEdge(1, 4, 7); // BE 7 191 | graph.addEdge(2, 3, 8); // CD 8 192 | graph.addEdge(2, 4, 5); // CE 5 193 | graph.addEdge(2, 5, 6); // CF 6 194 | graph.addEdge(3, 4, 12); // DE 12 195 | graph.addEdge(4, 5, 7); // EF 7 196 | 197 | stdout.write('Minimum spanning tree: '); 198 | graph.mstw(); 199 | } 200 | -------------------------------------------------------------------------------- /13_weighted_graph/path.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | class Vertex { 4 | String label; 5 | bool isInTree; 6 | 7 | Vertex(this.label) { 8 | isInTree = false; 9 | } 10 | } 11 | 12 | class DistPar { 13 | int distance; 14 | int parentVert; 15 | 16 | DistPar(this.parentVert, this.distance); 17 | } 18 | 19 | class GraphPath { 20 | final int maxVerts = 20; 21 | final int INFINITY = 1000000; 22 | List vertexList; 23 | List> adjMat; 24 | int nVerts; 25 | int nTree; 26 | int currentVert; 27 | List sPath; 28 | int startToCurrent; 29 | 30 | GraphPath() { 31 | nTree = 0; 32 | currentVert = 0; 33 | startToCurrent = 0; 34 | nVerts = 0; 35 | vertexList = new List(maxVerts); 36 | adjMat = new List.generate(maxVerts, (int i) => new List(maxVerts)); 37 | for(int i = 0; i < maxVerts; i ++) { 38 | for(int j = 0; j < maxVerts; j ++) { 39 | adjMat[i][j] = INFINITY; 40 | } 41 | } 42 | 43 | sPath = new List(maxVerts); 44 | } 45 | 46 | void addVertex(String label) { 47 | vertexList[nVerts++] = new Vertex(label); 48 | } 49 | 50 | void addEdge(int start, int end, int weight) { 51 | adjMat[start][end] = weight; 52 | } 53 | 54 | void path() { 55 | int startTree = 0; 56 | vertexList[startTree].isInTree = true; 57 | nTree = 1; 58 | 59 | for(int i = 0; i < nVerts; i ++) { 60 | int tempDist = adjMat[startTree][i]; 61 | sPath[i] = new DistPar(startTree, tempDist); 62 | } 63 | 64 | while(nTree < nVerts) { 65 | int indexMin = getMin(); 66 | int minDist = sPath[indexMin].distance; 67 | 68 | if(minDist == INFINITY) { 69 | stdout.writeln('There are unreachable verices'); 70 | break; 71 | } else { 72 | currentVert = indexMin; 73 | startToCurrent = sPath[indexMin].distance; 74 | } 75 | 76 | vertexList[currentVert].isInTree = true; 77 | nTree ++; 78 | adjust_sPath(); 79 | } 80 | 81 | displayPath(); 82 | 83 | nTree = 0; 84 | 85 | for(int i = 0; i < nVerts; i ++) { 86 | vertexList[i].isInTree = false; 87 | } 88 | } 89 | 90 | int getMin() { 91 | int minDist = INFINITY; 92 | int indexMin = 0; 93 | for(int i = 1; i < nVerts; i ++) { 94 | if(!vertexList[i].isInTree && sPath[i].distance < minDist) { 95 | minDist = sPath[i].distance; 96 | indexMin = i; 97 | } 98 | } 99 | 100 | return indexMin; 101 | } 102 | 103 | void adjust_sPath() { 104 | int column = 1; 105 | while(column < nVerts) { 106 | if(vertexList[column].isInTree) { 107 | column ++; 108 | 109 | continue; 110 | } 111 | 112 | int currentToFringe = adjMat[currentVert][column]; 113 | int startToFringe = startToCurrent + currentToFringe; 114 | int sPathDist = sPath[column].distance; 115 | 116 | if(startToFringe < sPathDist) { 117 | sPath[column].parentVert = currentVert; 118 | sPath[column].distance = startToFringe; 119 | } 120 | 121 | column ++; 122 | } 123 | } 124 | 125 | void displayPath() { 126 | for(int i = 0; i < nVerts; i ++) { 127 | stdout.write('${vertexList[i].label} = '); 128 | 129 | if(sPath[i].distance == INFINITY) { 130 | stdout.write('inf'); 131 | } else { 132 | stdout.write(sPath[i].distance); 133 | } 134 | 135 | String parent = vertexList[sPath[i].parentVert].label; 136 | stdout.write('($parent) '); 137 | } 138 | 139 | stdout.writeln(); 140 | } 141 | } 142 | 143 | 144 | void main() { 145 | GraphPath graphPath = new GraphPath(); 146 | 147 | graphPath.addVertex('A'); // 0 148 | graphPath.addVertex('B'); // 1 149 | graphPath.addVertex('C'); // 2 150 | graphPath.addVertex('D'); // 3 151 | graphPath.addVertex('E'); // 4 152 | 153 | graphPath.addEdge(0, 1, 50); // AB 50 154 | graphPath.addEdge(0, 3, 80); // AD 80 155 | graphPath.addEdge(1, 2, 60); // BC 60 156 | graphPath.addEdge(1, 3, 90); // BD 90 157 | graphPath.addEdge(2, 4, 40); // CE 40 158 | graphPath.addEdge(3, 2, 20); // DC 20 159 | graphPath.addEdge(3, 4, 70); // DE 70 160 | graphPath.addEdge(4, 1, 50); // EB 50 161 | 162 | stdout.writeln('Shortest Path: '); 163 | graphPath.path(); 164 | stdout.writeln(); 165 | } 166 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Artem Halas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms in Dart 2 | 3 | [![Build Status](https://travis-ci.org/artem-galas/data_structures_in_dart.svg?branch=master)](https://travis-ci.org/artem-galas/data_structures_in_dart) 4 | 5 | This is a repository inspired by **[Data Structures & Algorithms in Java by Robert Lafore](https://www.amazon.com/Data-Structures-Algorithms-Java-2nd/dp/0672324539)**. 6 | 7 | There you can find all code-example rewritten on Dart and all solved tasks 8 | 9 | ## Table of Contents 10 | ### 01. Arrays. 11 | - `low_array` - very simple example with arrays. 12 | - `high_array` - rewritten `low_array.dart` using more OOP way. Describes **LinerSearch** in Arrays. 13 | - `ordered_array` - Describes **BinarySearch** in sorted Arrays. 14 | - `class_data` - Using Arrays with Object. 15 | ### 02. Simple Sorting. 16 | - `bubble_sort` - Bubble Sort Example 17 | - `select_sort` 18 | - `insert_sort` 19 | - `object_sort` - Object sort example using **insert sort** and **Lexicographical Comparisons** 20 | ### 03. Stacks and Queues. 21 | - stack 22 | - `stack` - simple stack with array of integer 23 | - `reverse` - reversing a word eq: `artem` -> `metra` 24 | - `brackets` - Delimiter Matching - a program that checks the delimiters in a line of text typed by the user eq: `a{b(c]d}e` -> `Error ] at 5` 25 | - `queue` - simple queue. 26 | - `priority_queue` 27 | - `infix` - Convert Infix to Postfix eq `A+B*C` -> `ABC*+` 28 | - `postfix` - Evaluate Postfix Expressions eq `57+` -> `Evaluates to 12` 29 | ### 04. Linked Lists. 30 | - linked_list 31 | - `simple_linked_list ` - simple linked list implemintation with `deleteFirst` and `insertFirst` methods 32 | - `linked_list` - adding `delete` and `find` methods. 33 | - `first_last_list` - linked list with link to `first` and `last` object 34 | - `link_stack` - Stack implementation using `linked list` 35 | - `link_queue` - Queue implementation using `first_last_list` 36 | - `sorted_list` - sorted linked list 37 | - `list_insertion_sort` - insertion sort array using linked list 38 | - `double_linked_list` - linked list where each element contain `next` and `previous` link 39 | - `list_iterator` - implementation linked list with iterator 40 | ### 05. Recursion. 41 | - `triangle` - simple example of recursion - calculate triangle number. E.g `Triangle number 3 -> 6` (1, 3, 6, 10, 15, 21...) 42 | - `anagram` - simple program, which can do anagrams. 43 | E.g Input: `cat` 44 | Output: 45 | ``` 46 | 1 c a t 47 | 2 c t a 48 | 3 a t c 49 | 4 a c t 50 | 5 t c a 51 | 6 t a c 52 | ``` 53 | - `binary_search` - binary search implemented with recursion (binary search see 01_array/ordered_array) 54 | - `towers` - Tower of Hanoi algorithms using recursion 55 | - `merge` - very simple implementation merge 2 pre-sorted arrays. 56 | - `merge_sort` - Merge sorting array 57 | - `stack_triangle` - calculate triangle number with recursion and stack 58 | - `stack_triangle2` - calculate triangle number using stack instead of recension 59 | - `power` - X power Y using optimizing recursion method 60 | ### 06. Sorting. 61 | - `shell_sorting` - sorting used [Shell's Method](https://en.wikipedia.org/wiki/Shellsort) 62 | - `partion` 63 | - `quick_sort1` - Quick sort based on last element of array 64 | - `quick_sort2` - QuickSort based on median 65 | ### 07. Binary Tree. 66 | - `binary-tree` - Binary Search tree 67 | ```bash 68 | 50 69 | 25 75 70 | 12 37 -- 87 71 | -- -- 30 43 -- -- -- 93 72 | -- -- -- -- -- 33 -- -- -- -- -- -- -- -- -- 97 73 | ``` 74 | ### 08. Red-Black Tree. 75 | Unfortunately there no code. 76 | ### 09. Tree 2 3 4. 77 | - `tree_2_3_4` - Tree 2 3 4 78 | ```bash 79 | Enter first letter of show, insert, find: s 80 | Level = 0 child = 0 /50 81 | Level = 1 child = 0 /30/40 82 | Level = 1 child = 1 /60/70 83 | ``` 84 | ### 10. Hash. 85 | - `hash` - simple hash 86 | 87 | ```bash 88 | Enter size of hash table: 10 89 | Enter initial number of items: 8 90 | Enter first leter of show, insert, delete, find: 91 | s 92 | HashTable: 120 151 150 193 173 118 ** ** 148 99 93 | Enter first leter of show, insert, delete, find: 94 | i 95 | Enter key value to insert: 100 96 | Enter first leter of show, insert, delete, find: 97 | s 98 | HashTable: 120 151 150 193 173 118 100 ** 148 99 99 | Enter first leter of show, insert, delete, find: 100 | ``` 101 | 102 | - `hash_double` - Double Hash. It use two hashFunction: 103 | - `hashFunc` - for find first index; 104 | - `secondHashFunc` - for find the step (offset); 105 | 106 | ```bash 107 | Enter size of hash table: 10 108 | Enter initial number of items: 4 109 | Enter first leter of show, insert, delete, find: 110 | s 111 | HashTable: ** 121 ** ** ** ** 196 137 138 ** 112 | Enter first leter of show, insert, delete, find: 113 | i 114 | Enter key value to insert: 100 115 | Enter first leter of show, insert, delete, find: 116 | s 117 | HashTable: 100 121 ** ** ** ** 196 137 138 ** 118 | ``` 119 | 120 | - `hash_chain` - Chain method which use SortedLinkedList 121 | 122 | ```bash 123 | Enter size of hash table: 5 124 | Enter initial number of items: 5 125 | Enter first leter of show, insert, delete, find 126 | s 127 | 0. List (first -> last): 128 | 1. List (first -> last): 56 86 129 | 2. List (first -> last): 12 130 | 3. List (first -> last): 13 48 131 | 4. List (first -> last): 132 | Enter first leter of show, insert, delete, find 133 | ``` 134 | 135 | ### 11. Heap. 136 | 137 | - `heap` - heap implementation 138 | 139 | ```bash 140 | Enter first letter of show, insert, remove, change: 141 | s 142 | Heap Array: 100 90 80 30 60 50 70 20 10 40 143 | ........................................................ 144 | 100 145 | 90 80 146 | 30 60 50 70 147 | 20 10 40 148 | ........................................................ 149 | ``` 150 | 151 | - `heap_sort` - heap sorting - `O(N*logN)` 152 | 153 | ```bash 154 | Enter number of items: 10 155 | Random Array: 58 42 87 29 14 53 39 79 9 64 156 | Heap: 87 79 58 42 64 53 39 29 9 14 157 | ........................................................ 158 | 87 159 | 79 58 160 | 42 64 53 39 161 | 29 9 14 162 | ........................................................ 163 | Sorted: 9 14 29 39 42 53 58 64 79 87 164 | ``` 165 | 166 | ### 12 Graph. 167 | ![graph](./doc/graph.jpg) 168 | 169 | - `dfs` - Depth-first search 170 | ```bash 171 | Visits: ABCDE 172 | ``` 173 | 174 | - `bfs` - Breadth-first search 175 | ```bash 176 | Visits: ABDCE 177 | ``` 178 | 179 | - `mst` - Minimum spanning tree 180 | 181 | ![graph-not-optimized](./doc/graph-not-optimized.jpg) 182 | ![graph-mst](./doc/graph-mst.jpg) 183 | 184 | ```bash 185 | Minimum spanning tree: AB BC CD DE 186 | ``` 187 | 188 | - `topo` - Topology sorting 189 | 190 | ```bash 191 | Topologically sorted order: BAEDGCFH 192 | ``` 193 | 194 | ### 13. Weighted Graph. 195 | 196 | - `mstw`- Minimum Spanning Tree with Weighted Graphs 197 | 198 | ![weighted-graph-mstw-input](doc/weighted-graph-mstw-input.jpg) 199 | ![weighted-graph-mstw-output](doc/weighted-graph-mstw-output.jpg) 200 | 201 | ```bash 202 | Minimum spanning tree: AD AB BE EC CF 203 | ``` 204 | 205 | - `path` - Find Shortest Path ([Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)) 206 | 207 | ![graph_shortest_path](doc/graph_shortest_path.jpg) 208 | 209 | ```bash 210 | Shortest Path: 211 | A = inf(A) B = 50(A) C = 100(D) D = 80(A) E = 140(C) 212 | ``` 213 | 214 | ## How to Run Code? 215 | 216 | - Be sure you have installed [dart](https://webdev.dartlang.org/tools/sdk#install) 217 | - Open folder with project 218 | - Run into you terminal `dart path/to/file.dart` e.q `dart chap_02/low_array.dart` 219 | 220 | ## What IDE have support dart language? 221 | I prefer use [JetBrains](https://www.jetbrains.com/idea/) 222 | 223 | But you can use [VsCode](https://code.visualstudio.com/) + [DartCode](https://marketplace.visualstudio.com/items?itemName=Dart-Code.dart-code) Plugin 224 | 225 | ## How to test tasks? 226 | All tasks have a unit test, which located in `0N_name/tasks/test`. 227 | 228 | So you need: 229 | - copy and past that test to your project 230 | - change path to you solution 231 | - run `pub run test path/to_test.dart` 232 | 233 | ## Contributing 234 | If you want to contribute or you find a issue/mistake feel free to create an issue and pull-request 235 | 236 | ## TODO: 237 | - [ ] Add tests for implementations 238 | - [ ] Add task for each data structure 239 | - [ ] Add test for each task 240 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | analyzer: 2 | # exclude: 3 | # - path/to/excluded/files/** 4 | 5 | # Lint rules and documentation, see http://dart-lang.github.io/linter/lints 6 | linter: 7 | rules: 8 | - cancel_subscriptions 9 | - hash_and_equals 10 | - iterable_contains_unrelated_type 11 | - list_remove_unrelated_type 12 | - test_types_in_equals 13 | - unrelated_type_equality_checks 14 | - valid_regexps 15 | - library_prefixes 16 | - library_names 17 | - unnecessary_brace_in_string_interps 18 | - always_declare_return_types 19 | - always_specify_types 20 | - camel_case_types 21 | - file_names 22 | - no_duplicate_case_values 23 | - curly_braces_in_flow_control_structures -------------------------------------------------------------------------------- /dart_test.yaml: -------------------------------------------------------------------------------- 1 | platforms: [vm] 2 | 3 | paths: 4 | - 01_array/test 5 | - 01_array/tasks/test 6 | - 02_simple_sorting/test -------------------------------------------------------------------------------- /doc/graph-mst.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/graph-mst.jpg -------------------------------------------------------------------------------- /doc/graph-not-optimized.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/graph-not-optimized.jpg -------------------------------------------------------------------------------- /doc/graph.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/graph.jpg -------------------------------------------------------------------------------- /doc/graph_shortest_path.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/graph_shortest_path.jpg -------------------------------------------------------------------------------- /doc/weighted-graph-mstw-input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/weighted-graph-mstw-input.jpg -------------------------------------------------------------------------------- /doc/weighted-graph-mstw-output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/artem-galas/data_structures_in_dart/e0897cdbb6e4b2d7e2acc1390f2c33b8b1656549/doc/weighted-graph-mstw-output.jpg -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: data_structures_algorithms 2 | version: 0.0.1 3 | #homepage: https://www.example.com 4 | author: artem_galas 5 | 6 | environment: 7 | sdk: '>=2.0.0 <3.0.0' 8 | 9 | dev_dependencies: 10 | test: ^1.5.1 11 | --------------------------------------------------------------------------------