2

I have a list of n integers. I would like to randomly select three values out of this list and affect them to a three item list. How can I do that ?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
SylvainJack
  • 1,007
  • 1
  • 8
  • 27
  • Does this answer your question? [How do get a random element from a List in Dart?](https://stackoverflow.com/questions/17476718/how-do-get-a-random-element-from-a-list-in-dart) – MSpeed Apr 02 '21 at 11:10
  • In a way... I read this post. But I have problem to create the second list with the three elements in it... three elements taken randomly in the first list... – SylvainJack Apr 02 '21 at 11:12
  • [Shuffle the list](https://stackoverflow.com/a/48703094/) and select the first three items. – jamesdlin Apr 02 '21 at 11:14
  • use [sample](https://api.flutter.dev/flutter/package-collection_collection/IterableExtension/sample.html) - the docs say: *"Selects count elements at random from this iterable. The returned list contains count different elements of the iterable. If the iterable contains fewer that count elements, the result will contain all of them, but will be shorter than count. If the same value occurs more than once in the iterable, it can also occur more than once in the chosen elements."* – pskink Apr 02 '21 at 11:55
  • Here you can try this one. https://stackoverflow.com/questions/13554129/list-shuffle-in-dart Hope so you can shuffle with this. – Muhammad Ashir Apr 02 '21 at 12:33
  • Are you asking how to make a subset of three elements taken from a list? – Second Person Shooter Apr 02 '21 at 12:59

3 Answers3

5

Create this method:

import 'package:collection/collection.dart';

List<int> getList(int n, List<int> source) => source.sample(n);

Usage:

final outputList = getList(3, your_int_list);
print(outputList); // Prints non-repeating 3 random number
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
1

Try this exemple with List of String :

import "dart:math";

List<String> list = ['tata','toto','titi','tutu','lala','lolo','lili'];

final random= new Random();

String item= list[random.nextInt(list.length)];
print(item);
Abdelmjid Asouab
  • 170
  • 4
  • 15
  • This works. But I need to get three different items and put them into another list. Have been trying the "shuffle" method. – SylvainJack Apr 02 '21 at 11:49
0

With this code select three items from testList1 and add to another list(testList2), but this code sometimes selects the same items. Here is code:

    void getRandomItem(){
    T getRandomElement<T>(List<T> testList1) {
      final random = new Random();
      var i = random.nextInt(testList1.length);
      return testList1[i];
    }
    for(var i=0;i<3;i++){
      var randomItem= getRandomElement(testList1);
      print(randomItem);
      testList2.add(randomItem);
      print(testList2);
    }

  }

button event:

 onPressed: () {
        getRandomItem();
          },