Untitled

 avatar
unknown
typescript
a year ago
1.6 kB
4
Indexable
const stations = [
  [0, 0, 10],
  [20, 20, 5],
  [10, 0, 12],
];

const points = [
  [0, 0],
  [100, 100],
  [15, 10],
  [18, 18],
];

const calculatePower = ({
  reach,
  distance,
}: {
  reach: number;
  distance: number;
}) => {
  if (distance > reach) return 0;
  return (reach - distance) ** 2;
};

const calculateDistance = ({
  x1,
  y1,
  x2,
  y2,
}: {
  x1: number;
  y1: number;
  x2: number;
  y2: number;
}) => {
  const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
  return distance;
};

const main = (x: number, y: number) => {
  const stationsPower: Record<number, number> = {};

  stations.forEach((station, index) => {
    const distance = calculateDistance({
      x1: station[0],
      y1: station[1],
      x2: x,
      y2: y,
    });
    const power = calculatePower({
      reach: station[2],
      distance,
    });
    stationsPower[index] = power;
  });

  const powers = Object.values(stationsPower);
  powers.sort((a, b) => b - a);

  const maximumPower = powers[0];

  const stationWithMaximumPower = Object.entries(stationsPower).reduce(
    (acc: number[], cur) => {
      if (cur[1] === maximumPower) {
        return stations[cur[0] as unknown as number];
      }
      return acc;
    },
    []
  );

  if (maximumPower === 0) {
    return `No link station within reach for point ${x}, ${y}`;
  }
  return `Best link station for point ${x}, ${y} is ${stationWithMaximumPower[0]}, ${stationWithMaximumPower[1]} with power ${maximumPower}`;
};

points.forEach((point) => {
  console.log(main(point[0], point[1]));
});
Editor is loading...
Leave a Comment