0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 新・Bランクレベルアップメニュー JavaScript 【計算 1】マンハッタン距離

Posted at

【計算 1】マンハッタン距離 (paizaランク C 相当)

解答例

1〜N(>3) 番の番号が振られた地点のユークリッド距離とマンハッタン距離を計算し、配列に格納する。
配列を近い順に並べ替える。
近い3地点を出力する。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [P_x, P_y] = lines[0].split(" ").map(Number);
const N = Number(lines[1]);

const euclid = [];//ユークリッド距離
const manhattan = [];//マンハッタン距離

//距離を計算して配列に格納
for (let i = 1; i <= N; i++) {
  const [x, y] = lines[i + 1].split(" ").map(Number);
  //ユークリッド距離
  const l_e = Math.sqrt((x - P_x) ** 2 + (y - P_y) ** 2);
  euclid.push([l_e, i]);//[距離, 地点]で格納
  //マンハッタン距離
  const l_m = Math.abs(x - P_x) + Math.abs(y - P_y);
  manhattan.push([l_m, i]);//[距離, 地点]で格納
}

//距離が近い順に並べ替え
euclid.sort((a, b) => a[0] - b[0]);
manhattan.sort((a, b) => a[0] - b[0]);

//距離が近い3地点を出力
euclid.slice(0, 3).forEach(v => {
  console.log(v[1]);
});
manhattan.slice(0, 3).forEach(v => {
  console.log(v[1]);
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?