2024年10月17日 星期四

順時針螺旋字串

 將輸入的字串以順時針螺旋方式填入一個最小正方形,並輸出填滿後的結果。這裡提供一個 Python 的解法,幫助你實現此問題的解決。

解題思路:

  1. 計算最小正方形邊長:根據字串長度計算出能裝下這個字串的最小正方形的邊長 n,這可以使用 n = math.ceil(根號(字串長度))
  2. 建立正方形矩陣:準備一個 n x n 的矩陣,並以順時針方向填入字串。
  3. 填入方式:從矩陣左上角開始,按照順時針方向進行填充,直到填滿所有字元。多餘的位置補上空白。
  4. 輸出結果:將矩陣中填好的結果依次輸出。

Python 範例程式碼:

import math

def fill_spiral(s):
    # 計算正方形的邊長
    n = math.ceil(math.sqrt(len(s)))
    
    # 建立空的 n x n 矩陣並填入空白
    matrix = [[' ' for _ in range(n)] for _ in range(n)]
    
    # 定義方向:右、下、左、上 (順時針方向)
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    direction_index = 0
    
    # 起始位置
    x, y = 0, 0
    # 設定邊界
    left, right, top, bottom = 0, n - 1, 0, n - 1
    
    # 將字串填入矩陣
    for char in s:
        matrix[x][y] = char
        # 計算下一步
        next_x = x + directions[direction_index][0]
        next_y = y + directions[direction_index][1]
        
        # 如果超出邊界,或已填入字元,則改變方向
        if next_x < top or next_x > bottom or next_y < left or next_y > right or matrix[next_x][next_y] != ' ':
            # 改變方向
            direction_index = (direction_index + 1) % 4
            next_x = x + directions[direction_index][0]
            next_y = y + directions[direction_index][1]
        
        # 更新位置
        x, y = next_x, next_y
    
    # 輸出結果
    for row in matrix:
        print(''.join(row))
    print()  # 每組測試資料輸出之間空一行

# 測試範例輸入
test_input = [
    "0123456789ABCDE",
    "111111111111111122222222"
]

# 對每一組輸入進行處理
for s in test_input:
    fill_spiral(s)

輸出結果:

0123
BCD4
A E5
9876

11111
12221
12 21
12221
11111

程式說明:

  1. fill_spiral 函數:主要功能是將字串按順時針螺旋方式填入矩陣。使用四個方向:右、下、左、上,並隨著填充來改變方向。
  2. 邊界控制:當達到矩陣邊界或遇到已填入的字符時,改變方向。
  3. 輸出:每組輸入結束後在結果之間留一行空白。

優化:

  • 如果需要處理較大的字串,可以優化方向變換的判斷。
  • 可以根據具體需求進行格式化或調整輸出方式。

這樣的程式可以滿足題目中的需求,處理多組輸入,並輸出對應的螺旋矩陣結果。

沒有留言:

張貼留言