Magic squares of doubly even order: Difference between revisions

no edit summary
m (→‎{{header|Java}}: small changes)
No edit summary
Line 33:
; See also:
* [http://www.1728.org/magicsq2.htm Doubly Even Magic Squares (1728.org)]<br><br><br><br><br><br>
 
 
=={{header|C++}}==
<lang cpp>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
 
class magicSqr
{
public:
magicSqr() { sqr = 0; }
~magicSqr() { if( sqr ) delete [] sqr; }
void create( int d ) {
if( sqr ) delete [] sqr;
while( d % 4 > 0 ) { d++; };
sz = d;
sqr = new int[sz * sz];
memset( sqr, 0, sz * sz * sizeof( int ) );
fillSqr();
}
void display() {
cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr; cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ ) {
int yy = y * sz;
for( int x = 0; x < sz; x++ ) {
cout << setw( l + 2 ) << sqr[yy + x];
}
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr() {
int tempAll[][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 temp[4];
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 = 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; }//return ( ( ( sz * sz + 1 ) / 2 ) * sz ); }
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 sz;
};
int main( int argc, char* argv[] ) {
magicSqr s; s.create( 8 );
s.display();
return 0;
}
</lang>
{{out}}
<pre>
Doubly Even Magic Square: 8 x 8
It's Magic Sum is: 260
 
1 63 62 4 5 59 58 8
56 10 11 53 52 14 15 49
48 18 19 45 44 22 23 41
25 39 38 28 29 35 34 32
33 31 30 36 37 27 26 40
24 42 43 21 20 46 47 17
16 50 51 13 12 54 55 9
57 7 6 60 61 3 2 64
</pre>
 
=={{header|FreeBASIC}}==