#include
#include
#include
#include
/*! \brief MagicSqr ensupluate .
*
* 简要生成一个魔方.\n
* test here.
*/
class MagicSqr
{
protected:
/*!
* A list of events:
* - mouse events
* -# mouse move event
* -# mouse click event\n
* More info about the click event.
* -# mouse double click event
* - keyboard events
* -# key down event
* -# key up event
*
* More text here.
*/
struct Postion
{
int first;
int second;
int value;
Postion( int i, int j, int n): first(i), second(j), value(n)
{}
friend bool operator<(Postion const& lhs, Postion const& rhs)
{
return (lhs.first < rhs.first ||
(!(rhs.first < lhs.first) && lhs.second < rhs.second) ) ;
}
};
//typedef std::pair Postion;
typedef std::list < Postion > MagicList;
typedef MagicList::const_iterator ListIter;
const int mDimension;
MagicList mList;
//
//! \deprecated Rename to AdjustRange
//
int Range(int i)
{
//
//! \todo Make i more effective
//
if ( i <= 0)
return mDimension;
if ( i > mDimension)
return (i - mDimension);
return i;
}
Postion Next(Postion& prev, int n)
{
if ( (n - 1) % mDimension)
{
return Postion(Range(prev.first - 1), Range(prev.second + 1), n);
}
else
{
return Postion(Range(prev.first + 1), prev.second, n);
}
}
Postion First()
{
return Postion( 1, (mDimension + 1) / 2, 1);
}
public:
MagicSqr(int n) : mDimension(n)
{}
void Create()
{
if (mList.size() == mDimension * mDimension)
{
return ;
}
mList.push_back(First());
for (int i = 2; i < (mDimension * mDimension + 1); ++i)
{
Postion next = Next( mList.back(), i);
printf("%d at (%d, %d)\n", next.value, next.first, next.second);
mList.push_back(next);
}
}
void Print()
{
mList.sort(std::less < Postion > ());
int n = 1;
for (ListIter i = mList.begin(); i != mList.end(); ++i)
{
//printf("%d at (%d, %d)", i->value, i->first, i->second);
if ( n == i->first)
{
printf("% 3d", i->value);
}
else
{
n++;
printf("\n% 3d", i->value);
}
}
}
};
int main(int argc, char **argv)
{
int n = 3;
if (argc == 2)
{
n = atoi(argv[1]);
}
if (n == 0)
{
n = 3;
}
MagicSqr sqr(n);
sqr.Create();
sqr.Print();
return 0;
}
评论