From 70a5b8883efe6663c3ca15b1749a6cbd4f35ebf2 Mon Sep 17 00:00:00 2001 From: Evan Date: Mon, 20 Jan 2025 20:15:25 -0800 Subject: [PATCH] make calculate clusters more efficient --- src/core/Util.ts | 2 +- src/core/execution/PlayerExecution.ts | 31 +++++++++++---------------- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/src/core/Util.ts b/src/core/Util.ts index 2402ae095..67a3cd23f 100644 --- a/src/core/Util.ts +++ b/src/core/Util.ts @@ -133,7 +133,7 @@ export function inscribed(outer: { min: Cell; max: Cell }, inner: { min: Cell; m ); } -export function getMode(list: number[]): number { +export function getMode(list: Set): number { // Count occurrences const counts = new Map() for (const item of list) { diff --git a/src/core/execution/PlayerExecution.ts b/src/core/execution/PlayerExecution.ts index 1cfc4d6af..ed5097d6a 100644 --- a/src/core/execution/PlayerExecution.ts +++ b/src/core/execution/PlayerExecution.ts @@ -92,9 +92,6 @@ export class PlayerExecution implements Execution { private removeClusters() { const clusters = this.calculateClusters() - // if (clusters.length <= 1) { - // return - // } clusters.sort((a, b) => b.size - a.size); const main = clusters.shift() @@ -148,18 +145,20 @@ export class PlayerExecution implements Execution { } private removeCluster(cluster: Set) { - const arr = Array.from(cluster) - const mode = getMode( - arr - .flatMap(t => this.mg.neighbors(t)) - .filter(t => this.mg.hasOwner(t) && this.mg.ownerID(t) != this.player.smallID()) - .map(t => this.mg.ownerID(t)) - ) + const result = new Set(); // Use Set to automatically deduplicate ownerIDs + for (const t of cluster) { + for (const neighbor of this.mg.neighbors(t)) { + if (this.mg.ownerID(neighbor) != this.player.smallID()) { + result.add(this.mg.ownerID(neighbor)); + } + } + } + const mode = getMode(result) if (!this.mg.playerBySmallID(mode).isPlayer()) { consolex.warn('mode is not found') return } - const firstTile = arr[0] + const firstTile = cluster.values().next().value const filter = (_, t: TileRef): boolean => this.mg.ownerID(t) == this.mg.ownerID(firstTile) const tiles = this.mg.bfs(firstTile, filter) @@ -184,19 +183,15 @@ export class PlayerExecution implements Execution { const cluster = new Set() const queue: TileRef[] = [tile] seen.add(tile) - let loops = 0; while (queue.length > 0) { - loops += 1 const curr = queue.shift() cluster.add(curr) const neighbors = (this.mg as GameImpl).neighborsWithDiag(curr) for (const neighbor of neighbors) { - if (this.mg.isBorder(neighbor) && border.has(neighbor)) { - if (!seen.has(neighbor)) { - queue.push(neighbor) - seen.add(neighbor) - } + if (border.has(neighbor) && !seen.has(neighbor)) { + queue.push(neighbor) + seen.add(neighbor) } } }