Find Mean, Median and Mode

I created this custom code that find the Mean, Median and Mode from a list of numbers from text field.
To separate the numbers it is used "," character and the "." is for decimal numbers.
The function also validate if the user type non numbers characteres or empty spaces.

The Custom Function with the code is the next one:

List<double> funcionMatematica(String entradaTexto) {
  /// MODIFY CODE ONLY BELOW THIS LINE

  double suma = 0, promedio = 0, mediana = 0, moda = 0;

  List<double?> listaDoubles = entradaTexto
      .replaceAll(RegExp(r'[^0-9.,]'), '')
      .split(',')
      .map((str) => double.tryParse(str))
      .where((value) => value != null)
      .toList();

  //Promedio
  int cantNumeros = listaDoubles.length;
  for (var i = 0; i < cantNumeros; i++) {
    suma += listaDoubles[i]!;
  } //for
  promedio = suma / cantNumeros;

  //Mediana
  listaDoubles.sort();

  mediana = (listaDoubles.length % 2 == 0
      ? (listaDoubles[listaDoubles.length ~/ 2]! +
              listaDoubles[listaDoubles.length ~/ 2 - 1]!) /
          2
      : listaDoubles[listaDoubles.length ~/ 2])!;

  //Moda
  Map<double, int> frecuencia = {};
  for (double? num in listaDoubles) {
    frecuencia[num!] = (frecuencia[num] ?? 0) + 1;
  } //for
  int frecenciaMax = 0;

  for (double num in frecuencia.keys) {
    if (frecuencia[num]! > frecenciaMax) {
      frecenciaMax = frecuencia[num]!;
      moda = num;
    } //if
  } //for

  if (frecenciaMax == 1) {
    moda = 0;
  }

  return [promedio, mediana, moda];

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

The return value of the function is a list of type double and recive one argument type String.


Example of Mean:

Example of Median:

Example of Mode:

If the user type blank spaces or non numbers the app don't have any problem:


5
1 reply