encode method

dynamic encode(
  1. dynamic arrangement
)

Given an arrangement of pieces, returns the starting position's ID.

@see {@link https://chess960frc.blogspot.com/2010/11/calculate-sp-numbers-in-your-head.html}

@param {string[]|string} arrangement A starting position's arrangement @returns {number} The starting position's ID, or -1 if invalid arrangement

Implementation

dynamic encode(arrangement) {
    if (!FischerRandomValidators().isValidArrangement(arrangement)) return -1;
    List<String> arrng = [];
    if (arrangement is String) {
      arrng = arrangement.runes.map((e) => String.fromCharCode(e).toString()).toList();
    } else {
      arrng = arrangement;
    }

    int id = 0;

    // Add value for the sequence of K, R, N
    String sequence = arrng.where((piece) => 'KRN'.contains(piece)).join('');
    id += KRN_TABLE.indexOf(sequence) * 96;

    // Add value for the position of the queen within K, R, N, Q
    id += ((arrng.where((piece) => 'KRNQ'.contains(piece)).toList().indexOf('Q')) * 16).toInt();

    // Add value for the combined positions of the bishops
    int firstB = arrng.indexOf('B');
    int secondB = arrng.lastIndexOf('B');
    id += BISHOP_TABLE.indexOf(firstB + secondB);

    return (id < 0 ? -1 : id);
  }