Magic squares of doubly even order: Difference between revisions

Content added Content deleted
m (adjusted whitespace for the TOC.)
(→‎{{header|C++}}: simplified)
Line 38: Line 38:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<lang cpp>#include <iostream>
#include <iostream>
#include <sstream>
#include <sstream>
#include <iomanip>
#include <iomanip>
Line 47: Line 46:
{
{
public:
public:
magicSqr() { sqr = 0; }
magicSqr( int d ) {
~magicSqr() { if( sqr ) delete [] sqr; }
while( d % 4 > 0 ) { d++; }
void create( int d ) {
if( sqr ) delete [] sqr;
while( d % 4 > 0 ) { d++; };
sz = d;
sz = d;
sqr = new int[sz * sz];
sqr = new int[sz * sz]();
memset( sqr, 0, sz * sz * sizeof( int ) );
fillSqr();
fillSqr();
}
}
void display() {
~magicSqr() { delete [] sqr; }

void display() const {
cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
Line 75: Line 71:
private:
private:
void fillSqr() {
void fillSqr() {
int tempAll[][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };
static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };
int rep = sz / 4, s = 1, curRow = 0, curCol = 0;
int i = 0;
int temp[4];
for( int curRow = 0; curRow < sz; curRow++ ) {
for( int curCol = 0; curCol < sz; curCol++ ) {
sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;
for( int v = 0; v < rep; v++ ) {
for( int rt = 0; rt < 4; rt++ ) {
i++;
memcpy( temp, tempAll[rt], 4 * sizeof( int ) );
for( int h = 0; h < rep; h++ ) {
for( int t = 0; t < 4; t++ ) {
if( temp[t] ) sqr[curCol + sz * curRow] = s;
s++;
curCol++;
}
}
curCol = 0;
curRow++;
}
}
s = 1;
curRow = sz - 1;
curCol = curRow;
for( int v = 0; v < rep; v++ ) {
for( int rt = 0; rt < 4; rt++ ) {
memcpy( temp, tempAll[rt], 4 * sizeof( int ) );
for( int h = 0; h < rep; h++ ) {
for( int t = 0; t < 4; t++ ) {
if( !temp[t] ) sqr[curCol + sz * curRow] = s;
s++;
curCol--;
}
}
curCol = sz - 1;
curRow--;
}
}
}
}
}
}
int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }
int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a ) { if( ++a == sz ) a = 0; }
void dec( int& a ) { if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s ) { return ( s < sz && s > -1 ); }
int* sqr;
int* sqr;
Line 127: Line 87:
int main( int argc, char* argv[] ) {
int main( int argc, char* argv[] ) {
magicSqr s; s.create( 8 );
magicSqr s( 8 );
s.display();
s.display();
return 0;
return 0;
}</lang>
}
</lang>
{{out}}
{{out}}
<pre>
<pre>