|
[奇數魔方陣] 奇數魔方陣是一種將 1 到 N2 的數字,排列在 N × N 的陣列上,其
中 1 < N < 20 且 N 必須為奇數,且各列(水平走向)、各行(垂直走向)與各對
角線的加總必須相同;舉例來說,如下圖 I 所示(N = 3),每一列、每一行及對角
線的加總皆為 15。填魔方陣的方法是將數字 1 放在第一列的正中央,然後向右上填,
若超出上邊界就跳到同一行的下邊界繼續(如圖 B、I 所示),若超出右邊界就跳到
同一列的左邊界繼續(如圖 C、H 所示),如果右上已有數字,則向下填(如圖 D、
G 所示,圈圈代表右上已經有數字)。
輸入/輸出說明:請在表單上建立 1個 LABEL、2個 TEXTBOX及一個按鈕。LABEL表示「輸入方陣維度 N」,相對應的第 1個 TEXTBOX可以輸入維度 N,按下按鈕後,在第 2個 TEXTBOX中印出 N×N 奇數魔方陣,各數字間以空格隔開;注意,若輸入 N 為偶數時,請於第 2個 TEXTBOX中印出 “N需大於 1且 N為奇數” 的訊息。程式執行順序:輸入 N,按下按鈕,輸出。
家豪版
這一版增加了視窗自動調大小的動做(如下紅色指令碼),其實比賽可以省略,
除非全部做完了,可以花一些時間在美觀。
Dim n As Integer = Val(TextBox1.Text)
Dim dx As Integer, dy As Integer, x As Integer, y As Integer
Dim xy(19,19) As Integer
If (n Mod 2 = 0) Then
TextBox2.Text = "N 需大於 1 且 N 為奇數"
Exit Sub
ElseIf ((n > 19) Or (n < 3)) Then
MsgBox("n 值錯誤(1<N<20),請重新輸入。")
Exit Sub
End If
TextBox2.Width = n * 61.5 : TextBox2.Height = n * 31 + 2
x = TextBox2.Left + TextBox2.Width : y = TextBox2.Top + TextBox2.Height
Me.Width = If(x < Button1.Left + Button1.Width + 30, Button1.Left + Button1.Width + 30, x + TextBox2.Left - 70)
Me.Height = Button1.Top + Button1.Height + y
TextBox2.Text = "" : x = n \ 2 : y = 0 : dx = 1 : dy = n - 1
For i = 1 To n * n
If (xy(x, y) <> 0) Then "碰撞
x = (x - dx + n) Mod n
y = (y - dy + n + 1) Mod n "退回後,往後退一格
End If
xy(x, y) = i
x = (x + dx) Mod n : y = (y + dy) Mod n
Next
For y = 0 To n - 1
For x = 0 To n - 1
TextBox2.Text = TextBox2.Text & String.Format("{0,4}", xy(x, y))
Next
TextBox2.Text = TextBox2.Text & vbNewLine
Next
昊朋版
Dim n As Integer = Val(TextBox8.Text)
If (n Mod 2 = 0) Or (n < 1) Then
TextBox9.Text = "N 需大於 1 且 N 為奇數"
Exit Sub
End If
TextBox9.Text = ""
Dim a(n, n) As Integer
For i = 1 To n
For j = 1 To n
a(i, j) = 0
Next
Next
Dim x As Integer = 1, y As Integer = 1
x = (n + 1) / 2
For i = 1 To n * n
a(x, y) = i
If Not a(IIf(x + 1 > n, 1, x + 1), IIf(y - 1 < 1, n, y - 1)) = 0 Then
y = IIf(y + 1 > n, n, y + 1)
Else
x = IIf(x + 1 > n, 1, x + 1)
y = IIf(y - 1 < 1, n, y - 1)
End If
Next
For i = 1 To n
For j = 1 To n
TextBox9.Text &= a(j, i) & " "
Next
TextBox9.Text &= vbNewLine
Next
黃翰版
Dim n As Integer = val(TextBox1.Text)
Dim i, j As Integer
Dim x, y, dy As Integer
Dim bx, by As Integer
Dim str As String = ""
Dim arr(n, n) As Integer
If n >= 20 Then
MsgBox("您輸入的N>19")
Exit Sub
ElseIf n Mod 2 = 0 Or n <= 1 Then
MsgBox("N 需大於 1 且 N 為奇數")
Exit Sub
End If
x = (n - 1) \ 2
y = 0
dy = n - 1
arr(x, y) = 1
For i = 2 To n * n
bx = (x + 1) Mod n
by = (y + dy) Mod n
If arr(bx, by) = 0 Then
x = bx
y = by
Else
y += 1
End If
arr(x, y) = i
Next
For i = 0 To n - 1
For j = 0 To n - 1
str &= arr(j, i) & " "
Next
str &= vbCrLf
Next
TextBox2.Text = str
|