Skip to content

Instantly share code, notes, and snippets.

@esshka
Created October 26, 2023 17:46
Show Gist options
  • Save esshka/cc14724d3d7d578f006a559d85cc54b5 to your computer and use it in GitHub Desktop.
Save esshka/cc14724d3d7d578f006a559d85cc54b5 to your computer and use it in GitHub Desktop.
utility function for NEAT crossover
function getCombinedConnections(n1conns, n2conns, score1, score2, equal) {
// Split common conn genes from disjoint or excess conn genes
const keys1 = Object.keys(n1conns)
const keys2 = Object.keys(n2conns)
const commonKeys = keys1.filter(key => n2conns[key] !== undefined)
const commonConns = commonKeys.map(key => n1conns[key])
const other1Keys = keys1.filter(key => commonKeys.includes(key) === false)
const other2Keys = keys2.filter(key => commonKeys.includes(key) === false)
if (other1Keys.length === 0 && other2Keys.length === 0) return commonConns
const extraKeys = []
if (score1 >= score2 || equal) {
extraKeys.push(...other1Keys.filter(key => n2conns[key] === undefined)) // Excess/disjoint gene
}
if (score2 >= score1 || equal) {
extraKeys.push(...other2Keys.filter(key => n2conns[key] !== undefined)) // Excess/disjoint gene
}
const extraConns = extraKeys.map(key => n1conns[key] || n2conns[key])
return [...commonConns, ...extraConns].map(Number)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment