How to resolve the algorithm Magic squares of odd order step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Magic squares of odd order step by step in the Wren programming language
Table of Contents
Problem Statement
A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant). The numbers are usually (but not always) the first N2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Magic squares of odd order step by step in the Wren programming language
Source code in the wren programming language
import "/fmt" for Fmt
var ms = Fn.new { |n|
var M = Fn.new { |x| (x + n - 1) % n }
if (n <= 0 || n&1 == 0) {
n = 5
System.print("forcing size %(n)")
}
var m = List.filled(n * n, 0)
var i = 0
var j = (n/2).floor
for (k in 1..n*n) {
m[i*n + j] = k
if (m[M.call(i)*n + M.call(j)] != 0) {
i = (i + 1) % n
} else {
i = M.call(i)
j = M.call(j)
}
}
return [n, m]
}
var res = ms.call(5)
var n = res[0]
var m = res[1]
for (i in 0...n) {
for (j in 0...n) System.write(Fmt.d(4, m[i*n+j]))
System.print()
}
System.print("\nMagic number : %(((n*n + 1)/2).floor * n)")
You may also check:How to resolve the algorithm Semordnilap step by step in the Go programming language
You may also check:How to resolve the algorithm Variable-length quantity step by step in the jq programming language
You may also check:How to resolve the algorithm Host introspection step by step in the Babel programming language
You may also check:How to resolve the algorithm Matrix transposition step by step in the Scheme programming language
You may also check:How to resolve the algorithm Singleton step by step in the Objeck programming language