balance static method

String balance(
  1. String equation
)

Balances a chemical equation.

Input format: "H2 + O2 = H2O" or "H2 + O2 -> H2O" Output format: "2H2 + O2 = 2H2O"

Returns the balanced equation as a string. If the equation cannot be balanced, returns an error message.

Implementation

static String balance(String equation) {
  try {
    // Normalize the equation
    equation = equation.replaceAll(' ', '');
    equation = equation.replaceAll('->', '=');

    // Split into reactants and products
    final parts = equation.split('=');
    if (parts.length != 2) {
      return 'Error: Invalid equation format. Use format like "H2 + O2 = H2O"';
    }

    final reactants = parts[0].split('+');
    final products = parts[1].split('+');

    // Parse compounds and count elements
    final reactantCompounds = reactants.map((r) => _parseCompound(r.trim())).toList();
    final productCompounds = products.map((p) => _parseCompound(p.trim())).toList();

    // Get all unique elements in the reaction
    final allElements = <String>{};
    for (var compound in [...reactantCompounds, ...productCompounds]) {
      allElements.addAll(compound.keys);
    }

    // Construct the coefficient matrix for solving the system of equations
    final matrix = _constructMatrix(reactantCompounds, productCompounds, allElements.toList());

    // Solve the system using Gaussian elimination
    final coefficients = _solveMatrix(matrix);
    if (coefficients == null) {
      return 'Error: Could not balance equation. The equation may be invalid.';
    }

    // Scale coefficients to smallest possible integers
    final scaledCoefficients = _scaleCoefficients(coefficients);

    // Format the balanced equation
    return _formatBalancedEquation(reactants, products, scaledCoefficients.sublist(0, reactants.length), scaledCoefficients.sublist(reactants.length));
  } catch (e) {
    return 'Error balancing equation: $e';
  }
}