Home > database >  How to random select 3 element without repeating?
How to random select 3 element without repeating?

Time:02-27

Random 3 Element with repeating

How to random select 3 element without repeating?

List<Question> imageList = [
    Question(
      index: 1,
      image: 'assets/images/1.png',
    ),
    Question(
      index: 2,
      image: 'assets/images/2.png',
    ),
    Question(
      index: 3,
      image: 'assets/images/3.png',
    ),
    Question(
      index: 4,
      image: 'assets/images/4.png',
    ),
    Question(
      index: 5,
      image: 'assets/images/5.png',
    ),
    
  ];

  1. This is Element List
getRandom =
          List<Question>.generate(3, (_) => imageList[random.nextInt(imageList.length)]);
  1. This is Random Function with repeating.

CodePudding user response:

You could define an extension on List<T> so you can reuse it on all types of List:

List<String> alphabets = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

extension XList<T> on List<T> {
  List<T> takeRandom(int n) {
    return ([...this]..shuffle()).take(n).toList();
  }
}

void main() {
  print(alphabets.takeRandom(3));
  print(alphabets.takeRandom(5));
  print(alphabets.takeRandom(7));
}

Console log

[B, S, G]
[P, M, F, Q, K]
[U, M, R, C, Z, D, G]

CodePudding user response:

Get the list count;

int total = imageList.length;

create index list numbers;

var listindex = List<int>.generate(total, (i) => i  );

shuffle list;

listindex .shuffle();
//result
[3, 6, 2, 0, 9, 1, 5, 7, 8, 4]

and get data from first 3 index list.

imageList[3].image

imageList[6].image

imageList[2].image

  • Related