關於棋盤的一個

WBOY
發布: 2024-08-12 18:32:32
原創
532 人瀏覽過

每週挑戰 281

很抱歉在過去的幾週我沒有表現出來。我搬了家,換了新工作,所以這段時間沒有機會參與挑戰。

穆罕默德·S·安瓦爾 (Mohammad S. Anwar) 每週都會發出“每週挑戰”,讓我們所有人都有機會為兩週的任務提出解決方案。我的解決方案先用Python編寫,然後轉換為Perl。這對我們所有人來說都是練習編碼的好方法。

挑戰,我的解決方案

任務 1:檢查顏色

任務

給定座標,一個表示棋盤正方形座標的字串,如下所示:

The one about a chess board

寫一個腳本,如果方塊較亮則回傳 true,如果方塊較暗則傳回 false。

我的解決方案

這相對簡單。我做的第一件事是檢查提供的位置是否有效(第一個字元是 a-h,第二個字元在 1 到 8 之間)。

然後檢查第一個字母是否為 a、c、e 或 g 且數字是偶數,或第一個字母是 b、d、f 或 h 且數字是奇數,則傳回 true。否則返回 false。

def check_color(coords: str) -> bool:
    if not re.search('^[a-h][1-8]$', coords):
        raise ValueError('Not a valid chess coordinate!')

    if coords[0] in ('a', 'c', 'e', 'g') and int(coords[1]) % 2 == 0:
        return True
    if coords[0] in ('b', 'd', 'f', 'h') and int(coords[1]) % 2 == 1:
        return True
    return False
登入後複製

範例

$ ./ch-1.py d3
true

$ ./ch-1.py g5
false

$ ./ch-1.py e6
true
登入後複製

任務2:騎士的行動

任務

西洋棋中的馬可以從目前位置移動到兩行或兩列加一列或一行之外的任意方格。所以在下圖中,如果它以 S 開頭,它可以移動到任何標記為 E 的方格。

The one about a chess board

編寫一個腳本,以起始位置和結束位置為基礎,併計算所需的最少移動次數。

我的解決方案

這個比較詳細。我從以下變數開始:

  • deltas 是一個列表元組(Perl 中的數組的數組),其中包含騎士從當前位置移動的八種方式。
  • target 是我們想要到達的儲存格。為此,我將第一個字母轉換為從 1 到 8 的數字。它儲存為元組,第一個值是列,第二個值是行。
  • move 是移動次數,從 1 開始。
  • see 是我們已經造訪過的儲存格清單。
  • coords 是騎士目前位置的清單。它從起始座標開始。
def knights_move(start_coord: str, end_coord: str) -> int:
    for coord in (start_coord, end_coord):
        if not re.search('^[a-h][1-8]$', coord):
            raise ValueError(
                f'The position {coord} is not a valid chess coordinate!')

    deltas = ([2, 1], [2, -1], [-2, 1], [-2, -1],
              [1, 2], [1, -2], [-1, 2], [-1, -2])
    coords = [convert_coord_to_list(start_coord)]
    target = convert_coord_to_list(end_coord)
    moves = 1
    seen = []
登入後複製

然後我有一個當前座標列表和增量列表的雙循環。設定一個變數 new_pos 代表騎士的新座標。如果這導致了棋盤之外的位置或我們已經去過的座標,我會跳過它。如果它落在目標上,我將返回移動值。

循環結束後,我將座標列表重設為透過迭代收集的座標,並將移動值加一。這一直持續到我們到達目標座標。

    while True:
        new_coords = []

        for coord in coords:
            for delta in deltas:
                new_pos = (coord[0] + delta[0], coord[1] + delta[1])

                if not 0 < new_pos[0] < 9 or not 0 < new_pos[1] < 9 or new_pos in seen:
                    continue

                if new_pos == target:
                    return moves

                new_coords.append(new_pos)
                seen.append(new_pos)

        coords = new_coords
        moves += 1
登入後複製

範例

$ ./ch-2.py g2 a8
4

$ ./ch-2.py g2 h2
3
登入後複製

以上是關於棋盤的一個的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!