I'm looking every where on the web (dart website, stackoverflow, forums, etc), and I can't find my answer.
So there is my problem: I need to write a function, that print a random sort of a list, witch is provided as an argument. : In dart as well.
I try with maps, with Sets, with list ... I try the method with assert, with sort, I look at random method with Math on dart librabry ... nothing can do what I wana do.
Can some one help me with this?
Here some draft:
var element03 = query('#exercice03');
var uneliste03 = {'01':'Jean', '02':'Maximilien', '03':'Brigitte', '04':'Sonia', '05':'Jean-Pierre', '06':'Sandra'};
var alluneliste03 = new Map.from(uneliste03);
assert(uneliste03 != alluneliste03);
print(alluneliste03);
var ingredients = new Set();
ingredients.addAll(['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']);
var alluneliste03 = new Map.from(ingredients);
assert(ingredients != alluneliste03);
//assert(ingredients.length == 4);
print(ingredients);
var fruits = <String>['bananas', 'apples', 'oranges'];
fruits.sort();
print(fruits);
There is a shuffle method in the List class. The methods shuffles the list in place. You can call it without an argument or provide a random number generator instance:
var list = ['a', 'b', 'c', 'd'];
list.shuffle();
print('$list');
The collection package comes with a shuffle function/extension that also supports specifying a sub range to shuffle:
void shuffle (
List list,
[int start = 0,
int end]
)
Here is a basic shuffle function. Note that the resulting shuffle is not cryptographically strong. It uses Dart's Random class, which produces pseudorandom data not suitable for cryptographic use.
import 'dart:math';
List shuffle(List items) {
var random = new Random();
// Go through all elements.
for (var i = items.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
var temp = items[i];
items[i] = items[n];
items[n] = temp;
}
return items;
}
main() {
var items = ['foo', 'bar', 'baz', 'qux'];
print(shuffle(items));
}
You can use shuffle() with 2 dots like Vinoth Vino said.
List cities = ["Ankara","London","Paris"];
List mixed = cities..shuffle();
print(mixed);
// [London, Paris, Ankara]
Related
I have 2 Lists (uid and url) that are growable, and I need to set the first List as the key and the second as value. At some point, i'll have a 3rd List (randomUids) which will be keys and will print out the corresponding values. Here is the example code:
List<String> uid = ["uid1", "uid2","uid3","uid4"]; //Lists will grow larger after a while
List<String> url = ["url1","url2","url3","url4"];
List<String> randomUids = ["uid4", "uid2"];
When I try:
Map<List, List> mapKeyValue = Map();
mapKeyValue[uid] = url;
print( uid.contains(randomUids));
I get a false. Also, the print returns uid and url Lists as 2 long indices instead of separate Strings. How can I iterate the List so that url.contains(randomUids) is true. Also how can I print out the values of randomUids.
When I try:
print( uid.contains(randomUids));
I get a false.
Your code asks if uid (a List of Strings) contains randomUids (another List of Strings). It returns false because uid's elements are not Lists; they're Strings.
Presuming that you want the nth element of uid to correspond to the nth element of url, and you can guarantee that uid.length == url.length, you can construct a Map of UIDs to URLs:
assert(uid.length == url.length);
var uidMap = <String, String>{
for (var i = 0; i < uid.length; i += 1)
uid[i]: url[i],
};
And then you can iterate over randomUids and do lookups:
for (var uid in randomUids) {
if (uidMap.containsKey(uid)) {
print(uidMap[uid]);
}
}
I'm trying to sort an entire list according to one property. Afterwards I'd like to sort this list according to a second property, but in groups of 4. So, after sorting the list once, I want to look at the first 4 positions and sort only these 4 according to the second property - then move on to the next 4 positions and sort these again, and so on...
This is what I have so far:
class myElements {
int Position;
String text;
int Top;
int Left;
myElements(int Position, String text, int Top, int Left){
this.Position = Position;
this.text = text;
this.Top = Top;
this.Left = Left;
}
}
var FirstList = new List<myElements>();
var newList = new List<myElements>();
Adding Elements to my first list:
myElements Test = myElements(ElementNumber, text, Top, Left);
FirstList.add(Test);
Then sorting for the first time according to 'Top':
Comparator<myElements> TextComparator = (a, b) => a.Top.compareTo(b.Top);
FirstList.sort(TextComparator);
Here is where I'm stuck. I'm trying to sort the list again, but only in groups of 4 - this time according to 'Left':
for (int i = 0; i < FirstList.length; i += 4) {
Comparator<myElements> TextComparator2 = (a, b) =>
a.Left.compareTo(b.Left);
newList.addAll(FirstList.sublist(i, i + 3).sort(TextComparator2)); //this line does not work
}
I think I am stuck trying to access my sorted sublist: (FirstList.sublist(i, i + 4).sort(TextComparator2) . If I could add these to a new list, it should work.
However any other suggestions are more than welcome.
Thanks so much!
newList.addAll(FirstList.sublist(i, i + 3).sort(TextComparator2)); //this line does not work
Your code is almost correct. You have the right idea, but you ended up trying to do too much in one line of code.
Breaking it down a bit, your code is equivalent to:
var sublist = FirstList.sublist(i, i + 3);
newList.addAll(sublist.sort(...)); // Does not work
And that doesn't work because List.sort does not return a value. It mutates the list instead of returning a new list.
It would work if you instead did:
var sublist = FirstList.sublist(i, i + 3);
sublist.sort();
newList.addAll(sublist);
Also, List.sublist uses an exclusive end index. If you want to create sublists with 4 elements, you would need to use sublist(i, i + 4).
I wish to create a list of 7 gradient colors which i can apply randomly as background to a container.
gradientColors[rand(0,6)];
The list needs to be stored locally in app in seprate file.
the idea was to do some thing like below:
List<Color> gradientRed = Colors.amber, Colors.red;
List<Color> gradientBlue = Colors.blue, Colors.blueAccent;
List<Colors> gradientColor = [
gradientRed, gradientBlue, ...
];
but i am facing following error:
The element type 'List<Color>' can't be assigned to the list type 'Colors'.dart(list_element_type_not_assignable)
plus i was trying to generate random number between the given range. but i am always get same number.
using this code inside foreach loop in flutter
int min = 0;
int max = gradientColors.length;
var randIndex = min + (Random(1).nextInt(max - 1));
print(randIndex);
what is a solution here ?
Your List type needs to be a list itself:
List<List<Colors>> gradientColor = [color gradients go here]
for the list issue i had, i just removed the List type and let it be dynamic now like below:
List gradientColors = [
gradientRed,
gradientBlue,
gradientGreen,
gradientYellow,
gradientPurple,
gradientPink,
gradientOrange,
gradientAmber,
];
and for the random number on list length i used below code:
const int min = 0;
int max = gradientColors.length;
var randIndex = Random().nextInt(max);
print(randIndex);
I am creating a list of random numbers using the following approach
val randomList = List(4) { Random.nextInt(0, 100) }
However, this approach doesn't work as I want to avoid repetitions
One way is to shuffle a Range and take as many items as you want:
val randomList = (0..99).shuffled().take(4)
This is not so efficient if the range is big and you only need just a few numbers.In this case it's better to use a Set like this:
val s: MutableSet<Int> = mutableSetOf()
while (s.size < 4) { s.add((0..99).random()) }
val randomList = s.toList()
Create:
val list = (0 until 100).toMutableList()
val randList = mutableListOf<Int>()
for (i in 0 until 4) {
val uniqueRand = list.random()
randList.add(uniqueRand)
list.remove(uniqueRand)
}
One line approach to get a list of n distinct random elements. Random is not limited in any way.
val list = mutableSetOf<Int>().let { while (it.size() < n) it += Random.nextInt(0, 100) }.toList()
I'm developing my first application with Dart, which had previously created in JavaScript.
In my statement in JavaScript I have declared a List, and I assign values to the first three positions, as seen here:
serpF var = new List ();
serpF [0] = 10;
serpF [1] = 10;
serpF [2] = 10;
How I can do the same in Dart? I have read the documentation of Lists and Arrays of Seth Ladd in "http://blog.sethladd.com/2011/12/lists-and-arrays-in-dart.html" and I've tried everything, but it is being impossible.
The javaScript code does not work in Dart because it is an error to access past the end of the List. Dart is like many other languages as this is a way to catch logic errors.
What you can do is add elements to a List:
var serpF = new List(); // This list has length == 0.
serpF.add(10);
serpF.add(10);
serpF.add(10);
You can use method cascades to shorten the code:
var serfP = [];
serpF..add(10)..add(10)..add(10);
If you do know the length, you might also try one of the other List constructors:
var serfP = new List.filled(3, 10);
var serfP = new List.generate(3, (i) => 10);
I addition to what Stephen suggests you can also do:
var serpF = [10, 10, 10];
or
var serpF = new List();
serpF.length = 3;
serpF[0] = 10;
serpF[1] = 10;
serpF[2] = 10;
You can also use the List.generate() constructor:
var list = new List.generate(3, (_) => 10, growable: true);
print(list); // Prints [10, 10, 10].
The first arg specifies the number of elements in the list, the second arg takes a callback to give each element a value, and the third arg ensures that the list is not fixed-width.