How to resolve the algorithm Magic squares of odd order step by step in the jq 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 jq 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 jq programming language
Source code in the jq programming language
def odd_magic_square:
if type != "number" or . % 2 == 0 or . <= 0
then error("odd_magic_square requires an odd positive integer")
else
. as $n
| reduce range(1; 1 + ($n*$n)) as $i
( [0, (($n-1)/2), []];
.[0] as $x | .[1] as $y
| .[2]
| setpath([$x, $y]; $i )
| if getpath([(($x+$n-1) % $n), (($y+$n+1) % $n)])
then [(($x+$n+1) % $n), $y, .]
else [ (($x+$n-1) % $n), (($y+$n+1) % $n), .]
end ) | .[2]
end ;
def task:
def pp: if length == 0 then empty
else "\(.[0])", (.[1:] | pp )
end;
"The magic sum for a square of size \(.) is \( (.*. + 1)*./2 ):",
(odd_magic_square | pp)
;
(3, 5, 9) | task
$ jq -n -r -M -c -f odd_magic_square.jq
The magic sum for a square of size 3 is 15:
[8,1,6]
[3,5,7]
[4,9,2]
The magic sum for a square of size 5 is 65:
[17,24,1,8,15]
[23,5,7,14,16]
[4,6,13,20,22]
[10,12,19,21,3]
[11,18,25,2,9]
The magic sum for a square of size 9 is 369:
[47,58,69,80,1,12,23,34,45]
[57,68,79,9,11,22,33,44,46]
[67,78,8,10,21,32,43,54,56]
[77,7,18,20,31,42,53,55,66]
[6,17,19,30,41,52,63,65,76]
[16,27,29,40,51,62,64,75,5]
[26,28,39,50,61,72,74,4,15]
[36,38,49,60,71,73,3,14,25]
[37,48,59,70,81,2,13,24,35]
You may also check:How to resolve the algorithm Square form factorization step by step in the Sidef programming language
You may also check:How to resolve the algorithm Price fraction step by step in the R programming language
You may also check:How to resolve the algorithm Permutation test step by step in the C# programming language
You may also check:How to resolve the algorithm Arrays step by step in the Vim Script programming language
You may also check:How to resolve the algorithm Heronian triangles step by step in the EchoLisp programming language