🚀 imrpove algorithm

This commit is contained in:
platane
2020-10-31 17:23:19 +01:00
parent d81ecec836
commit b595e7de53
22 changed files with 707 additions and 451 deletions

View File

@@ -1,34 +1,40 @@
import { getBestRoute } from "../getBestRoute";
import { snake3 } from "@snk/types/__fixtures__/snake";
import { snake3, snake4 } from "@snk/types/__fixtures__/snake";
import {
getHeadX,
getHeadY,
getSnakeLength,
Snake,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { createFromSeed } from "@snk/types/__fixtures__/createFromSeed";
const n = 1000;
const width = 5;
const height = 5;
it(`should find solution for ${n} ${width}x${height} generated grids`, () => {
const results = Array.from({ length: n }, (_, seed) => {
const grid = createFromSeed(seed, width, height);
try {
const chain = getBestRoute(grid, snake3);
for (const { width, height, snake } of [
{ width: 5, height: 5, snake: snake3 },
{ width: 5, height: 5, snake: snake4 },
])
it(`should find solution for ${n} ${width}x${height} generated grids for ${getSnakeLength(
snake
)} length snake`, () => {
const results = Array.from({ length: n }, (_, seed) => {
const grid = createFromSeed(seed, width, height);
assertValidPath(chain);
try {
const chain = getBestRoute(grid, snake);
return { seed };
} catch (error) {
return { seed, error };
}
assertValidPath(chain);
return { seed };
} catch (error) {
return { seed, error };
}
});
expect(results.filter((x) => x.error)).toEqual([]);
});
expect(results.filter((x) => x.error)).toEqual([]);
});
const assertValidPath = (chain: Snake[]) => {
for (let i = 0; i < chain.length - 1; i++) {
const dx = getHeadX(chain[i + 1]) - getHeadX(chain[i]);

View File

@@ -1,147 +0,0 @@
import { Color, getColor, isEmpty, setColorEmpty } from "@snk/types/grid";
import {
getHeadX,
getHeadY,
getSnakeLength,
nextSnake,
} from "@snk/types/snake";
import type { Snake } from "@snk/types/snake";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
import { getBestTunnel, trimTunnelEnd, trimTunnelStart } from "./getBestTunnel";
import { getPathTo } from "./getPathTo";
import { getTunnels } from "./getTunnels";
/**
* eat all the cell for which the color is smaller or equals to color and are reachable without going though cells with color+1 or higher
* attempt to eat the smaller color first
*/
export const cleanColoredLayer = (grid: Grid, snake0: Snake, color: Color) => {
const chain: Snake[] = [snake0];
const snakeN = getSnakeLength(snake0);
const tunnels = getTunnels(grid, getSnakeLength(snake0), color)
.map((tunnel) => ({ tunnel, f: tunnelScore(grid, color, tunnel) }))
.sort((a, b) => a.f - b.f);
while (tunnels.length) {
// get the best candidates
const candidates = tunnels.filter((a, _, [a0]) => a.f === a0.f);
// get the closest one
{
const x = getHeadX(chain[0]);
const y = getHeadY(chain[0]);
candidates.sort(
({ tunnel: [a] }, { tunnel: [b] }) =>
distanceSq(x, y, a.x, a.y) - distanceSq(x, y, b.x, b.y)
);
}
// pick tunnel and recompute it
// it might not be relevant since the grid changes
// in some edge case, it could lead to the snake reaching the first cell from the initial exit side
// causing it to self collide when on it's way through the tunnel
const { tunnel: tunnelCandidate } = candidates[0];
const tunnel = getBestTunnel(
grid,
tunnelCandidate[0].x,
tunnelCandidate[0].y,
color,
snakeN
)!;
// move to the start of the tunnel
chain.unshift(...getPathTo(grid, chain[0], tunnel[0].x, tunnel[0].y)!);
// move into the tunnel
chain.unshift(...getTunnelPath(chain[0], tunnel));
// update grid
for (const { x, y } of tunnel) setColorEmpty(grid, x, y);
// update other tunnels
// eventually remove the ones made empty
for (let i = tunnels.length; i--; ) {
updateTunnel(grid, tunnels[i].tunnel, tunnel);
if (tunnels[i].tunnel.length === 0) tunnels.splice(i, 1);
else tunnels[i].f = tunnelScore(grid, color, tunnels[i].tunnel);
}
tunnels.sort((a, b) => a.f - b.f);
}
return chain.slice(0, -1);
};
/**
* get the score of the tunnel
* prioritize tunnel with maximum color smaller than <color> and with minimum <color>
* with some tweaks
*/
const tunnelScore = (grid: Grid, color: Color, tunnel: Point[]) => {
let nColor = 0;
let nLess = 0;
let nLessLead = -1;
for (const { x, y } of tunnel) {
const c = getColor(grid, x, y);
if (!isEmpty(c)) {
if (c === color) {
nColor++;
if (nLessLead === -1) nLessLead = nLess;
} else nLess += color - c;
}
}
if (nLess === 0) return 999999;
return -nLessLead * 100 + (1 - nLess / nColor);
};
const distanceSq = (ax: number, ay: number, bx: number, by: number) =>
(ax - bx) ** 2 + (ay - by) ** 2;
/**
* get the sequence of snake to cross the tunnel
*/
const getTunnelPath = (snake0: Snake, tunnel: Point[]) => {
const chain: Snake[] = [];
let snake = snake0;
for (let i = 1; i < tunnel.length; i++) {
const dx = tunnel[i].x - getHeadX(snake);
const dy = tunnel[i].y - getHeadY(snake);
snake = nextSnake(snake, dx, dy);
chain.unshift(snake);
}
return chain;
};
/**
* assuming the grid change and the colors got deleted, update the tunnel
*/
const updateTunnel = (grid: Grid, tunnel: Point[], toDelete: Point[]) => {
trimTunnelStart(grid, tunnel);
trimTunnelEnd(grid, tunnel);
while (tunnel.length) {
const { x, y } = tunnel[0];
if (toDelete.some((p) => p.x === x && p.y === y)) {
tunnel.shift();
trimTunnelStart(grid, tunnel);
} else break;
}
while (tunnel.length) {
const { x, y } = tunnel[tunnel.length - 1];
if (toDelete.some((p) => p.x === x && p.y === y)) {
tunnel.pop();
trimTunnelEnd(grid, tunnel);
} else break;
}
};

View File

@@ -0,0 +1,130 @@
import {
getColor,
isEmpty,
isInside,
isInsideLarge,
setColorEmpty,
} from "@snk/types/grid";
import {
getHeadX,
getHeadY,
getSnakeLength,
nextSnake,
snakeEquals,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { around4, Point } from "@snk/types/point";
import { getBestTunnel } from "./getBestTunnel";
import { fillOutside } from "./outside";
import type { Outside } from "./outside";
import type { Snake } from "@snk/types/snake";
import type { Color, Empty, Grid } from "@snk/types/grid";
export const clearCleanColoredLayer = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const snakeN = getSnakeLength(snake0);
const points = getTunnellablePoints(grid, outside, snakeN, color);
const chain: Snake[] = [snake0];
while (points.length) {
const path = getPathToNextPoint(grid, chain[0], color, points)!;
path.pop();
for (const snake of path)
setEmptySafe(grid, getHeadX(snake), getHeadY(snake));
chain.unshift(...path);
}
fillOutside(outside, grid);
chain.pop();
return chain;
};
type M = { snake: Snake; parent: M | null };
const unwrap = (m: M | null): Snake[] =>
!m ? [] : [m.snake, ...unwrap(m.parent)];
const getPathToNextPoint = (
grid: Grid,
snake0: Snake,
color: Color,
points: Point[]
) => {
const closeList: Snake[] = [];
const openList: M[] = [{ snake: snake0 } as any];
while (openList.length) {
const o = openList.shift()!;
const x = getHeadX(o.snake);
const y = getHeadY(o.snake);
const i = points.findIndex((p) => p.x === x && p.y === y);
if (i >= 0) {
points.splice(i, 1);
return unwrap(o);
}
for (const { x: dx, y: dy } of around4) {
if (
isInsideLarge(grid, 2, x + dx, y + dy) &&
!snakeWillSelfCollide(o.snake, dx, dy) &&
getColorSafe(grid, x + dx, y + dy) <= color
) {
const snake = nextSnake(o.snake, dx, dy);
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
closeList.push(snake);
openList.push({ snake, parent: o });
}
}
}
}
};
/**
* get all cells that are tunnellable
*/
export const getTunnellablePoints = (
grid: Grid,
outside: Outside,
snakeN: number,
color: Color
) => {
const points: Point[] = [];
for (let x = grid.width; x--; )
for (let y = grid.height; y--; ) {
const c = getColor(grid, x, y);
if (
!isEmpty(c) &&
c <= color &&
!points.some((p) => p.x === x && p.y === y)
) {
const tunnel = getBestTunnel(grid, outside, x, y, color, snakeN);
if (tunnel)
for (const p of tunnel)
if (!isEmptySafe(grid, p.x, p.y)) points.push(p);
}
}
return points;
};
const getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};
const isEmptySafe = (grid: Grid, x: number, y: number) =>
!isInside(grid, x, y) && isEmpty(getColor(grid, x, y));

View File

@@ -0,0 +1,152 @@
import {
Empty,
getColor,
isEmpty,
isInside,
setColorEmpty,
} from "@snk/types/grid";
import { getHeadX, getHeadY, getSnakeLength } from "@snk/types/snake";
import { getBestTunnel } from "./getBestTunnel";
import { fillOutside, Outside } from "./outside";
import { getTunnelPath } from "./tunnel";
import { getPathTo } from "./getPathTo";
import type { Snake } from "@snk/types/snake";
import type { Color, Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
type T = Point & { tunnel: Point[]; priority: number };
export const clearResidualColoredLayer = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const snakeN = getSnakeLength(snake0);
const tunnels = getTunnellablePoints(grid, outside, snakeN, color);
// sort
tunnels.sort((a, b) => a.priority - b.priority);
const chain: Snake[] = [snake0];
while (tunnels.length) {
// get the best next tunnel
let t = getNextTunnel(tunnels, chain[0]);
// goes to the start of the tunnel
chain.unshift(...getPathTo(grid, chain[0], t[0].x, t[0].y)!);
// goes to the end of the tunnel
chain.unshift(...getTunnelPath(chain[0], t));
// update grid
for (const { x, y } of t) setEmptySafe(grid, x, y);
// update outside
fillOutside(outside, grid);
// update tunnels
for (let i = tunnels.length; i--; )
if (isEmpty(getColor(grid, tunnels[i].x, tunnels[i].y)))
tunnels.splice(i, 1);
else {
const t = tunnels[i];
const tunnel = getBestTunnel(grid, outside, t.x, t.y, color, snakeN);
if (!tunnel) tunnels.splice(i, 1);
else {
t.tunnel = tunnel;
t.priority = getPriority(grid, color, tunnel);
}
}
// re-sort
tunnels.sort((a, b) => a.priority - b.priority);
}
chain.pop();
return chain;
};
const getNextTunnel = (ts: T[], snake: Snake) => {
let minDistance = Infinity;
let closestTunnel: Point[] | null = null;
const x = getHeadX(snake);
const y = getHeadY(snake);
const priority = ts[0].priority;
for (let i = 0; ts[i] && ts[i].priority <= priority; i++) {
const t = ts[i].tunnel;
const d = distanceSq(t[0].x, t[0].y, x, y);
if (d < minDistance) {
minDistance = d;
closestTunnel = t;
}
}
return closestTunnel!;
};
/**
* get all the tunnels for all the cells accessible
*/
export const getTunnellablePoints = (
grid: Grid,
outside: Outside,
snakeN: number,
color: Color
) => {
const points: T[] = [];
for (let x = grid.width; x--; )
for (let y = grid.height; y--; ) {
const c = getColor(grid, x, y);
if (!isEmpty(c) && c < color) {
const tunnel = getBestTunnel(grid, outside, x, y, color, snakeN);
if (tunnel) {
const priority = getPriority(grid, color, tunnel);
points.push({ x, y, priority, tunnel });
}
}
}
return points;
};
/**
* get the score of the tunnel
* prioritize tunnel with maximum color smaller than <color> and with minimum <color>
* with some tweaks
*/
export const getPriority = (grid: Grid, color: Color, tunnel: Point[]) => {
let nColor = 0;
let nLess = 0;
for (let i = 0; i < tunnel.length; i++) {
const { x, y } = tunnel[i];
const c = getColorSafe(grid, x, y);
if (!isEmpty(c) && i === tunnel.findIndex((p) => p.x === x && p.y === y)) {
if (c === color) nColor += 1;
else nLess += color - c;
}
}
if (nColor === 0) return 99999;
return nLess / nColor;
};
const distanceSq = (ax: number, ay: number, bx: number, by: number) =>
(ax - bx) ** 2 + (ay - by) ** 2;
const getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};

View File

@@ -1,14 +1,22 @@
import { Color, copyGrid } from "@snk/types/grid";
import type { Grid } from "@snk/types/grid";
import { cleanColoredLayer } from "./cleanColoredLayer";
import { copyGrid } from "@snk/types/grid";
import { createOutside } from "./outside";
import { clearResidualColoredLayer } from "./clearResidualColoredLayer";
import { clearCleanColoredLayer } from "./clearCleanColoredLayer";
import type { Color, Grid } from "@snk/types/grid";
import type { Snake } from "@snk/types/snake";
export const getBestRoute = (grid0: Grid, snake0: Snake) => {
const grid = copyGrid(grid0);
const outside = createOutside(grid);
const chain: Snake[] = [snake0];
for (const color of extractColors(grid))
chain.unshift(...cleanColoredLayer(grid, chain[0], color));
for (const color of extractColors(grid)) {
if (color > 1)
chain.unshift(
...clearResidualColoredLayer(grid, outside, chain[0], color)
);
chain.unshift(...clearCleanColoredLayer(grid, outside, chain[0], color));
}
return chain.reverse();
};

View File

@@ -1,10 +1,4 @@
import {
copyGrid,
getColor,
isEmpty,
isInside,
setColorEmpty,
} from "@snk/types/grid";
import { copyGrid, getColor, isInside, setColorEmpty } from "@snk/types/grid";
import { around4 } from "@snk/types/point";
import { sortPush } from "./utils/sortPush";
import {
@@ -15,75 +9,57 @@ import {
snakeEquals,
snakeWillSelfCollide,
} from "@snk/types/snake";
import { isOutside } from "./outside";
import { trimTunnelEnd, trimTunnelStart } from "./tunnel";
import type { Outside } from "./outside";
import type { Snake } from "@snk/types/snake";
import type { Color, Grid } from "@snk/types/grid";
import type { Empty, Color, Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
type M = {
snake: Snake;
grid: Grid;
parent: M | null;
w: number;
h: number;
f: number;
const getColorSafe = (grid: Grid, x: number, y: number) =>
isInside(grid, x, y) ? getColor(grid, x, y) : (0 as Empty);
const setEmptySafe = (grid: Grid, x: number, y: number) => {
if (isInside(grid, x, y)) setColorEmpty(grid, x, y);
};
type M = { snake: Snake; parent: M | null; w: number };
const unwrap = (m: M | null): Point[] =>
!m
? []
: [...unwrap(m.parent), { x: getHeadX(m.snake), y: getHeadY(m.snake) }];
/**
* returns the path to reach the outside which contains the least color cell
*/
const getSnakeEscapePath = (grid0: Grid, snake0: Snake, color: Color) => {
const openList: M[] = [
{ snake: snake0, grid: grid0, w: 0, h: 0, f: 0, parent: null },
];
const getSnakeEscapePath = (
grid: Grid,
outside: Outside,
snake0: Snake,
color: Color
) => {
const openList: M[] = [{ snake: snake0, w: 0 } as any];
const closeList: Snake[] = [];
while (openList.length) {
while (openList[0]) {
const o = openList.shift()!;
const x = getHeadX(o.snake);
const y = getHeadY(o.snake);
if (isOutside(outside, x, y)) return unwrap(o);
for (const a of around4) {
if (!snakeWillSelfCollide(o.snake, a.x, a.y)) {
const y = getHeadY(o.snake) + a.y;
const x = getHeadX(o.snake) + a.x;
const c = getColorSafe(grid, x + a.x, y + a.y);
if (!isInside(grid0, x, y)) {
// unwrap and return
const points: Point[] = [];
if (c <= color && !snakeWillSelfCollide(o.snake, a.x, a.y)) {
const snake = nextSnake(o.snake, a.x, a.y);
points.push({ x, y });
let e: M["parent"] = o;
while (e) {
points.unshift({
x: getHeadX(e.snake),
y: getHeadY(e.snake),
});
e = e.parent;
}
return points;
}
const u = getColor(grid0, x, y);
if (isEmpty(u) || u <= color) {
const snake = nextSnake(o.snake, a.x, a.y);
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
let grid = o.grid;
if (!isEmpty(u)) {
grid = copyGrid(grid);
setColorEmpty(grid, x, y);
}
const h = Math.abs(grid.height / 2 - y);
const w = o.w + (u === color ? 1 : 0);
const f = w * 1000 - h;
sortPush(
openList,
{ snake, grid, parent: o, h, w, f },
(a, b) => a.f - b.f
);
closeList.push(snake);
}
if (!closeList.some((s0) => snakeEquals(s0, snake))) {
const w = o.w + 1 + +(c === color) * 1000;
sortPush(openList, { snake, w, parent: o }, (a, b) => a.w - b.w);
closeList.push(snake);
}
}
}
@@ -99,15 +75,16 @@ const getSnakeEscapePath = (grid0: Grid, snake0: Snake, color: Color) => {
*/
export const getBestTunnel = (
grid: Grid,
outside: Outside,
x: number,
y: number,
color: Color,
snakeN: number
) => {
const c = { x, y };
const snake = createSnakeFromCells(Array.from({ length: snakeN }, () => c));
const snake0 = createSnakeFromCells(Array.from({ length: snakeN }, () => c));
const one = getSnakeEscapePath(grid, snake, color);
const one = getSnakeEscapePath(grid, outside, snake0, color);
if (!one) return null;
@@ -119,46 +96,18 @@ export const getBestTunnel = (
// remove from the grid the colors that one eat
const gridI = copyGrid(grid);
for (const { x, y } of one)
if (isInside(grid, x, y)) setColorEmpty(gridI, x, y);
for (const { x, y } of one) setEmptySafe(gridI, x, y);
const two = getSnakeEscapePath(gridI, snakeI, color);
const two = getSnakeEscapePath(gridI, outside, snakeI, color);
if (!two) return null;
one.shift();
one.reverse();
one.push(...two);
trimTunnelStart(grid, one);
trimTunnelEnd(grid, one);
return one;
};
/**
* remove empty cell from start
*/
export const trimTunnelStart = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const { x, y } = tunnel[0];
if (!isInside(grid, x, y) || isEmpty(getColor(grid, x, y))) tunnel.shift();
else break;
}
};
/**
* remove empty cell from end
*/
export const trimTunnelEnd = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const i = tunnel.length - 1;
const { x, y } = tunnel[i];
if (
!isInside(grid, x, y) ||
isEmpty(getColor(grid, x, y)) ||
tunnel.findIndex((p) => p.x === x && p.y === y) < i
)
tunnel.pop();
else break;
}
};

View File

@@ -1,21 +0,0 @@
import { Color, getColor, isEmpty } from "@snk/types/grid";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
import { getBestTunnel } from "./getBestTunnel";
/**
* get all the tunnels for all the cells accessible
*/
export const getTunnels = (grid: Grid, snakeN: number, color: Color) => {
const tunnels: Point[][] = [];
for (let x = grid.width; x--; )
for (let y = grid.height; y--; ) {
const c = getColor(grid, x, y);
if (!isEmpty(c) && c <= color) {
const tunnel = getBestTunnel(grid, x, y, color, snakeN);
if (tunnel) tunnels.push(tunnel);
}
}
return tunnels;
};

View File

@@ -0,0 +1,48 @@
import {
createEmptyGrid,
getColor,
isEmpty,
isInside,
setColor,
setColorEmpty,
} from "@snk/types/grid";
import { around4 } from "@snk/types/point";
import type { Color, Grid } from "@snk/types/grid";
export type Outside = Grid & { __outside: true };
export const createOutside = (grid: Grid, color: Color = 0 as Color) => {
const outside = createEmptyGrid(grid.width, grid.height) as Outside;
for (let x = outside.width; x--; )
for (let y = outside.height; y--; ) setColor(outside, x, y, 1 as Color);
fillOutside(outside, grid, color);
return outside;
};
export const fillOutside = (
outside: Outside,
grid: Grid,
color: Color = 0 as Color
) => {
let changed = true;
while (changed) {
changed = false;
for (let x = outside.width; x--; )
for (let y = outside.height; y--; )
if (
getColor(grid, x, y) <= color &&
!isOutside(outside, x, y) &&
around4.some((a) => isOutside(outside, x + a.x, y + a.y))
) {
changed = true;
setColorEmpty(outside, x, y);
}
}
return outside;
};
export const isOutside = (outside: Outside, x: number, y: number) =>
!isInside(outside, x, y) || isEmpty(getColor(outside, x, y));

View File

@@ -0,0 +1,81 @@
import { getColor, isEmpty, isInside } from "@snk/types/grid";
import { getHeadX, getHeadY, nextSnake } from "@snk/types/snake";
import type { Snake } from "@snk/types/snake";
import type { Grid } from "@snk/types/grid";
import type { Point } from "@snk/types/point";
/**
* get the sequence of snake to cross the tunnel
*/
export const getTunnelPath = (snake0: Snake, tunnel: Point[]) => {
const chain: Snake[] = [];
let snake = snake0;
for (let i = 1; i < tunnel.length; i++) {
const dx = tunnel[i].x - getHeadX(snake);
const dy = tunnel[i].y - getHeadY(snake);
snake = nextSnake(snake, dx, dy);
chain.unshift(snake);
}
return chain;
};
/**
* assuming the grid change and the colors got deleted, update the tunnel
*/
export const updateTunnel = (
grid: Grid,
tunnel: Point[],
toDelete: Point[]
) => {
while (tunnel.length) {
const { x, y } = tunnel[0];
if (
isEmptySafe(grid, x, y) ||
toDelete.some((p) => p.x === x && p.y === y)
) {
tunnel.shift();
} else break;
}
while (tunnel.length) {
const { x, y } = tunnel[tunnel.length - 1];
if (
isEmptySafe(grid, x, y) ||
toDelete.some((p) => p.x === x && p.y === y)
) {
tunnel.pop();
} else break;
}
};
const isEmptySafe = (grid: Grid, x: number, y: number) =>
!isInside(grid, x, y) || isEmpty(getColor(grid, x, y));
/**
* remove empty cell from start
*/
export const trimTunnelStart = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const { x, y } = tunnel[0];
if (isEmptySafe(grid, x, y)) tunnel.shift();
else break;
}
};
/**
* remove empty cell from end
*/
export const trimTunnelEnd = (grid: Grid, tunnel: Point[]) => {
while (tunnel.length) {
const i = tunnel.length - 1;
const { x, y } = tunnel[i];
if (
isEmptySafe(grid, x, y) ||
tunnel.findIndex((p) => p.x === x && p.y === y) < i
)
tunnel.pop();
else break;
}
};