4N 魔方陣


說明

奇數魔術方陣 相同,在於求各行、各列與各對角線的和相等,而這次方陣的維度是4的倍數。

解法

先來看看4X4方陣的解法:
4N 魔方陣


簡單的說,就是一個從左上由1依序開始填,但遇對角線不填,另一個由左上由16開始填,但只填在對角線,再將兩個合起來就是解答了;如果N大於2,則以 4X4為單位畫對角線:
4N 魔方陣

至於對角線的位置該如何判斷,有兩個公式,有興趣的可以畫圖印證看看,如下所示:
左上至右下:j % 4 == i % 4
右上至左下:(j % 4 + i) % 4 == 1

實作:C    Java    Python    Scala    Ruby

  • C
#include <stdio.h> 
#include <stdlib.h>

#define N 8

int main(void) {
int square[N+1][N+1] = {0};

int i, j;
for(j = 1; j <= N; j++) {
for(i = 1; i <= N; i++){
if(j % 4 == i % 4 || (j % 4 + i) % 4 == 1)
square[i][j] = (N+1-i) * N -j + 1;
else
square[i][j] = (i - 1) * N + j;
}
}

for(i = 1; i <= N; i++) {
for(j = 1; j <= N; j++)
printf("%2d ", square[i][j]);
printf("\n");
}

return 0;
}

  • Java
public class Matrix {
public static int[][] magic(int n) {
int[][] square = new int[n+1][n+1];

for(int j = 1; j <= n; j++) {
for(int i = 1; i <= n; i++){
if(j % 4 == i % 4 || (j % 4 + i) % 4 == 1)
square[i][j] = (n+1-i) * n -j + 1;
else
square[i][j] = (i - 1) * n + j;
}
}

int[][] matrix = new int[n][n];

for(int k = 0; k < matrix.length; k++) {
for(int l = 0; l < matrix[0].length; l++) {
matrix[k][l] = square[k+1][l+1];
}
}

return matrix;
}

public static void main(String[] args) {
for(int[] row : Matrix.magic(8)) {
for(int number: row) {
System.out.printf("%2d ", number);
}
System.out.println();
}
}
}

  • Python
def magic(n):
square = []
for i in range(n + 1):
square.append([0] * (n + 1))
for j in range(1, n + 1):
for i in range(1, n + 1):
if j % 4 == i % 4 or (j % 4 + i) % 4 == 1:
square[i][j] = (n + 1 - i) * n - j + 1
else:
square[i][j] = (i - 1) * n + j
matrix = []
for i in range(n):
matrix.append([0] * n)
for k in range(len(matrix)):
for l in range(len(matrix[0])):
matrix[k][l] = square[k + 1][l + 1]
return matrix

matrix = magic(8)
print(matrix)

  • Scala
object Matrix {
def magic(n: Int) = {
val square = new Array[Array[Int]](n + 1, n + 1)

for(j <- 1 to n; i <- 1 to n) {
square(i)(j) = if(j % 4 == i % 4 || (j % 4 + i) % 4 == 1)
(n+1-i) * n -j + 1
else
(i - 1) * n + j
}

val matrix = new Array[Array[Int]](n, n)
for(k <- 0 until matrix.length; l <- 0 until matrix(0).length) {
matrix(k)(l) = square(k + 1)(l + 1)
}
matrix
}
}

Matrix.magic(8).foreach(row => {
row.foreach(number => printf("%2d ", number))
println()
})

  • Ruby
def magic(n)
square = Array.new(n + 1) {
Array.new(n + 1, 0)
}
1.upto(n) { |j|
1.upto(n) { |i|
if j % 4 == i % 4 || (j % 4 + i) % 4 == 1
square[i][j] = (n + 1 - i) * n - j + 1
else
square[i][j] = (i - 1) * n + j
end
}
}
matrix = Array.new(n) {
Array.new(n, 0)
}
matrix.length.times { |k|
matrix[0].length.times { |l|
matrix[k][l] = square[k + 1][l + 1]
}
}

matrix
end

matrix = magic(8)
p matrix