├── .gitattributes ├── .github └── workflows │ └── dart.yml ├── .gitignore ├── .vscode └── settings.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── README.md ├── analysis_options.yaml ├── bin ├── colection_ex.dart ├── collection │ ├── LinkedList │ │ ├── constructor.dart │ │ ├── mothod.dart │ │ ├── problem │ │ │ ├── problem1.dart │ │ │ ├── problem1.md │ │ │ ├── problem2.dart │ │ │ └── problem2.md │ │ └── properties.dart │ ├── List │ │ ├── constructors.dart │ │ ├── discription.md │ │ ├── method.dart │ │ ├── problem │ │ │ ├── problem1.dart │ │ │ ├── problem1.md │ │ │ ├── problem2.dart │ │ │ └── problem2.md │ │ └── properties.dart │ ├── Map │ │ ├── HashMap │ │ │ ├── allconstructor.dart │ │ │ ├── allmethod.dart │ │ │ ├── allmethod_test.dart │ │ │ └── allproperty.dart │ │ ├── LinkedHashMap │ │ │ ├── allconstructor.dart │ │ │ ├── allmethod.dart │ │ │ └── allproperty.dart │ │ ├── SplayTreeMap │ │ │ ├── allconstructor.dart │ │ │ ├── allmethods.dart │ │ │ ├── allproperty.dart │ │ │ ├── problem.md │ │ │ ├── problmes │ │ │ │ ├── prob1.dart │ │ │ │ ├── prob2.dart │ │ │ │ └── prob2.md │ │ │ └── splaytreemap.md │ │ └── UnmodifiableMapView │ │ │ ├── allconstructor.dart │ │ │ ├── allmethod.dart │ │ │ └── allproperties.dart │ ├── Queue │ │ ├── DoubleLinkedQueue │ │ │ ├── constructor.dart │ │ │ ├── method.dart │ │ │ ├── pronblems │ │ │ │ ├── problem1.dart │ │ │ │ ├── problem1.md │ │ │ │ ├── problem2.dart │ │ │ │ └── problem2.md │ │ │ ├── properties.dart │ │ │ └── threadsafe.md │ │ ├── ListQueue │ │ │ ├── constructor.dart │ │ │ ├── method.dart │ │ │ ├── problem │ │ │ │ ├── problem1.dart │ │ │ │ └── problem1.md │ │ │ └── properties.dart │ │ ├── Queue │ │ │ ├── constructor.dart │ │ │ ├── method.dart │ │ │ ├── problem │ │ │ │ └── problem1.md │ │ │ └── properties.dart │ │ └── queue.md │ ├── Set │ │ ├── HashSet │ │ │ ├── constructors.dart │ │ │ ├── hashset.md │ │ │ ├── mehods.dart │ │ │ ├── problesm │ │ │ │ ├── problem1.dart │ │ │ │ ├── problem1.md │ │ │ │ ├── problem2.dart │ │ │ │ └── problem2.md │ │ │ └── properties.dart │ │ ├── LinkedHashSet │ │ │ ├── LinkedHashSet.md │ │ │ ├── constructor.dart │ │ │ ├── methods.dart │ │ │ ├── problem │ │ │ │ ├── problem1.dart │ │ │ │ ├── problem1.md │ │ │ │ └── problem2.md │ │ │ └── properties.dart │ │ ├── SplayTreeSet │ │ │ ├── constructor.dart │ │ │ ├── methods.dart │ │ │ ├── problem │ │ │ │ ├── problem1.dart │ │ │ │ ├── problem1.md │ │ │ │ ├── problem2.dart │ │ │ │ └── problem2.md │ │ │ └── propertis.dart │ │ └── UnmodifiableSetView │ │ │ ├── UnmodifiableSetView.md │ │ │ ├── constructor.dart │ │ │ ├── method.dart │ │ │ └── properties.dart │ ├── developer │ │ └── classes.dart │ └── math │ │ ├── classes.dart │ │ ├── constant.dart │ │ └── function.dart ├── convert │ ├── allclasses.dart │ └── jsondecoder.dart ├── dart_programming.dart └── difference.md ├── lib └── dart_programming.dart ├── pubspec.lock ├── pubspec.yaml └── test └── dart_programming_test.dart /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/workflows/dart.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | 6 | name: Dart 7 | 8 | on: 9 | push: 10 | branches: [ "main" ] 11 | pull_request: 12 | branches: [ "main" ] 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | 21 | # Note: This workflow uses the latest stable version of the Dart SDK. 22 | # You can specify other versions if desired, see documentation here: 23 | # https://github.com/dart-lang/setup-dart/blob/main/README.md 24 | # - uses: dart-lang/setup-dart@v1 25 | - uses: dart-lang/setup-dart@9a04e6d73cca37bd455e0608d7e5092f881fd603 26 | 27 | - name: Install dependencies 28 | run: dart pub get 29 | 30 | # Uncomment this step to verify the use of 'dart format' on each commit. 31 | # - name: Verify formatting 32 | # run: dart format --output=none --set-exit-if-changed . 33 | 34 | # Consider passing '--fatal-infos' for slightly stricter analysis. 35 | - name: Analyze project source 36 | run: dart analyze 37 | 38 | # Your project will need to have tests in test/ and a dependency on 39 | # package:test for this step to succeed. Note that Flutter projects will 40 | # want to change this to 'flutter test'. 41 | - name: Run tests 42 | run: dart test 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # https://dart.dev/guides/libraries/private-files 2 | # Created by `dart pub` 3 | .dart_tool/ 4 | redme.rst 5 | 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "workbench.editorAssociations": { 3 | "*.md": "vscode.markdown.preview.editor" 4 | }, 5 | "commentTranslate.hover.enabled": false 6 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.0.0 2 | 3 | - Initial version. 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Contributing to the Dart Programming Documentation Project 4 | 5 | Thank you for considering contributing to the Dart Programming Documentation Project! Your contributions help improve the quality and accessibility of Dart documentation for developers worldwide. 6 | 7 | ## Getting Started 8 | 9 | To contribute to this project, follow these steps: 10 | 11 | ### 1. Fork the Repository 12 | 13 | Click the "Fork" button on the top right corner of the repository's page to create your own fork. 14 | 15 | ### 2. Clone the Repository 16 | 17 | Clone your forked repository to your local machine using the following command: 18 | 19 | ```bash 20 | git clone https://github.com/xeron56/dart_programming.git 21 | ``` 22 | 23 | ### 3. Install Dependencies (if any) 24 | 25 | ```bash 26 | dart pub get 27 | ``` 28 | 29 | ### 4. Make Changes 30 | 31 | Make your desired changes to the project on your local machine. 32 | First got to this url https://api.dart.dev/stable/3.3.0/index.html 33 | and find the part that is not covered on the project (currently dart:collection is maximum covered) do add ur code 34 | ![image](https://github.com/xeron56/dart_programming/assets/11449967/d2022e98-daeb-4142-9fc9-2387d742cc77) 35 | 36 | 37 | ### 5. Test Your Changes 38 | 39 | Before submitting a pull request, test your changes thoroughly to ensure they work as expected. 40 | 41 | ### 6. Commit Your Changes 42 | 43 | Once you're satisfied with your changes, commit them to your forked repository with descriptive commit messages. 44 | 45 | ```bash 46 | git add . 47 | git commit -m "Your descriptive commit message here" 48 | ``` 49 | 50 | ### 7. Push Your Changes 51 | 52 | Push your committed changes to your forked repository: 53 | 54 | ```bash 55 | git push origin main 56 | ``` 57 | 58 | ### 8. Submit a Pull Request 59 | 60 | Go to the original repository on GitHub and click on the "New Pull Request" button. Provide a clear title and description for your pull request, detailing the changes you've made. 61 | 62 | ## Contribution Guidelines 63 | 64 | Please adhere to the following guidelines when contributing to this project: 65 | 66 | 67 | - Ensure your changes are well-documented and include appropriate comments where necessary. 68 | - Avoid introducing breaking changes unless absolutely necessary, and provide clear justification for such changes. 69 | 70 | 71 | 72 | ## Questions or Concerns? 73 | 74 | If you have any questions or concerns about contributing to this project, feel free to reach out to the project maintainers via email: shahidul7889@gmail.com 75 | 76 | We appreciate your contributions and look forward to your involvement in improving the Dart Programming Documentation Project! 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

3 | Cintel Logo 4 |

5 | 6 | 7 | 8 |

Dart Programming Documentation Project

9 | 10 | 11 |

12 | 13 | Dart Version 14 | 15 | 16 | Flutter Version 17 | 18 |

19 | 20 | 21 |

22 | Welcome to the Dart Programming Documentation Project! This open-source initiative aims to provide comprehensive and clear documentation with code example for the Dart programming language's core library. 23 |

