UNPKG

tycho-solver

Version:

Evolutionary computation and optimization library

34 lines 1.18 kB
export class SelectionOperatorImpl { rng; constructor(rng) { this.rng = rng; } // Tournament selection as the default logic select(population, fitnesses, numParents, tournamentSize = 2) { const selected = []; const n = population.length; if (n === 0) { return selected; } const tSize = Math.max(1, Math.min(tournamentSize, n)); for (let i = 0; i < numParents; i++) { // Randomly pick tSize individuals (with replacement) const indices = []; for (let k = 0; k < tSize; k++) { const idx = this.rng ? this.rng.int(n) : Math.floor(Math.random() * n); indices.push(Math.max(0, Math.min(n - 1, idx))); } let bestIdx = indices[0]; for (const idx of indices) { if ((fitnesses[idx] ?? -Infinity) > (fitnesses[bestIdx] ?? -Infinity)) { bestIdx = idx; } } selected.push(population[bestIdx]); } return selected; } } //# sourceMappingURL=SelectionOperator.js.map