[ya-day1] swimmer problem WIP

main
Vasily Guzov 1 year ago
parent 89a0abcbaf
commit 643d42c748

@ -0,0 +1,3 @@
import { toGetClosestPoint } from "./toGetClosestPoint";
export default toGetClosestPoint;

@ -0,0 +1,36 @@
import { describe, it, expect } from "vitest";
import { toGetClosestPoint } from "./toGetClosestPoint.ts";
describe("toGetClosestPoint", () => {
it("toGetClosestPoint equale NW", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, -4, 6)).toBe("NW");
});
it("toGetClosestPoint equale N", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, 4, 5)).toBe("N");
});
it("toGetClosestPoint equale NE", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, 9, 3)).toBe("NE");
});
it("toGetClosestPoint equale E", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, 7, 0)).toBe("E");
});
it("toGetClosestPoint equale SE", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, 8, -4)).toBe("SE");
});
it("toGetClosestPoint equale S", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, 2, -4)).toBe("S");
});
it("toGetClosestPoint equale SW", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, -5, -2)).toBe("SW");
});
it("toGetClosestPoint equale W", () => {
expect(toGetClosestPoint(-1, -2, 5, 3, -5, 2)).toBe("W");
});
});

@ -0,0 +1,66 @@
type Direction = "N" | "E" | "S" | "W" | "NW" | "NE" | "SW" | "SE";
export function toGetClosestPoint(
x1: number,
y1: number,
x2: number,
y2: number,
sx: number,
sy: number,
) {
let direction: Direction = "N";
const sectors: Record<Direction, number[]> = {
NW: [x1, y2],
N: [x1, y2],
NE: [x2, y2],
E: [x2, y2],
SE: [x2, y1],
S: [x1, y1],
SW: [x1, y1],
W: [x1, y2],
};
for (let key in sectors) {
const [x, y] = sectors[key];
if (sx <= x && sy >= y) {
direction = "NW";
break;
}
if (sx >= x && sy > y && sx <= x2) {
direction = "N";
break;
}
if (sx >= x && sy >= y) {
direction = "NE";
break;
}
if (sx >= x && sy <= y && sy >= y1) {
direction = "E";
break;
}
if (sx >= x && sy <= y && sx <= x2) {
direction = "S";
break;
}
if (sx >= x && sy <= y) {
direction = "SE";
break;
}
if (sy <= y && sx <= x) {
direction = "SW";
break;
}
if (sy <= y2 && sy >= y1 && sx <= x) {
direction = "W";
break;
}
}
return direction;
}
Loading…
Cancel
Save