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( |
magicSqr( int d ) { |
||
while( d % 4 > 0 ) { 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(); |
||
} |
} |
||
~magicSqr() { delete [] sqr; } |
|||
⚫ | |||
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() { |
||
static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; |
|||
int |
int i = 0; |
||
int |
for( int curRow = 0; curRow < sz; curRow++ ) { |
||
⚫ | |||
sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; |
|||
for( int v = 0; v < rep; v++ ) { |
|||
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++ ) { |
|||
⚫ | |||
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 |
magicSqr s( 8 ); |
||
s.display(); |
s.display(); |
||
return 0; |
return 0; |
||
⚫ | |||
} |
|||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre> |