For loop 为什么赢了';我的随机选择没有替换算法行吗?

For loop 为什么赢了';我的随机选择没有替换算法行吗?,for-loop,dart,random,For Loop,Dart,Random,我已经做了一个非常简单的算法,可以从0到batchMax范围内选取一组numToPick随机数,而不需要替换。然后,它将每个选定的数字放入一个名为numsPicked的数组中。由于某种原因我无法解释,它在DartPad上不起作用 import 'dart:math'; void main() { print(randNoReplace(2, 9)); } List<int> randNoReplace(int numToPick, int batchMax) { List

我已经做了一个非常简单的算法,可以从0到batchMax范围内选取一组numToPick随机数,而不需要替换。然后,它将每个选定的数字放入一个名为numsPicked的数组中。由于某种原因我无法解释,它在DartPad上不起作用

import 'dart:math';

void main() {
  print(randNoReplace(2, 9));
}

List<int> randNoReplace(int numToPick, int batchMax) {
  List<int> numsPicked = List(numToPick);
  List<int> tmpArray = List(batchMax);
//this for loop creates the tmpArray from 0 to batchMax.
  for (int i = 0; i <= batchMax; i++) {
    tmpArray[i] = i;
  }
//this for loop randomly scrambles said tmpArray.
  for (int i = 0; i <= batchMax; i++) {
    int randIndex = Random().nextInt(batchMax);
    int tmp = tmpArray[i];
    tmpArray[i] = tmpArray[randIndex];
    tmpArray[randIndex] = tmp;
  }
//finally, this for loop adds the first numToPick entries of the scrambled tmpArray and adds them to numsPicked.
  for (int i = 0; i < numToPick; i++) {
    numsPicked[i] = tmpArray[i];
  }
  return numsPicked;
}
import'dart:math';
void main(){
印刷品(randNoReplace(2,9));
}
列表randNoReplace(int numToPick,int batchMax){
List numsPicked=列表(numToPick);
列表tmpArray=列表(batchMax);
//此for循环将创建从0到batchMax的tmpArray。

for(inti=0;i我认为代码中的主要问题是前两个for循环从0变为0
batchMax
包括
batchMax
。这是一个问题,因为您正在使用
batchMax
指定
tmpArray
的大小。由于
列表的索引从0开始,我们不能请求
batchMax
-元素,最多只能请求
batchMax-1

因此,您的代码应该正确地是(或者`tmpArray应该大一个元素):


您的两个前for循环超出了列表的大小。而不是例如
for(int i=0;例如,可以在一行代码中生成相同的代码:
List randNoReplace(int numToPick,int batchMax)=>(List.generate(batchMax,(index)=>index)…shuffle()。take(numToPick)。toList()
Omg太笨了,非常感谢。我只是忘了将tmpArray(batchMax+1)的大小改为batchMax。
import 'dart:math';

void main() {
  print(randNoReplace(2, 9));
}

List<int> randNoReplace(int numToPick, int batchMax) {
  List<int> numsPicked = List(numToPick);
  List<int> tmpArray = List(batchMax);
//this for loop creates the tmpArray from 0 to batchMax.
  for (int i = 0; i < batchMax; i++) {
    tmpArray[i] = i;
  }
//this for loop randomly scrambles said tmpArray.
  for (int i = 0; i < batchMax; i++) {
    int randIndex = Random().nextInt(batchMax);
    int tmp = tmpArray[i];
    tmpArray[i] = tmpArray[randIndex];
    tmpArray[randIndex] = tmp;
  }
//finally, this for loop adds the first numToPick entries of the scrambled tmpArray and adds them to numsPicked.
  for (int i = 0; i < numToPick; i++) {
    numsPicked[i] = tmpArray[i];
  }
  return numsPicked;
}
void main() {
  print(randNoReplace(2, 9));
}

List<int> randNoReplace(int numToPick, int batchMax) =>
    (List.generate(batchMax, (index) => index)..shuffle())
        .sublist(0, numToPick);