Home > Blockchain >  Generate 4 random numbers that add to a certain value in Dart
Generate 4 random numbers that add to a certain value in Dart

Time:06-03

I want to make 4 numbers that add up to a certain number that is predefined. For instance, I want four random numbers when added gives me 243.

Any type of way works as long as it works :)

CodePudding user response:

this is more a math problem than a programming problem.

Maybe you can do something like this, if 0 is allowed.

var random = new Random();
final predefindedNumber = 243;
var rest = predefindedNumber;
final firstValue = random.nextInt(predefindedNumber);
rest -= firstValue;
final secondValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= secondValue;
final thirdValue =  rest <= 0 ? 0 : random.nextInt(rest);
rest -= thirdValue;
final fourthValue =  rest;


print("$fourthValue $secondValue $thirdValue $fourthValue");

With this implementation it´s possible to get somthing like this 243 0 0 0

CodePudding user response:

This works:

import 'dart:math';
  
void main() {
  int numberOfRandNb = 4;
  List randomNumbers = [];
  int predefinedNumber = 243;
  
  for(int i = 0; i < numberOfRandNb - 1; i  ) {
    int randNb = Random().nextInt(predefinedNumber);
    randomNumbers.add(randNb);
    predefinedNumber -= randNb;
  }
  
  randomNumbers.add(predefinedNumber);
  
  print(randomNumbers.join(' '));
}
  • Related