1
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ラーニング レベルアップ問題集 巡回セールスマン問題メニュー JavaScript ユークリッド距離

Last updated at Posted at 2022-09-27

ユークリッド距離 (paizaランク D 相当)

JavaScriptで解いてみました。
問題文にしたがって実装します。

ユークリッド距離は、√((x_1-x_2)^2 + (y_1-y_2)^2)です。

解答例

平方根はMath.sqrt()で、二乗を**で計算します。

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

const [x_1, y_1] = lines[0].split(" ").map(Number);
const [x_2, y_2] = lines[1].split(" ").map(Number);
console.log(Math.sqrt((x_1 - x_2) ** 2 + (y_1 - y_2) ** 2))

解答例(C++の場合とPython3の場合参考)

ユークリッド距離の計算式を、関数定義しています。
二乗の計算は、Math.pow()を使います。

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

//ユークリッド距離の計算式を、関数定義
const dist = (a, b) => {
  return Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2));    
}; 

const [x_1, y_1] = lines[0].split(" ").map(Number);
const [x_2, y_2] = lines[1].split(" ").map(Number);

console.log(dist([x_1, y_1], [x_2, y_2]));
1
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
1
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?