Divide a List in Dart - dart

I want to divide a List to two parts.
I have a list 1 = List cardbank = ["1","2","3","4","5","6","7","8"]
How can i create list2 and list3 from list 1 random ?
For example ;
List 2 be like = [3,6,7,8]
and
List 3 be like = [1,2,4,5]
This is my CardClass :
class CardClass {
int deger;
String tip;
int id;
CardClass(this.deger, this.tip, this.id);
#override
String toString() {
return '{ ${deger}, ${tip}}';
}
}
and this is my list
class CardBrain {
List<CardClass> cardbank = [
CardClass(1, "for", 1),
CardClass(2, "for", 2),
CardClass(3, "for", 3),
];
Random _random = new Random();
int max = (cardbank.length / 2).floor(); //It says The instance member cant be accessed to initializer
final anan = cardbank.length;
}

I think you can do it shorter like this:
void main() {
final list1 = ["1", "2", "3", "4", "5", "6", "7", "8"];
final list1Copy = list1.toList()..shuffle();
final list2 = list1Copy.sublist(0, list1Copy.length ~/ 2);
final list3 = list1Copy.sublist(list1Copy.length ~/ 2);
print(list1); // [1, 2, 3, 4, 5, 6, 7, 8]
print(list2); // [4, 6, 8, 3]
print(list3); // [5, 1, 7, 2]
}
You can skip the list1Copy if you don't care about list1 being shuffled under the process.