24 | 25 | 26 | 27 | # Dart Programming Documentation Project 28 | 29 | Welcome to the Dart Programming Documentation Project! This open-source initiative aims to provide comprehensive and clear documentation for the Dart programming language's core library. 30 | 31 | ![code](https://github.com/xeron56/dart_programming/assets/11449967/1cfda0ff-9918-458f-be04-c3174df3c029) 32 | 33 | 34 | ## Objective 35 | 36 | The primary objective of this project is to elucidate the Dart core library, breaking it down section by section, and providing detailed explanations along with clean, illustrative examples for every constructor, property, method, and other essential components. 37 | 38 | ## Why Dart Programming Documentation? 39 | 40 | While Dart is a powerful and versatile language, its documentation may sometimes lack clarity or depth, especially for newcomers or those seeking in-depth understanding. This project seeks to bridge that gap by offering meticulously crafted documentation with practical examples to aid learning and understanding. 41 | 42 | ## How to Contribute 43 | 44 | Contributions to this project are highly encouraged and welcomed! Whether you're a seasoned Dart developer or just getting started, there are numerous ways to contribute: 45 | 46 | - **Documentation:** Help improve existing documentation by clarifying explanations, adding examples, or filling in missing details. 47 | - **Code Examples:** Provide new, clear, and concise code examples for constructors, properties, methods, etc., to enhance understanding. 48 | 49 | - **Feedback:** Share your feedback, suggestions, or report issues to help us continuously improve the quality of the documentation. 50 | 51 | For detailed instructions on how to contribute, please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file. 52 | 53 | ## Getting Started 54 | 55 | To start contributing, simply fork this repository, make your changes, and submit a pull request. Make sure to follow the guidelines outlined in the [CONTRIBUTING.md](CONTRIBUTING.md) file to ensure smooth collaboration. 56 | 57 | 58 | ## Acknowledgments 59 | 60 | We extend our gratitude to the Dart community for their continuous support and contributions to making this project a valuable resource for learners and developers alike. 61 | 62 | ## License 63 | 64 | This project is licensed under the [MIT License](LICENSE), which means you are free to use, modify, and distribute the code and documentation, with appropriate attribution. 65 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the static analysis results for your project (errors, 2 | # warnings, and lints). 3 | # 4 | # This enables the 'recommended' set of lints from `package:lints`. 5 | # This set helps identify many issues that may lead to problems when running 6 | # or consuming Dart code, and enforces writing Dart using a single, idiomatic 7 | # style and format. 8 | # 9 | # If you want a smaller set of lints you can change this to specify 10 | # 'package:lints/core.yaml'. These are just the most critical lints 11 | # (the recommended set includes the core lints). 12 | # The core lints are also what is used by pub.dev for scoring packages. 13 | 14 | include: package:lints/recommended.yaml 15 | 16 | # Uncomment the following section to specify additional rules. 17 | 18 | # linter: 19 | # rules: 20 | # - camel_case_types 21 | 22 | # analyzer: 23 | # exclude: 24 | # - path/to/excluded/files/** 25 | 26 | # For more information about the core and recommended set of lints, see 27 | # https://dart.dev/go/core-lints 28 | 29 | # For additional information about configuring this file, see 30 | # https://dart.dev/guides/language/analysis-options 31 | -------------------------------------------------------------------------------- /bin/colection_ex.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | //listqueue 4 | void listqueue() { 5 | ListQueue queue = ListQueue(); 6 | 7 | queue.add(1); // Add elements at the end 8 | queue.add(2); 9 | queue.addLast(3); 10 | 11 | queue.addFirst(0); // Add elements at the beginning 12 | 13 | print(queue); // Output: (0, 1, 2, 3) 14 | 15 | queue.removeFirst(); // Remove element from the front 16 | queue.removeLast(); // Remove element from the end 17 | 18 | print(queue); // Output: (1, 2) 19 | } 20 | 21 | //queue 22 | void queue() { 23 | Queue queue = Queue(); 24 | 25 | queue.add(1); // Add elements at the end 26 | queue.add(2); 27 | queue.addLast(3); 28 | 29 | queue.addFirst(0); // Add elements at the beginning 30 | 31 | print(queue); // Output: (0, 1, 2, 3) 32 | 33 | queue.removeFirst(); // Remove element from the front 34 | queue.removeLast(); // Remove element from the end 35 | 36 | print(queue); // Output: (1, 2) 37 | } 38 | 39 | //hashset 40 | void hashset() { 41 | HashSet hashSet = HashSet(); 42 | 43 | hashSet.add(1); 44 | hashSet.add(2); 45 | hashSet.add(3); 46 | hashSet.add(4); 47 | hashSet.add(5); 48 | 49 | print(hashSet); // Output: {1, 2, 3, 4, 5} 50 | 51 | hashSet.remove(3); 52 | 53 | print(hashSet); // Output: {1, 2, 4, 5} 54 | } 55 | 56 | //hashmap 57 | void hashmap() { 58 | HashMap hashMap = HashMap(); 59 | 60 | hashMap['one'] = 1; 61 | hashMap['two'] = 2; 62 | hashMap['three'] = 3; 63 | hashMap['four'] = 4; 64 | hashMap['five'] = 5; 65 | 66 | print(hashMap); // Output: {one: 1, two: 2, three: 3, four: 4, five: 5} 67 | 68 | hashMap.remove('three'); 69 | 70 | print(hashMap); // Output: {one: 1, two: 2, four: 4, five: 5} 71 | } 72 | 73 | //linkedhashmap 74 | void linkedhashmap() { 75 | LinkedHashMap linkedHashMap = LinkedHashMap(); 76 | 77 | linkedHashMap['one'] = 1; 78 | linkedHashMap['two'] = 2; 79 | linkedHashMap['three'] = 3; 80 | linkedHashMap['four'] = 4; 81 | linkedHashMap['five'] = 5; 82 | 83 | print(linkedHashMap); // Output: {one: 1, two: 2, three: 3, four: 4, five: 5} 84 | 85 | linkedHashMap.remove('three'); 86 | 87 | print(linkedHashMap); // Output: {one: 1, two: 2, four: 4, five: 5} 88 | } 89 | 90 | //splaytreeset 91 | void splaytreeset() { 92 | SplayTreeSet splayTreeSet = SplayTreeSet(); 93 | 94 | splayTreeSet.addAll([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]); 95 | 96 | print(splayTreeSet); // Output: {1, 2, 3, 4, 5, 6, 9} 97 | } 98 | 99 | //splaytreemap 100 | void splaytreemap() { 101 | SplayTreeMap splayTreeMap = SplayTreeMap(); 102 | 103 | splayTreeMap['one'] = 1; 104 | splayTreeMap['two'] = 2; 105 | splayTreeMap['three'] = 3; 106 | splayTreeMap['four'] = 4; 107 | splayTreeMap['five'] = 5; 108 | 109 | print(splayTreeMap); // Output: {five: 5, four: 4, one: 1, three: 3, two: 2} 110 | 111 | splayTreeMap.remove('three'); 112 | 113 | print(splayTreeMap); // Output: {five: 5, four: 4, one: 1, two: 2} 114 | } 115 | -------------------------------------------------------------------------------- /bin/collection/LinkedList/constructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | // Define a custom LinkedListEntry class 4 | final class EntryItem extends LinkedListEntry { 5 | final int id; 6 | final String text; 7 | 8 | EntryItem(this.id, this.text); 9 | 10 | @override 11 | String toString() { 12 | return '$id : $text'; 13 | } 14 | } 15 | 16 | void main() { 17 | // Create a new empty LinkedList 18 | final emptyList = LinkedList(); 19 | print('Created an empty LinkedList: $emptyList'); 20 | // Output: Created an empty LinkedList: () 21 | 22 | // Add some elements to the list 23 | emptyList.add(EntryItem(1, 'Apple')); 24 | emptyList.add(EntryItem(2, 'Banana')); 25 | emptyList.add(EntryItem(3, 'Cherry')); 26 | print('List after adding elements: $emptyList'); 27 | // Output: List after adding elements: (1 : Apple, 2 : Banana, 3 : Cherry) 28 | 29 | // Create a new LinkedList with initial elements 30 | // final initialList = LinkedList.addAll([ 31 | // EntryItem(4, 'Date'), 32 | // EntryItem(5, 'Elderberry'), 33 | // EntryItem(6, 'Fig'), 34 | // ]); 35 | 36 | final initialList = LinkedList(); 37 | initialList.addAll([ 38 | EntryItem(4, 'Date'), 39 | EntryItem(5, 'Elderberry'), 40 | EntryItem(6, 'Fig'), 41 | ]); 42 | 43 | print('Created a LinkedList with initial elements: $initialList'); 44 | // Output: Created a LinkedList with initial elements: (4 : Date, 5 : Elderberry, 6 : Fig) 45 | 46 | // Combine the two lists 47 | emptyList.addAll(initialList); 48 | print('Combined lists: $emptyList'); 49 | // Output: Combined lists: (1 : Apple, 2 : Banana, 3 : Cherry, 4 : Date, 5 : Elderberry, 6 : Fig) 50 | 51 | // Clear the combined list 52 | emptyList.clear(); 53 | print('Cleared the combined list: $emptyList'); 54 | // Output: Cleared the combined list: () 55 | } -------------------------------------------------------------------------------- /bin/collection/LinkedList/mothod.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | // Define a custom LinkedListEntry class 4 | final class EntryItem extends LinkedListEntry { 5 | final int id; 6 | final String text; 7 | 8 | EntryItem(this.id, this.text); 9 | 10 | @override 11 | String toString() { 12 | return '$id : $text'; 13 | } 14 | } 15 | 16 | void main() { 17 | // Create a new LinkedList 18 | final linkedList = LinkedList(); 19 | 20 | // Add elements to the list 21 | linkedList.add(EntryItem(1, 'Apple')); 22 | linkedList.addFirst(EntryItem(0, 'Pear')); 23 | linkedList.addAll([EntryItem(2, 'Banana'), EntryItem(3, 'Cherry'), EntryItem(4, 'Date')]); 24 | 25 | // Check if the list contains an element 26 | print('Does the list contain "Banana"? ${linkedList.contains(EntryItem(2, 'Banana'))}'); // Output: true 27 | print('Does the list contain "Elderberry"? ${linkedList.contains(EntryItem(5, 'Elderberry'))}'); // Output: false 28 | 29 | // Iterate over the list using forEach 30 | print('Iterating over the list using forEach:'); 31 | for (var entry in linkedList) { 32 | print(entry); 33 | } 34 | // Output: 35 | // 0 : Pear 36 | // 1 : Apple 37 | // 2 : Banana 38 | // 3 : Cherry 39 | // 4 : Date 40 | 41 | // Get an element by index 42 | print('Element at index 2: ${linkedList.elementAt(2)}'); // Output: 2 : Banana 43 | 44 | // Remove an element from the list 45 | linkedList.remove(linkedList.elementAt(3)); // Remove the 4th element (Cherry) 46 | print('List after removing an element: $linkedList'); 47 | // Output: (0 : Pear, 1 : Apple, 2 : Banana, 4 : Date) 48 | 49 | // Remove the first element 50 | linkedList.first.unlink(); 51 | print('List after removing the first element: $linkedList'); 52 | // Output: (1 : Apple, 2 : Banana, 4 : Date) 53 | 54 | // Remove the last element 55 | linkedList.remove(linkedList.last); 56 | print('List after removing the last element: $linkedList'); 57 | // Output: (1 : Apple, 2 : Banana) 58 | 59 | // Clear the list 60 | linkedList.clear(); 61 | print('Is the list empty after clearing? ${linkedList.isEmpty}'); // Output: true 62 | } -------------------------------------------------------------------------------- /bin/collection/LinkedList/problem/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | // Define a custom LinkedListEntry class for songs 4 | final class Song extends LinkedListEntry { 5 | final String title; 6 | final String artist; 7 | final int duration; 8 | 9 | Song(this.title, this.artist, this.duration); 10 | 11 | @override 12 | String toString() { 13 | return '$title - $artist ($duration s)'; 14 | } 15 | } 16 | 17 | class MusicPlayer { 18 | final LinkedList playlist = LinkedList(); 19 | 20 | void addSong(Song song) { 21 | playlist.add(song); 22 | print('Added "$song" to the playlist.'); 23 | } 24 | 25 | void addSongAtStart(Song song) { 26 | playlist.addFirst(song); 27 | print('Added "$song" at the start of the playlist.'); 28 | } 29 | 30 | void addSongAtIndex(int index, Song song) { 31 | if (index == 0) { 32 | addSongAtStart(song); 33 | } else { 34 | var entry = playlist.elementAt(index - 1); 35 | entry.insertAfter(song); 36 | print('Added "$song" at index $index in the playlist.'); 37 | } 38 | } 39 | 40 | void removeSong(Song song) { 41 | if (playlist.contains(song)) { 42 | song.unlink(); 43 | print('Removed "$song" from the playlist.'); 44 | } else { 45 | print('Song not found in the playlist.'); 46 | } 47 | } 48 | 49 | void moveSong(Song song, int newIndex) { 50 | if (playlist.contains(song)) { 51 | song.unlink(); 52 | if (newIndex == 0) { 53 | playlist.addFirst(song); 54 | } else { 55 | var entry = playlist.elementAt(newIndex - 1); 56 | entry.insertAfter(song); 57 | } 58 | print('Moved "$song" to index $newIndex in the playlist.'); 59 | } else { 60 | print('Song not found in the playlist.'); 61 | } 62 | } 63 | 64 | void playPlaylist() { 65 | if (playlist.isEmpty) { 66 | print('Playlist is empty. Nothing to play.'); 67 | } else { 68 | print('Playing the playlist:'); 69 | for (var song in playlist) { 70 | print('Playing: $song'); 71 | } 72 | } 73 | } 74 | } 75 | 76 | void main() { 77 | final player = MusicPlayer(); 78 | 79 | player.addSong(Song('Imagine', 'John Lennon', 240)); 80 | player.addSong(Song('Bohemian Rhapsody', 'Queen', 355)); 81 | player.addSongAtStart(Song('Stairway to Heaven', 'Led Zeppelin', 482)); 82 | player.addSongAtIndex(1, Song('Hotel California', 'Eagles', 390)); 83 | 84 | player.playPlaylist(); 85 | print(''); 86 | 87 | player.removeSong(player.playlist.elementAt(2)); 88 | player.moveSong(player.playlist.last, 1); 89 | 90 | player.playPlaylist(); 91 | } -------------------------------------------------------------------------------- /bin/collection/LinkedList/problem/problem1.md: -------------------------------------------------------------------------------- 1 | A real-life problem that can be effectively solved using a `LinkedList` is managing a playlist or queue in a music player application. 2 | 3 | Imagine you have a music player application that allows users to create and manage playlists. Users can add, remove, and rearrange songs in their playlists. Here's how a `LinkedList` can be used to solve this problem: 4 | 5 | **Problem Statement:** 6 | Develop a music player application that allows users to manage their playlists efficiently, with the ability to add, remove, and reorder songs in the playlist. 7 | 8 | **Solution using a LinkedList:** 9 | 1. **Playlist Representation:** 10 | - Each song in the playlist can be represented as a `LinkedListEntry` object, where the `EntryItem` class extends `LinkedListEntry`. 11 | - The `EntryItem` class can have properties like `songTitle`, `artist`, `duration`, etc. 12 | - The `LinkedList` can be used to represent the playlist, where each `EntryItem` represents a song in the playlist. 13 | 14 | 2. **Adding Songs to the Playlist:** 15 | - Users can add a new song to the end of the playlist using the `add()` method. 16 | - Users can add a new song at the beginning of the playlist using the `addFirst()` method. 17 | - Users can add a new song at a specific position in the playlist using the `insertAfter()` or `insertBefore()` methods of the `LinkedListEntry` class. 18 | 19 | 3. **Removing Songs from the Playlist:** 20 | - Users can remove a specific song from the playlist using the `remove()` method. 21 | - Users can remove the first or last song from the playlist using the `first.unlink()` or `last.unlink()` methods, respectively. 22 | 23 | 4. **Rearranging Songs in the Playlist:** 24 | - Users can move a song to a different position in the playlist using the `insertAfter()` or `insertBefore()` methods of the `LinkedListEntry` class. 25 | - Users can swap the positions of two songs by first removing one song and then inserting it before or after the other song. 26 | 27 | 5. **Playlist Navigation and Playback:** 28 | - The `first` and `last` properties of the `LinkedList` can be used to access the first and last songs in the playlist, respectively. 29 | - The `iterator` property can be used to iterate over the songs in the playlist and play them sequentially. 30 | 31 | 6. **Playlist Persistence:** 32 | - The playlist data can be saved to a file or a database, and loaded back into the `LinkedList` when the application is started. 33 | 34 | By using a `LinkedList` to represent the playlist, the music player application can efficiently manage the addition, removal, and rearrangement of songs, as well as provide constant-time access to the first and last songs in the playlist. This makes the application responsive and user-friendly, as users can quickly manipulate their playlists without performance bottlenecks. 35 | 36 | The use of a `LinkedList` in this scenario showcases its strengths in handling dynamic collections where the order of elements is important, and where efficient insertion and removal operations are crucial for providing a smooth user experience. -------------------------------------------------------------------------------- /bin/collection/LinkedList/problem/problem2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | // Define a custom LinkedListEntry class for tasks 4 | final class Task extends LinkedListEntry { 5 | final String title; 6 | final String description; 7 | final DateTime dueDate; 8 | bool isCompleted; 9 | 10 | Task(this.title, this.description, this.dueDate, {this.isCompleted = false}); 11 | 12 | @override 13 | String toString() { 14 | return '[$isCompleted] $title - $description (Due: $dueDate)'; 15 | } 16 | } 17 | 18 | class TaskManager { 19 | final LinkedList toDoList = LinkedList(); 20 | 21 | void addTask(Task task) { 22 | toDoList.add(task); 23 | print('Added task: $task'); 24 | } 25 | 26 | void addTaskAtStart(Task task) { 27 | toDoList.addFirst(task); 28 | print('Added task at the start: $task'); 29 | } 30 | 31 | void addTaskAtIndex(int index, Task task) { 32 | if (index == 0) { 33 | addTaskAtStart(task); 34 | } else { 35 | var entry = toDoList.elementAt(index - 1); 36 | entry.insertAfter(task); 37 | print('Added task at index $index: $task'); 38 | } 39 | } 40 | 41 | void markTaskAsCompleted(Task task) { 42 | if (toDoList.contains(task)) { 43 | task.isCompleted = true; 44 | print('Marked task as completed: $task'); 45 | } else { 46 | print('Task not found in the to-do list.'); 47 | } 48 | } 49 | 50 | void moveTask(Task task, int newIndex) { 51 | if (toDoList.contains(task)) { 52 | task.unlink(); 53 | if (newIndex == 0) { 54 | toDoList.addFirst(task); 55 | } else { 56 | var entry = toDoList.elementAt(newIndex - 1); 57 | entry.insertAfter(task); 58 | } 59 | print('Moved task to index $newIndex: $task'); 60 | } else { 61 | print('Task not found in the to-do list.'); 62 | } 63 | } 64 | 65 | void viewToDoList() { 66 | if (toDoList.isEmpty) { 67 | print('To-do list is empty.'); 68 | } else { 69 | print('To-do list:'); 70 | for (var task in toDoList) { 71 | print(task); 72 | } 73 | } 74 | } 75 | } 76 | 77 | void main() { 78 | final taskManager = TaskManager(); 79 | 80 | taskManager.addTask(Task('Finish project report', 'Complete the quarterly project report', DateTime(2023, 5, 15))); 81 | taskManager.addTask(Task('Grocery shopping', 'Buy milk, eggs, and bread', DateTime(2023, 4, 20))); 82 | taskManager.addTaskAtStart(Task('Schedule team meeting', 'Discuss the project roadmap', DateTime(2023, 4, 18))); 83 | taskManager.addTaskAtIndex(1, Task('Clean the apartment', 'Vacuum, mop, and dust the entire apartment', DateTime(2023, 4, 22))); 84 | 85 | taskManager.viewToDoList(); 86 | print(''); 87 | 88 | taskManager.markTaskAsCompleted(taskManager.toDoList.elementAt(1)); 89 | taskManager.moveTask(taskManager.toDoList.last, 1); 90 | 91 | taskManager.viewToDoList(); 92 | } -------------------------------------------------------------------------------- /bin/collection/LinkedList/problem/problem2.md: -------------------------------------------------------------------------------- 1 | Sure, here's another real-life problem that can be solved using a `LinkedList`: 2 | 3 | **Problem Statement:** 4 | Develop a task management application that allows users to manage a to-do list. Users should be able to add new tasks, mark tasks as completed, reorder tasks, and view the list of tasks in the order they need to be completed. 5 | 6 | **Solution using a LinkedList:** 7 | 1. **Task Representation:** 8 | - Each task can be represented as a `LinkedListEntry` object, where the `Task` class extends `LinkedListEntry`. 9 | - The `Task` class can have properties like `title`, `description`, `dueDate`, `isCompleted`, etc. 10 | - The `LinkedList` can be used to represent the to-do list, where each `Task` object represents a task in the list. 11 | 12 | 2. **Adding Tasks:** 13 | - Users can add a new task to the end of the to-do list using the `add()` method. 14 | - Users can add a new task at the beginning of the to-do list using the `addFirst()` method. 15 | - Users can add a new task at a specific position in the to-do list using the `insertAfter()` or `insertBefore()` methods of the `LinkedListEntry` class. 16 | 17 | 3. **Marking Tasks as Completed:** 18 | - Users can mark a task as completed by setting the `isCompleted` property of the `Task` object. 19 | - The application can provide a view that only shows the uncompleted tasks, allowing users to focus on their remaining work. 20 | 21 | 4. **Reordering Tasks:** 22 | - Users can move a task to a different position in the to-do list using the `insertAfter()` or `insertBefore()` methods of the `LinkedListEntry` class. 23 | - Users can swap the positions of two tasks by first removing one task and then inserting it before or after the other task. 24 | 25 | 5. **Viewing the To-Do List:** 26 | - The `first` and `last` properties of the `LinkedList` can be used to access the first and last tasks in the to-do list, respectively. 27 | - The `iterator` property can be used to iterate over the tasks in the to-do list and display them in the order they need to be completed. 28 | 29 | 6. **Task Persistence:** 30 | - The to-do list data can be saved to a file or a database, and loaded back into the `LinkedList` when the application is started. 31 | 32 | By using a `LinkedList` to represent the to-do list, the task management application can efficiently manage the addition, removal, and reordering of tasks, as well as provide constant-time access to the first and last tasks in the list. This makes the application responsive and user-friendly, as users can quickly manipulate their to-do list without performance bottlenecks. 33 | 34 | The use of a `LinkedList` in this scenario showcases its strengths in handling dynamic collections where the order of elements is important, and where efficient insertion and removal operations are crucial for providing a smooth user experience. 35 | 36 | Here's an example implementation of the task management application using a `LinkedList`: 37 | 38 | ```dart 39 | import 'dart:collection'; 40 | 41 | // Define a custom LinkedListEntry class for tasks 42 | class Task extends LinkedListEntry { 43 | final String title; 44 | final String description; 45 | final DateTime dueDate; 46 | bool isCompleted; 47 | 48 | Task(this.title, this.description, this.dueDate, {this.isCompleted = false}); 49 | 50 | @override 51 | String toString() { 52 | return '[$isCompleted] $title - $description (Due: $dueDate)'; 53 | } 54 | } 55 | 56 | class TaskManager { 57 | final LinkedList toDoList = LinkedList(); 58 | 59 | void addTask(Task task) { 60 | toDoList.add(task); 61 | print('Added task: $task'); 62 | } 63 | 64 | void addTaskAtStart(Task task) { 65 | toDoList.addFirst(task); 66 | print('Added task at the start: $task'); 67 | } 68 | 69 | void addTaskAtIndex(int index, Task task) { 70 | if (index == 0) { 71 | addTaskAtStart(task); 72 | } else { 73 | var entry = toDoList.elementAt(index - 1); 74 | entry.insertAfter(task); 75 | print('Added task at index $index: $task'); 76 | } 77 | } 78 | 79 | void markTaskAsCompleted(Task task) { 80 | if (toDoList.contains(task)) { 81 | task.isCompleted = true; 82 | print('Marked task as completed: $task'); 83 | } else { 84 | print('Task not found in the to-do list.'); 85 | } 86 | } 87 | 88 | void moveTask(Task task, int newIndex) { 89 | if (toDoList.contains(task)) { 90 | task.unlink(); 91 | if (newIndex == 0) { 92 | toDoList.addFirst(task); 93 | } else { 94 | var entry = toDoList.elementAt(newIndex - 1); 95 | entry.insertAfter(task); 96 | } 97 | print('Moved task to index $newIndex: $task'); 98 | } else { 99 | print('Task not found in the to-do list.'); 100 | } 101 | } 102 | 103 | void viewToDoList() { 104 | if (toDoList.isEmpty) { 105 | print('To-do list is empty.'); 106 | } else { 107 | print('To-do list:'); 108 | for (var task in toDoList) { 109 | print(task); 110 | } 111 | } 112 | } 113 | } 114 | 115 | void main() { 116 | final taskManager = TaskManager(); 117 | 118 | taskManager.addTask(Task('Finish project report', 'Complete the quarterly project report', DateTime(2023, 5, 15))); 119 | taskManager.addTask(Task('Grocery shopping', 'Buy milk, eggs, and bread', DateTime(2023, 4, 20))); 120 | taskManager.addTaskAtStart(Task('Schedule team meeting', 'Discuss the project roadmap', DateTime(2023, 4, 18))); 121 | taskManager.addTaskAtIndex(1, Task('Clean the apartment', 'Vacuum, mop, and dust the entire apartment', DateTime(2023, 4, 22))); 122 | 123 | taskManager.viewToDoList(); 124 | print(''); 125 | 126 | taskManager.markTaskAsCompleted(taskManager.toDoList.elementAt(1)); 127 | taskManager.moveTask(taskManager.toDoList.last, 1); 128 | 129 | taskManager.viewToDoList(); 130 | } 131 | ``` 132 | 133 | In this example, we define a `Task` class that extends `LinkedListEntry`. The `TaskManager` class manages the to-do list using a `LinkedList`. 134 | 135 | The `TaskManager` class provides the following methods: 136 | 137 | - `addTask(Task task)`: Adds a task to the end of the to-do list. 138 | - `addTaskAtStart(Task task)`: Adds a task at the beginning of the to-do list. 139 | - `addTaskAtIndex(int index, Task task)`: Adds a task at the specified index in the to-do list. 140 | - `markTaskAsCompleted(Task task)`: Marks a specific task as completed. 141 | - `moveTask(Task task, int newIndex)`: Moves a task to the specified index in the to-do list. 142 | - `viewToDoList()`: Displays the tasks in the current to-do list. 143 | 144 | In the `main()` function, we create a `TaskManager` instance and demonstrate the usage of these methods to manage the to-do list. 145 | 146 | The output of the code will be: 147 | 148 | ``` 149 | Added task: [false] Finish project report - Complete the quarterly project report (Due: 2023-05-15 00:00:00.000) 150 | Added task: [false] Grocery shopping - Buy milk, eggs, and bread (Due: 2023-04-20 00:00:00.000) 151 | Added task at the start: [false] Schedule team meeting - Discuss the project roadmap (Due: 2023-04-18 00:00:00.000) 152 | Added task at index 1: [false] Clean the apartment - Vacuum, mop, and dust the entire apartment (Due: 2023-04-22 00:00:00.000) 153 | To-do list: 154 | [false] Schedule team meeting - Discuss the project roadmap (Due: 2023-04-18 00:00:00.000) 155 | [false] Clean the apartment - Vacuum, mop, and dust the entire apartment (Due: 2023-04-22 00:00:00.000) 156 | [false] Finish project report - Complete the quarterly project report (Due: 2023-05-15 00:00:00.000) 157 | [false] Grocery shopping - Buy milk, eggs, and bread (Due: 2023-04-20 00:00:00.000) 158 | 159 | Marked task as completed: [true] Clean the apartment - Vacuum, mop, and dust the entire apartment (Due: 2023-04-22 00:00:00.000) 160 | Moved task to index 1: [true] Clean the apartment - Vacuum, mop, and dust the entire apartment (Due: 2023-04-22 00:00:00.000) 161 | To-do list: 162 | [false] Schedule team meeting - Discuss the project roadmap (Due: 2023-04-18 00:00:00.000) 163 | [true] Clean the apartment - Vacuum, mop, and dust the entire apartment (Due: 2023-04-22 00:00:00.000) 164 | [false] Finish project report - Complete the quarterly project report (Due: 2023-05-15 00:00:00.000) 165 | [false] Grocery shopping - Buy milk, eggs, and bread (Due: 2023-04-20 00:00:00.000) 166 | ``` 167 | 168 | This implementation demonstrates how a `LinkedList` can be used to efficiently manage a to-do list in a task management application, allowing users to add, mark as completed, reorder, and view the tasks in the order they need to be completed. -------------------------------------------------------------------------------- /bin/collection/LinkedList/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | // Define a custom LinkedListEntry class 4 | final class EntryItem extends LinkedListEntry { 5 | final int id; 6 | final String text; 7 | 8 | EntryItem(this.id, this.text); 9 | 10 | @override 11 | String toString() { 12 | return '$id : $text'; 13 | } 14 | } 15 | 16 | void main() { 17 | // Create a new LinkedList 18 | final linkedList = LinkedList(); 19 | 20 | // Add elements to the list 21 | linkedList.addAll([ 22 | EntryItem(1, 'Apple'), 23 | EntryItem(2, 'Banana'), 24 | EntryItem(3, 'Cherry'), 25 | EntryItem(4, 'Date'), 26 | EntryItem(5, 'Elderberry'), 27 | ]); 28 | 29 | // Access the first and last elements 30 | print('First element: ${linkedList.first}'); // Output: 1 : Apple 31 | print('Last element: ${linkedList.last}'); // Output: 5 : Elderberry 32 | 33 | // Check if the list is empty 34 | print('Is the list empty? ${linkedList.isEmpty}'); // Output: false 35 | print('Is the list not empty? ${linkedList.isNotEmpty}'); // Output: true 36 | 37 | // Iterate over the list 38 | print('Iterating over the list:'); 39 | for (var entry in linkedList) { 40 | print(entry); 41 | } 42 | // Output: 43 | // 1 : Apple 44 | // 2 : Banana 45 | // 3 : Cherry 46 | // 4 : Date 47 | // 5 : Elderberry 48 | 49 | // Get the number of elements in the list 50 | print('Length of the list: ${linkedList.length}'); // Output: 5 51 | 52 | // Get the only element in the list (throws an exception if the list has more than one element) 53 | print('Single element: ${linkedList.single}'); // Output: 1 : Apple 54 | 55 | // Remove an element from the list 56 | linkedList.remove(linkedList.elementAt(2)); // Remove the 3rd element (Cherry) 57 | print('List after removing an element: $linkedList'); 58 | // Output: (1 : Apple, 2 : Banana, 4 : Date, 5 : Elderberry) 59 | 60 | // Clear the list 61 | linkedList.clear(); 62 | print('Is the list empty after clearing? ${linkedList.isEmpty}'); // Output: true 63 | } -------------------------------------------------------------------------------- /bin/collection/List/constructors.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | void main(){ 4 | // List.empty() 5 | final emptyList = List.empty(); 6 | print(emptyList); // Output: [] 7 | 8 | // List.filled() 9 | final fixedLengthList = List.filled(5, 0); 10 | print(fixedLengthList); // Output: [0, 0, 0, 0, 0] 11 | 12 | // List.from() 13 | final iterableList = List.from(['apple', 'banana', 'cherry']); 14 | print(iterableList); // Output: [apple, banana, cherry] 15 | 16 | // List.generate() 17 | final generatedList = List.generate(10, (index) => index * 2); 18 | print(generatedList); // Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 19 | 20 | // List.of() 21 | final listFromIterable = List.of([1, 2.5, 3, 4.0]); 22 | print(listFromIterable); // Output: [1, 2.5, 3, 4.0] 23 | 24 | // List.unmodifiable() 25 | final unmodifiableList = List.unmodifiable(['one', 'two', 'three']); 26 | print(unmodifiableList); // Output: [one, two, three] 27 | // unmodifiableList[0] = 'four'; // This will throw an UnsupportedError 28 | 29 | // Mixing constructors 30 | final mixedList = List.from([1, 2, 3], growable: false) 31 | ..addAll([4, 5, 6]) 32 | ..insert(0, 0) 33 | ..removeAt(3); 34 | print(mixedList); // Output: [0, 1, 2, 5, 6] 35 | 36 | // Casting lists 37 | // final sourceList = [1, 2.5, 3, 4.0]; 38 | // final castedList = List.castFrom(sourceList); 39 | // print(castedList); // Output: [1, 2, 3, 4] 40 | 41 | // Copying ranges between lists 42 | final targetList = [10, 20, 30, 40, 50]; 43 | final sourceRange = [60, 70, 80]; 44 | List.copyRange(targetList, 2, sourceRange, 0, 2); 45 | print(targetList); // Output: [10, 20, 60, 70, 50] 46 | } -------------------------------------------------------------------------------- /bin/collection/List/discription.md: -------------------------------------------------------------------------------- 1 | Here is a table of all the Constructors, Properties, and Methods of the `List` class in Dart, along with a brief description of what they do: 2 | 3 | | Type | Name | Description | 4 | | --- | --- | --- | 5 | | **Constructors** | 6 | | `List.empty()` | Creates a new empty list. | 7 | | `List.filled()` | Creates a list of the given length with a specific fill value. | 8 | | `List.from()` | Creates a list containing all elements from an iterable. | 9 | | `List.generate()` | Generates a list of values using a provided generator function. | 10 | | `List.of()` | Creates a list from an iterable, preserving the element types. | 11 | | `List.unmodifiable()` | Creates an unmodifiable list containing all elements from an iterable. | 12 | | **Properties** | 13 | | `first` | The first element of the list. | 14 | | `last` | The last element of the list. | 15 | | `length` | The number of elements in the list. | 16 | | `isEmpty` | Whether the list has no elements. | 17 | | `isNotEmpty` | Whether the list has at least one element. | 18 | | `iterator` | An iterator that allows iterating over the elements of the list. | 19 | | `reversed` | An iterable that iterates over the elements of the list in reverse order. | 20 | | `single` | The single element of the list (throws if the list has more or less than one element). | 21 | | `hashCode` | The hash code for the list. | 22 | | `runtimeType` | The runtime type of the list. | 23 | | **Methods** | 24 | | `add()` | Adds a value to the end of the list. | 25 | | `addAll()` | Appends all elements of an iterable to the end of the list. | 26 | | `any()` | Checks whether any element of the list satisfies a given predicate. | 27 | | `asMap()` | Creates an unmodifiable map view of the list. | 28 | | `cast()` | Returns a view of this list as a list of instances of type `R`. | 29 | | `clear()` | Removes all objects from the list. | 30 | | `contains()` | Checks whether the list contains a given element. | 31 | | `elementAt()` | Returns the element at the given index. | 32 | | `every()` | Checks whether every element of the list satisfies a given predicate. | 33 | | `expand()` | Expands each element of this iterable into zero or more elements. | 34 | | `fillRange()` | Overwrites a range of elements with a given value. | 35 | | `firstWhere()` | Returns the first element that satisfies the given predicate. | 36 | | `fold()` | Reduces a collection to a single value by iteratively combining each element. | 37 | | `followedBy()` | Creates the lazy concatenation of this iterable and another iterable. | 38 | | `forEach()` | Applies an operation to each element of the list. | 39 | | `getRange()` | Creates an iterable that iterates over a range of elements. | 40 | | `indexOf()` | Returns the first index of the given element in the list. | 41 | | `indexWhere()` | Returns the index of the first element that satisfies the given predicate. | 42 | | `insert()` | Inserts an element at the given index. | 43 | | `insertAll()` | Inserts all elements of an iterable at the given index. | 44 | | `join()` | Converts each element to a string and concatenates the strings. | 45 | | `lastIndexOf()` | Returns the last index of the given element in the list. | 46 | | `lastIndexWhere()` | Returns the index of the last element that satisfies the given predicate. | 47 | | `lastWhere()` | Returns the last element that satisfies the given predicate. | 48 | | `remove()` | Removes the first occurrence of the given value. | 49 | | `removeAt()` | Removes and returns the element at the given index. | 50 | | `removeLast()` | Removes and returns the last element. | 51 | | `removeRange()` | Removes the elements in the given range. | 52 | | `removeWhere()` | Removes all elements that satisfy the given predicate. | 53 | | `replaceRange()` | Replaces the elements in the given range with the given replacements. | 54 | | `retainWhere()` | Removes all elements that fail to satisfy the given predicate. | 55 | | `setAll()` | Overwrites the elements at the given positions with the elements of the given iterable. | 56 | | `setRange()` | Writes the elements of an iterable into a range of this list. | 57 | | `shuffle()` | Shuffles the elements of the list randomly. | 58 | | `skip()` | Creates an iterable that provides all but the first `count` elements. | 59 | | `skipWhile()` | Creates an iterable that skips leading elements while a given condition is true. | 60 | | `sort()` | Sorts the elements of the list according to the order specified by a compare function. | 61 | | `sublist()` | Returns a new list containing the elements in the given range. | 62 | | `take()` | Creates an iterable that provides the first `count` elements. | 63 | | `takeWhile()` | Creates an iterable that provides elements as long as a given condition is true. | 64 | | `toList()` | Creates a new list containing the elements of this iterable. | 65 | | `toSet()` | Creates a new set containing the unique elements of this iterable. | 66 | | `where()` | Creates a new lazy iterable with all elements that satisfy the given predicate. | 67 | | `whereType()` | Creates a new lazy iterable with all elements that have type `T`. | 68 | 69 | This table provides a comprehensive overview of the various Constructors, Properties, and Methods available in the `List` class, allowing you to quickly reference and understand their purpose and functionality. -------------------------------------------------------------------------------- /bin/collection/List/method.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | void main() 4 | { 5 | // Creating a sample list 6 | final myList = [10, 20, 30, 40, 50]; 7 | 8 | // add() 9 | myList.add(60); 10 | print('After add(): $myList'); // Output: [10, 20, 30, 40, 50, 60] 11 | 12 | // addAll() 13 | myList.addAll([70, 80, 90]); 14 | print('After addAll(): $myList'); // Output: [10, 20, 30, 40, 50, 60, 70, 80, 90] 15 | 16 | // any() 17 | final anyGreaterThan50 = myList.any((element) => element > 50); 18 | print('Any element greater than 50? $anyGreaterThan50'); // Output: true 19 | 20 | // asMap() 21 | final myListAsMap = myList.asMap(); 22 | print('List as Map: $myListAsMap'); // Output: {0: 10, 1: 20, 2: 30, 3: 40, 4: 50, 5: 60, 6: 70, 7: 80, 8: 90} 23 | 24 | // cast() 25 | final myListOfStrings = myList.cast(); 26 | print('List of Strings: $myListOfStrings'); // Output: [10, 20, 30, 40, 50, 60, 70, 80, 90] 27 | 28 | // clear() 29 | myList.clear(); 30 | print('After clear(): $myList'); // Output: [] 31 | 32 | // contains() 33 | final myNewList = [10, 20, 30, 40, 50]; 34 | print('myNewList contains 30? ${myNewList.contains(30)}'); // Output: true 35 | 36 | // elementAt() 37 | final elementAt3 = myNewList.elementAt(3); 38 | print('Element at index 3: $elementAt3'); // Output: 40 39 | 40 | // every() 41 | final allGreaterThan0 = myNewList.every((element) => element > 0); 42 | print('All elements greater than 0? $allGreaterThan0'); // Output: true 43 | 44 | // expand() 45 | final expandedList = myNewList.expand((element) => [element, element * 10]); 46 | print('Expanded list: $expandedList'); // Output: [10, 100, 20, 200, 30, 300, 40, 400, 50, 500] 47 | 48 | // fillRange() 49 | myNewList.fillRange(1, 4, 0); 50 | print('After fillRange(): $myNewList'); // Output: [10, 0, 0, 0, 50] 51 | 52 | // firstWhere() 53 | final firstEvenNumber = myNewList.firstWhere((element) => element.isEven, orElse: () => -1); 54 | print('First even number: $firstEvenNumber'); // Output: 10 55 | 56 | // fold() 57 | final sum = myNewList.fold(0, (previousValue, element) => previousValue + element); 58 | print('Sum of elements: $sum'); // Output: 60 59 | 60 | // followedBy() 61 | final followedByList = myNewList.followedBy([60, 70, 80]); 62 | print('Followed by list: $followedByList'); // Output: (10, 0, 0, 0, 50, 60, 70, 80) 63 | 64 | // forEach() 65 | for (var element in myNewList) { 66 | print('Element: $element'); 67 | } 68 | 69 | // getRange() 70 | final rangeList = myNewList.getRange(1, 4).toList(); 71 | print('Range list: $rangeList'); // Output: [0, 0, 0] 72 | 73 | // indexOf() 74 | final indexOfElement = myNewList.indexOf(0); 75 | print('Index of 0: $indexOfElement'); // Output: 1 76 | 77 | // indexWhere() 78 | final indexWhereEven = myNewList.indexWhere((element) => element.isEven); 79 | print('Index of first even number: $indexWhereEven'); // Output: 0 80 | 81 | // insert() 82 | myNewList.insert(2, 25); 83 | print('After insert(): $myNewList'); // Output: [10, 0, 25, 0, 0, 50] 84 | 85 | // insertAll() 86 | myNewList.insertAll(4, [35, 45]); 87 | print('After insertAll(): $myNewList'); // Output: [10, 0, 25, 0, 35, 45, 50] 88 | 89 | // join() 90 | final joinedString = myNewList.join(', '); 91 | print('Joined string: $joinedString'); // Output: 10, 0, 25, 0, 35, 45, 50 92 | 93 | // lastIndexOf() 94 | final lastIndexOfElement = myNewList.lastIndexOf(0); 95 | print('Last index of 0: $lastIndexOfElement'); // Output: 3 96 | 97 | // lastIndexWhere() 98 | final lastIndexWhereEven = myNewList.lastIndexWhere((element) => element.isEven); 99 | print('Last index of even number: $lastIndexWhereEven'); // Output: 6 100 | 101 | // lastWhere() 102 | final lastEvenNumber = myNewList.lastWhere((element) => element.isEven, orElse: () => -1); 103 | print('Last even number: $lastEvenNumber'); // Output: 50 104 | 105 | // remove() 106 | myNewList.remove(0); 107 | print('After remove(): $myNewList'); // Output: [10, 25, 0, 35, 45, 50] 108 | 109 | // removeAt() 110 | myNewList.removeAt(2); 111 | print('After removeAt(): $myNewList'); // Output: [10, 25, 35, 45, 50] 112 | 113 | // removeLast() 114 | myNewList.removeLast(); 115 | print('After removeLast(): $myNewList'); // Output: [10, 25, 35, 45] 116 | 117 | // removeRange() 118 | myNewList.removeRange(1, 3); 119 | print('After removeRange(): $myNewList'); // Output: [10, 45] 120 | 121 | // removeWhere() 122 | myNewList.removeWhere((element) => element.isEven); 123 | print('After removeWhere(): $myNewList'); // Output: [45] 124 | 125 | // replaceRange() 126 | myNewList.replaceRange(0, 1, [50, 60]); 127 | print('After replaceRange(): $myNewList'); // Output: [50, 60] 128 | 129 | // retainWhere() 130 | myNewList.retainWhere((element) => element > 50); 131 | print('After retainWhere(): $myNewList'); // Output: [60] 132 | 133 | // setAll() 134 | myNewList.setAll(0, [70, 80, 90]); 135 | print('After setAll(): $myNewList'); // Output: [70, 80, 90] 136 | 137 | // setRange() 138 | myNewList.setRange(1, 3, [100, 110]); 139 | print('After setRange(): $myNewList'); // Output: [70, 100, 110] 140 | 141 | // shuffle() 142 | myNewList.shuffle(); 143 | print('After shuffle(): $myNewList'); // Output: [110, 100, 70] 144 | 145 | // skip() 146 | final skippedList = myNewList.skip(1).toList(); 147 | print('Skipped list: $skippedList'); // Output: [100, 70] 148 | 149 | // skipWhile() 150 | final skippedWhileList = myNewList.skipWhile((element) => element > 100).toList(); 151 | print('Skipped while list: $skippedWhileList'); // Output: [70] 152 | 153 | // sort() 154 | myNewList.sort(); 155 | print('After sort(): $myNewList'); // Output: [70, 100, 110] 156 | 157 | // sublist() 158 | final sublist = myNewList.sublist(1, 3); 159 | print('Sublist: $sublist'); // Output: [100, 110] 160 | 161 | // take() 162 | final takenList = myNewList.take(2).toList(); 163 | print('Taken list: $takenList'); // Output: [70, 100] 164 | 165 | // takeWhile() 166 | final takenWhileList = myNewList.takeWhile((element) => element < 105).toList(); 167 | print('Taken while list: $takenWhileList'); // Output: [70, 100] 168 | 169 | // toList() 170 | final listFromIterable = [1, 2, 3, 4, 5].toList(growable: false); 171 | print('List from Iterable: $listFromIterable'); // Output: [1, 2, 3, 4, 5] 172 | 173 | // toSet() 174 | final setFromList = myNewList.toSet(); 175 | print('Set from List: $setFromList'); // Output: {70, 100, 110} 176 | 177 | // where() 178 | final evenNumbersList = myNewList.where((element) => element.isEven).toList(); 179 | print('Even numbers list: $evenNumbersList'); // Output: [70, 100, 110] 180 | 181 | // whereType() 182 | final myListOfObjects = [10, 'hello', 20.5, true]; 183 | final listOfInts = myListOfObjects.whereType().toList(); 184 | print('List of Integers: $listOfInts'); // Output: [10, 20] 185 | } -------------------------------------------------------------------------------- /bin/collection/List/problem/problem1.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | void main(){ 4 | // Create a list to store the attendance records 5 | final attendanceRecords = []; 6 | 7 | // Track attendance for each day of the week 8 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'Alice', 'Bob']); 9 | attendanceRecords.addAll(['Alice', 'Charlie', 'David', 'Bob', 'Alice']); 10 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'David', 'Alice']); 11 | attendanceRecords.addAll(['Bob', 'Charlie', 'David', 'Alice', 'Alice']); 12 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'David', 'Alice']); 13 | 14 | // Generate the attendance report 15 | final attendanceReport = {}; 16 | for (final student in attendanceRecords) { 17 | if (attendanceReport.containsKey(student)) { 18 | attendanceReport[student] = attendanceReport[student]! + 1; 19 | } else { 20 | attendanceReport[student] = 1; 21 | } 22 | } 23 | 24 | // Print the attendance report 25 | for (final entry in attendanceReport.entries) { 26 | print('${entry.key} was present for ${entry.value} days'); 27 | } 28 | } -------------------------------------------------------------------------------- /bin/collection/List/problem/problem1.md: -------------------------------------------------------------------------------- 1 | Here's a real-life problem that can be solved using the `List` class in Dart: 2 | 3 | **Problem**: A school wants to keep track of the attendance records for their students. Each day, the teacher takes attendance and records the students who are present. The school wants to generate a report at the end of the week that shows the total number of days each student was present. 4 | 5 | **Solution using List**: 6 | 7 | 1. Create a `List` to store the attendance records for each student. 8 | 2. Each day, the teacher can add the names of the present students to the list. 9 | 3. At the end of the week, iterate through the list and count the number of times each student's name appears, which will give the total number of days they were present. 10 | 11 | Here's the Dart code that demonstrates this solution: 12 | 13 | ```dart 14 | // Create a list to store the attendance records 15 | final attendanceRecords = []; 16 | 17 | // Track attendance for each day of the week 18 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'Alice', 'Bob']); 19 | attendanceRecords.addAll(['Alice', 'Charlie', 'David', 'Bob', 'Alice']); 20 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'David', 'Alice']); 21 | attendanceRecords.addAll(['Bob', 'Charlie', 'David', 'Alice', 'Alice']); 22 | attendanceRecords.addAll(['Alice', 'Bob', 'Charlie', 'David', 'Alice']); 23 | 24 | // Generate the attendance report 25 | final attendanceReport = {}; 26 | for (final student in attendanceRecords) { 27 | if (attendanceReport.containsKey(student)) { 28 | attendanceReport[student] = attendanceReport[student]! + 1; 29 | } else { 30 | attendanceReport[student] = 1; 31 | } 32 | } 33 | 34 | // Print the attendance report 35 | for (final entry in attendanceReport.entries) { 36 | print('${entry.key} was present for ${entry.value} days'); 37 | } 38 | ``` 39 | 40 | In this example, we use a `List` to store the attendance records for each day of the week. We then iterate through the list and count the number of times each student's name appears, which gives us the total number of days they were present. Finally, we print the attendance report. 41 | 42 | The output of this code would be: 43 | 44 | ``` 45 | Alice was present for 5 days 46 | Bob was present for 5 days 47 | Charlie was present for 4 days 48 | David was present for 4 days 49 | ``` 50 | 51 | This real-life problem demonstrates the usefulness of the `List` class in Dart for tracking and reporting on data. The `List` data structure allows us to easily store and manipulate the attendance records, making it a powerful tool for solving practical problems. -------------------------------------------------------------------------------- /bin/collection/List/problem/problem2.dart: -------------------------------------------------------------------------------- 1 | // import 'dart:math'; 2 | 3 | // void main() { 4 | // // Simulate the user's listening history 5 | // final listeningHistory = [ 6 | // {'song': 'Song A', 'count': 15}, 7 | // {'song': 'Song B', 'count': 20}, 8 | // {'song': 'Song C', 'count': 8}, 9 | // {'song': 'Song D', 'count': 12}, 10 | // {'song': 'Song E', 'count': 18}, 11 | // {'song': 'Song F', 'count': 10}, 12 | // {'song': 'Song G', 'count': 6}, 13 | // {'song': 'Song H', 'count': 14}, 14 | // {'song': 'Song I', 'count': 9}, 15 | // {'song': 'Song J', 'count': 7}, 16 | // ]; 17 | 18 | // // Constants 19 | // const topSongsCount = 10; 20 | // const newSongsCount = 5; 21 | 22 | // List generatePersonalizedPlaylist( 23 | // List> listeningHistory, 24 | // int topSongsCount, 25 | // int newSongsCount) { 26 | // // Sort the listening history by song count in descending order 27 | // listeningHistory.sort((a, b) => b['count']!.compareTo(a['count']!)); 28 | 29 | // // Get the top N most frequently listened songs 30 | // final topSongs = 31 | // listeningHistory.take(topSongsCount).map((e) => e['song']!).toList(); 32 | 33 | // // Get the unique songs in the user's listening history 34 | // final uniqueSongs = listeningHistory.map((e) => e['song']!).toSet(); 35 | 36 | // // Simulate finding new recommended songs 37 | // final newSongs = []; 38 | // final random = Random(); 39 | // while (newSongs.length < newSongsCount) { 40 | // final newSong = 'New Song ${newSongs.length + 1}'; 41 | // if (!uniqueSongs.contains(newSong)) { 42 | // newSongs.add(newSong); 43 | // } 44 | // } 45 | 46 | // // Combine the top songs and new recommended songs 47 | // return [...topSongs, ...newSongs]; 48 | // } 49 | 50 | // // Generate the personalized playlist 51 | // final personalizedPlaylist = generatePersonalizedPlaylist( 52 | // listeningHistory, topSongsCount, newSongsCount); 53 | // print('Personalized Playlist:'); 54 | // for (final song in personalizedPlaylist) { 55 | // print('- $song'); 56 | // } 57 | // } 58 | -------------------------------------------------------------------------------- /bin/collection/List/problem/problem2.md: -------------------------------------------------------------------------------- 1 | Sure, here's another more complex real-life problem that can be solved using the `List` class in Dart: 2 | 3 | **Problem**: A music streaming service wants to provide personalized playlists for their users based on their listening history. The service keeps track of the songs each user has listened to, along with the number of times they've listened to each song. The service wants to generate a playlist for each user that includes the user's most frequently listened songs, as well as some new songs that the user might enjoy based on their listening history. 4 | 5 | **Solution using List**: 6 | 7 | 1. Create a `List` to store the user's listening history, where each element is a map containing the song title and the number of times the user has listened to it. 8 | 2. Sort the listening history `List` by the number of times each song has been listened to, in descending order. 9 | 3. Create a new `List` that includes the top N most frequently listened songs, where N is a configurable value (e.g., 10 songs). 10 | 4. Recommend additional songs for the user's playlist by: 11 | - Creating a `Set` of all the unique songs the user has listened to. 12 | - Querying a database or an external API to find new songs that are similar to the songs in the user's listening history. 13 | - Filtering out the songs that are already in the user's listening history, and adding the remaining new songs to the playlist. 14 | 5. Combine the top N most frequently listened songs and the new recommended songs to create the final personalized playlist. 15 | 16 | Here's the Dart code that demonstrates this solution: 17 | 18 | ```dart 19 | import 'dart:math'; 20 | 21 | // Simulate the user's listening history 22 | final listeningHistory = [ 23 | {'song': 'Song A', 'count': 15}, 24 | {'song': 'Song B', 'count': 20}, 25 | {'song': 'Song C', 'count': 8}, 26 | {'song': 'Song D', 'count': 12}, 27 | {'song': 'Song E', 'count': 18}, 28 | {'song': 'Song F', 'count': 10}, 29 | {'song': 'Song G', 'count': 6}, 30 | {'song': 'Song H', 'count': 14}, 31 | {'song': 'Song I', 'count': 9}, 32 | {'song': 'Song J', 'count': 7}, 33 | ]; 34 | 35 | // Constants 36 | const topSongsCount = 10; 37 | const newSongsCount = 5; 38 | 39 | // Generate the personalized playlist 40 | final personalizedPlaylist = generatePersonalizedPlaylist(listeningHistory, topSongsCount, newSongsCount); 41 | print('Personalized Playlist:'); 42 | for (final song in personalizedPlaylist) { 43 | print('- $song'); 44 | } 45 | 46 | List generatePersonalizedPlaylist( 47 | List> listeningHistory, int topSongsCount, int newSongsCount) { 48 | // Sort the listening history by song count in descending order 49 | listeningHistory.sort((a, b) => b['count']!.compareTo(a['count']!)); 50 | 51 | // Get the top N most frequently listened songs 52 | final topSongs = listeningHistory.take(topSongsCount).map((e) => e['song']!).toList(); 53 | 54 | // Get the unique songs in the user's listening history 55 | final uniqueSongs = listeningHistory.map((e) => e['song']!).toSet(); 56 | 57 | // Simulate finding new recommended songs 58 | final newSongs = []; 59 | final random = Random(); 60 | while (newSongs.length < newSongsCount) { 61 | final newSong = 'New Song ${newSongs.length + 1}'; 62 | if (!uniqueSongs.contains(newSong)) { 63 | newSongs.add(newSong); 64 | } 65 | } 66 | 67 | // Combine the top songs and new recommended songs 68 | return [...topSongs, ...newSongs]; 69 | } 70 | ``` 71 | 72 | In this example, we first simulate the user's listening history by creating a `List` of maps, where each map represents a song and the number of times the user has listened to it. We then use this listening history to generate a personalized playlist for the user. 73 | 74 | The `generatePersonalizedPlaylist` function first sorts the listening history by the number of times each song has been listened to, in descending order. It then selects the top `topSongsCount` most frequently listened songs and adds them to the playlist. 75 | 76 | Next, the function creates a `Set` of the unique songs in the user's listening history. It then simulates finding new recommended songs by generating a list of `newSongsCount` unique song titles that are not already in the user's listening history. 77 | 78 | Finally, the function combines the top frequently listened songs and the new recommended songs to create the final personalized playlist. 79 | 80 | This example demonstrates the power of the `List` data structure in Dart for solving complex real-life problems. By using a combination of sorting, filtering, and set operations on the `List`, we can efficiently generate personalized recommendations for the user based on their listening history. -------------------------------------------------------------------------------- /bin/collection/List/properties.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | void main(){ 4 | // Creating a sample list 5 | final myList = [10, 20, 30, 40, 50]; 6 | 7 | // Accessing properties 8 | print(myList.first); // Output: 10 9 | print(myList.last); // Output: 50 10 | print(myList.length); // Output: 5 11 | print(myList.isEmpty); // Output: false 12 | print(myList.isNotEmpty); // Output: true 13 | print(myList.hashCode); // Output: some integer value 14 | print(myList.runtimeType); // Output: _GrowableList 15 | 16 | // Iterating over the list 17 | print('Iterating over the list:'); 18 | for (final element in myList) { 19 | print(element); 20 | } 21 | 22 | // Accessing the iterator 23 | final iterator = myList.iterator; 24 | print('\nIterating using the iterator:'); 25 | while (iterator.moveNext()) { 26 | print(iterator.current); 27 | } 28 | 29 | // Accessing the reversed list 30 | print('\nReversed list:'); 31 | for (final element in myList.reversed) { 32 | print(element); 33 | } 34 | 35 | // Accessing the single element 36 | print('\nSingle element: ${myList.single}'); // Throws if list has more than one element 37 | 38 | // Creating a new list from the original 39 | final newList = [...myList]; 40 | print('\nNew list: $newList'); 41 | } -------------------------------------------------------------------------------- /bin/collection/Map/HashMap/allconstructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating an empty HashMap 5 | final Map planets = HashMap(); 6 | 7 | // Adding key-value pairs to the map 8 | planets.addAll({1: 'Mercury', 2: 'Venus'}); 9 | print('After adding key-value pairs: $planets'); 10 | 11 | // Adding entries to the map 12 | final List> newEntries = [MapEntry(3, 'Earth'), MapEntry(4, 'Mars')]; 13 | planets.addEntries(newEntries); 14 | print('After adding entries: $planets'); 15 | 16 | // Casting the map keys and values 17 | final Map castedMap = planets.cast(); 18 | print('Casted map: $castedMap'); 19 | 20 | // Clearing the map 21 | castedMap.clear(); 22 | print('After clearing the map: $castedMap'); 23 | 24 | // Checking if a key exists 25 | final bool containsKey = planets.containsKey(2); 26 | print('Contains key 2: $containsKey'); 27 | 28 | // Checking if a value exists 29 | final bool containsValue = planets.containsValue('Earth'); 30 | print('Contains value "Earth": $containsValue'); 31 | 32 | // Iterating over key-value pairs 33 | planets.forEach((key, value) { 34 | print('Planet $key: $value'); 35 | }); 36 | 37 | // Mapping values to a new map 38 | final Map mappedPlanets = planets.map((key, value) => MapEntry(value, 'Planet $key')); 39 | print('Mapped planets: $mappedPlanets'); 40 | 41 | // Using putIfAbsent 42 | planets.putIfAbsent(5, () => 'Jupiter'); 43 | print('After using putIfAbsent: $planets'); 44 | 45 | // Removing a key-value pair 46 | final String? removedValue = planets.remove(4); 47 | print('Removed value: $removedValue, Map after removal: $planets'); 48 | 49 | // Removing entries based on condition 50 | planets.removeWhere((key, value) => key % 2 == 0); 51 | print('Map after removeWhere: $planets'); 52 | 53 | // Converting map to string 54 | final String mapString = planets.toString(); 55 | print('String representation of map: $mapString'); 56 | 57 | // Updating a value 58 | planets.update(1, (value) => 'Shrouded $value'); 59 | print('Map after update: $planets'); 60 | 61 | // Updating all values 62 | planets.updateAll((key, value) => 'Inhabited $value'); 63 | print('Map after updateAll: $planets'); 64 | } 65 | -------------------------------------------------------------------------------- /bin/collection/Map/HashMap/allmethod.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // 1. Using default constructor 5 | final Map planetsDefault = HashMap(); 6 | planetsDefault[1] = 'Mercury'; 7 | planetsDefault[2] = 'Venus'; 8 | print('Planets (default constructor): $planetsDefault'); 9 | 10 | // 2. Using HashMap.from() 11 | final Map otherMap = {3: 'Earth', 4: 'Mars'}; 12 | final Map planetsFrom = HashMap.from(otherMap); 13 | print('Planets (from): $planetsFrom'); 14 | 15 | // 3. Using HashMap.fromEntries() 16 | final List> entriesList = [MapEntry(5, 'Jupiter'), MapEntry(6, 'Saturn')]; 17 | final Map planetsFromEntries = HashMap.fromEntries(entriesList); 18 | print('Planets (fromEntries): $planetsFromEntries'); 19 | 20 | // 4. Using HashMap.fromIterable() 21 | final List planetsList = ['Uranus', 'Neptune']; 22 | final Map planetsFromIterable = HashMap.fromIterable( 23 | planetsList, 24 | key: (planet) => planetsList.indexOf(planet) + 7, 25 | value: (planet) => planet, 26 | ); 27 | print('Planets (fromIterable): $planetsFromIterable'); 28 | 29 | // 5. Using HashMap.fromIterables() 30 | final List keysList = [8, 9]; 31 | final List valuesList = ['Pluto', 'Haumea']; 32 | final Map planetsFromIterables = HashMap.fromIterables(keysList, valuesList); 33 | print('Planets (fromIterables): $planetsFromIterables'); 34 | 35 | // 6. Using identity constructor 36 | final Map planetsIdentity = HashMap.identity(); 37 | planetsIdentity[10] = 'Makemake'; 38 | print('Planets (identity): $planetsIdentity'); 39 | 40 | // 7. Using HashMap.of() 41 | final Map planetsOf = HashMap.of(planetsDefault); 42 | print('Planets (of): $planetsOf'); 43 | } 44 | -------------------------------------------------------------------------------- /bin/collection/Map/HashMap/allmethod_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | 4 | // ignore: depend_on_referenced_packages 5 | import 'package:test/test.dart'; 6 | 7 | void main() { 8 | test('HashMap creation using different methods', () { 9 | // 1. Using default constructor 10 | final planetsDefault = HashMap(); 11 | planetsDefault[1] = 'Mercury'; 12 | planetsDefault[2] = 'Venus'; 13 | expect(planetsDefault, {1: 'Mercury', 2: 'Venus'}); 14 | 15 | // 2. Using HashMap.from() 16 | final otherMap = {3: 'Earth', 4: 'Mars'}; 17 | final planetsFrom = HashMap.from(otherMap); 18 | expect(planetsFrom, {3: 'Earth', 4: 'Mars'}); 19 | 20 | // 3. Using HashMap.fromEntries() 21 | final entriesList = [MapEntry(5, 'Jupiter'), MapEntry(6, 'Saturn')]; 22 | final planetsFromEntries = HashMap.fromEntries(entriesList); 23 | expect(planetsFromEntries, {5: 'Jupiter', 6: 'Saturn'}); 24 | 25 | // 4. Using HashMap.fromIterable() 26 | final planetsList = ['Uranus', 'Neptune']; 27 | final planetsFromIterable = HashMap.fromIterable( 28 | planetsList, 29 | key: (planet) => planetsList.indexOf(planet) + 7, 30 | value: (planet) => planet, 31 | ); 32 | expect(planetsFromIterable, {7: 'Uranus', 8: 'Neptune'}); 33 | 34 | // 5. Using HashMap.fromIterables() 35 | final keysList = [8, 9]; 36 | final valuesList = ['Pluto', 'Haumea']; 37 | final planetsFromIterables = HashMap.fromIterables(keysList, valuesList); 38 | expect(planetsFromIterables, {8: 'Pluto', 9: 'Haumea'}); 39 | 40 | // 6. Using identity constructor 41 | final planetsIdentity = HashMap.identity(); 42 | planetsIdentity[10] = 'Makemake'; 43 | expect(planetsIdentity, {10: 'Makemake'}); 44 | 45 | // 7. Using HashMap.of() 46 | final planetsOf = HashMap.of(planetsDefault); 47 | expect(planetsOf, {1: 'Mercury', 2: 'Venus'}); 48 | }); 49 | } -------------------------------------------------------------------------------- /bin/collection/Map/HashMap/allproperty.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a HashMap 5 | final Map planets = HashMap(); 6 | 7 | // Adding key-value pairs to the map 8 | planets[1] = 'Mercury'; 9 | planets[2] = 'Venus'; 10 | planets[3] = 'Earth'; 11 | planets[4] = 'Mars'; 12 | 13 | // Properties 14 | // 1. entries 15 | final Iterable> entries = planets.entries; 16 | print('Entries: $entries'); 17 | 18 | // 2. hashCode 19 | final int hashCode = planets.hashCode; 20 | print('Hash Code: $hashCode'); 21 | 22 | // 3. isEmpty 23 | final bool isEmpty = planets.isEmpty; 24 | print('Is Empty: $isEmpty'); 25 | 26 | // 4. isNotEmpty 27 | final bool isNotEmpty = planets.isNotEmpty; 28 | print('Is Not Empty: $isNotEmpty'); 29 | 30 | // 5. keys 31 | final Iterable keys = planets.keys; 32 | print('Keys: $keys'); 33 | 34 | // 6. length 35 | final int length = planets.length; 36 | print('Length: $length'); 37 | 38 | // 7. runtimeType 39 | final Type type = planets.runtimeType; 40 | print('Runtime Type: $type'); 41 | 42 | // 8. values 43 | final Iterable values = planets.values; 44 | print('Values: $values'); 45 | } 46 | -------------------------------------------------------------------------------- /bin/collection/Map/LinkedHashMap/allconstructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Constructor: LinkedHashMap() 5 | var linkedHashMap1 = {}; 6 | linkedHashMap1[1] = 'One'; 7 | linkedHashMap1[2] = 'Two'; 8 | linkedHashMap1[3] = 'Three'; 9 | print('LinkedHashMap 1: $linkedHashMap1'); 10 | 11 | // Constructor: LinkedHashMap.from(Map other) 12 | var map = {4: 'Four', 5: 'Five', 6: 'Six'}; 13 | var linkedHashMap2 = LinkedHashMap.from(map); 14 | print('LinkedHashMap 2: $linkedHashMap2'); 15 | 16 | // Constructor: LinkedHashMap.fromEntries(Iterable> entries) 17 | var entries = [MapEntry(7, 'Seven'), MapEntry(8, 'Eight'), MapEntry(9, 'Nine')]; 18 | var linkedHashMap3 = LinkedHashMap.fromEntries(entries); 19 | print('LinkedHashMap 3: $linkedHashMap3'); 20 | 21 | // Constructor: LinkedHashMap.fromIterable(Iterable iterable, {K key(dynamic element)?, V value(dynamic element)?}) 22 | var iterable = ['Ten', 'Eleven', 'Twelve']; 23 | var linkedHashMap4 = LinkedHashMap.fromIterable(iterable, key: (element) => iterable.indexOf(element) + 10); 24 | print('LinkedHashMap 4: $linkedHashMap4'); 25 | 26 | // Constructor: LinkedHashMap.fromIterables(Iterable keys, Iterable values) 27 | var keys = [13, 14, 15]; 28 | var values = ['Thirteen', 'Fourteen', 'Fifteen']; 29 | var linkedHashMap5 = LinkedHashMap.fromIterables(keys, values); 30 | print('LinkedHashMap 5: $linkedHashMap5'); 31 | 32 | // Constructor: LinkedHashMap.identity() 33 | var linkedHashMap6 = LinkedHashMap.identity(); 34 | linkedHashMap6[16] = 'Sixteen'; 35 | linkedHashMap6[17] = 'Seventeen'; 36 | linkedHashMap6[18] = 'Eighteen'; 37 | print('LinkedHashMap 6: $linkedHashMap6'); 38 | 39 | // Constructor: LinkedHashMap.of(Map other) 40 | var linkedHashMap7 = LinkedHashMap.of({19: 'Nineteen', 20: 'Twenty', 21: 'Twenty-One'}); 41 | print('LinkedHashMap 7: $linkedHashMap7'); 42 | } 43 | -------------------------------------------------------------------------------- /bin/collection/Map/LinkedHashMap/allmethod.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | void main() { 4 | // Creating an empty LinkedHashMap 5 | final Map planets = {}; 6 | 7 | // Adding key-value pairs to the map 8 | planets.addAll({1: 'Mercury', 2: 'Venus'}); 9 | print('After adding key-value pairs: $planets'); 10 | 11 | // Adding entries to the map 12 | final List> newEntries = [MapEntry(3, 'Earth'), MapEntry(4, 'Mars')]; 13 | planets.addEntries(newEntries); 14 | print('After adding entries: $planets'); 15 | 16 | // Casting the map keys and values 17 | final Map castedMap = planets.cast(); 18 | print('Casted map: $castedMap'); 19 | 20 | // Clearing the map 21 | castedMap.clear(); 22 | print('After clearing the map: $castedMap'); 23 | 24 | // Checking if a key exists 25 | final bool containsKey = planets.containsKey(2); 26 | print('Contains key 2: $containsKey'); 27 | 28 | // Checking if a value exists 29 | final bool containsValue = planets.containsValue('Earth'); 30 | print('Contains value "Earth": $containsValue'); 31 | 32 | // Iterating over key-value pairs 33 | planets.forEach((key, value) { 34 | print('Planet $key: $value'); 35 | }); 36 | 37 | // Mapping values to a new map 38 | final Map mappedPlanets = planets.map((key, value) => MapEntry(value, 'Planet $key')); 39 | print('Mapped planets: $mappedPlanets'); 40 | 41 | // Using putIfAbsent 42 | planets.putIfAbsent(5, () => 'Jupiter'); 43 | print('After using putIfAbsent: $planets'); 44 | 45 | // Removing a key-value pair 46 | final String? removedValue = planets.remove(4); 47 | print('Removed value: $removedValue, Map after removal: $planets'); 48 | 49 | // Removing entries based on condition 50 | planets.removeWhere((key, value) => key % 2 == 0); 51 | print('Map after removeWhere: $planets'); 52 | 53 | // Converting map to string 54 | final String mapString = planets.toString(); 55 | print('String representation of map: $mapString'); 56 | 57 | // Updating a value 58 | planets.update(1, (value) => 'Shrouded $value'); 59 | print('Map after update: $planets'); 60 | 61 | // Updating all values 62 | planets.updateAll((key, value) => 'Inhabited $value'); 63 | print('Map after updateAll: $planets'); 64 | 65 | // Getting the first key and value 66 | final int firstKey = planets.keys.first; 67 | final String firstValue = planets.values.first; 68 | print('First key: $firstKey, First value: $firstValue'); 69 | 70 | // Getting the last key and value 71 | final int lastKey = planets.keys.last; 72 | final String lastValue = planets.values.last; 73 | print('Last key: $lastKey, Last value: $lastValue'); 74 | 75 | // Getting the length of the map 76 | final int length = planets.length; 77 | print('Length of the map: $length'); 78 | 79 | // Checking if the map is empty 80 | final bool isEmpty = planets.isEmpty; 81 | print('Is the map empty: $isEmpty'); 82 | 83 | // Checking if the map is not empty 84 | final bool isNotEmpty = planets.isNotEmpty; 85 | print('Is the map not empty: $isNotEmpty'); 86 | } 87 | -------------------------------------------------------------------------------- /bin/collection/Map/LinkedHashMap/allproperty.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a LinkedHashMap 5 | LinkedHashMap linkedHashMap = LinkedHashMap(); 6 | 7 | // Adding entries to the map 8 | linkedHashMap[1] = 'One'; 9 | linkedHashMap[2] = 'Two'; 10 | linkedHashMap[3] = 'Three'; 11 | 12 | // Printing all properties 13 | print('Entries:'); 14 | for (var entry in linkedHashMap.entries) { 15 | print('Key: ${entry.key}, Value: ${entry.value}'); 16 | } 17 | 18 | print('HashCode: ${linkedHashMap.hashCode}'); 19 | print('Is Empty: ${linkedHashMap.isEmpty}'); 20 | print('Is Not Empty: ${linkedHashMap.isNotEmpty}'); 21 | print('Keys: ${linkedHashMap.keys}'); 22 | print('Length: ${linkedHashMap.length}'); 23 | print('RuntimeType: ${linkedHashMap.runtimeType}'); 24 | print('Values: ${linkedHashMap.values}'); 25 | } 26 | -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/allconstructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Using the default constructor 5 | final defaultMap = SplayTreeMap((a, b) => a.compareTo(b)); 6 | defaultMap.addAll({3: 'C', 1: 'A', 2: 'B'}); 7 | print('Default SplayTreeMap: $defaultMap'); 8 | 9 | // Using the constructor SplayTreeMap.from 10 | // final fromMap = {'a': 1, 'b': 2, 'c': 3}; 11 | // final fromConstructor = SplayTreeMap.from(fromMap, (a, b) => a.compareTo(b)); 12 | // print('SplayTreeMap.from: $fromConstructor'); 13 | 14 | // Using the factory constructor SplayTreeMap.fromIterable 15 | final iterable = [1, 2, 3, 4, 5]; 16 | final fromIterable = SplayTreeMap.fromIterable( 17 | iterable, 18 | key: (element) => element, 19 | value: (element) => 'Value $element', 20 | compare: (a, b) => a.compareTo(b), 21 | ); 22 | print('SplayTreeMap.fromIterable: $fromIterable'); 23 | 24 | // Using the factory constructor SplayTreeMap.fromIterables 25 | final keys = [1, 2, 3]; 26 | final values = ['one', 'two', 'three']; 27 | final fromIterables = SplayTreeMap.fromIterables( 28 | keys, 29 | values, 30 | (a, b) => a.compareTo(b), 31 | ); 32 | print('SplayTreeMap.fromIterables: $fromIterables'); 33 | 34 | // Using the factory constructor SplayTreeMap.of 35 | final ofMap = {'x': 10, 'y': 20, 'z': 30}; 36 | final ofConstructor = SplayTreeMap.of(ofMap, (a, b) => a.compareTo(b)); 37 | print('SplayTreeMap.of: $ofConstructor'); 38 | } 39 | -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/allmethods.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a SplayTreeMap 5 | final map = SplayTreeMap((a, b) => a.compareTo(b)); 6 | 7 | // Adding key-value pairs 8 | map.addAll({3: 'C', 1: 'A', 2: 'B'}); 9 | print('Initial Map: $map'); 10 | 11 | // Adding individual entries 12 | map[4] = 'D'; 13 | map.putIfAbsent(5, () => 'E'); 14 | print('Map after adding entries: $map'); 15 | 16 | // Adding entries from another map 17 | final additionalMap = {6: 'F', 7: 'G'}; 18 | map.addEntries(additionalMap.entries); 19 | print('Map after adding entries from another map: $map'); 20 | 21 | // Removing entries 22 | map.remove(2); 23 | print('Map after removing entry with key 2: $map'); 24 | 25 | // Removing entries based on a condition 26 | map.removeWhere((key, value) => value.startsWith('C')); 27 | print('Map after removing entries starting with "C": $map'); 28 | 29 | // Clearing the map 30 | map.clear(); 31 | print('Map after clearing: $map'); 32 | 33 | // Checking for key existence 34 | final containsKey = map.containsKey(3); 35 | print('Does map contain key 3? $containsKey'); 36 | 37 | // Checking for value existence 38 | final containsValue = map.containsValue('G'); 39 | print('Does map contain value "G"? $containsValue'); 40 | 41 | // Accessing first and last keys 42 | final firstKey = map.firstKey; 43 | final lastKey = map.lastKey; 44 | print('First Key: $firstKey, Last Key: $lastKey'); 45 | 46 | // Iterating over map entries 47 | map.forEach((key, value) { 48 | print('Key: $key, Value: $value'); 49 | }); 50 | 51 | // Updating values based on a condition 52 | map.updateAll((key, value) => value.toUpperCase()); 53 | print('Map after updating values: $map'); 54 | 55 | // Mapping keys and values 56 | final mappedKeys = map.keys.map((key) => key * 2); 57 | final mappedValues = map.values.map((value) => value.toLowerCase()); 58 | print('Mapped Keys: $mappedKeys, Mapped Values: $mappedValues'); 59 | 60 | // Converting map to string 61 | final mapString = map.toString(); 62 | print('String representation of map: $mapString'); 63 | } 64 | -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/allproperty.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a SplayTreeMap 5 | final map = SplayTreeMap((a, b) => a.compareTo(b)); 6 | map.addAll({3: 'C', 1: 'A', 2: 'B'}); 7 | 8 | // Properties 9 | print('Entries: ${map.entries}'); // Returns an iterable of all key-value pairs in the map. 10 | print('Hash Code: ${map.hashCode}'); // Returns the hash code of the map. 11 | print('Is Empty: ${map.isEmpty}'); // Returns true if the map is empty, false otherwise. 12 | print('Is Not Empty: ${map.isNotEmpty}'); // Returns true if the map is not empty, false otherwise. 13 | print('Keys: ${map.keys}'); // Returns an iterable of all keys in the map. 14 | print('Length: ${map.length}'); // Returns the number of key-value pairs in the map. 15 | print('Runtime Type: ${map.runtimeType}'); // Returns the runtime type of the map. 16 | print('Values: ${map.values}'); // Returns an iterable of all values in the map. 17 | 18 | // Modifying the map 19 | map[4] = 'D'; // Adds or updates the value associated with the key 4. 20 | map.remove(1); // Removes the key-value pair with the key 1. 21 | map.update(2, (value) => 'BB'); // Updates the value associated with the key 2 using the provided update function. 22 | 23 | // Displaying the modified map 24 | print('Modified Map: $map'); 25 | 26 | // Accessing properties after modification 27 | print('Entries: ${map.entries}'); 28 | print('Hash Code: ${map.hashCode}'); 29 | print('Is Empty: ${map.isEmpty}'); 30 | print('Is Not Empty: ${map.isNotEmpty}'); 31 | print('Keys: ${map.keys}'); 32 | print('Length: ${map.length}'); 33 | print('Runtime Type: ${map.runtimeType}'); 34 | print('Values: ${map.values}'); 35 | } 36 | -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/problem.md: -------------------------------------------------------------------------------- 1 | Sure! Let's consider a real-life problem where a `SplayTreeMap` can be utilized effectively: 2 | 3 | **Problem: Event Scheduling** 4 | 5 | Suppose you are organizing a series of events over a period of time, and you need to efficiently manage the scheduling of these events to ensure there are no conflicts in the timings. Each event has a start time and an end time. 6 | 7 | Here's how you can use a `SplayTreeMap` to solve this problem: 8 | 9 | 1. **Data Representation**: Represent each event with its start time as the key and its end time as the value in the `SplayTreeMap`. This allows you to quickly retrieve events based on their start times, which are sorted naturally in ascending order. 10 | 11 | 2. **Conflict Detection**: As you add events to the `SplayTreeMap`, you can check for conflicts with existing events. If the start time of a new event falls within the time range of an existing event, it indicates a scheduling conflict. 12 | 13 | 3. **Efficient Retrieval**: With the events sorted by start time in the `SplayTreeMap`, you can efficiently retrieve events within a specific time range or find the next available time slot for scheduling a new event. 14 | 15 | 4. **Dynamic Updates**: If there are changes to the event schedule, such as rescheduling or cancelling events, you can easily update the `SplayTreeMap` accordingly without needing to re-sort the events. 16 | 17 | ```dart 18 | import 'dart:collection'; 19 | 20 | void main() { 21 | // Create a SplayTreeMap to manage event scheduling 22 | final eventSchedule = SplayTreeMap(); 23 | 24 | // Add events to the schedule 25 | addEvent(eventSchedule, 900, 1000); // Event 1: 9:00 AM - 10:00 AM 26 | addEvent(eventSchedule, 1030, 1100); // Event 2: 10:30 AM - 11:00 AM 27 | addEvent(eventSchedule, 930, 1100); // Event 3: 9:30 AM - 11:00 AM (Conflict) 28 | 29 | // Check for conflicts when adding events 30 | bool hasConflict = checkForConflict(eventSchedule, 930, 1100); // Should return true 31 | print('Conflict Detected: $hasConflict'); 32 | 33 | // Find the next available time slot after 11:00 AM 34 | int nextAvailableTime = findNextAvailableTime(eventSchedule, 1100); 35 | print('Next Available Time: $nextAvailableTime'); // Should return 1100 (11:00 AM) 36 | } 37 | 38 | // Function to add an event to the schedule 39 | void addEvent(SplayTreeMap schedule, int startTime, int endTime) { 40 | // Check for conflicts 41 | if (checkForConflict(schedule, startTime, endTime)) { 42 | print('Scheduling Conflict: Unable to add event from $startTime to $endTime'); 43 | } else { 44 | schedule[startTime] = endTime; 45 | print('Event scheduled from $startTime to $endTime'); 46 | } 47 | } 48 | 49 | // Function to check for conflicts with existing events 50 | bool checkForConflict(SplayTreeMap schedule, int startTime, int endTime) { 51 | // Iterate through events to check for conflicts 52 | for (var entry in schedule.entries) { 53 | if (entry.key <= startTime && startTime < entry.value) { 54 | return true; // Conflict detected 55 | } 56 | if (entry.key < endTime && endTime <= entry.value) { 57 | return true; // Conflict detected 58 | } 59 | } 60 | return false; // No conflicts found 61 | } 62 | 63 | // Function to find the next available time slot after a given time 64 | int findNextAvailableTime(SplayTreeMap schedule, int time) { 65 | // Iterate through events to find the next available time slot 66 | for (var entry in schedule.entries) { 67 | if (entry.key > time) { 68 | return entry.key; // Next available time found 69 | } 70 | } 71 | return time; // No events scheduled after the given time 72 | } 73 | ``` 74 | 75 | In this example, the `SplayTreeMap` is used to manage event scheduling efficiently. It allows for easy addition of events, conflict detection, and retrieval of available time slots, making it a suitable solution for organizing events in a real-life scenario. -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/problmes/prob1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a SplayTreeMap to manage event scheduling 5 | final eventSchedule = SplayTreeMap(); 6 | 7 | // Add events to the schedule 8 | addEvent(eventSchedule, 900, 1000); // Event 1: 9:00 AM - 10:00 AM 9 | addEvent(eventSchedule, 1030, 1100); // Event 2: 10:30 AM - 11:00 AM 10 | addEvent(eventSchedule, 930, 1100); // Event 3: 9:30 AM - 11:00 AM (Conflict) 11 | 12 | // Check for conflicts when adding events 13 | bool hasConflict = checkForConflict(eventSchedule, 930, 1100); // Should return true 14 | print('Conflict Detected: $hasConflict'); 15 | 16 | // Find the next available time slot after 11:00 AM 17 | int nextAvailableTime = findNextAvailableTime(eventSchedule, 1100); 18 | print('Next Available Time: $nextAvailableTime'); // Should return 1100 (11:00 AM) 19 | } 20 | 21 | // Function to add an event to the schedule 22 | void addEvent(SplayTreeMap schedule, int startTime, int endTime) { 23 | // Check for conflicts 24 | if (checkForConflict(schedule, startTime, endTime)) { 25 | print('Scheduling Conflict: Unable to add event from $startTime to $endTime'); 26 | } else { 27 | schedule[startTime] = endTime; 28 | print('Event scheduled from $startTime to $endTime'); 29 | } 30 | } 31 | 32 | // Function to check for conflicts with existing events 33 | bool checkForConflict(SplayTreeMap schedule, int startTime, int endTime) { 34 | // Iterate through events to check for conflicts 35 | for (var entry in schedule.entries) { 36 | if (entry.key <= startTime && startTime < entry.value) { 37 | return true; // Conflict detected 38 | } 39 | if (entry.key < endTime && endTime <= entry.value) { 40 | return true; // Conflict detected 41 | } 42 | } 43 | return false; // No conflicts found 44 | } 45 | 46 | // Function to find the next available time slot after a given time 47 | int findNextAvailableTime(SplayTreeMap schedule, int time) { 48 | // Iterate through events to find the next available time slot 49 | for (var entry in schedule.entries) { 50 | if (entry.key > time) { 51 | return entry.key; // Next available time found 52 | } 53 | } 54 | return time; // No events scheduled after the given time 55 | } -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/problmes/prob2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a SplayTreeMap to manage tasks based on priority 5 | final taskPriorityMap = SplayTreeMap>(); 6 | 7 | // Add tasks to the priority map 8 | addTask(taskPriorityMap, 3, 'Implement Feature A'); 9 | addTask(taskPriorityMap, 1, 'Fix Critical Bug'); 10 | addTask(taskPriorityMap, 2, 'Write Unit Tests'); 11 | addTask(taskPriorityMap, 3, 'Refactor Codebase'); 12 | addTask(taskPriorityMap, 2, 'Review Pull Requests'); 13 | 14 | // Execute tasks based on priority 15 | executeTasks(taskPriorityMap); 16 | } 17 | 18 | // Function to add a task to the priority map 19 | void addTask(SplayTreeMap> priorityMap, int priority, String task) { 20 | if (!priorityMap.containsKey(priority)) { 21 | priorityMap[priority] = []; 22 | } 23 | priorityMap[priority]!.add(task); 24 | print('Task added: $task (Priority: $priority)'); 25 | } 26 | 27 | // Function to execute tasks based on priority 28 | void executeTasks(SplayTreeMap> priorityMap) { 29 | // Iterate through the priority map to execute tasks 30 | for (var priorityEntry in priorityMap.entries) { 31 | final priority = priorityEntry.key; 32 | final tasks = priorityEntry.value; 33 | print('Executing tasks with Priority $priority:'); 34 | for (var task in tasks) { 35 | print('- $task'); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /bin/collection/Map/SplayTreeMap/problmes/prob2.md: -------------------------------------------------------------------------------- 1 | **Problem: Task Priority Management** 2 | 3 | Consider a scenario where you are managing tasks for a project, and each task has a priority level associated with it. You need to efficiently manage the tasks based on their priorities, ensuring that higher priority tasks are executed before lower priority ones. Additionally, tasks with the same priority should be executed in the order they were added. 4 | 5 | Here's how you can use a `SplayTreeMap` to solve this problem: 6 | 7 | 1. **Data Representation**: Represent each task with its priority level as the key and a list of tasks with the same priority as the value in the `SplayTreeMap`. This allows you to quickly retrieve tasks based on their priorities, with tasks of the same priority grouped together and sorted naturally in ascending order of priority. 8 | 9 | 2. **Task Addition**: When adding a new task, insert it into the list of tasks with the corresponding priority level. If no tasks with that priority exist yet, create a new list for that priority level. 10 | 11 | 3. **Task Execution**: Retrieve tasks from the `SplayTreeMap` in ascending order of priority. For tasks with the same priority, execute them in the order they were added to maintain FIFO (First-In-First-Out) order. 12 | 13 | 4. **Dynamic Updates**: If there are changes to task priorities or new tasks are added with higher priorities, you can easily update the `SplayTreeMap` accordingly without needing to re-sort the tasks. 14 | 15 | ```dart 16 | import 'dart:collection'; 17 | 18 | void main() { 19 | // Create a SplayTreeMap to manage tasks based on priority 20 | final taskPriorityMap = SplayTreeMap>(); 21 | 22 | // Add tasks to the priority map 23 | addTask(taskPriorityMap, 3, 'Implement Feature A'); 24 | addTask(taskPriorityMap, 1, 'Fix Critical Bug'); 25 | addTask(taskPriorityMap, 2, 'Write Unit Tests'); 26 | addTask(taskPriorityMap, 3, 'Refactor Codebase'); 27 | addTask(taskPriorityMap, 2, 'Review Pull Requests'); 28 | 29 | // Execute tasks based on priority 30 | executeTasks(taskPriorityMap); 31 | } 32 | 33 | // Function to add a task to the priority map 34 | void addTask(SplayTreeMap> priorityMap, int priority, String task) { 35 | if (!priorityMap.containsKey(priority)) { 36 | priorityMap[priority] = []; 37 | } 38 | priorityMap[priority]!.add(task); 39 | print('Task added: $task (Priority: $priority)'); 40 | } 41 | 42 | // Function to execute tasks based on priority 43 | void executeTasks(SplayTreeMap> priorityMap) { 44 | // Iterate through the priority map to execute tasks 45 | for (var priorityEntry in priorityMap.entries) { 46 | final priority = priorityEntry.key; 47 | final tasks = priorityEntry.value; 48 | print('Executing tasks with Priority $priority:'); 49 | for (var task in tasks) { 50 | print('- $task'); 51 | } 52 | } 53 | } 54 | ``` 55 | 56 | In this example, the `SplayTreeMap` is used to efficiently manage tasks based on their priority levels. It allows for easy addition of tasks, execution of tasks in the correct order of priority, and dynamic updates to the task list. This solution demonstrates how `SplayTreeMap` can be applied to real-life scenarios involving task management and prioritization. -------------------------------------------------------------------------------- /bin/collection/Map/UnmodifiableMapView/allconstructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a base map 5 | final baseMap = {1: 'Mars', 2: 'Mercury', 3: 'Venus'}; 6 | 7 | // Constructor: UnmodifiableMapView(Map map) 8 | final unmodifiableMapView1 = UnmodifiableMapView(baseMap); 9 | 10 | 11 | // Print the unmodifiable maps 12 | print('Unmodifiable Map 1: $unmodifiableMapView1'); 13 | 14 | 15 | // Access properties and methods of the unmodifiable maps 16 | print('Length of Map 1: ${unmodifiableMapView1.length}'); 17 | 18 | 19 | // Attempt modification (which should throw errors) 20 | try { 21 | unmodifiableMapView1.remove(1); // Throws an error 22 | } catch (e) { 23 | print('Error occurred: $e'); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /bin/collection/Map/UnmodifiableMapView/allmethod.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a base map 5 | final baseMap = {1: 'Mars', 2: 'Mercury', 3: 'Venus'}; 6 | final unmodifiableMapView = UnmodifiableMapView(baseMap); 7 | 8 | // Method: addAll 9 | try { 10 | unmodifiableMapView.addAll({4: 'Earth'}); // Throws an error 11 | } catch (e) { 12 | print('Error occurred: $e'); 13 | } 14 | 15 | // Method: addEntries 16 | try { 17 | unmodifiableMapView.addEntries([MapEntry(4, 'Earth')]); // Throws an error 18 | } catch (e) { 19 | print('Error occurred: $e'); 20 | } 21 | 22 | // Method: cast 23 | final castedMap = unmodifiableMapView.cast(); 24 | print('Casted Map: $castedMap'); 25 | 26 | // Method: clear 27 | try { 28 | unmodifiableMapView.clear(); // Throws an error 29 | } catch (e) { 30 | print('Error occurred: $e'); 31 | } 32 | 33 | // Method: containsKey 34 | print('Contains key 2? ${unmodifiableMapView.containsKey(2)}'); 35 | 36 | // Method: containsValue 37 | print('Contains value "Earth"? ${unmodifiableMapView.containsValue("Earth")}'); 38 | 39 | // Method: forEach 40 | unmodifiableMapView.forEach((key, value) { 41 | print('$key: $value'); 42 | }); 43 | 44 | // Method: map 45 | final mapped = unmodifiableMapView.map((key, value) => MapEntry('$key', value)); 46 | print('Mapped: $mapped'); 47 | 48 | // Method: putIfAbsent 49 | try { 50 | unmodifiableMapView.putIfAbsent(4, () => 'Earth'); // Throws an error 51 | } catch (e) { 52 | print('Error occurred: $e'); 53 | } 54 | 55 | // Method: remove 56 | try { 57 | unmodifiableMapView.remove(1); // Throws an error 58 | } catch (e) { 59 | print('Error occurred: $e'); 60 | } 61 | 62 | // Method: removeWhere 63 | try { 64 | unmodifiableMapView.removeWhere((key, value) => key == 1); // Throws an error 65 | } catch (e) { 66 | print('Error occurred: $e'); 67 | } 68 | 69 | // Method: toString 70 | print('Map as string: $unmodifiableMapView'); 71 | 72 | // Method: update 73 | try { 74 | unmodifiableMapView.update(1, (value) => 'Earth'); // Throws an error 75 | } catch (e) { 76 | print('Error occurred: $e'); 77 | } 78 | 79 | // Method: updateAll 80 | try { 81 | unmodifiableMapView.updateAll((key, value) => value.toUpperCase()); // Throws an error 82 | } catch (e) { 83 | print('Error occurred: $e'); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /bin/collection/Map/UnmodifiableMapView/allproperties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a base map 5 | final baseMap = {1: 'Mars', 2: 'Mercury', 3: 'Venus'}; 6 | final unmodifiableMapView = UnmodifiableMapView(baseMap); 7 | 8 | // Access properties of UnmodifiableMapView 9 | print('Map entries:'); 10 | for (var entry in unmodifiableMapView.entries) { 11 | print('${entry.key}: ${entry.value}'); 12 | } 13 | 14 | print('Hash code of the map: ${unmodifiableMapView.hashCode}'); 15 | print('Is the map empty? ${unmodifiableMapView.isEmpty}'); 16 | print('Is the map not empty? ${unmodifiableMapView.isNotEmpty}'); 17 | print('Keys in the map: ${unmodifiableMapView.keys}'); 18 | print('Length of the map: ${unmodifiableMapView.length}'); 19 | print('Type of the map: ${unmodifiableMapView.runtimeType}'); 20 | print('Values in the map: ${unmodifiableMapView.values}'); 21 | 22 | // Attempting to modify the map (which should throw errors) 23 | try { 24 | unmodifiableMapView.remove(1); // Throws an error 25 | } catch (e) { 26 | print('Error occurred: $e'); 27 | } 28 | 29 | // Attempting to modify the map (which should throw errors) 30 | try { 31 | unmodifiableMapView.clear(); // Throws an error 32 | } catch (e) { 33 | print('Error occurred: $e'); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/constructor.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | // ignore_for_file: override_on_non_overriding_member 4 | 5 | void main() { 6 | // Creating an empty DoubleLinkedQueue 7 | var emptyQueue = DoubleLinkedQueue(); 8 | 9 | // Creating a DoubleLinkedQueue from an Iterable 10 | var iterable = [1, 2, 3, 4, 5]; 11 | var queueFromIterable = DoubleLinkedQueue.from(iterable); 12 | 13 | // Creating a DoubleLinkedQueue from an Iterable using factory constructor 14 | var queueFromFactory = DoubleLinkedQueue.of(iterable); 15 | 16 | // Displaying the contents of each queue 17 | print('Empty Queue: $emptyQueue'); 18 | print('Queue from Iterable: $queueFromIterable'); 19 | print('Queue from Factory Constructor: $queueFromFactory'); 20 | } 21 | 22 | class DoubleLinkedQueue extends Iterable { 23 | // Implementing the Queue interface based on a double-linked list 24 | 25 | // Properties and Methods... 26 | 27 | // Constructors 28 | DoubleLinkedQueue(); 29 | factory DoubleLinkedQueue.from(Iterable elements) { 30 | var queue = DoubleLinkedQueue(); 31 | queue.addAll(elements as Iterable); 32 | return queue; 33 | } 34 | factory DoubleLinkedQueue.of(Iterable elements) { 35 | return DoubleLinkedQueue.from(elements); 36 | } 37 | 38 | @override 39 | 40 | void add(E value) { 41 | // TODO: implement add 42 | } 43 | 44 | @override 45 | 46 | void addAll(Iterable iterable) { 47 | // TODO: implement addAll 48 | } 49 | 50 | @override 51 | 52 | void addFirst(E value) { 53 | // TODO: implement addFirst 54 | } 55 | 56 | @override 57 | 58 | void addLast(E value) { 59 | // TODO: implement addLast 60 | } 61 | 62 | @override 63 | 64 | void clear() { 65 | // TODO: implement clear 66 | } 67 | 68 | @override 69 | // TODO: implement iterator 70 | Iterator get iterator => throw UnimplementedError(); 71 | 72 | @override 73 | 74 | bool remove(Object? value) { 75 | // TODO: implement remove 76 | throw UnimplementedError(); 77 | } 78 | 79 | @override 80 | E removeFirst() { 81 | // TODO: implement removeFirst 82 | throw UnimplementedError(); 83 | } 84 | 85 | @override 86 | E removeLast() { 87 | // TODO: implement removeLast 88 | throw UnimplementedError(); 89 | } 90 | 91 | @override 92 | void removeWhere(bool Function(E element) test) { 93 | // TODO: implement removeWhere 94 | } 95 | 96 | @override 97 | void retainWhere(bool Function(E element) test) { 98 | // TODO: implement retainWhere 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/method.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a DoubleLinkedQueue 5 | var queue = DoubleLinkedQueue(); 6 | 7 | // Adding elements to the queue 8 | queue.addAll([1, 2, 3, 4, 5]); 9 | 10 | // Displaying the queue 11 | print('Initial Queue: $queue'); 12 | 13 | // Removing elements from the queue 14 | queue.removeFirst(); 15 | queue.removeLast(); 16 | 17 | // Displaying the modified queue 18 | print('Queue after removing first and last elements: $queue'); 19 | 20 | // Checking if the queue contains a specific element 21 | var containsThree = queue.contains(3); 22 | print('Queue contains 3: $containsThree'); 23 | 24 | // Checking if the queue is empty 25 | var isEmpty = queue.isEmpty; 26 | print('Queue is empty: $isEmpty'); 27 | 28 | // Getting the first and last elements of the queue 29 | var firstElement = queue.first; 30 | var lastElement = queue.last; 31 | print('First element: $firstElement, Last element: $lastElement'); 32 | 33 | // Getting the length of the queue 34 | var length = queue.length; 35 | print('Length of the queue: $length'); 36 | 37 | // Creating an iterator to iterate over the queue 38 | var iterator = queue.iterator; 39 | while (iterator.moveNext()) { 40 | print('Iterating: ${iterator.current}'); 41 | } 42 | 43 | // Clearing the queue 44 | queue.clear(); 45 | print('Queue after clearing: $queue'); 46 | } 47 | -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/pronblems/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class TextEditor { 4 | final DoubleLinkedQueue _undoQueue = DoubleLinkedQueue(); 5 | final DoubleLinkedQueue _redoQueue = DoubleLinkedQueue(); 6 | String _currentText = ''; 7 | 8 | void type(String text) { 9 | _currentText += text; 10 | _undoQueue.addLast(text); 11 | _redoQueue.clear(); 12 | } 13 | 14 | void delete(int count) { 15 | if (count > _currentText.length) { 16 | count = _currentText.length; 17 | } 18 | final deletedText = _currentText.substring(_currentText.length - count); 19 | _currentText = _currentText.substring(0, _currentText.length - count); 20 | _undoQueue.addLast(deletedText); 21 | _redoQueue.clear(); 22 | } 23 | 24 | void undo() { 25 | if (_undoQueue.isNotEmpty) { 26 | final undoText = _undoQueue.removeLast(); 27 | _redoQueue.addFirst(undoText); 28 | _currentText = _currentText.substring(0, _currentText.length - undoText.length); 29 | } 30 | } 31 | 32 | void redo() { 33 | if (_redoQueue.isNotEmpty) { 34 | final redoText = _redoQueue.removeFirst(); 35 | _undoQueue.addLast(redoText); 36 | _currentText += redoText; 37 | } 38 | } 39 | 40 | String get currentText => _currentText; 41 | } 42 | 43 | void main() { 44 | final editor = TextEditor(); 45 | editor.type('hello'); 46 | print(editor.currentText); // Output: "hello" 47 | editor.delete(2); 48 | print(editor.currentText); // Output: "he" 49 | editor.undo(); 50 | print(editor.currentText); // Output: "hello" 51 | editor.redo(); 52 | print(editor.currentText); // Output: "he" 53 | } -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/pronblems/problem1.md: -------------------------------------------------------------------------------- 1 | Here's a real-life problem that can be solved using a DoubleLinkedQueue in Dart: 2 | 3 | **Problem: Undo/Redo functionality in a text editor** 4 | 5 | In a text editor, users often need to be able to undo and redo their actions, such as typing, deleting, or formatting text. To implement this functionality, we can use a DoubleLinkedQueue to keep track of the user's actions. 6 | 7 | **Solution using DoubleLinkedQueue:** 8 | 9 | ```dart 10 | import 'dart:collection'; 11 | 12 | class TextEditor { 13 | final DoubleLinkedQueue _undoQueue = DoubleLinkedQueue(); 14 | final DoubleLinkedQueue _redoQueue = DoubleLinkedQueue(); 15 | String _currentText = ''; 16 | 17 | void type(String text) { 18 | _currentText += text; 19 | _undoQueue.addLast(text); 20 | _redoQueue.clear(); 21 | } 22 | 23 | void delete(int count) { 24 | if (count > _currentText.length) { 25 | count = _currentText.length; 26 | } 27 | final deletedText = _currentText.substring(_currentText.length - count); 28 | _currentText = _currentText.substring(0, _currentText.length - count); 29 | _undoQueue.addLast(deletedText); 30 | _redoQueue.clear(); 31 | } 32 | 33 | void undo() { 34 | if (_undoQueue.isNotEmpty) { 35 | final undoText = _undoQueue.removeLast(); 36 | _redoQueue.addFirst(undoText); 37 | _currentText = _currentText.substring(0, _currentText.length - undoText.length); 38 | } 39 | } 40 | 41 | void redo() { 42 | if (_redoQueue.isNotEmpty) { 43 | final redoText = _redoQueue.removeFirst(); 44 | _undoQueue.addLast(redoText); 45 | _currentText += redoText; 46 | } 47 | } 48 | 49 | String get currentText => _currentText; 50 | } 51 | 52 | void main() { 53 | final editor = TextEditor(); 54 | editor.type('hello'); 55 | print(editor.currentText); // Output: "hello" 56 | editor.delete(2); 57 | print(editor.currentText); // Output: "he" 58 | editor.undo(); 59 | print(editor.currentText); // Output: "hello" 60 | editor.redo(); 61 | print(editor.currentText); // Output: "he" 62 | } 63 | ``` 64 | 65 | Explanation: 66 | 67 | 1. We create a `TextEditor` class that has two `DoubleLinkedQueue`s: one for storing the user's actions to be undone (`_undoQueue`) and one for storing the actions to be redone (`_redoQueue`). 68 | 2. The `type()` method adds the typed text to the `_currentText` string and adds the text to the `_undoQueue`. It also clears the `_redoQueue` since any previous redo actions are no longer valid. 69 | 3. The `delete()` method removes the specified number of characters from the `_currentText` string and adds the deleted text to the `_undoQueue`. It also clears the `_redoQueue`. 70 | 4. The `undo()` method removes the last action from the `_undoQueue` and adds it to the `_redoQueue`. It then updates the `_currentText` string accordingly. 71 | 5. The `redo()` method removes the first action from the `_redoQueue` and adds it to the `_undoQueue`. It then updates the `_currentText` string accordingly. 72 | 73 | The `DoubleLinkedQueue` is a suitable data structure for this problem because it allows us to efficiently add and remove elements from both the beginning and the end of the queue, which is necessary for the undo and redo functionality. -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/pronblems/problem2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class BrowserHistory { 4 | final DoubleLinkedQueue _visitedPages = DoubleLinkedQueue(); 5 | String _currentPage; 6 | 7 | BrowserHistory(String initialPage) 8 | : _currentPage = initialPage { 9 | _currentPage = initialPage; 10 | _visitedPages.addLast(initialPage); 11 | } 12 | 13 | void visit(String page) { 14 | _currentPage = page; 15 | _visitedPages.addLast(page); 16 | 17 | // Clear the redo queue 18 | while (_visitedPages.length > _visitedPages.toList().indexOf(_currentPage) + 1) { 19 | _visitedPages.removeLast(); 20 | } 21 | } 22 | 23 | void back(int steps) { 24 | for (int i = 0; i < steps && _visitedPages.length > 1; i++) { 25 | _currentPage = _visitedPages.removeLast(); 26 | _visitedPages.addFirst(_currentPage); 27 | } 28 | } 29 | 30 | void forward(int steps) { 31 | for (int i = 0; i < steps && _visitedPages.length > _visitedPages.toList().indexOf(_currentPage) + 1; i++) { 32 | _currentPage = _visitedPages.removeFirst(); 33 | _visitedPages.addLast(_currentPage); 34 | } 35 | } 36 | 37 | String get currentPage => _currentPage; 38 | } 39 | 40 | void main() { 41 | final browser = BrowserHistory('Google'); 42 | print(browser.currentPage); // Output: "Google" 43 | 44 | browser.visit('Yahoo'); 45 | print(browser.currentPage); // Output: "Yahoo" 46 | 47 | browser.visit('Bing'); 48 | print(browser.currentPage); // Output: "Bing" 49 | 50 | browser.back(1); 51 | print(browser.currentPage); // Output: "Yahoo" 52 | 53 | browser.forward(1); 54 | print(browser.currentPage); // Output: "Bing" 55 | } -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/pronblems/problem2.md: -------------------------------------------------------------------------------- 1 | Here's another real-life problem that can be solved using a DoubleLinkedQueue in Dart: 2 | 3 | **Problem: Implementing a browser's back and forward navigation** 4 | 5 | When using a web browser, users can navigate between pages by clicking on links or using the browser's back and forward buttons. To implement this functionality, we can use a DoubleLinkedQueue to keep track of the visited pages. 6 | 7 | **Solution using DoubleLinkedQueue:** 8 | 9 | ```dart 10 | import 'dart:collection'; 11 | 12 | class BrowserHistory { 13 | final DoubleLinkedQueue _visitedPages = DoubleLinkedQueue(); 14 | String _currentPage; 15 | 16 | BrowserHistory(String initialPage) { 17 | _currentPage = initialPage; 18 | _visitedPages.addLast(initialPage); 19 | } 20 | 21 | void visit(String page) { 22 | _currentPage = page; 23 | _visitedPages.addLast(page); 24 | 25 | // Clear the redo queue 26 | while (_visitedPages.length > _visitedPages.indexOf(_currentPage) + 1) { 27 | _visitedPages.removeLast(); 28 | } 29 | } 30 | 31 | void back(int steps) { 32 | for (int i = 0; i < steps && _visitedPages.length > 1; i++) { 33 | _currentPage = _visitedPages.removeLast(); 34 | _visitedPages.addFirst(_currentPage); 35 | } 36 | } 37 | 38 | void forward(int steps) { 39 | for (int i = 0; i < steps && _visitedPages.length > _visitedPages.indexOf(_currentPage) + 1; i++) { 40 | _currentPage = _visitedPages.removeFirst(); 41 | _visitedPages.addLast(_currentPage); 42 | } 43 | } 44 | 45 | String get currentPage => _currentPage; 46 | } 47 | 48 | void main() { 49 | final browser = BrowserHistory('Google'); 50 | print(browser.currentPage); // Output: "Google" 51 | 52 | browser.visit('Yahoo'); 53 | print(browser.currentPage); // Output: "Yahoo" 54 | 55 | browser.visit('Bing'); 56 | print(browser.currentPage); // Output: "Bing" 57 | 58 | browser.back(1); 59 | print(browser.currentPage); // Output: "Yahoo" 60 | 61 | browser.forward(1); 62 | print(browser.currentPage); // Output: "Bing" 63 | } 64 | ``` 65 | 66 | Explanation: 67 | 68 | 1. We create a `BrowserHistory` class that has a `DoubleLinkedQueue` called `_visitedPages` to keep track of the visited pages. 69 | 2. The constructor initializes the `_currentPage` variable with the initial page and adds it to the `_visitedPages` queue. 70 | 3. The `visit()` method adds the new page to the `_visitedPages` queue and updates the `_currentPage` variable. It also clears the redo queue by removing any pages that come after the current page. 71 | 4. The `back()` method moves the `_currentPage` variable backwards in the `_visitedPages` queue by the specified number of steps, if possible. 72 | 5. The `forward()` method moves the `_currentPage` variable forwards in the `_visitedPages` queue by the specified number of steps, if possible. 73 | 6. The `currentPage` getter returns the current page. 74 | 75 | The `DoubleLinkedQueue` is a suitable data structure for this problem because it allows us to efficiently add and remove elements from both the beginning and the end of the queue, which is necessary for the back and forward navigation functionality. -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a DoubleLinkedQueue 5 | var queue = DoubleLinkedQueue(); 6 | 7 | // Adding elements to the queue 8 | queue.addAll([1, 2, 3, 4, 5]); 9 | 10 | // Displaying the properties of the queue 11 | print('First element: ${queue.first}'); 12 | print('Last element: ${queue.last}'); 13 | print('Length of the queue: ${queue.length}'); 14 | print('Is queue empty: ${queue.isEmpty}'); 15 | print('Is queue not empty: ${queue.isNotEmpty}'); 16 | 17 | // Iterating over the queue 18 | print('Elements of the queue:'); 19 | for (var element in queue) { 20 | print(element); 21 | } 22 | } -------------------------------------------------------------------------------- /bin/collection/Queue/DoubleLinkedQueue/threadsafe.md: -------------------------------------------------------------------------------- 1 | 2 | # What is Threadsafe 3 | Thread-safety is a property of a data structure or algorithm that ensures its correct behavior and integrity when accessed by multiple threads concurrently. In other words, a thread-safe implementation guarantees that the data structure will not experience race conditions or other concurrency-related issues when accessed by multiple threads. 4 | 5 | Here's an example of a thread-safe `Counter` class using the `Queue` class in Dart: 6 | 7 | ```dart 8 | import 'dart:collection'; 9 | import 'dart:async'; 10 | 11 | class Counter { 12 | final _queue = Queue(); 13 | final _lock = Lock(); 14 | 15 | void increment() async { 16 | await _lock.acquire(); 17 | try { 18 | final currentValue = _queue.isEmpty ? 0 : _queue.last; 19 | _queue.addLast(currentValue + 1); 20 | } finally { 21 | _lock.release(); 22 | } 23 | } 24 | 25 | int get value { 26 | _lock.synchronized(() { 27 | return _queue.isEmpty ? 0 : _queue.last; 28 | }); 29 | } 30 | } 31 | 32 | void main() { 33 | final counter = Counter(); 34 | 35 | // Increment the counter from multiple threads 36 | final futures = []; 37 | for (int i = 0; i < 10; i++) { 38 | futures.add(Future(() => counter.increment())); 39 | } 40 | Future.wait(futures).then((_) { 41 | print('Final value: ${counter.value}'); // Output: Final value: 10 42 | }); 43 | } 44 | ``` 45 | 46 | In this example, the `Counter` class uses a `Queue` to store the values of the counter. The class also has a `_lock` object, which is an instance of the `Lock` class from the `dart:async` library. 47 | 48 | The `increment()` method is responsible for updating the counter value. It first acquires the lock using `_lock.acquire()`, which ensures that only one thread can access the critical section at a time. Inside the critical section, it retrieves the current value of the counter (or 0 if the queue is empty) and then adds the incremented value to the queue. 49 | 50 | The `value` getter is also synchronized using the `_lock.synchronized()` method, which ensures that the current value of the counter is always retrieved in a thread-safe manner. 51 | 52 | In the `main()` function, we create a `Counter` instance and increment the counter from 10 different threads using `Future.wait()`. The final value of the counter is then printed, which should always be 10 since the implementation is thread-safe. 53 | 54 | The key aspects that make this implementation thread-safe are: 55 | 56 | 1. The use of the `Queue` class, which is inherently thread-safe. 57 | 2. The use of the `Lock` class to protect the critical section of the `increment()` method. 58 | 3. The use of the `_lock.synchronized()` method to ensure thread-safe access to the `value` getter. 59 | 60 | By using these techniques, we can ensure that the `Counter` class can be safely accessed by multiple threads without the risk of race conditions or other concurrency-related issues. 61 | 62 | # ListQueue showing the it not thread-safe 63 | 64 | Sure, here's an example that demonstrates how `ListQueue` is not thread-safe in Dart: 65 | 66 | ```dart 67 | import 'dart:collection'; 68 | import 'dart:async'; 69 | 70 | class Counter { 71 | final _queue = ListQueue(); 72 | 73 | void increment() { 74 | final currentValue = _queue.isEmpty ? 0 : _queue.last; 75 | _queue.addLast(currentValue + 1); 76 | } 77 | 78 | int get value { 79 | return _queue.isEmpty ? 0 : _queue.last; 80 | } 81 | } 82 | 83 | void main() { 84 | final counter = Counter(); 85 | 86 | // Increment the counter from multiple threads 87 | final futures = []; 88 | for (int i = 0; i < 10; i++) { 89 | futures.add(Future(() => counter.increment())); 90 | } 91 | Future.wait(futures).then((_) { 92 | print('Final value: ${counter.value}'); // This may not always be 10 93 | }); 94 | } 95 | ``` 96 | 97 | In this example, we have a `Counter` class that uses a `ListQueue` to store the values of the counter. Unlike the previous example with `Queue`, we don't use a `Lock` to protect the critical section. 98 | 99 | In the `main()` function, we create a `Counter` instance and increment the counter from 10 different threads using `Future.wait()`. The final value of the counter is then printed. 100 | 101 | The issue with this implementation is that the `ListQueue` is not thread-safe, which means that multiple threads can access the same queue simultaneously, leading to race conditions and potentially incorrect results. 102 | 103 | For example, if two threads execute the `increment()` method at the same time, they may both read the same current value from the queue, increment it, and then add the new values to the queue. This could result in the final value being less than 10, as some of the increments may be lost. 104 | 105 | To demonstrate this, you can run the code several times and observe that the final value may not always be 10: 106 | 107 | ``` 108 | Final value: 10 109 | Final value: 9 110 | Final value: 8 111 | ``` 112 | 113 | This is because the `ListQueue` is not protected by any synchronization mechanism, and the concurrent access to the queue can lead to race conditions and incorrect results. 114 | 115 | To make this implementation thread-safe, you would need to use a synchronization mechanism, such as a `Lock` or a `Mutex`, to protect the critical sections of the `increment()` and `value` getter methods, similar to the previous example with the `Queue` class. -------------------------------------------------------------------------------- /bin/collection/Queue/ListQueue/constructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a ListQueue 5 | var queue = ListQueue(); 6 | 7 | // Add elements to the queue 8 | queue.add(1); 9 | queue.add(2); 10 | queue.add(3); 11 | queue.add(4); 12 | 13 | // Accessing properties 14 | print('First element: ${queue.first}'); 15 | print('Last element: ${queue.last}'); 16 | print('Length of the queue: ${queue.length}'); 17 | print('Is the queue empty? ${queue.isEmpty}'); 18 | print('Is the queue not empty? ${queue.isNotEmpty}'); 19 | 20 | // Converting the queue to a list 21 | var listFromQueue = queue.toList(); 22 | print('List from queue: $listFromQueue'); 23 | 24 | // Removing elements 25 | var removedElement = queue.removeFirst(); 26 | print('Removed element: $removedElement'); 27 | print('Queue after removing first element: $queue'); 28 | 29 | queue.remove(3); 30 | print('Queue after removing element 3: $queue'); 31 | 32 | // Clearing the queue 33 | queue.clear(); 34 | print('Queue after clearing: $queue'); 35 | } 36 | -------------------------------------------------------------------------------- /bin/collection/Queue/ListQueue/method.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a ListQueue 5 | var queue = ListQueue(); 6 | 7 | // Add elements to the queue 8 | queue.add(1); 9 | queue.add(2); 10 | queue.add(3); 11 | queue.add(4); 12 | 13 | print('Initial Queue: $queue'); 14 | 15 | // Adding elements using addAll 16 | queue.addAll([5, 6, 7]); 17 | print('Queue after addAll: $queue'); 18 | 19 | // Adding elements using addFirst 20 | queue.addFirst(0); 21 | print('Queue after addFirst: $queue'); 22 | 23 | // Adding elements using addLast 24 | queue.addLast(8); 25 | print('Queue after addLast: $queue'); 26 | 27 | // Checking if any element satisfies a condition 28 | var hasEven = queue.any((element) => element.isEven); 29 | print('Does the queue have any even number? $hasEven'); 30 | 31 | // Checking if all elements satisfy a condition 32 | var allPositive = queue.every((element) => element > 0); 33 | print('Are all elements in the queue positive? $allPositive'); 34 | 35 | // Removing an element 36 | var removedElement = queue.remove(5); 37 | print('Removed element: $removedElement, Queue after removing 5: $queue'); 38 | 39 | // Removing the first element 40 | var firstElement = queue.removeFirst(); 41 | print('Removed first element: $firstElement, Queue after removing first element: $queue'); 42 | 43 | // Removing the last element 44 | var lastElement = queue.removeLast(); 45 | print('Removed last element: $lastElement, Queue after removing last element: $queue'); 46 | 47 | // Removing elements that satisfy a condition 48 | queue.removeWhere((element) => element.isOdd); 49 | print('Queue after removing odd numbers: $queue'); 50 | 51 | // Retaining only elements that satisfy a condition 52 | queue.retainWhere((element) => element > 3); 53 | print('Queue after retaining elements greater than 3: $queue'); 54 | 55 | // Iterating over elements 56 | for (var element in queue) { 57 | print('Element: $element'); 58 | } 59 | 60 | // Converting the queue to a list 61 | var queueAsList = queue.toList(); 62 | print('Queue as list: $queueAsList'); 63 | } 64 | -------------------------------------------------------------------------------- /bin/collection/Queue/ListQueue/problem/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Initialize the printer queue 5 | var printerQueue = ListQueue(); 6 | 7 | // Users send print jobs 8 | addPrintJob(printerQueue, "Document1.pdf"); 9 | addPrintJob(printerQueue, "Presentation.pptx"); 10 | addPrintJob(printerQueue, "Photo.jpg"); 11 | addPrintJob(printerQueue, "UrgentContract.pdf", priority: true); 12 | 13 | // Process print jobs 14 | processPrintJobs(printerQueue); 15 | } 16 | 17 | // Function to add print jobs to the queue 18 | void addPrintJob(ListQueue queue, String job, {bool priority = false}) { 19 | if (priority) { 20 | queue.addFirst(job); // Add priority print job to the front of the queue 21 | } else { 22 | queue.add(job); // Add regular print job to the end of the queue 23 | } 24 | print("Added $job to print queue."); 25 | } 26 | 27 | // Function to process print jobs 28 | void processPrintJobs(ListQueue queue) { 29 | while (queue.isNotEmpty) { 30 | var currentJob = queue.removeFirst(); // Process the first print job 31 | print("Printing: $currentJob"); 32 | print("Remaining print jobs: ${queue.length}"); 33 | } 34 | } -------------------------------------------------------------------------------- /bin/collection/Queue/ListQueue/problem/problem1.md: -------------------------------------------------------------------------------- 1 | Sure! Let's consider a scenario where we need to simulate a printer queue system in a busy office environment. 2 | 3 | **Problem: Printer Queue Management** 4 | 5 | In a busy office, multiple users send print jobs to a shared printer. However, the printer can only handle one print job at a time. To manage the print queue efficiently, we can use a ListQueue. 6 | 7 | Here's how we can simulate this scenario using ListQueue: 8 | 9 | 1. **Initialization**: We create a ListQueue to represent the print queue. 10 | 11 | 2. **Adding Print Jobs**: As users send print jobs, we add them to the end of the print queue using the `add` method of ListQueue. 12 | 13 | 3. **Processing Print Jobs**: The printer can handle one print job at a time. So, we remove the first print job from the queue using the `removeFirst` method when the printer becomes available. We then process the print job and remove it from the queue. 14 | 15 | 4. **Monitoring Queue Status**: We can check the status of the print queue to see how many print jobs are waiting using properties like `isEmpty` and `length`. 16 | 17 | 5. **Handling Priority Print Jobs**: If there are priority print jobs that need to be processed before others, we can use methods like `addFirst` to add them to the front of the queue. 18 | 19 | **Example:** 20 | 21 | ```dart 22 | import 'dart:collection'; 23 | 24 | void main() { 25 | // Initialize the printer queue 26 | var printerQueue = ListQueue(); 27 | 28 | // Users send print jobs 29 | addPrintJob(printerQueue, "Document1.pdf"); 30 | addPrintJob(printerQueue, "Presentation.pptx"); 31 | addPrintJob(printerQueue, "Photo.jpg"); 32 | addPrintJob(printerQueue, "UrgentContract.pdf", priority: true); 33 | 34 | // Process print jobs 35 | processPrintJobs(printerQueue); 36 | } 37 | 38 | // Function to add print jobs to the queue 39 | void addPrintJob(ListQueue queue, String job, {bool priority = false}) { 40 | if (priority) { 41 | queue.addFirst(job); // Add priority print job to the front of the queue 42 | } else { 43 | queue.add(job); // Add regular print job to the end of the queue 44 | } 45 | print("Added $job to print queue."); 46 | } 47 | 48 | // Function to process print jobs 49 | void processPrintJobs(ListQueue queue) { 50 | while (queue.isNotEmpty) { 51 | var currentJob = queue.removeFirst(); // Process the first print job 52 | print("Printing: $currentJob"); 53 | print("Remaining print jobs: ${queue.length}"); 54 | } 55 | } 56 | ``` 57 | 58 | In this example, we simulate users sending print jobs (`Document1.pdf`, `Presentation.pptx`, `Photo.jpg`, `UrgentContract.pdf`). The urgent contract is added with priority to the front of the queue using `addFirst`. The `processPrintJobs` function simulates the printer processing each job by removing the first job from the queue and printing it. -------------------------------------------------------------------------------- /bin/collection/Queue/ListQueue/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a ListQueue 5 | var queue = ListQueue(); 6 | 7 | // Add elements to the queue 8 | queue.add(1); 9 | queue.add(2); 10 | queue.add(3); 11 | queue.add(4); 12 | 13 | // Accessing properties 14 | print('First element: ${queue.first}'); 15 | print('Last element: ${queue.last}'); 16 | print('Length of the queue: ${queue.length}'); 17 | print('Is the queue empty? ${queue.isEmpty}'); 18 | print('Is the queue not empty? ${queue.isNotEmpty}'); 19 | 20 | // Converting the queue to a list 21 | var listFromQueue = queue.toList(); 22 | print('List from queue: $listFromQueue'); 23 | 24 | // Removing elements 25 | var removedElement = queue.removeFirst(); 26 | print('Removed element: $removedElement'); 27 | print('Queue after removing first element: $queue'); 28 | 29 | queue.remove(3); 30 | print('Queue after removing element 3: $queue'); 31 | 32 | // Clearing the queue 33 | queue.clear(); 34 | print('Queue after clearing: $queue'); 35 | } 36 | -------------------------------------------------------------------------------- /bin/collection/Queue/Queue/constructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a queue using the default constructor 5 | Queue queue1 = Queue(); 6 | print('Queue created using default constructor: $queue1'); 7 | 8 | // Creating a queue from an iterable using the `from` constructor 9 | Iterable iterable = [1, 2, 3, 4, 5]; 10 | Queue queue2 = Queue.from(iterable); 11 | print('Queue created from an iterable: $queue2'); 12 | 13 | // Creating a queue from a typed iterable using the `of` constructor 14 | Iterable typedIterable = [6, 7, 8, 9, 10]; 15 | Queue queue3 = Queue.of(typedIterable); 16 | print('Queue created from a typed iterable: $queue3'); 17 | } 18 | -------------------------------------------------------------------------------- /bin/collection/Queue/Queue/method.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a queue 5 | Queue queue = Queue.from([1, 2, 3, 4, 5]); 6 | 7 | // Adding elements 8 | queue.add(6); 9 | print('Queue after adding 6: $queue'); 10 | 11 | queue.addAll([7, 8, 9]); 12 | print('Queue after adding [7, 8, 9]: $queue'); 13 | 14 | queue.addFirst(0); 15 | print('Queue after adding 0 at the beginning: $queue'); 16 | 17 | queue.addLast(10); 18 | print('Queue after adding 10 at the end: $queue'); 19 | 20 | // Checking 21 | print('Does the queue contain 5? ${queue.contains(5)}'); 22 | print('Index of element 3: ${queue.elementAt(2)}'); 23 | 24 | // Removing elements 25 | queue.remove(5); 26 | print('Queue after removing 5: $queue'); 27 | 28 | queue.removeFirst(); 29 | print('Queue after removing the first element: $queue'); 30 | 31 | queue.removeLast(); 32 | print('Queue after removing the last element: $queue'); 33 | 34 | queue.removeWhere((element) => element % 2 == 0); 35 | print('Queue after removing even numbers: $queue'); 36 | 37 | // Iterating 38 | for (var element in queue) { 39 | print('Element: $element'); 40 | } 41 | 42 | // Clearing the queue 43 | queue.clear(); 44 | print('Queue after clearing: $queue'); 45 | } 46 | -------------------------------------------------------------------------------- /bin/collection/Queue/Queue/problem/problem1.md: -------------------------------------------------------------------------------- 1 | Real-life Problem: Supermarket Checkout Queue Management 2 | 3 | Problem Description: 4 | In a supermarket, customers arrive at different times and join the checkout queue to purchase their items. However, the supermarket management wants to optimize the checkout process to minimize customer waiting times and improve overall efficiency. 5 | 6 | Solution Using Queue: 7 | A queue data structure can be used to manage the checkout process effectively. Each customer who arrives at the checkout counter joins the queue, and they are served in a first-come-first-serve manner. Here's how the queue can be utilized to solve this real-life problem: 8 | 9 | 1. Arrival of Customers: As customers arrive at the checkout counters, their details (such as name, number of items, etc.) are added to the queue. 10 | 11 | 2. Serving Customers: The cashier serves the customer at the front of the queue. The customer's items are scanned and processed, and they are removed from the queue once the transaction is complete. 12 | 13 | 3. Efficient Management: By using a queue, the supermarket can ensure that customers are served in the order they arrived, minimizing waiting times and ensuring fairness in service. 14 | 15 | 4. Handling Multiple Checkout Counters: If there are multiple checkout counters, each counter can have its own queue. Customers are directed to the shortest queue, ensuring that all counters are utilized efficiently. 16 | 17 | 5. Priority Handling: The queue can also be modified to prioritize certain types of customers, such as elderly or disabled individuals, by allowing them to move to the front of the queue. 18 | 19 | 6. Dynamic Queue Length: The length of the queue can vary based on factors such as the time of day, day of the week, or special events. The queue can expand or contract dynamically to accommodate changes in customer traffic. 20 | 21 | By implementing a queue-based system for managing checkout queues in supermarkets, the management can streamline the checkout process, improve customer satisfaction, and optimize operational efficiency. -------------------------------------------------------------------------------- /bin/collection/Queue/Queue/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a queue 5 | Queue queue = Queue.from([1, 2, 3, 4, 5]); 6 | 7 | // Accessing properties 8 | print('Queue: $queue'); 9 | print('First element: ${queue.first}'); 10 | print('Last element: ${queue.last}'); 11 | print('Length of the queue: ${queue.length}'); 12 | print('Is the queue empty? ${queue.isEmpty}'); 13 | print('Is the queue not empty? ${queue.isNotEmpty}'); 14 | print('Runtime type of the queue: ${queue.runtimeType}'); 15 | 16 | // Modifying the queue 17 | queue.add(6); 18 | print('Queue after adding an element: $queue'); 19 | queue.removeFirst(); 20 | print('Queue after removing the first element: $queue'); 21 | } 22 | -------------------------------------------------------------------------------- /bin/collection/Queue/queue.md: -------------------------------------------------------------------------------- 1 | A Queue in Dart is a collection that allows manipulation at both ends. It supports operations like adding and removing elements, iterating over its elements, and checking properties like whether it is empty or not. Modifying a queue while iterating over it can lead to issues and is generally not recommended to avoid breaking the iteration process. 2 | 3 | ### Implemented Types: 4 | - Queue 5 | - Implementers 6 | - Available Extensions 7 | 8 | ### Constructors: 9 | - Queue(): Creates a queue. 10 | - Queue.from(Iterable elements): Creates a queue containing all elements. 11 | - Queue.of(Iterable elements): Creates a queue from elements. 12 | 13 | ### Properties: 14 | - first → E: Represents the first element. 15 | - hashCode → int: Hash code for the object. 16 | - isEmpty → bool: Indicates if the collection has no elements. 17 | - isNotEmpty → bool: Indicates if the collection has at least one element. 18 | - iterator → Iterator: Allows iterating the elements. 19 | - last → E: Represents the last element. 20 | - length → int: Number of elements in the queue. 21 | - runtimeType → Type: Represents the runtime type of the object. 22 | - single → E: Returns the single element if the iterable has only one element. 23 | 24 | ### Methods: 25 | - add(E value): Adds a value at the end of the queue. 26 | - addAll(Iterable iterable): Adds all elements of an iterable to the queue. 27 | - addFirst(E value): Adds a value at the beginning of the queue. 28 | - addLast(E value): Adds a value at the end of the queue. 29 | - clear(): Removes all elements in the queue. 30 | - contains(Object? element): Checks if the collection contains a specific element. 31 | - elementAt(int index): Returns the element at a specific index. 32 | - and more methods for operations like filtering, transforming, and reducing elements in the queue. 33 | 34 | ### Operators: 35 | - operator ==(Object other): The equality operator. 36 | 37 | In summary, a Queue in Dart is a versatile data structure that allows efficient manipulation of elements at both ends, providing a range of methods for adding, removing, and processing elements within the queue. 38 | 39 | Here's a table summarizing the constructors, properties, and methods of the `Queue` class in Dart along with their functionalities: 40 | 41 | | **Constructors** | **Description** | 42 | |-----------------------------------------------|---------------------------------------------------------| 43 | | `Queue()` | Creates an empty queue. | 44 | | `Queue.from(Iterable elements)` | Creates a queue containing all elements of the iterable. | 45 | | `Queue.of(Iterable elements)` | Creates a queue from the given iterable elements. | 46 | 47 | | **Properties** | **Description** | 48 | |----------------------------------------------|---------------------------------------------------------| 49 | | `first` | Returns the first element of the queue. | 50 | | `last` | Returns the last element of the queue. | 51 | | `length` | Returns the number of elements in the queue. | 52 | | `isEmpty` | Returns `true` if the queue is empty, `false` otherwise. | 53 | | `isNotEmpty` | Returns `true` if the queue is not empty, `false` otherwise. | 54 | 55 | | **Methods** | **Description** | 56 | |----------------------------------------------|---------------------------------------------------------| 57 | | `add(E value)` | Adds a value at the end of the queue. | 58 | | `addAll(Iterable iterable)` | Adds all elements of the iterable at the end of the queue. | 59 | | `addFirst(E value)` | Adds a value at the beginning of the queue. | 60 | | `addLast(E value)` | Adds a value at the end of the queue. | 61 | | `remove(Object? value)` | Removes a single instance of the specified value from the queue. | 62 | | `removeFirst()` | Removes and returns the first element of the queue. | 63 | | `removeLast()` | Removes and returns the last element of the queue. | 64 | | `removeWhere(bool test(E element))` | Removes all elements that satisfy the test condition. | 65 | | `elementAt(int index)` | Returns the element at the specified index. | 66 | | `clear()` | Removes all elements from the queue. | 67 | 68 | These are the constructors, properties, and methods of the `Queue` class in Dart along with their respective functionalities. -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/constructors.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Using the default constructor 5 | final defaultHashSet = HashSet(); 6 | 7 | // Using the HashSet.from constructor with an iterable 8 | final iterableHashSet = HashSet.from(['apple', 'banana', 'orange']); 9 | 10 | // Using the HashSet.identity constructor 11 | final identityHashSet = HashSet.identity(); 12 | 13 | // Using the HashSet.of constructor with an iterable 14 | final ofHashSet = HashSet.of(['dog', 'cat', 'bird']); 15 | 16 | // Add elements to the defaultHashSet 17 | defaultHashSet.addAll(['one', 'two', 'three']); 18 | 19 | // Display elements in each HashSet 20 | print('defaultHashSet: $defaultHashSet'); 21 | print('iterableHashSet: $iterableHashSet'); 22 | print('identityHashSet: $identityHashSet'); 23 | print('ofHashSet: $ofHashSet'); 24 | } 25 | -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/hashset.md: -------------------------------------------------------------------------------- 1 | # HashSet in Dart 2 | 3 | A `HashSet` is a built-in Dart class that represents a collection of unordered, unique items. It is part of Dart's `dart:collection` library. 4 | 5 | ## Creating a HashSet 6 | 7 | There are several ways to create a `HashSet` in Dart: 8 | 9 | ### Default Constructor 10 | 11 | The default constructor creates an empty `HashSet`. 12 | 13 | ```dart 14 | final defaultHashSet = HashSet(); 15 | ``` 16 | 17 | ### HashSet.from 18 | 19 | The `HashSet.from` constructor creates a `HashSet` from an iterable. The `HashSet` will contain all elements from the iterable, but only unique elements will be kept. 20 | 21 | ```dart 22 | final iterableHashSet = HashSet.from(['apple', 'banana', 'orange']); 23 | ``` 24 | 25 | ### HashSet.identity 26 | 27 | The `HashSet.identity` constructor creates an empty `HashSet` that uses identity of elements for equality and hash code generation. 28 | 29 | ```dart 30 | final identityHashSet = HashSet.identity(); 31 | ``` 32 | 33 | ### HashSet.of 34 | 35 | The `HashSet.of` constructor creates a `HashSet` from an iterable. The `HashSet` will contain all elements from the iterable, but only unique elements will be kept. 36 | 37 | ```dart 38 | final ofHashSet = HashSet.of(['dog', 'cat', 'bird']); 39 | ``` 40 | 41 | ## Adding Elements 42 | 43 | You can add elements to a `HashSet` using the `add` or `addAll` methods. 44 | 45 | ```dart 46 | defaultHashSet.addAll(['one', 'two', 'three']); 47 | ``` 48 | 49 | ## Displaying Elements 50 | 51 | You can display all elements in a `HashSet` by printing it. 52 | 53 | ```dart 54 | print('defaultHashSet: $defaultHashSet'); 55 | ``` 56 | 57 | This will print all elements in the `HashSet` to the console. 58 | 59 | ## Summary 60 | 61 | A `HashSet` is a useful data structure when you need a collection of unique items. It provides several constructors for creating a `HashSet` and methods for adding elements and displaying the `HashSet`. -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/mehods.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a HashSet 5 | final hashSet = HashSet(); 6 | 7 | // Add elements to the set 8 | hashSet.addAll([1, 2, 3, 4, 5]); 9 | 10 | // Print the elements of the set 11 | print('Initial set: $hashSet'); 12 | 13 | // Add a single element to the set 14 | hashSet.add(6); 15 | print('After adding 6: $hashSet'); 16 | 17 | // Add multiple elements to the set 18 | hashSet.addAll([7, 8, 9]); 19 | print('After adding 7, 8, 9: $hashSet'); 20 | 21 | // Check if the set contains a specific value 22 | print('Does the set contain 3? ${hashSet.contains(3)}'); 23 | 24 | // Check if the set contains all elements of another iterable 25 | final containsAll = hashSet.containsAll([2, 4, 6]); 26 | print('Does the set contain all elements of [2, 4, 6]? $containsAll'); 27 | 28 | // Remove a single element from the set 29 | hashSet.remove(5); 30 | print('After removing 5: $hashSet'); 31 | 32 | // Remove multiple elements from the set 33 | hashSet.removeAll([7, 8]); 34 | print('After removing 7, 8: $hashSet'); 35 | 36 | // Remove elements that satisfy a condition 37 | hashSet.removeWhere((element) => element.isEven); 38 | print('After removing even elements: $hashSet'); 39 | 40 | // Retain elements that satisfy a condition 41 | hashSet.retainWhere((element) => element < 4); 42 | print('After retaining elements less than 4: $hashSet'); 43 | 44 | // Remove all elements from the set 45 | hashSet.clear(); 46 | print('After clearing the set: $hashSet'); 47 | } 48 | -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/problesm/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class SocialMediaApp { 4 | HashSet registeredUsernames = HashSet(); 5 | 6 | // Method to register a new user 7 | void registerUser(String username) { 8 | if (!registeredUsernames.contains(username)) { 9 | registeredUsernames.add(username); 10 | print('Registration successful for username: $username'); 11 | } else { 12 | print('Username "$username" is already taken. Please choose a different one.'); 13 | } 14 | } 15 | } 16 | 17 | void main() { 18 | SocialMediaApp socialMediaApp = SocialMediaApp(); 19 | 20 | // Registering new users 21 | socialMediaApp.registerUser('john_doe'); // Registration successful 22 | socialMediaApp.registerUser('jane_doe'); // Registration successful 23 | socialMediaApp.registerUser('john_doe'); // Username "john_doe" is already taken 24 | socialMediaApp.registerUser('john_smith'); // Registration successful 25 | } -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/problesm/problem1.md: -------------------------------------------------------------------------------- 1 | Sure! Let's consider a real-life problem where we need to manage a list of unique usernames in a social media application. We can use a `HashSet` to efficiently handle this task. 2 | 3 | Problem: 4 | In a social media application, we need to ensure that each user has a unique username when they register. Users can attempt to register with usernames that are already taken, and we need to check if a username is available or not. 5 | 6 | Solution using HashSet: 7 | We can use a `HashSet` to store all the registered usernames. When a user attempts to register with a new username, we can quickly check if the username is already in use by looking it up in the `HashSet`. If the username is not found, it means it's available, and the user can proceed with registration. If the username is found, it means it's already taken, and the user needs to choose a different username. 8 | 9 | Example: 10 | 11 | ```dart 12 | import 'dart:collection'; 13 | 14 | class SocialMediaApp { 15 | HashSet registeredUsernames = HashSet(); 16 | 17 | // Method to register a new user 18 | void registerUser(String username) { 19 | if (!registeredUsernames.contains(username)) { 20 | registeredUsernames.add(username); 21 | print('Registration successful for username: $username'); 22 | } else { 23 | print('Username "$username" is already taken. Please choose a different one.'); 24 | } 25 | } 26 | } 27 | 28 | void main() { 29 | SocialMediaApp socialMediaApp = SocialMediaApp(); 30 | 31 | // Registering new users 32 | socialMediaApp.registerUser('john_doe'); // Registration successful 33 | socialMediaApp.registerUser('jane_doe'); // Registration successful 34 | socialMediaApp.registerUser('john_doe'); // Username "john_doe" is already taken 35 | socialMediaApp.registerUser('john_smith'); // Registration successful 36 | } 37 | ``` 38 | 39 | In this example, the `HashSet` `registeredUsernames` stores all registered usernames. The `registerUser` method checks if the provided username already exists in the `HashSet`. If it doesn't exist, the username is added to the `HashSet`, indicating a successful registration. If the username already exists, the method notifies the user that the username is already taken. -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/problesm/problem2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class CommunityCenter { 4 | // HashMap to store program memberships where key is program name and value is HashSet of member IDs 5 | HashMap> programMemberships = HashMap>(); 6 | 7 | // Method to enroll member in a program 8 | void enrollMember(String programName, int memberId) { 9 | // Check if program exists in HashMap, if not, create a new HashSet for the program 10 | if (!programMemberships.containsKey(programName)) { 11 | programMemberships[programName] = HashSet(); 12 | } 13 | 14 | // Get the HashSet of member IDs for the program 15 | HashSet members = programMemberships[programName]!; 16 | 17 | // Check if member ID is already enrolled in the program 18 | if (!members.contains(memberId)) { 19 | members.add(memberId); 20 | print('Enrollment successful for member ID $memberId in program: $programName'); 21 | } else { 22 | print('Member ID $memberId is already enrolled in program: $programName'); 23 | } 24 | } 25 | } 26 | 27 | void main() { 28 | CommunityCenter center = CommunityCenter(); 29 | 30 | // Enrolling members in programs 31 | center.enrollMember('Fitness Classes', 1001); // Enrollment successful 32 | center.enrollMember('Fitness Classes', 1002); // Enrollment successful 33 | center.enrollMember('Art Workshops', 1001); // Enrollment successful 34 | center.enrollMember('Fitness Classes', 1001); // Member ID 1001 is already enrolled 35 | center.enrollMember('Language Courses', 1003); // Enrollment successful 36 | 37 | // Displaying program memberships 38 | print(center.programMemberships); 39 | } -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/problesm/problem2.md: -------------------------------------------------------------------------------- 1 | Let's consider a more complex real-life problem where we need to manage memberships for a community center. The community center offers various programs and activities, and members can enroll in multiple programs. However, we need to ensure that each member's enrollment is unique across all programs to avoid duplication. 2 | 3 | Problem: 4 | A community center offers multiple programs such as fitness classes, art workshops, and language courses. Members can enroll in one or more programs based on their interests. The center needs to manage memberships efficiently and ensure that each member is enrolled only once in each program. 5 | 6 | Solution using HashSet: 7 | We can use a `HashSet` to manage memberships for each program. Each program will have its `HashSet` containing unique member IDs. When a member enrolls in a program, the system checks if the member ID is already present in the program's `HashSet`. If it's not found, the member ID is added to the set, indicating a successful enrollment. If the member ID is found, it means the member is already enrolled, and no action is taken. 8 | 9 | Example: 10 | 11 | ```dart 12 | import 'dart:collection'; 13 | 14 | class CommunityCenter { 15 | // HashMap to store program memberships where key is program name and value is HashSet of member IDs 16 | HashMap> programMemberships = HashMap>(); 17 | 18 | // Method to enroll member in a program 19 | void enrollMember(String programName, int memberId) { 20 | // Check if program exists in HashMap, if not, create a new HashSet for the program 21 | if (!programMemberships.containsKey(programName)) { 22 | programMemberships[programName] = HashSet(); 23 | } 24 | 25 | // Get the HashSet of member IDs for the program 26 | HashSet members = programMemberships[programName]!; 27 | 28 | // Check if member ID is already enrolled in the program 29 | if (!members.contains(memberId)) { 30 | members.add(memberId); 31 | print('Enrollment successful for member ID $memberId in program: $programName'); 32 | } else { 33 | print('Member ID $memberId is already enrolled in program: $programName'); 34 | } 35 | } 36 | } 37 | 38 | void main() { 39 | CommunityCenter center = CommunityCenter(); 40 | 41 | // Enrolling members in programs 42 | center.enrollMember('Fitness Classes', 1001); // Enrollment successful 43 | center.enrollMember('Fitness Classes', 1002); // Enrollment successful 44 | center.enrollMember('Art Workshops', 1001); // Enrollment successful 45 | center.enrollMember('Fitness Classes', 1001); // Member ID 1001 is already enrolled 46 | center.enrollMember('Language Courses', 1003); // Enrollment successful 47 | 48 | // Displaying program memberships 49 | print(center.programMemberships); 50 | } 51 | ``` 52 | 53 | In this example, the `HashMap` `programMemberships` stores memberships for each program, where the key is the program name and the value is a `HashSet` containing unique member IDs. The `enrollMember` method checks if the program exists in the HashMap and creates a new HashSet if it doesn't. It then checks if the member ID is already enrolled in the program and adds it to the HashSet if not. Finally, it displays the program memberships after enrolling members. -------------------------------------------------------------------------------- /bin/collection/Set/HashSet/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a HashSet 5 | final hashSet = HashSet(); 6 | 7 | // Check if the set is empty 8 | print('Is the set empty? ${hashSet.isEmpty}'); 9 | 10 | // Add elements to the set 11 | hashSet.addAll([1, 2, 3, 4, 5]); 12 | 13 | // Print the first element 14 | print('First element: ${hashSet.first}'); 15 | 16 | // Print the last element 17 | print('Last element: ${hashSet.last}'); 18 | 19 | // Print the number of elements in the set 20 | print('Number of elements: ${hashSet.length}'); 21 | 22 | // Check if the set is not empty 23 | print('Is the set not empty? ${hashSet.isNotEmpty}'); 24 | 25 | // Create an iterator and print all elements 26 | final iterator = hashSet.iterator; 27 | while (iterator.moveNext()) { 28 | print('Current element: ${iterator.current}'); 29 | } 30 | 31 | // Convert the set to a list and print it 32 | final listFromSet = hashSet.toList(); 33 | print('List from set: $listFromSet'); 34 | 35 | // Convert the set to a set (no effect) and print it 36 | final setFromSet = hashSet.toSet(); 37 | print('Set from set: $setFromSet'); 38 | 39 | // Print the type of the set 40 | print('Type of set: ${hashSet.runtimeType}'); 41 | } 42 | -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/LinkedHashSet.md: -------------------------------------------------------------------------------- 1 | A `LinkedHashSet` in Dart is a special type of set that preserves the order of elements as they were inserted. It combines the features of a hash-table based set with the ability to maintain insertion order, making it suitable for scenarios where both uniqueness and order are important. 2 | 3 | ### Features of LinkedHashSet: 4 | 5 | 1. **Insertion Order Preservation**: Elements are stored in the order they were inserted. Iterating over a `LinkedHashSet` will always return elements in the order they were added. 6 | 7 | 2. **Uniqueness**: Like other sets, `LinkedHashSet` ensures that each element is unique. If you try to add an element that already exists, it will not be added again. 8 | 9 | 3. **Efficient Operations**: Basic set operations such as adding, removing, and checking for the presence of an element are done in constant time, similar to a regular `HashSet`. 10 | 11 | ### Example Usage: 12 | 13 | ```dart 14 | import 'dart:collection'; 15 | 16 | void main() { 17 | // Create a LinkedHashSet of integers 18 | LinkedHashSet numbers = LinkedHashSet(); 19 | 20 | // Add elements to the set 21 | numbers.add(5); 22 | numbers.addAll([10, 15, 20]); 23 | 24 | // Print the set 25 | print(numbers); // Output: {5, 10, 15, 20} 26 | 27 | // Check if set contains a specific element 28 | print(numbers.contains(10)); // Output: true 29 | 30 | // Remove an element from the set 31 | numbers.remove(15); 32 | print(numbers); // Output: {5, 10, 20} 33 | 34 | // Iterate over the set (preserves insertion order) 35 | for (int num in numbers) { 36 | print(num); // Output: 5, 10, 20 37 | } 38 | } 39 | ``` 40 | 41 | ### Use Cases: 42 | 43 | 1. **Maintaining Order**: When you need to preserve the order in which elements were added, such as maintaining the order of user actions in an application. 44 | 45 | 2. **Removing Duplicates**: If you have a list of items where duplicates are common but you also need to maintain the original order, you can use a `LinkedHashSet` to remove duplicates while preserving order. 46 | 47 | 3. **Caching**: In scenarios where you need to cache recent items and also access them in the order they were cached, a `LinkedHashSet` can be used to efficiently manage the cache. 48 | 49 | Overall, `LinkedHashSet` provides a convenient way to manage collections of unique elements while preserving insertion order, making it a valuable tool in various Dart applications.A `LinkedHashSet` in Dart is a special type of set that preserves the order of elements as they were inserted. It combines the features of a hash-table based set with the ability to maintain insertion order, making it suitable for scenarios where both uniqueness and order are important. 50 | 51 | -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/constructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // 1. Using the default constructor 5 | LinkedHashSet set1 = LinkedHashSet(); 6 | 7 | // 2. Using LinkedHashSet.from constructor with an Iterable 8 | List elements = [1, 2, 3, 4, 5]; 9 | LinkedHashSet set2 = LinkedHashSet.from(elements); 10 | 11 | // 3. Using LinkedHashSet.identity constructor 12 | LinkedHashSet set3 = LinkedHashSet.identity(); 13 | 14 | // 4. Using LinkedHashSet.of constructor with individual elements 15 | LinkedHashSet set4 = LinkedHashSet.of([6, 7, 8, 9, 10]); 16 | 17 | // Displaying the contents of each set 18 | print("Set 1: $set1"); 19 | print("Set 2: $set2"); 20 | print("Set 3: $set3"); 21 | print("Set 4: $set4"); 22 | } 23 | -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/methods.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a LinkedHashSet 5 | LinkedHashSet linkedHashSet = LinkedHashSet(); 6 | 7 | // Adding elements to the set 8 | linkedHashSet.add("Apple"); 9 | linkedHashSet.add("Banana"); 10 | linkedHashSet.add("Orange"); 11 | 12 | // Printing the initial set 13 | print("Initial LinkedHashSet: $linkedHashSet"); 14 | 15 | // Methods 16 | 17 | // 1. add() 18 | linkedHashSet.add("Mango"); 19 | print("LinkedHashSet after adding Mango: $linkedHashSet"); 20 | 21 | // 2. addAll() 22 | linkedHashSet.addAll(["Grapes", "Pineapple"]); 23 | print("LinkedHashSet after adding Grapes and Pineapple: $linkedHashSet"); 24 | 25 | // 3. contains() 26 | print("Is Orange in the LinkedHashSet? ${linkedHashSet.contains("Orange")}"); // true 27 | 28 | // 4. remove() 29 | linkedHashSet.remove("Banana"); 30 | print("LinkedHashSet after removing Banana: $linkedHashSet"); 31 | 32 | // 5. removeAll() 33 | linkedHashSet.removeAll(["Apple", "Mango"]); 34 | print("LinkedHashSet after removing Apple and Mango: $linkedHashSet"); 35 | 36 | // 6. retainAll() 37 | linkedHashSet.retainAll(["Grapes", "Pineapple"]); 38 | print("LinkedHashSet after retaining Grapes and Pineapple: $linkedHashSet"); 39 | 40 | // 7. clear() 41 | linkedHashSet.clear(); 42 | print("LinkedHashSet after clearing: $linkedHashSet"); 43 | 44 | // 8. isEmpty() and isNotEmpty() 45 | print("Is the LinkedHashSet empty? ${linkedHashSet.isEmpty}"); // true 46 | print("Is the LinkedHashSet not empty? ${linkedHashSet.isNotEmpty}"); // false 47 | } 48 | -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/problem/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class MusicPlaylist { 4 | LinkedHashSet playlist = LinkedHashSet(); 5 | 6 | // Method to add a song to the playlist 7 | void addSong(String song) { 8 | if (!playlist.contains(song)) { 9 | playlist.add(song); 10 | print("$song has been added to the playlist."); 11 | } else { 12 | print("$song is already in the playlist."); 13 | } 14 | } 15 | 16 | // Method to remove a song from the playlist 17 | void removeSong(String song) { 18 | if (playlist.contains(song)) { 19 | playlist.remove(song); 20 | print("$song has been removed from the playlist."); 21 | } else { 22 | print("$song is not in the playlist."); 23 | } 24 | } 25 | 26 | // Method to display the playlist 27 | void displayPlaylist() { 28 | if (playlist.isEmpty) { 29 | print("Playlist is empty."); 30 | } else { 31 | print("Current Playlist:"); 32 | for (var song in playlist) { 33 | print("- $song"); 34 | } 35 | } 36 | } 37 | } 38 | 39 | void main() { 40 | MusicPlaylist playlistManager = MusicPlaylist(); 41 | 42 | // Adding songs to the playlist 43 | playlistManager.addSong("Song A"); 44 | playlistManager.addSong("Song B"); 45 | playlistManager.addSong("Song C"); 46 | 47 | // Displaying the playlist 48 | playlistManager.displayPlaylist(); 49 | 50 | // Adding a duplicate song 51 | playlistManager.addSong("Song B"); 52 | 53 | // Removing a song from the playlist 54 | playlistManager.removeSong("Song C"); 55 | 56 | // Displaying the updated playlist 57 | playlistManager.displayPlaylist(); 58 | } -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/problem/problem1.md: -------------------------------------------------------------------------------- 1 | Let's consider a real-life problem of managing a playlist for a music streaming service. In a playlist, the order of songs is crucial, as users expect songs to be played in the sequence they added them. We can use a `LinkedHashSet` to maintain the playlist, ensuring that songs are stored in the order they were added, and there are no duplicate songs. 2 | 3 | Here's how we can implement this problem: 4 | 5 | ```dart 6 | import 'dart:collection'; 7 | 8 | class MusicPlaylist { 9 | LinkedHashSet playlist = LinkedHashSet(); 10 | 11 | // Method to add a song to the playlist 12 | void addSong(String song) { 13 | if (!playlist.contains(song)) { 14 | playlist.add(song); 15 | print("$song has been added to the playlist."); 16 | } else { 17 | print("$song is already in the playlist."); 18 | } 19 | } 20 | 21 | // Method to remove a song from the playlist 22 | void removeSong(String song) { 23 | if (playlist.contains(song)) { 24 | playlist.remove(song); 25 | print("$song has been removed from the playlist."); 26 | } else { 27 | print("$song is not in the playlist."); 28 | } 29 | } 30 | 31 | // Method to display the playlist 32 | void displayPlaylist() { 33 | if (playlist.isEmpty) { 34 | print("Playlist is empty."); 35 | } else { 36 | print("Current Playlist:"); 37 | playlist.forEach((song) => print("- $song")); 38 | } 39 | } 40 | } 41 | 42 | void main() { 43 | MusicPlaylist playlistManager = MusicPlaylist(); 44 | 45 | // Adding songs to the playlist 46 | playlistManager.addSong("Song A"); 47 | playlistManager.addSong("Song B"); 48 | playlistManager.addSong("Song C"); 49 | 50 | // Displaying the playlist 51 | playlistManager.displayPlaylist(); 52 | 53 | // Adding a duplicate song 54 | playlistManager.addSong("Song B"); 55 | 56 | // Removing a song from the playlist 57 | playlistManager.removeSong("Song C"); 58 | 59 | // Displaying the updated playlist 60 | playlistManager.displayPlaylist(); 61 | } 62 | ``` 63 | 64 | In this example, we create a `MusicPlaylist` class with methods to add, remove, and display songs in the playlist. We use a `LinkedHashSet` to store the songs, ensuring that the order of insertion is maintained and duplicates are automatically ignored. This allows us to manage the playlist efficiently, ensuring that songs are played in the correct order without any duplicates. -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/problem/problem2.md: -------------------------------------------------------------------------------- 1 | Let's consider a real-life problem where we need to manage the attendance of students in a classroom. We want to keep track of the students who attended the class on a particular day. We'll use a `LinkedHashSet` to store the names of the students who attended, ensuring that the order of insertion is maintained. 2 | 3 | ```dart 4 | import 'dart:collection'; 5 | 6 | void main() { 7 | // Creating a LinkedHashSet to store attendance 8 | LinkedHashSet attendance = LinkedHashSet(); 9 | 10 | // Function to mark attendance 11 | void markAttendance(String studentName) { 12 | attendance.add(studentName); 13 | print("$studentName marked present."); 14 | } 15 | 16 | // Simulating students attending the class 17 | markAttendance("John"); 18 | markAttendance("Alice"); 19 | markAttendance("Bob"); 20 | markAttendance("Emma"); 21 | 22 | // Printing the attendance list 23 | print("\nAttendance for the day:"); 24 | attendance.forEach((student) => print(student)); 25 | 26 | // Checking if a student is present 27 | String studentToCheck = "Alice"; 28 | print("\nIs $studentToCheck present? ${attendance.contains(studentToCheck) ? "Yes" : "No"}"); 29 | 30 | // Removing a student from attendance 31 | String studentToRemove = "Bob"; 32 | attendance.remove(studentToRemove); 33 | print("\n$studentToRemove has been removed from attendance."); 34 | 35 | // Printing the updated attendance list 36 | print("\nUpdated Attendance:"); 37 | attendance.forEach((student) => print(student)); 38 | } 39 | ``` 40 | 41 | In this example, we simulate students attending a class by calling the `markAttendance()` function for each student. The function adds the student's name to the `LinkedHashSet` representing the attendance. We then print out the attendance list. 42 | 43 | Later, we demonstrate checking whether a specific student is present in the class and remove a student from the attendance list. Finally, we print the updated attendance list. 44 | 45 | Using a `LinkedHashSet` for this problem ensures that the order in which students arrived is maintained, which can be useful for various analytics or administrative purposes. -------------------------------------------------------------------------------- /bin/collection/Set/LinkedHashSet/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Creating a LinkedHashSet 5 | LinkedHashSet linkedHashSet = LinkedHashSet(); 6 | 7 | // Adding elements to the set 8 | linkedHashSet.add("Apple"); 9 | linkedHashSet.add("Banana"); 10 | linkedHashSet.add("Orange"); 11 | 12 | // Printing the properties of the LinkedHashSet 13 | print("Elements in the LinkedHashSet: $linkedHashSet"); 14 | 15 | // 1. Properties 16 | print("First element: ${linkedHashSet.first}"); 17 | print("Last element: ${linkedHashSet.last}"); 18 | print("Length of the LinkedHashSet: ${linkedHashSet.length}"); 19 | print("Is the LinkedHashSet empty? ${linkedHashSet.isEmpty}"); 20 | print("Is the LinkedHashSet not empty? ${linkedHashSet.isNotEmpty}"); 21 | 22 | // 2. Iterating over the LinkedHashSet 23 | print("Iterating over the LinkedHashSet:"); 24 | for (var element in linkedHashSet) { 25 | print(element); 26 | } 27 | 28 | // 3. Accessing elements by index (not supported in LinkedHashSet) 29 | // Uncommenting the following line will result in a compile-time error 30 | // print("Element at index 1: ${linkedHashSet[1]}"); 31 | } 32 | -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/constructor.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | import 'dart:collection'; 4 | 5 | void main() { 6 | // Create a SplayTreeSet with a custom compare function 7 | final customCompareSet = SplayTreeSet((a, b) => a.compareTo(b)); 8 | customCompareSet.addAll(['banana', 'apple', 'orange']); 9 | print(customCompareSet); // {apple, banana, orange} 10 | 11 | // Create a SplayTreeSet from an existing iterable 12 | final fromIterableSet = SplayTreeSet.from(['dog', 'cat', 'bird']); 13 | print(fromIterableSet); // {bird, cat, dog} 14 | 15 | // Create a SplayTreeSet from elements directly 16 | final ofElementsSet = SplayTreeSet.of(['summer', 'winter', 'spring']); 17 | print(ofElementsSet); // {spring, summer, winter} 18 | } -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/methods.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a SplayTreeSet 5 | final splayTreeSet = SplayTreeSet(); 6 | 7 | // Methods 8 | 9 | /// Method 1: add 10 | /// Adds the specified [element] to the set. 11 | splayTreeSet.add(5); 12 | splayTreeSet.addAll([2, 8, 1, 10]); 13 | 14 | /// Method 2: any 15 | /// Checks if any element in the set satisfies the given [test]. 16 | final anyElement = splayTreeSet.any((element) => element % 2 == 0); 17 | print('Does any element satisfy the condition? $anyElement'); 18 | 19 | /// Method 3: clear 20 | /// Removes all elements from the set. 21 | splayTreeSet.clear(); 22 | print('After clearing, the set is empty: ${splayTreeSet.isEmpty}'); 23 | 24 | /// Method 4: contains 25 | /// Checks if the set contains the specified [element]. 26 | final containsElement = splayTreeSet.contains(5); 27 | print('Does the set contain 5? $containsElement'); 28 | 29 | /// Method 5: containsAll 30 | /// Checks if the set contains all the elements in the specified [collection]. 31 | final containsAllElements = splayTreeSet.containsAll([2, 8]); 32 | print('Does the set contain all elements [2, 8]? $containsAllElements'); 33 | 34 | /// Method 6: difference 35 | /// Returns a new set with the elements that are in this set but not in the [other] set. 36 | final differenceSet = splayTreeSet.difference({2, 8}); 37 | print('Difference set: $differenceSet'); 38 | 39 | /// Method 7: elementAt 40 | /// Returns the element at the specified [index] in the set. 41 | final elementAt = splayTreeSet.elementAt(0); 42 | print('Element at index 0: $elementAt'); 43 | 44 | /// Method 8: every 45 | /// Checks if every element in the set satisfies the given [test]. 46 | final everyElement = splayTreeSet.every((element) => element < 20); 47 | print('Are all elements less than 20? $everyElement'); 48 | 49 | /// Method 9: expand 50 | /// Expands each element of the set into zero or more elements. 51 | final expandedSet = splayTreeSet.expand((element) => [element, element + 1]); 52 | print('Expanded set: $expandedSet'); 53 | 54 | /// Method 10: firstWhere 55 | /// Returns the first element that satisfies the given [test]. 56 | /// If no element satisfies the test, returns the result of [orElse]. 57 | final firstWhereElement = splayTreeSet.firstWhere((element) => element > 5, orElse: () => -1); 58 | print('First element greater than 5: $firstWhereElement'); 59 | 60 | /// Method 11: fold 61 | /// Combines the elements of the set using the specified [combine] function. 62 | final foldedValue = splayTreeSet.fold(0, (previousValue, element) => previousValue + element); 63 | print('Sum of all elements: $foldedValue'); 64 | 65 | /// Method 12: forEach 66 | /// Applies the specified [action] to each element in the set. 67 | for (var element in splayTreeSet) { 68 | print('Element: $element'); 69 | } 70 | 71 | /// Method 13: intersection 72 | /// Returns a new set with the elements that are common to both this set and the [other] set. 73 | final intersectionSet = splayTreeSet.intersection({5, 8}); 74 | print('Intersection set: $intersectionSet'); 75 | 76 | /// Method 14: join 77 | /// Converts each element to a [String] and concatenates them using the specified [separator]. 78 | final joinedElements = splayTreeSet.join(', '); 79 | print('Joined elements: $joinedElements'); 80 | 81 | /// Method 15: lastWhere 82 | /// Returns the last element that satisfies the given [test]. 83 | /// If no element satisfies the test, returns the result of [orElse]. 84 | final lastWhereElement = splayTreeSet.lastWhere((element) => element < 5, orElse: () => -1); 85 | print('Last element less than 5: $lastWhereElement'); 86 | 87 | /// Method 16: lookup 88 | /// Returns the element in the set that is equal to the specified [object]. 89 | final lookupElement = splayTreeSet.lookup(5); 90 | print('Element lookup for 5: $lookupElement'); 91 | 92 | /// Method 17: map 93 | /// Applies the specified [transform] function to each element in the set and returns a new set with the results. 94 | final mappedSet = splayTreeSet.map((element) => element * 2); 95 | print('Mapped set: $mappedSet'); 96 | 97 | /// Method 18: reduce 98 | /// Combines the elements of the set using the specified [combine] function. 99 | final reducedValue = splayTreeSet.reduce((value, element) => value + element); 100 | print('Reduced value: $reducedValue'); 101 | 102 | /// Method 19: remove 103 | /// Removes the specified [element] from the set. 104 | final removedElement = splayTreeSet.remove(5); 105 | print('Removed element 5: $removedElement'); 106 | 107 | /// Method 20: removeAll 108 | /// Removes all elements in the specified [collection] from the set. 109 | splayTreeSet.removeAll([2, 8]); 110 | print('After removing all elements [2, 8], the set is: $splayTreeSet'); 111 | 112 | /// Method 21: removeWhere 113 | /// Removes all elements that satisfy the given [test] from the set. 114 | splayTreeSet.removeWhere((element) => element % 2 != 0); 115 | print('After removing odd elements, the set is: $splayTreeSet'); 116 | 117 | /// Method 22: retainAll 118 | /// Removes all elements from the set that are not in the specified [collection]. 119 | splayTreeSet.retainAll([1, 10]); 120 | print('After retaining elements [1, 10], the set is: $splayTreeSet'); 121 | 122 | /// Method 23: retainWhere 123 | /// Removes all elements that do not satisfy the given [test] from the set. 124 | splayTreeSet.retainWhere((element) => element < 10); 125 | print('After retaining elements less than 10, the set is: $splayTreeSet'); 126 | 127 | /// Method 24: singleWhere 128 | /// Returns the single element that satisfies the given [test]. 129 | /// If no element satisfies the test or more than one element satisfies the test, throws an exception. 130 | try { 131 | final singleWhereElement = splayTreeSet.singleWhere((element) => element == 1); 132 | print('Single element where element equals 1: $singleWhereElement'); 133 | } catch (e) { 134 | print('Exception thrown: $e'); 135 | } 136 | 137 | /// Method 25: skip 138 | /// Returns a new set with the first [count] elements skipped. 139 | final skippedSet = splayTreeSet.skip(2); 140 | print('Skipped set: $skippedSet'); 141 | 142 | /// Method 26: skipWhile 143 | /// Returns a new set with the leading elements skipped while they satisfy the given [test]. 144 | final skippedWhileSet = splayTreeSet.skipWhile((element) => element < 5); 145 | print('Skipped while set: $skippedWhileSet'); 146 | 147 | /// Method 27: take 148 | /// Returns a new set with the first [count] elements taken. 149 | final takenSet = splayTreeSet.take(2); 150 | print('Taken set: $takenSet'); 151 | 152 | /// Method 28: takeWhile 153 | /// Returns a new set with the leading elements taken while they satisfy the given [test]. 154 | final takenWhileSet = splayTreeSet.takeWhile((element) => element < 5); 155 | print('Taken while set: $takenWhileSet'); 156 | 157 | /// Method 29: toList 158 | /// Returns a new list containing all the elements of the set in the same order. 159 | final list = splayTreeSet.toList(); 160 | print('Converted set to list: $list'); 161 | 162 | /// Method 30: toSet 163 | /// Returns a new set containing all the elements of the set. 164 | final set = splayTreeSet.toSet(); 165 | print('Converted set to another set: $set'); 166 | 167 | /// Method 31: union 168 | /// Returns a new set with the elements that are in either this set or the [other] set. 169 | final unionSet = splayTreeSet.union({5, 8}); 170 | print('Union set: $unionSet'); 171 | 172 | /// Method 32: where 173 | /// Returns a new set with all elements that satisfy the given [test]. 174 | final whereSet = splayTreeSet.where((element) => element > 5); 175 | print('Filtered set: $whereSet'); 176 | } 177 | -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/problem/problem1.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class Player { 4 | final String name; 5 | int score; 6 | 7 | Player(this.name, this.score); 8 | 9 | @override 10 | String toString() => '$name: $score'; 11 | } 12 | int findRank(SplayTreeSet leaderboard, Player targetPlayer) { 13 | int rank = 1; 14 | for (var player in leaderboard) { 15 | if (player == targetPlayer) { 16 | return rank; 17 | } 18 | rank++; 19 | } 20 | return -1; // return -1 if the player is not found 21 | } 22 | void main() { 23 | // Create a SplayTreeSet to store players sorted by score 24 | final leaderboard = SplayTreeSet( 25 | (a, b) => a.score != b.score ? b.score.compareTo(a.score) : a.name.compareTo(b.name), 26 | ); 27 | 28 | // Add initial players 29 | leaderboard.addAll([ 30 | Player('Alice', 100), 31 | Player('Bob', 90), 32 | Player('Charlie', 80), 33 | Player('David', 70), 34 | ]); 35 | 36 | // Update player scores 37 | leaderboard.firstWhere((player) => player.name == 'Bob').score = 95; 38 | leaderboard.firstWhere((player) => player.name == 'David').score = 85; 39 | 40 | // Find top 3 players 41 | final topPlayers = leaderboard.take(3).toList(); 42 | print('Top 3 Players: $topPlayers'); 43 | 44 | // Find rank of a player 45 | final player = leaderboard.firstWhere((player) => player.name == 'Alice'); 46 | final rank = findRank(leaderboard, player); 47 | print('Rank of ${player.name}: $rank'); 48 | } -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/problem/problem1.md: -------------------------------------------------------------------------------- 1 | **Problem:** Maintaining a Leaderboard with Dynamic Scores 2 | 3 | **Description:** 4 | You're developing a leaderboard system for an online game where players' scores change frequently based on their performance. The leaderboard needs to be dynamically updated whenever a player's score changes, and it should efficiently handle queries like finding the top N players or finding a player's rank. 5 | 6 | **Solution using `SplayTreeSet`:** 7 | A `SplayTreeSet` is particularly suitable for this problem due to its ability to efficiently maintain a sorted set of elements and perform operations like finding the minimum or maximum element, and finding elements within a specific range. 8 | 9 | 1. **Insertion and Update:** When a player's score changes, you can update their score in the `SplayTreeSet`. The set automatically maintains the sorted order based on the scores. 10 | 11 | 2. **Finding Top N Players:** You can efficiently find the top N players by iterating over the last N elements of the `SplayTreeSet`, which represent the players with the highest scores. 12 | 13 | 3. **Finding Player's Rank:** To find a player's rank, you can use the `indexOf` method of the `SplayTreeSet` to get the index of the player's score in the sorted set. The rank can be calculated by subtracting the index from the total number of players. 14 | 15 | **Why `SplayTreeSet` is suitable:** 16 | 1. **Efficient Sorting:** `SplayTreeSet` automatically maintains the sorted order of elements, making it efficient to find the top players or players within a specific range of scores. 17 | 18 | 2. **Dynamic Updates:** As player scores change frequently, `SplayTreeSet` allows for efficient insertion and removal of elements, ensuring that the leaderboard stays updated in real-time. 19 | 20 | 3. **Balanced Tree Structure:** The underlying self-balancing binary tree structure of `SplayTreeSet` ensures efficient performance for operations like insertion, deletion, and retrieval, making it suitable for dynamic leaderboard management. 21 | 22 | **Example:** 23 | ```dart 24 | import 'dart:collection'; 25 | 26 | class Player { 27 | final String name; 28 | int score; 29 | 30 | Player(this.name, this.score); 31 | 32 | @override 33 | String toString() => '$name: $score'; 34 | } 35 | 36 | void main() { 37 | // Create a SplayTreeSet to store players sorted by score 38 | final leaderboard = SplayTreeSet( 39 | (a, b) => a.score != b.score ? b.score.compareTo(a.score) : a.name.compareTo(b.name), 40 | ); 41 | 42 | // Add initial players 43 | leaderboard.addAll([ 44 | Player('Alice', 100), 45 | Player('Bob', 90), 46 | Player('Charlie', 80), 47 | Player('David', 70), 48 | ]); 49 | 50 | // Update player scores 51 | leaderboard.firstWhere((player) => player.name == 'Bob').score = 95; 52 | leaderboard.firstWhere((player) => player.name == 'David').score = 85; 53 | 54 | // Find top 3 players 55 | final topPlayers = leaderboard.take(3).toList(); 56 | print('Top 3 Players: $topPlayers'); 57 | 58 | // Find rank of a player 59 | final player = leaderboard.firstWhere((player) => player.name == 'Alice'); 60 | final rank = leaderboard.indexOf(player) + 1; 61 | print('Rank of ${player.name}: $rank'); 62 | } 63 | ``` 64 | 65 | In this example, the `Player` class represents each player with a name and score. Players are stored in a `SplayTreeSet` sorted by their scores. As players' scores change, their scores are updated in the set, and the leaderboard is dynamically maintained. The `SplayTreeSet` efficiently handles operations like finding the top players and calculating a player's rank. -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/problem/problem2.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | class Event { 4 | final String name; 5 | final DateTime startTime; 6 | final DateTime endTime; 7 | 8 | Event(this.name, this.startTime, this.endTime); 9 | } 10 | 11 | void main() { 12 | // Create a SplayTreeSet to store events sorted by start time 13 | final eventSet = SplayTreeSet( 14 | (a, b) => a.startTime.compareTo(b.startTime), 15 | ); 16 | 17 | // Add events 18 | eventSet.addAll([ 19 | Event('Event 1', DateTime(2024, 4, 1, 10, 0), DateTime(2024, 4, 1, 12, 0)), 20 | Event('Event 2', DateTime(2024, 4, 1, 11, 0), DateTime(2024, 4, 1, 13, 0)), 21 | Event('Event 3', DateTime(2024, 4, 1, 14, 0), DateTime(2024, 4, 1, 15, 0)), 22 | ]); 23 | 24 | // Check for overlaps 25 | bool hasOverlap = false; 26 | Event? previousEvent; 27 | for (var event in eventSet) { 28 | if (previousEvent != null && event.startTime.isBefore(previousEvent.endTime)) { 29 | hasOverlap = true; 30 | print('Overlap detected between ${previousEvent.name} and ${event.name}'); 31 | } 32 | previousEvent = event; 33 | } 34 | if (!hasOverlap) { 35 | print('No overlaps detected.'); 36 | } 37 | 38 | // Retrieve events within a time range 39 | final startTime = DateTime(2024, 4, 1, 10, 0); 40 | final endTime = DateTime(2024, 4, 1, 13, 0); 41 | final eventsInRange = eventSet 42 | .where((event) => event.startTime.isAfter(startTime) && event.endTime.isBefore(endTime)) 43 | .toList(); 44 | print('Events within time range: $eventsInRange'); 45 | } -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/problem/problem2.md: -------------------------------------------------------------------------------- 1 | Sure! Here's a real-life problem that can be solved using a `SplayTreeSet`: 2 | 3 | **Problem:** Managing Event Schedules 4 | 5 | **Description:** 6 | Imagine you're developing a scheduling application for a conference or a series of events. Each event has a start time and an end time, and you need to efficiently manage these events to ensure there are no conflicts in the schedule. You want to quickly identify if there's any overlap between events and efficiently retrieve events within a specific time range. 7 | 8 | **Solution using `SplayTreeSet`:** 9 | You can use a `SplayTreeSet` to store the events sorted by their start time. This allows you to easily find events that start after a given time, making it efficient to check for overlaps and retrieve events within a specific time range. 10 | 11 | 1. **Insertion:** When adding events to the set, you can insert them based on their start time. The `SplayTreeSet` automatically maintains the sorted order of events by their start time. 12 | 13 | 2. **Overlap Detection:** To check for overlaps, you can use the `lowerBound` and `upperBound` methods of the `SplayTreeSet` to find events that start before or after a given time. If an event's start time is before the end time of another event, there's an overlap. 14 | 15 | 3. **Retrieval within Time Range:** You can efficiently retrieve events within a specific time range by finding the events that start after the start time of the range and before the end time of the range. 16 | 17 | **Example:** 18 | ```dart 19 | import 'dart:collection'; 20 | 21 | class Event { 22 | final String name; 23 | final DateTime startTime; 24 | final DateTime endTime; 25 | 26 | Event(this.name, this.startTime, this.endTime); 27 | } 28 | 29 | void main() { 30 | // Create a SplayTreeSet to store events sorted by start time 31 | final eventSet = SplayTreeSet( 32 | (a, b) => a.startTime.compareTo(b.startTime), 33 | ); 34 | 35 | // Add events 36 | eventSet.addAll([ 37 | Event('Event 1', DateTime(2024, 4, 1, 10, 0), DateTime(2024, 4, 1, 12, 0)), 38 | Event('Event 2', DateTime(2024, 4, 1, 11, 0), DateTime(2024, 4, 1, 13, 0)), 39 | Event('Event 3', DateTime(2024, 4, 1, 14, 0), DateTime(2024, 4, 1, 15, 0)), 40 | ]); 41 | 42 | // Check for overlaps 43 | bool hasOverlap = false; 44 | Event previousEvent; 45 | for (var event in eventSet) { 46 | if (previousEvent != null && event.startTime.isBefore(previousEvent.endTime)) { 47 | hasOverlap = true; 48 | print('Overlap detected between ${previousEvent.name} and ${event.name}'); 49 | } 50 | previousEvent = event; 51 | } 52 | if (!hasOverlap) { 53 | print('No overlaps detected.'); 54 | } 55 | 56 | // Retrieve events within a time range 57 | final startTime = DateTime(2024, 4, 1, 10, 0); 58 | final endTime = DateTime(2024, 4, 1, 13, 0); 59 | final eventsInRange = eventSet 60 | .where((event) => event.startTime.isAfter(startTime) && event.endTime.isBefore(endTime)) 61 | .toList(); 62 | print('Events within time range: $eventsInRange'); 63 | } 64 | ``` 65 | 66 | In this example, the `Event` class represents each event with a name, start time, and end time. Events are added to the `SplayTreeSet` sorted by their start time. The program then checks for overlaps between events and retrieves events within a specific time range efficiently using the `SplayTreeSet`. -------------------------------------------------------------------------------- /bin/collection/Set/SplayTreeSet/propertis.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a SplayTreeSet 5 | final splayTreeSet = SplayTreeSet(); 6 | 7 | // Properties 8 | splayTreeSet.addAll([5, 2, 8, 1, 10]); // Adding elements to the set 9 | 10 | // Property 1: first 11 | final firstElement = splayTreeSet.first; 12 | print('First element: $firstElement'); 13 | 14 | // Property 2: isEmpty 15 | final isEmpty = splayTreeSet.isEmpty; 16 | print('Is the set empty? $isEmpty'); 17 | 18 | // Property 3: isNotEmpty 19 | final isNotEmpty = splayTreeSet.isNotEmpty; 20 | print('Is the set not empty? $isNotEmpty'); 21 | 22 | // Property 4: iterator 23 | final iterator = splayTreeSet.iterator; 24 | print('Iterator: $iterator'); 25 | 26 | // Property 5: last 27 | final lastElement = splayTreeSet.last; 28 | print('Last element: $lastElement'); 29 | 30 | // Property 6: length 31 | final length = splayTreeSet.length; 32 | print('Length of the set: $length'); 33 | 34 | // Property 7: runtimeType 35 | final runtimeType = splayTreeSet.runtimeType; 36 | print('Runtime type of the set: $runtimeType'); 37 | 38 | // Property 8: single 39 | try { 40 | final singleElement = splayTreeSet.single; 41 | print('Single element: $singleElement'); 42 | } catch (e) { 43 | print('Exception thrown: $e'); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /bin/collection/Set/UnmodifiableSetView/UnmodifiableSetView.md: -------------------------------------------------------------------------------- 1 | The `UnmodifiableSetView` class in Dart is designed to provide an unmodifiable view of another set, preventing modifications like adding or removing elements. This class inherits properties and methods from the `Set` class but restricts operations that could alter the set. When creating an `UnmodifiableSetView`, changes to the original set reflect in the view, maintaining consistency. Key features of the `UnmodifiableSetView` class include: 2 | 3 | - **Inheritance**: Inherits properties and methods from the `Set` class. 4 | - **Constructors**: Provides a constructor to create an `UnmodifiableSetView` from a source set. 5 | - **Properties**: Includes properties like `first`, `last`, `length`, and more for accessing set elements and information. 6 | - **Methods**: Offers methods such as `contains`, `difference`, `intersection`, `map`, and others for set operations, ensuring immutability. 7 | 8 | The `UnmodifiableSetView` class is crucial for scenarios where a read-only view of a set is required to prevent unintended modifications. By leveraging this class, developers can ensure data integrity and immutability in their applications, enhancing reliability and predictability in set operations. 9 | 10 | 11 | 12 | Here's a table summarizing the constructors, properties, and methods of the `UnmodifiableSetView` class in Dart along with brief descriptions of what they do: 13 | 14 | | Type | Name | Description | 15 | |-------------|--------------------------|-------------------------------------------------------------------------------------------------| 16 | | Constructor | `UnmodifiableSetView` | Creates an UnmodifiableSetView of the provided source Set. | 17 | | Property | `first` | Returns the first element of the set. | 18 | | Property | `hashCode` | Returns the hash code for this object. | 19 | | Property | `isEmpty` | Returns true if the set contains no elements. | 20 | | Property | `isNotEmpty` | Returns true if the set contains at least one element. | 21 | | Property | `iterator` | Returns an iterator that iterates over the elements of the set. | 22 | | Property | `last` | Returns the last element of the set. | 23 | | Property | `length` | Returns the number of elements in the set. | 24 | | Property | `runtimeType` | Returns a representation of the runtime type of the object. | 25 | | Property | `single` | Checks that the set has only one element, and returns that element. | 26 | | Method | `add` | Adds an element to the set. **Not supported by an unmodifiable set**. | 27 | | Method | `addAll` | Adds all elements from the provided iterable to the set. **Not supported by an unmodifiable set**.| 28 | | Method | `any` | Checks whether any element of the set satisfies the provided test. | 29 | | Method | `cast` | Provides a view of the set as a set of elements of a different type. | 30 | | Method | `clear` | Removes all elements from the set. **Not supported by an unmodifiable set**. | 31 | | Method | `contains` | Checks if the set contains the provided element. | 32 | | Method | `containsAll` | Checks if the set contains all elements from the provided iterable. | 33 | | Method | `difference` | Creates a new set with elements from this set that are not in the provided set. | 34 | | Method | `elementAt` | Returns the element at the specified index. | 35 | | Method | `every` | Checks whether every element of the set satisfies the provided test. | 36 | | Method | `expand` | Expands each element of the set into zero or more elements. | 37 | | Method | `firstWhere` | Returns the first element of the set that satisfies the provided test. | 38 | | Method | `fold` | Reduces the set to a single value by iteratively combining elements. | 39 | | Method | `followedBy` | Creates the lazy concatenation of this set and another iterable. | 40 | | Method | `forEach` | Invokes a function on each element of the set. | 41 | | Method | `intersection` | Creates a new set which is the intersection between this set and another set. | 42 | | Method | `join` | Converts each element to a string and concatenates the strings. | 43 | | Method | `lastWhere` | Returns the last element of the set that satisfies the provided test. | 44 | | Method | `lookup` | If an object equal to the provided object is in the set, returns it. | 45 | | Method | `map` | Returns a new set with each element modified by the provided function. | 46 | | Method | `reduce` | Reduces the set to a single value by iteratively combining elements. | 47 | | Method | `remove` | Removes the provided element from the set. **Not supported by an unmodifiable set**. | 48 | | Method | `removeAll` | Removes all elements from the set that are also in the provided iterable. | 49 | | Method | `removeWhere` | Removes all elements of the set that satisfy the provided test. **Not supported by an unmodifiable set**.| 50 | | Method | `retainAll` | Retains only the elements of the set that are also in the provided iterable. **Not supported by an unmodifiable set**.| 51 | | Method | `retainWhere` | Removes all elements of the set that do not satisfy the provided test. **Not supported by an unmodifiable set**.| 52 | | Method | `singleWhere` | Returns the single element of the set that satisfies the provided test. Throws StateError if none or more than one element satisfies the test.| 53 | | Method | `skip` | Creates an iterable that skips the specified number of elements. | 54 | | Method | `skipWhile` | Creates an iterable that skips elements while the provided test is satisfied. | 55 | | Method | `take` | Creates an iterable with the specified number of elements. | 56 | | Method | `takeWhile` | Creates an iterable with elements taken from the beginning until the provided test is no longer satisfied.| 57 | | Method | `toList` | Converts the set to a list. | 58 | | Method | `toSet` | Creates a new set with the same elements and behavior as this set. | 59 | | Method | `union` | Creates a new set with all elements from this set and another set. | 60 | | Method | `where` | Creates an iterable with elements that satisfy the provided test. | 61 | | Method | `whereType` | Creates an iterable with elements that have the specified type. | 62 | 63 | This table provides an overview of the functionality provided by each constructor, property, and method of the `UnmodifiableSetView` class, helping developers understand how to use this class effectively in their Dart applications. -------------------------------------------------------------------------------- /bin/collection/Set/UnmodifiableSetView/constructor.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Constructor 1: Create an UnmodifiableSetView from an existing set 5 | final baseSet = {'apple', 'banana', 'orange'}; 6 | final unmodifiableSetView1 = UnmodifiableSetView(baseSet); 7 | print('Unmodifiable Set View 1: $unmodifiableSetView1'); 8 | 9 | // Constructor 2: Create an UnmodifiableSetView from an empty set 10 | final emptySet = {}; 11 | final unmodifiableSetView2 = UnmodifiableSetView(emptySet); 12 | print('Unmodifiable Set View 2: $unmodifiableSetView2'); 13 | 14 | // Constructor 3: Create an UnmodifiableSetView from an iterable 15 | final iterable = ['cat', 'dog', 'fish']; 16 | final unmodifiableSetView3 = UnmodifiableSetView(iterable.toSet()); 17 | print('Unmodifiable Set View 3: $unmodifiableSetView3'); 18 | 19 | // Constructor 4: Create an UnmodifiableSetView from another UnmodifiableSetView 20 | final unmodifiableSetView4 = UnmodifiableSetView(unmodifiableSetView3); 21 | print('Unmodifiable Set View 4: $unmodifiableSetView4'); 22 | } 23 | -------------------------------------------------------------------------------- /bin/collection/Set/UnmodifiableSetView/method.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a base set 5 | final baseSet = {'apple', 'banana', 'orange'}; 6 | 7 | // Create an UnmodifiableSetView from the base set 8 | final unmodifiableSetView = UnmodifiableSetView(baseSet); 9 | 10 | // Methods 11 | 12 | // 1. add 13 | // This operation is not supported by an unmodifiable set. 14 | // unmodifiableSetView.add('pear'); 15 | 16 | // 2. addAll 17 | // This operation is not supported by an unmodifiable set. 18 | // unmodifiableSetView.addAll(['grape', 'kiwi']); 19 | 20 | // 3. any 21 | print('Any orange: ${unmodifiableSetView.any((element) => element == 'orange')}'); 22 | 23 | // 4. cast 24 | final castedSet = unmodifiableSetView.cast(); 25 | print('Casted set: $castedSet'); 26 | 27 | // 5. clear 28 | // This operation is not supported by an unmodifiable set. 29 | // unmodifiableSetView.clear(); 30 | 31 | // 6. contains 32 | print('Contains banana: ${unmodifiableSetView.contains('banana')}'); 33 | 34 | // 7. containsAll 35 | print('Contains all [apple, banana]: ${unmodifiableSetView.containsAll(['apple', 'banana'])}'); 36 | 37 | // 8. difference 38 | final differenceSet = unmodifiableSetView.difference({'apple'}); 39 | print('Difference set: $differenceSet'); 40 | 41 | // 9. elementAt 42 | print('Element at index 1: ${unmodifiableSetView.elementAt(1)}'); 43 | 44 | // 10. every 45 | print('Every element contains "a": ${unmodifiableSetView.every((element) => element.contains('a'))}'); 46 | 47 | // 11. expand 48 | final expandedSet = unmodifiableSetView.expand((element) => element.split('')); 49 | print('Expanded set: $expandedSet'); 50 | 51 | // 12. firstWhere 52 | print('First element containing "a": ${unmodifiableSetView.firstWhere((element) => element.contains('a'))}'); 53 | 54 | // 13. fold 55 | final foldedValue = unmodifiableSetView.fold(0, (previousValue, element) => previousValue + element.length); 56 | print('Folded value: $foldedValue'); 57 | 58 | // 14. followedBy 59 | final followedBySet = unmodifiableSetView.followedBy({'grape'}); 60 | print('Followed by set: $followedBySet'); 61 | 62 | // 15. forEach 63 | for (var element in unmodifiableSetView) { 64 | print('Element: $element'); 65 | } 66 | 67 | // 16. intersection 68 | final intersectionSet = unmodifiableSetView.intersection({'apple', 'orange'}); 69 | print('Intersection set: $intersectionSet'); 70 | 71 | // 17. join 72 | final joinedString = unmodifiableSetView.join(', '); 73 | print('Joined string: $joinedString'); 74 | 75 | // 18. lastWhere 76 | print('Last element containing "a": ${unmodifiableSetView.lastWhere((element) => element.contains('a'))}'); 77 | 78 | // 19. map 79 | final mappedSet = unmodifiableSetView.map((element) => element.toUpperCase()); 80 | print('Mapped set: $mappedSet'); 81 | 82 | // 20. reduce 83 | final reducedValue = unmodifiableSetView.reduce((value, element) => value + element); 84 | print('Reduced value: $reducedValue'); 85 | 86 | // 21. remove 87 | // This operation is not supported by an unmodifiable set. 88 | // unmodifiableSetView.remove('banana'); 89 | 90 | // 22. removeAll 91 | // This operation is not supported by an unmodifiable set. 92 | // unmodifiableSetView.removeAll({'apple', 'banana'}); 93 | 94 | // 23. removeWhere 95 | // This operation is not supported by an unmodifiable set. 96 | // unmodifiableSetView.removeWhere((element) => element.length < 6); 97 | 98 | // 24. retainAll 99 | // This operation is not supported by an unmodifiable set. 100 | // unmodifiableSetView.retainAll({'banana', 'orange'}); 101 | 102 | // 25. retainWhere 103 | // This operation is not supported by an unmodifiable set. 104 | // unmodifiableSetView.retainWhere((element) => element.contains('a')); 105 | 106 | // 26. singleWhere 107 | // Throws StateError if no or more than one element satisfy the condition 108 | try { 109 | print('Single element containing "e": ${unmodifiableSetView.singleWhere((element) => element.contains('e'))}'); 110 | } catch (e) { 111 | print('Error: $e'); 112 | } 113 | 114 | // 27. skip 115 | final skippedSet = unmodifiableSetView.skip(1); 116 | print('Skipped set: $skippedSet'); 117 | 118 | // 28. skipWhile 119 | final skippedWhileSet = unmodifiableSetView.skipWhile((element) => element != 'banana'); 120 | print('Skipped while set: $skippedWhileSet'); 121 | 122 | // 29. take 123 | final takenSet = unmodifiableSetView.take(2); 124 | print('Taken set: $takenSet'); 125 | 126 | // 30. takeWhile 127 | final takenWhileSet = unmodifiableSetView.takeWhile((element) => element != 'banana'); 128 | print('Taken while set: $takenWhileSet'); 129 | 130 | // 31. toList 131 | final listFromSet = unmodifiableSetView.toList(); 132 | print('List from set: $listFromSet'); 133 | 134 | // 32. toSet 135 | final setFromSet = unmodifiableSetView.toSet(); 136 | print('Set from set: $setFromSet'); 137 | 138 | // 33. union 139 | final unionSet = unmodifiableSetView.union({'grape'}); 140 | print('Union set: $unionSet'); 141 | 142 | // 34. where 143 | final filteredSet = unmodifiableSetView.where((element) => element.length > 5); 144 | print('Filtered set: $filteredSet'); 145 | 146 | // 35. whereType 147 | final whereTypeSet = unmodifiableSetView.whereType(); 148 | print('Where type set: $whereTypeSet'); 149 | } 150 | -------------------------------------------------------------------------------- /bin/collection/Set/UnmodifiableSetView/properties.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // Create a base set 5 | final baseSet = {'apple', 'banana', 'orange'}; 6 | 7 | // Create an UnmodifiableSetView from the base set 8 | final unmodifiableSetView = UnmodifiableSetView(baseSet); 9 | 10 | // Properties 11 | 12 | // 1. first 13 | print('First element: ${unmodifiableSetView.first}'); 14 | 15 | // 2. hashCode 16 | print('Hash code: ${unmodifiableSetView.hashCode}'); 17 | 18 | // 3. isEmpty 19 | print('Is empty: ${unmodifiableSetView.isEmpty}'); 20 | 21 | // 4. isNotEmpty 22 | print('Is not empty: ${unmodifiableSetView.isNotEmpty}'); 23 | 24 | // 5. iterator 25 | print('Iterator:'); 26 | for (var element in unmodifiableSetView) { 27 | print(element); 28 | } 29 | 30 | // 6. last 31 | print('Last element: ${unmodifiableSetView.last}'); 32 | 33 | // 7. length 34 | print('Length: ${unmodifiableSetView.length}'); 35 | 36 | // 8. runtimeType 37 | print('Runtime type: ${unmodifiableSetView.runtimeType}'); 38 | 39 | // 9. single 40 | // Throws StateError if the set contains more than one element 41 | try { 42 | print('Single element: ${unmodifiableSetView.single}'); 43 | } catch (e) { 44 | print('Error: $e'); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /bin/collection/developer/classes.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xeron56/dart_programming/cef55e6513226c6c9707c0fb461720cdce7b1b48/bin/collection/developer/classes.dart -------------------------------------------------------------------------------- /bin/collection/math/classes.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | // Random 5 | var random = Random(); 6 | int intValue = random.nextInt(100); 7 | double doubleValue = random.nextDouble(); 8 | bool boolValue = random.nextBool(); 9 | print('Random int: $intValue'); 10 | print('Random double: $doubleValue'); 11 | print('Random bool: $boolValue'); 12 | 13 | // Point 14 | Point point1 = const Point(10.5, 20.3); 15 | Point point2 = const Point(50, 75); 16 | print('Point1: ($point1.x, $point1.y)'); 17 | print('Point2: ($point2.x, $point2.y)'); 18 | 19 | // Rectangle 20 | Point point1Double = Point(point1.x.toDouble(), point1.y.toDouble()); 21 | Point point2Double = Point(point2.x.toDouble(), point2.y.toDouble()); 22 | Rectangle rectangle1 = Rectangle.fromPoints(point1Double, point2Double); 23 | Rectangle rectangle2 = const Rectangle(20, 50, 100, 200); 24 | print('Rectangle1: (${rectangle1.left}, ${rectangle1.top}) ${rectangle1.width} x ${rectangle1.height}'); 25 | print('Rectangle2: (${rectangle2.left}, ${rectangle2.top}) ${rectangle2.width} x ${rectangle2.height}'); 26 | 27 | // MutableRectangle 28 | MutableRectangle mutableRectangle = MutableRectangle(20.5, 50.2, 100.0, 200.0); 29 | print('Mutable Rectangle: (${mutableRectangle.left}, ${mutableRectangle.top}) ${mutableRectangle.width} x ${mutableRectangle.height}'); 30 | mutableRectangle.width = 150.0; 31 | mutableRectangle.height = 300.0; 32 | print('Mutable Rectangle (updated): (${mutableRectangle.left}, ${mutableRectangle.top}) ${mutableRectangle.width} x ${mutableRectangle.height}'); 33 | 34 | // Math functions 35 | double angle = pi / 4; 36 | double sine = sin(angle); 37 | double cosine = cos(angle); 38 | double tangent = tan(angle); 39 | double arcSine = asin(sine); 40 | double arcCosine = acos(cosine); 41 | double arcTangent = atan(tangent); 42 | double arcTangent2 = atan2(sine, cosine); 43 | double exponential = exp(2.0); 44 | double logarithm = log(exponential); 45 | //double max = max(10, 20); 46 | //double min = min(10, 20); 47 | num power = pow(2.0, 3.0); 48 | double squareRoot = sqrt(16.0); 49 | print('Sine: $sine'); 50 | print('Cosine: $cosine'); 51 | print('Tangent: $tangent'); 52 | print('Arc Sine: $arcSine'); 53 | print('Arc Cosine: $arcCosine'); 54 | print('Arc Tangent: $arcTangent'); 55 | print('Arc Tangent2: $arcTangent2'); 56 | print('Exponential: $exponential'); 57 | print('Logarithm: $logarithm'); 58 | print('Max: $max'); 59 | print('Min: $min'); 60 | print('Power: $power'); 61 | print('Square Root: $squareRoot'); 62 | } -------------------------------------------------------------------------------- /bin/collection/math/constant.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | // Constants 5 | print('e: $e'); // Base of the natural logarithms 6 | print('ln10: $ln10'); // Natural logarithm of 10 7 | print('ln2: $ln2'); // Natural logarithm of 2 8 | print('log10e: $log10e'); // Base-10 logarithm of e 9 | print('log2e: $log2e'); // Base-2 logarithm of e 10 | print('pi: $pi'); // The PI constant 11 | print('sqrt1_2: $sqrt1_2'); // Square root of 1/2 12 | print('sqrt2: $sqrt2'); // Square root of 2 13 | 14 | // Using the constants in calculations 15 | double angle = pi / 4; // 45 degrees 16 | double sine = sin(angle); 17 | double cosine = cos(angle); 18 | double tangent = tan(angle); 19 | print('Sine of 45 degrees: $sine'); 20 | print('Cosine of 45 degrees: $cosine'); 21 | print('Tangent of 45 degrees: $tangent'); 22 | 23 | double logarithm = log(e); // Natural logarithm of e is 1 24 | print('Natural logarithm of e: $logarithm'); 25 | 26 | double exponential = exp(1.0); // e raised to the power of 1 is e 27 | print('e raised to the power of 1: $exponential'); 28 | 29 | double squareRoot = sqrt(2); // Square root of 2 30 | print('Square root of 2: $squareRoot'); 31 | 32 | num power = pow(2, log2e); // 2 raised to the power of log2e is e 33 | print('2 raised to the power of log2e: $power'); 34 | 35 | // Combining constants in calculations 36 | double area = pi * pow(10, 2); // Area of a circle with radius 10 37 | print('Area of a circle with radius 10: $area'); 38 | 39 | double circumference = 2 * pi * 10; // Circumference of a circle with radius 10 40 | print('Circumference of a circle with radius 10: $circumference'); 41 | 42 | double diagonalLength = sqrt(pow(20, 2) + pow(30, 2)); // Length of a diagonal in a rectangle with sides 20 and 30 43 | print('Length of a diagonal in a rectangle with sides 20 and 30: $diagonalLength'); 44 | 45 | double sinPi = sin(pi); // Sine of pi is 0 46 | print('Sine of pi: $sinPi'); 47 | 48 | double cosPi = cos(pi); // Cosine of pi is -1 49 | print('Cosine of pi: $cosPi'); 50 | 51 | double tanPi = tan(pi); // Tangent of pi is 0 52 | print('Tangent of pi: $tanPi'); 53 | } -------------------------------------------------------------------------------- /bin/collection/math/function.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | // Trigonometric Functions 5 | double angle = pi / 4; // 45 degrees 6 | double sine = sin(angle); 7 | double cosine = cos(angle); 8 | double tangent = tan(angle); 9 | double arcSine = asin(sine); 10 | double arcCosine = acos(cosine); 11 | double arcTangent = atan(tangent); 12 | double arcTangent2 = atan2(sine, cosine); 13 | print('Sine of 45 degrees: $sine'); 14 | print('Cosine of 45 degrees: $cosine'); 15 | print('Tangent of 45 degrees: $tangent'); 16 | print('Arc Sine: $arcSine'); 17 | print('Arc Cosine: $arcCosine'); 18 | print('Arc Tangent: $arcTangent'); 19 | print('Arc Tangent2: $arcTangent2'); 20 | 21 | // Exponential and Logarithmic Functions 22 | double exponential = exp(2.0); 23 | double logarithm = log(exponential); 24 | print('Exponential of 2: $exponential'); 25 | print('Natural Logarithm of Exponential of 2: $logarithm'); 26 | 27 | // Min and Max Functions 28 | int maxValue = max(10, 20); 29 | int minValue = min(10, 20); 30 | print('Maximum of 10 and 20: $maxValue'); 31 | print('Minimum of 10 and 20: $minValue'); 32 | 33 | // Power and Square Root Functions 34 | num power = pow(2.0, 3.0) as double; 35 | double squareRoot = sqrt(16.0); 36 | print('2 raised to the power of 3: $power'); 37 | print('Square root of 16: $squareRoot'); 38 | 39 | // Random Number Generation 40 | Random random = Random(); 41 | int randomInt = random.nextInt(100); 42 | double randomDouble = random.nextDouble(); 43 | bool randomBool = random.nextBool(); 44 | print('Random integer between 0 and 99: $randomInt'); 45 | print('Random double between 0.0 and 1.0: $randomDouble'); 46 | print('Random boolean: $randomBool'); 47 | 48 | // Points and Rectangles 49 | Point point1 = const Point(10.5, 20.3); 50 | Point point2 = const Point(50, 75); 51 | Rectangle rectangle1 = Rectangle.fromPoints(Point(point1.x.toDouble(), point1.y.toDouble()), Point(point2.x.toDouble(), point2.y.toDouble())); 52 | Rectangle rectangle2 = const Rectangle(20, 50, 100, 200); 53 | MutableRectangle mutableRectangle = MutableRectangle(20.5, 50.2, 100.0, 200.0); 54 | print('Point1: ($point1.x, $point1.y)'); 55 | print('Point2: ($point2.x, $point2.y)'); 56 | print('Rectangle1: (${rectangle1.left}, ${rectangle1.top}) ${rectangle1.width} x ${rectangle1.height}'); 57 | print('Rectangle2: (${rectangle2.left}, ${rectangle2.top}) ${rectangle2.width} x ${rectangle2.height}'); 58 | print('Mutable Rectangle: (${mutableRectangle.left}, ${mutableRectangle.top}) ${mutableRectangle.width} x ${mutableRectangle.height}'); 59 | } -------------------------------------------------------------------------------- /bin/convert/allclasses.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | 4 | void main() { 5 | // JSON 6 | Map jsonObject = { 7 | 'name': 'John Doe', 8 | 'age': 30, 9 | 'isStudent': true, 10 | 'grades': [90, 85, 92], 11 | }; 12 | String jsonString = json.encode(jsonObject); 13 | print('JSON Encoded: $jsonString'); 14 | 15 | Map decodedJson = json.decode(jsonString); 16 | print('JSON Decoded: $decodedJson'); 17 | 18 | // UTF-8 19 | String utf8String = 'Îñţérñåţîöñåļîžåţîờñ'; 20 | List encodedUtf8 = utf8.encode(utf8String); 21 | print('UTF-8 Encoded: $encodedUtf8'); 22 | 23 | String decodedUtf8 = utf8.decode(encodedUtf8); 24 | print('UTF-8 Decoded: $decodedUtf8'); 25 | 26 | // ASCII 27 | String asciiString = 'This is ASCII!'; 28 | List encodedAscii = ascii.encode(asciiString); 29 | print('ASCII Encoded: $encodedAscii'); 30 | 31 | String decodedAscii = ascii.decode(encodedAscii); 32 | print('ASCII Decoded: $decodedAscii'); 33 | 34 | // Latin-1 35 | String latin1String = 'blåbærgrød'; 36 | List encodedLatin1 = latin1.encode(latin1String); 37 | print('Latin-1 Encoded: $encodedLatin1'); 38 | 39 | String decodedLatin1 = latin1.decode(encodedLatin1); 40 | print('Latin-1 Decoded: $decodedLatin1'); 41 | 42 | // Base64 43 | List bytesToEncode = [0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6, 0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]; 44 | String base64Encoded = base64.encode(bytesToEncode); 45 | print('Base64 Encoded: $base64Encoded'); 46 | 47 | List decodedBase64 = base64.decode('YmzDpWLDpnJncsO4ZAo='); 48 | print('Base64 Decoded: $decodedBase64'); 49 | 50 | // HTML Escape 51 | String unescapedHtml = 'Text & subject bold'; 52 | String escapedHtml = htmlEscape.convert(unescapedHtml); 53 | print('HTML Escaped: $escapedHtml'); 54 | 55 | // Converters 56 | const showLineNumbers = true; 57 | var lineNumber = 1; 58 | var stream = Stream>.fromIterable([ 59 | [0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x20, 0x31], 60 | [0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x20, 0x32], 61 | [0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x20, 0x33], 62 | ]); 63 | stream 64 | .transform(utf8.decoder) 65 | .transform(const LineSplitter()) 66 | .forEach((line) { 67 | if (showLineNumbers) { 68 | stdout.write('${lineNumber++} '); 69 | } 70 | stdout.writeln(line); 71 | }); 72 | } 73 | 74 | 75 | // OUTPUT: 76 | // JSON Encoded: {"name":"John Doe","age":30,"isStudent":true,"grades":[90,85,92]} 77 | // JSON Decoded: {name: John Doe, age: 30, isStudent: true, grades: [90, 85, 92]} 78 | // UTF-8 Encoded: [195, 142, 195, 177, 197, 163, 195, 169, 114, 195, 177, 195, 165, 197, 163, 195, 174, 195, 182, 195, 177, 195, 165, 196, 188, 195, 174, 197, 190, 195, 165, 197, 163, 195, 174, 225, 187, 157, 195, 177] 79 | // UTF-8 Decoded: Îñţérñåţîöñåļîžåţîờñ 80 | // ASCII Encoded: [84, 104, 105, 115, 32, 105, 115, 32, 65, 83, 67, 73, 73, 33] 81 | // ASCII Decoded: This is ASCII! 82 | // Latin-1 Encoded: [98, 108, 229, 98, 230, 114, 103, 114, 248, 100] 83 | // Latin-1 Decoded: blåbærgrød 84 | // Base64 Encoded: YmzDpWLDpnJncsO4ZA== 85 | // Base64 Decoded: [98, 108, 195, 165, 98, 195, 166, 114, 103, 114, 195, 184, 100, 10] 86 | // HTML Escaped: Text & subject <b>bold</b> 87 | // 1 This is line 1This is line 2This is line 3 -------------------------------------------------------------------------------- /bin/convert/jsondecoder.dart: -------------------------------------------------------------------------------- 1 | // import 'dart:async'; 2 | // import 'dart:convert'; 3 | 4 | // void main() { 5 | // // Create an instance of JsonDecoder 6 | // const JsonDecoder decoder = JsonDecoder(); 7 | 8 | // // Example 1: Using convert() method 9 | // const String jsonString = ''' 10 | // { 11 | // "data": [{"text": "foo", "value": 1 }, 12 | // {"text": "bar", "value": 2 }], 13 | // "text": "Dart" 14 | // } 15 | // '''; 16 | 17 | // final Map object = decoder.convert(jsonString); 18 | 19 | // final item = object['data'][0]; 20 | // print(item['text']); // foo 21 | // print(item['value']); // 1 22 | 23 | // print(object['text']); // Dart 24 | 25 | // // Example 2: Using bind() and startChunkedConversion() methods 26 | // Stream jsonChunks = Stream.fromIterable([ 27 | // '{"data": [', 28 | // '{"text": "chunk1", "value": 10},', 29 | // '{"text": "chunk2", "value": 20}', 30 | // ']}', 31 | // ]); 32 | 33 | // final jsonStreamTransformer = decoder.bind(jsonChunks); 34 | 35 | // final objectSink = jsonStreamTransformer.listen((event) { 36 | // print('Decoded object: $event'); 37 | // }); 38 | 39 | // // Example 3: Using startChunkedConversion() method with a custom reviver 40 | // const String jsonStringWithReviver = ''' 41 | // { 42 | // "data": [ 43 | // {"text": "foo", "value": 1, "createdAt": "2023-04-28T12:34:56.789Z"}, 44 | // {"text": "bar", "value": 2, "createdAt": "2023-04-29T09:10:11.012Z"} 45 | // ] 46 | // } 47 | // '''; 48 | 49 | // final StringConversionSink chunkedSink = decoder.startChunkedConversion((key, value) { 50 | // if (key == 'createdAt') { 51 | // // Custom reviver function to parse DateTime objects 52 | // return DateTime.parse(value.toString()); 53 | // } 54 | // return value; 55 | // }); 56 | 57 | // chunkedSink 58 | // ..add(jsonStringWithReviver) 59 | // ..close() 60 | // ..then((decodedObject) { 61 | // final data = decodedObject['data'] as List; 62 | // print('Decoded object with reviver:'); 63 | // for (final item in data) { 64 | // print('Text: ${item['text']}, Value: ${item['value']}, Created At: ${item['createdAt']}'); 65 | // } 66 | // }); 67 | // } -------------------------------------------------------------------------------- /bin/dart_programming.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | void main() { 4 | // 1. ListQueue 5 | var listQueue = ListQueue(); 6 | listQueue.addAll([1, 2, 3]); 7 | listQueue.add(4); 8 | print(listQueue); // Output: (1, 2, 3, 4) 9 | 10 | // 2. Queue 11 | var queue = Queue(); 12 | queue.addAll([1, 2, 3]); 13 | queue.add(4); 14 | print(queue); // Output: (1, 2, 3, 4) 15 | 16 | // 3. HashSet 17 | var hashSet = HashSet(); 18 | hashSet.addAll([1, 2, 3]); 19 | hashSet.add(4); 20 | print(hashSet); // Output: {1, 2, 3, 4} 21 | 22 | // 4. HashMap 23 | var hashMap = HashMap(); 24 | hashMap.addAll({'one': 1, 'two': 2, 'three': 3}); 25 | hashMap['four'] = 4; 26 | print(hashMap); // Output: {one: 1, two: 2, three: 3, four: 4} 27 | 28 | // 5. LinkedHashMap 29 | var linkedHashMap = {}; 30 | linkedHashMap.addAll({'one': 1, 'two': 2, 'three': 3}); 31 | linkedHashMap['four'] = 4; 32 | print(linkedHashMap); // Output: {one: 1, two: 2, three: 3, four: 4} 33 | 34 | // 6. SplayTreeSet 35 | var splayTreeSet = SplayTreeSet(); 36 | splayTreeSet.addAll([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]); 37 | print(splayTreeSet); // Output: {1, 2, 3, 4, 5, 6, 9} 38 | 39 | // 7. SplayTreeMap 40 | var splayTreeMap = SplayTreeMap(); 41 | splayTreeMap.addAll({'one': 1, 'two': 2, 'three': 3}); 42 | splayTreeMap['four'] = 4; 43 | print(splayTreeMap); // Output: {four: 4, one: 1, three: 3, two: 2} 44 | } 45 | -------------------------------------------------------------------------------- /bin/difference.md: -------------------------------------------------------------------------------- 1 | Sure, here's a comparison table highlighting the differences between `LinkedHashSet` and `HashSet` in Dart: 2 | 3 | | Feature | LinkedHashSet | HashSet | 4 | |-------------------|-------------------------------------------------------|------------------------------------------------------| 5 | | Order Preservation| Maintains insertion order of elements | Order of elements is not preserved | 6 | | Implementation | Implemented as a hash-table based set | Implemented as a hash-table based set | 7 | | Iteration | Iteration happens in first-to-last insertion order | Iteration order not guaranteed | 8 | | Element Equality | Elements must have consistent `==` and `hashCode` | Elements must have consistent `==` and `hashCode` | 9 | | Performance | Mostly constant time for basic operations | Mostly constant time for basic operations | 10 | | Use Case | When maintaining order of insertion is important | When order of elements is not important | 11 | | Constructors | `LinkedHashSet()`
`LinkedHashSet.from(iterable)` | `HashSet()`
`HashSet.from(iterable)` | 12 | 13 | These are some of the key differences between `LinkedHashSet` and `HashSet` in Dart. Depending on the requirements of your application, you can choose the appropriate set implementation. -------------------------------------------------------------------------------- /lib/dart_programming.dart: -------------------------------------------------------------------------------- 1 | int calculate() { 2 | return 6 * 7; 3 | } 4 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: dart_programming 2 | description: A sample command-line application. 3 | version: 1.0.0 4 | # repository: https://github.com/my_org/my_repo 5 | 6 | environment: 7 | sdk: ^3.0.6 8 | 9 | # Add regular dependencies here. 10 | dependencies: 11 | path: ^1.8.0 12 | synchronized: ^3.1.0+1 13 | 14 | dev_dependencies: 15 | lints: ^2.0.0 16 | test: ^1.21.0 17 | -------------------------------------------------------------------------------- /test/dart_programming_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:dart_programming/dart_programming.dart'; 2 | import 'package:test/test.dart'; 3 | 4 | void main() { 5 | test('calculate', () { 6 | expect(calculate(), 42); 7 | }); 8 | } 9 | --------------------------------------------------------------------------------