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?

【電脳少女プログラミング2088 ─壊レタ君を再構築─】Python初心者がやってみた(自然の残る公園編)

Last updated at Posted at 2025-02-24

はじめに

前回の記事で「ギャングのアジト」をクリアして、今回は「自然の残る公園」をクリアしたので書こうと思います。

難しくてまだクリアできてない方などに参考にしてもらえると嬉しいです。

【問題】

image.png
image.png

解答

今回もPython3を選択して書いてみました。

解答
# coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!

manhattan_distance_list = []

N, current_location_x, current_location_y = map(int, input().split()) # 空白で区切ってNと現在地を代入する

for i in range(N): # Nの数繰り返す
    beacon_str = input()  # 入力を受け取る
    
    beacon_x, beacon_y = (map(int, beacon_str.split())) # スペースで区切ってリストに変換
    
    manhattan_distance = (beacon_x - current_location_x) ** 2 + (beacon_y - current_location_y) ** 2 # ユークリッド距離を計算
    
    manhattan_distance_list.append(manhattan_distance) # リストに追加
    
answer = manhattan_distance_list.index(min(manhattan_distance_list)) + 1 # リストから一番小さい値の順番を取得して1足す

print(answer) # 解答を表示

コード解説

上のコードの解説をすると

7行目
N, current_location_x, current_location_y = map(int, input().split())

N(ビーコンの数)、current_location_x(現在地のx座標)、current_location_y(現在地のy座標)に入力された値を空白で区切って整数として代入


8行目~14行目
for i in range(N): # Nの数繰り返す
    beacon_str = input()  # 入力を受け取る
    
    beacon_x, beacon_y = (map(int, beacon_str.split())) # スペースで区切って代入
    
    manhattan_distance = (beacon_x - current_location_x) ** 2 + (beacon_y - current_location_y) ** 2 # 距離を計算
    
    manhattan_distance_list.append(manhattan_distance) # リストに追加

for文でNの数だけ下の処理を繰り返す

  1. 入力を受け取る
  2. スペースで区切ってbeacon_xbeacon_yにビーコンの座標を代入
  3. 問題文から引用した式で距離を計算

    (ビーコンの x 座標 - 現在地の x 座標 ) ^ 2 + (ビーコンの y 座標 - 現在地の y 座標) ^ 2

  4. 計算した値をリストmanhattan_distance_listに追加

6行目
answer = manhattan_distance_list.index(min(manhattan_distance_list))

答えをいれる変数answerを作成。
リストmanhattan_distance_listの中から一番小さい値が何番目かを取得してanswerに代入


こんな感じのコードで問題を解くことができました。

最後に

記事を最後までお読みいただきありがとうございます!
次回は「廃マンションの一室」をしようと思っています。次回も見てくださると嬉しいです。

ではまた他の記事で会いましょう!またねーヾ(´∀`)ノ

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?