You may try the code below : [Please see the answer by #julemand101 for a better solution]
import 'dart:math';
void main() {
List<String> list1 = ["1", "2", "3", "4", "5", "6", "7", "8"];
List<String> list2 = [];
List<String> list3 = [];
Random _random = new Random();
int max = (list1.length / 2).floor();
for (int i = 0; i < max; i++) {
int nextInt = _random.nextInt(list1.length);
list2.add(list1[nextInt]);
list1.removeAt(nextInt);
}
list3 = List.from(list1);
print(list2);
print(list3);
}

Related

Filtering arrays in Dart

Can anyone guide me and tell me where I am making mistake in the code.
I want to filter all the food which have Pizzatype veggie.
I am getting an empty array in the output.
where iterates one pizza at a time. Something like this might work.
final findVeggiePizza = pizzaList.where((pizza) => pizza.type == PizzaType.veggie).toList();
Probably as so
enum PizzaType {
veggie,
meatLover
}
class PizzaWithToppings {
String typeDes;
int price;
List list;
PizzaType type;
PizzaWithToppings(this.typeDes, this.price, this.list, this.type);
bool filter(PizzaType type) {
return this.type == type;
}
}
void main() {
final pizzaWithToppings =
PizzaWithToppings('Mushroom Pizza', 12, [1, 2, 3], PizzaType.veggie);
final pizzaWithToppings2 =
PizzaWithToppings('Chiken Pizza', 20, [1, 2, 3], PizzaType.meatLover);
final pizzaWithToppings3 =
PizzaWithToppings('Veggie Pizza', 15, [1, 2, 3], PizzaType.veggie);
final pizzaList = [pizzaWithToppings, pizzaWithToppings2,pizzaWithToppings3];
final findVeggiePizza = pizzaList.where((pizza) => pizza.filter(PizzaType.veggie)).toList();
print (findVeggiePizza);
}
Is that so?

Why can't I assign a shuffled array to a new array

Why can't I assign a shuffled array to a new array?
For example, this is my list:
List nums = [1, 2, 3];
List newlist=nums.shuffle();
However, this does not work for me.
Because shuffle() on List does not return anything (which is indicated by void which means the method does not return anything usable) but are instead shuffling the list you are calling the method on.
void shuffle([Random? random])
Shuffles the elements of this list randomly.
https://api.dart.dev/stable/2.15.1/dart-core/List/shuffle.html
If you want to output your nums list after it have been shuffled, you just need to print nums like this after the nums.shuffle() call:
void main() {
final nums = [1, 2, 3];
nums.shuffle();
print(nums); // [2, 3, 1]
}
If you want to have a new list there is shuffled and based on another list, you can do something like this (the .. is called a cascade call, you can read more about it here: https://dart.dev/guides/language/language-tour#cascade-notation):
void main() {
final nums = [1, 2, 3];
final shuffeledNums = nums.toList()..shuffle();
print(nums); // [1, 2, 3]
print(shuffeledNums); // [2, 1, 3]
}
Which is the same as this without the use of cascade:
void main() {
final nums = [1, 2, 3];
final shuffeledNums = nums.toList();
shuffeledNums.shuffle();
print(nums); // [1, 2, 3]
print(shuffeledNums); // [2, 1, 3]
}

find the index of item even there is duplication in Dart

I'm really confused on how I'm gonna find the index of item in array where there's a lot of duplicated words.
List<String> _words = "the quick brown fox jumps over the lazy dog".split(" ");
now I want to get the all the index in word "the" programmatically.
I expect a result of
List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);
// [0, 6]
You can define indexOfAll as an extension method. I would implement it like this:
extension ListExtension<T> on List<T> {
List<int> indexOfAll(T item) => [
for (int i = 0; i < length; i++)
if (this[i] == item) i,
];
}
You can create an extension method. like this:
extension Occurrences on List {
List<int> indexOfAll(String pattern) {
List<int> indexes = [];
for (int i = 0; i < this.length; i++) {
if (this[i] == pattern) {
indexes.add(i);
}
}
return indexes;
}
}
then you can use it as function on your list
print(_words.indexOfAll("the")); // [0, 6]
I don't know if there is a direct solution for this job. To solve this problem I developed a function called GetIndexes() and it works successfully.
This example prints the following output to the console:
[the, quick, brown, fox, jumps, over, the, lazy, dog]
[3, 9, 15, 19, 25, 30, 34, 39]
The solution I developed is available below:
void main()
{
String text = "the quick brown fox jumps over the lazy dog";
var split = ' ';
List<int> indexes = [];
List<String> words;
words = text.split(split);
GetIndexes(text, split, indexes);
print(words);
print(indexes);
}
void GetIndexes(String text, var split, List<int> indexes)
{
int index = 0;
for(int i=0 ; i<text.length; ++i)
{
if(text[i] == split)
{
indexes.insert(index, i);
++index;
}
}
}

Dart how to get max duplicated element in a list

I have List list= [1,2,3,4,4,4,9,6,7,7,7,8,8,8,8,8,8,8];
how can i return 8 as max repeated value
Something like this?
void main() {
final list = [1, 2, 3, 4, 4, 4, 9, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8];
print(findMaxDuplicatedElementInList(list)); // 8
}
T findMaxDuplicatedElementInList<T>(Iterable<T> list) => list
.fold<Map<T, int>>(
{},
(map, element) =>
map..update(element, (value) => value + 1, ifAbsent: () => 1))
.entries
.reduce((e1, e2) => e1.value > e2.value ? e1 : e2)
.key;
I'd just write it out, as straight-forward as possible:
Assuming the equal elements are always adjacent, and list cannot be empty, return arbitrary element with maximal count if there is more than one:
T maxDuplicated<T>(List<T> elements) {
var element = elements.count;
var count = 1;
var maxElement = element;
var maxCount = count;
for (var i = 1; i < elements.length; i++) {
var nextElement = elements[i];
if (element != nextElement) {
element = nextElement;
count = 1;
} else {
count += 1;
if (count > maxCount) {
maxElement = element;
maxCount = count;
}
}
}
return maxElement;
}
Assuming elements come in random order, so we need to remember every element we have seen,
still not allowing an empty list as input:
T maxDuplicated<T>(List<T> elements) {
var maxCount = 1;
var maxElement = elements.first
var seen = <T, int>{maxElement: maxCount};
for (var i = 1; i < elements.length; i++) {
var element = elements[i];
var count = seen[element] = (seen[element] ?? 0) + 1;
if (count > maxCount) {
maxCount = count;
maxElement = element;
}
}
return maxElement;
}
(Alternatively, I'd sort the list first, if allowed, to always be in the former situation. It's not faster than using a map, if we assume hash map lookup to be a constant time operation, but it will be more memory efficient.)

Dart List min/max value

How do you get the min and max values of a List in Dart.
[1, 2, 3, 4, 5].min //returns 1
[1, 2, 3, 4, 5].max //returns 5
I'm sure I could a) write a short function or b) copy then sort the list and select the last value,
but I'm looking to see if there is a more native solution if there is any.
Assuming the list is not empty you can use Iterable.reduce :
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
If you don't want to import dart: math and still wants to use reduce:
main() {
List list = [2,8,1,6]; // List should not be empty.
print(list.reduce((curr, next) => curr > next? curr: next)); // 8 --> Max
print(list.reduce((curr, next) => curr < next? curr: next)); // 1 --> Min
}
You can now achieve this with an extension as of Dart 2.6:
import 'dart:math';
void main() {
[1, 2, 3, 4, 5].min; // returns 1
[1, 2, 3, 4, 5].max; // returns 5
}
extension FancyIterable on Iterable<int> {
int get max => reduce(math.max);
int get min => reduce(math.min);
}
An example to get Min/Max value using reduce based on condition for a list of Map objects
Map studentA = {
'Name': 'John',
'Marks': 85
};
Map studentB = {
'Name': 'Peter',
'Marks': 70
};
List<Map> students = [studentA, studentB];
// Get student having maximum mark from the list
Map studentWithMaxMarks = students.reduce((a, b) {
if (a["Marks"] > b["Marks"])
return a;
else
return b;
});
// Get student having minimum mark from the list (one liner)
Map studentWithMinMarks = students.reduce((a, b) => a["Marks"] < b["Marks"] ? a : b);
Another example to get Min/Max value using reduce based on condition for a list of class objects
class Student {
final String Name;
final int Marks;
Student(this.Name, this.Marks);
}
final studentA = Student('John', 85);
final studentB = Student('Peter', 70);
List<Student> students = [studentA, studentB];
// Get student having minimum marks from the list
Student studentWithMinMarks = students.reduce((a, b) => a.Marks < b.Marks ? a : b);
If your list is empty, reduce will throw an error.
You can use fold instead of reduce.
// nan compare to any number will return false
final initialValue = number.nan;
// max
values.fold(initialValue, (previousValue, element) => element.value > previousValue ? element.value : previousValue);
// min
values.fold(initialValue, (previousValue, element) => element.value < previousValue ? element.value : previousValue);
It can also use to calculate sum.
final initialValue = 0;
values.fold(initialValue, (previousValue, element) => element.value + previousValue);
Although fold is not cleaner than reduce for getting min/max, it is still a powerful method to do more flexible actions.
For empty lists: This will return 0 if list is empty, the max value otherwise.
List<int> x = [ ];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 0
List<int> x = [1,32,5];
print(x.isEmpty ? 0 : x.reduce(max)); //prints 32
int minF() {
final mass = [1, 2, 0, 3, 5];
mass.sort();
return mass[0];
}
void main() {
firstNonConsecutive([1,2,3,4,6,7,8]);
}
int? firstNonConsecutive(List<int> arr) {
var max = arr.reduce((curr, next) => curr > next? curr: next);
print(max); // 8 --> Max
var min = arr.reduce((curr, next) => curr < next? curr: next);
print(min); // 1 --> Min
return null;
}
If you need a more sophisticated min/max, such as finding an object with a min/max of a field, or use of a comparison predicate, use minBy() and maxBy() from the collection package:
import 'package:collection/collection.dart';
class Person {
final String name;
final int age;
Person(this.name, this.age);
#override
String toString() => '$name (age $age)';
}
main() {
final alice = Person('Alice', 30);
final bob = Person('Bob', 40);
final chris = Person('Chris', 25);
final dan = Person('Dan', 35);
final people = [alice, bob, chris, dan];
print('Youngest is ${minBy(people, (e) => e.age)}');
print('Oldest is ${maxBy(people, (e) => e.age)}');
print('First alphabetically is ${minBy(people, (e) => e.name)}');
print('Last alphabetically is ${maxBy(people, (e) => e.name)}');
print('Largest name length times age is ${maxBy(people, (e) => e, compare: (a, b) => (a.name.length * a.age).compareTo(b.name.length * b.age))}');
}
Output:
Youngest is Chris (age 25)
Oldest is Bob (age 40)
First alphabetically is Alice (age 30)
Last alphabetically is Dan (age 35)
Largest name length times age is Alice (age 30)```

Resources