2012年8月28日 星期二

奇數階魔方陣

Problem Description


所謂的 n階魔方陣,就是把1到n 的這n 個 連續的正 整數填到一個 n×n的方陣中,使得每一列的和、每一行的和、以及兩個對角線的和都相等。請設計一個程式可以完成n為奇數的魔方陣。

Input

n (奇數) 

Output

奇數階魔方陣
Sample Input

請輸入 n: 5
Sample Output

17, 24, 01, 08, 15
23, 05, 07, 14, 16
04, 06, 13, 20, 22
10, 12, 19, 21, 03
11, 18, 25, 02, 09

2 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Dim b() As String
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, n
    a = n * n
    ReDim b(n, n)
    c = 1
    d = (n \ 2) + 1
    For i = 1 To a
    If c > n Then c = 1
    If i < 10 Then i = "0" & i
    b(c, d) = i
    If i Mod n = 0 Then c = c + 2: d = d - 1
    d = d + 1
    d = d Mod n
    If d = 0 Then d = n
    c = c - 1
    If c = 0 Then c = n
    Next
    For i = 1 To n
    For j = 1 To n
    If j Mod n = 0 Then
    Print #2, b(i, j);
    Else
    Print #2, b(i, j) & ", ";
    End If
    Next
    Print #2,
    Next
    Close
    Close
    End
    End Sub
    用自己看到的規律下去寫,不然想不到其他方式了。

    回覆刪除
  2. Dim x, y, n As Integer
    Dim a() As String
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim ss As Boolean
    Input #1, n
    ReDim a(n, n)
    m = n ^ 2
    t = 1
    x = n \ 2 + 1: y = 1
    For k = 1 To n
    For G = 1 To n
    a(k, G) = "0"
    Next G, k

    For i = 1 To m
    If i = 1 Then
    a(x, y) = i
    Else
    x = x - 1: y = y + 1
    Call check(x, y)
    a(x, y) = i
    End If
    If Val(a(x, y)) < 10 Then a(x, y) = 0 & a(x, y)
    Next i
    For i2 = 1 To n
    For i3 = 1 To n
    If i3 Mod n = 0 Then
    Print #2, a(i2, i3);
    Else
    Print #2, a(i2, i3) & ",";
    End If
    Next i3
    Print #2,
    Next i2
    Close #2
    Close #1
    End
    End Sub
    Sub check(x, y)
    If x <= 0 Then x = n
    If y <= 0 Then y = n
    If y > n Then y = y - n
    If x > n Then x = x - n
    If a(x, y) <> "0" Then x = x + 2: y = y - 1: Call check(x, y)
    End Sub

    回覆刪除