Flutter: How to force randomly generated value to be higher than the second one Dart

Viewed 26

So I have this function where the system generates random numbers for an arithmetic quiz app. Addition and Multiplication work perfectly. But since it is for kids between the age of 5 to 10, I do not want Subtraction to generate negative answers and Division needs to generate whole numbers. Currently the subtration generates lower number than the second number which gives negative answer. Please help on how to force the randomly generated number to be higher than the second value.

List<dynamic> questions = [];
  List<dynamic> answers = [];
  bool isMarked = false;
  List<List<dynamic>> mcq = [];
  List<dynamic> userAnswer = [];
  List<dynamic> ansData = [];
  List<dynamic> ans = [];
  var j = 0;
  final CountDownController _controller = CountDownController();
  @override
  void initState() {
    super.initState();
    for (var i = 1; i < int.parse(widget.numOfQuestions) + 1; i++) {
      ans = [];
      final val1 = Random().nextInt(int.parse(widget.range1)) + 1;
      final val2 = Random().nextInt(int.parse(widget.range2)) + 1;
      if (widget.operator == 'sum') {
        questions.add('$val1  +  $val2 =  ? ');
        answers.add(val1 + val2);
        ansData = [
          val1 + val2,
          val1 + val2 + Random().nextInt(10) + 1,
          val1 + val2 - Random().nextInt(10) - 1,
          val1 + val2 + Random().nextInt(16) + 1,
        ];
      } else if (widget.operator == 'minus') {
        questions.add('$val1  -  $val2 =  ? ');
        answers.add(val1 - val2);
        ansData = [
          val1 - val2,
          val1 - val2 + Random().nextInt(10) + 1,
          val1 - val2 - Random().nextInt(10) - 1,
          val1 - val2 + Random().nextInt(16) + 1,
        ];
      } else if (widget.operator == 'multiplication') {
        questions.add('$val1  *  $val2 =  ? ');
        answers.add(val1 * val2);
        ansData = [
          val1 * val2,
          val1 * val2 + Random().nextInt(10) + 1,
          val1 * val2 - Random().nextInt(10) - 1,
          val1 * val2 + Random().nextInt(20) + 1,
        ];
      } else {
        questions.add('$val1  /  $val2 =  ? ');
        answers.add((val1 / val2).toStringAsFixed(2));
        ansData = [
          (val1 / val2).toStringAsFixed(2),
          (val1 / val2 + Random().nextInt(10) + 1).toStringAsFixed(2),
          (val1 / val2 - Random().nextInt(10) - 1).toStringAsFixed(2),
          (val1 / val2 + Random().nextInt(16) + 1).toStringAsFixed(2),
        ];
      }
      for (var j = 0; j < 4; j++) {
        final rNum = Random().nextInt(ansData.length).round();
        ans.add(ansData[rNum]);
        ansData.removeAt(rNum);
      }
      mcq.add(ans);
    }
  }
1 Answers

You could do

  final val2 = val1 + Random().nextInt(int.parse(widget.range2) - val1) + 1;
Related