├── .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 | 
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 |
4 |
5 |
6 |
7 |
8 | Dart Programming Documentation Project
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
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 | 
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