How to resolve the algorithm Magic squares of odd order step by step in the Seed7 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 Seed7 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 Seed7 programming language
Source code in the seed7 programming language
$ include "seed7_05.s7i";
const func integer: succ (in integer: num, in integer: max) is
return succ(num mod max);
const func integer: pred (in integer: num, in integer: max) is
return succ((num - 2) mod max);
const proc: main is func
local
var integer: size is 3;
var array array integer: magic is 0 times 0 times 0;
var integer: row is 1;
var integer: column is 1;
var integer: number is 0;
begin
if length(argv(PROGRAM)) >= 1 then
size := integer parse (argv(PROGRAM)[1]);
end if;
magic := size times size times 0;
column := succ(size div 2);
for number range 1 to size ** 2 do
magic[row][column] := number;
if magic[pred(row, size)][succ(column, size)] = 0 then
row := pred(row, size);
column := succ(column, size);
else
row := succ(row, size);
end if;
end for;
for key row range magic do
for key column range magic[row] do
write(magic[row][column] lpad 4);
end for;
writeln;
end for;
end func;
You may also check:How to resolve the algorithm Hash join step by step in the Perl programming language
You may also check:How to resolve the algorithm Kernighans large earthquake problem step by step in the Klingphix programming language
You may also check:How to resolve the algorithm Assertions step by step in the Wren programming language
You may also check:How to resolve the algorithm Formal power series step by step in the Maxima programming language
You may also check:How to resolve the algorithm Generate random chess position step by step in the FutureBasic programming language