Home > Mobile >  I want to divide adynamic List int five equal parts
I want to divide adynamic List int five equal parts

Time:08-04

I want to divide a dynamic list into five equal parts and take out one random number from each part. In doing so, I want to avoid duplicate numbers. Here is my code and it was not good at all.

List document;

int value1 = Random().nextInt((document.length / 5).round());
int value2 = Random().nextInt((document.length / 5).round())  
    ((document.length / 5).round())   1;
int value3 = Random().nextInt((document.length / 5).round())  
    ((document.length / 5).round() * 2)   1;
int value4 = Random().nextInt((document.length / 5).round())  
    ((document.length / 5).round() * 3)   1;
int value5 = Random().nextInt((document.length / 5).round())  
    ((document.length / 5).round() * 4)   1;`

If you have a better way, I would appreciate it.

CodePudding user response:

You can get this with a simple while loop and check if the element exists in the list already like the following

import "dart:math";

void main() {
  List<int> intList = [];
  List<int> randomList = [];
  for (int i = 0; i < 100; i  ) {
    intList.add(i);
  }
  
  while(randomList.length < 5){
    int _randomNum = Random().nextInt(intList.length);
    if(randomList.contains(_randomNum) == false)
    {
      randomList.add(_randomNum);
    }
  }
  print(randomList);
}

  • Related