diandian82的专栏

Welcome to my blog. Hope you can get what you want.

C++ 计算约瑟夫环算法

#include <iostream>

using namespace std;

<?xml:namespace prefix = o />

 

class YsfRing

{

public:

              YsfRing(int length);

              void Resolve(int firstStep);         // 求约瑟夫环

              void MoveOneStep(int& index);  // 移动一个步长

              void DisplayResult();              // 显示结果

              ~YsfRing();

private:

              int m_Length;                   // 环的长度

              int *m_Ring;                                  // 保存初始环

              int *m_Result;                  // 保存约瑟夫环的结果

};

 

YsfRing::YsfRing(int length)

{

        // 初始化环的各项数值

              m_Ring   = new int[length];

              m_Result = new int[length];

              memset(m_Ring  , 0 , sizeof(int)*length);

              memset(m_Result, 0 , sizeof(int)*length);

              m_Length = length;

              for(int i=0 ; i<m_Length;i++)

              {

                            m_Ring[i] = i+1;

              }

}

 

void YsfRing::DisplayResult()

{

        // 显示结果

              for(int i=0 ; i<m_Length;i++)

              {

                            cout<<m_Result[i]<<" ";

              }

              cout<<endl;

}

 

void YsfRing::Resolve(int firstStep)

{

        // 计算约瑟夫环

              int count = this->m_Length ;

              int resultIndex = 0;

              int index = 0 ;

              int step = firstStep;

              while( count > 0 )

              {

                // 移动相应的步长,找到下一个没有被移走的元素

                            for(int k=0;k<step;k++)

                            {

                                          MoveOneStep(index);

                            }

                // 将当前的元素保存在结果数组里面

                            m_Result[resultIndex++] = step = m_Ring[index];

                // 移走当前的元素

                            m_Ring[index] = -1;

                // 元素总数减一

                            count --;

              }

}

 

void YsfRing::MoveOneStep(int& index)

{

              do

              {

                            // 找到下一个元素

                            index ++;

                          // 如果到环尾,再跳回环头

                            if(index >= this->m_Length)

                            {

                                          index =0;

                            }

              }while(m_Ring[index] < 0 );

}

 

YsfRing::~YsfRing()

{

              delete [] m_Ring;

              delete [] m_Result;

}

 

int main()

{

              YsfRing *ring = new YsfRing(10);

              ring->Resolve(7);

              ring->DisplayResult();

              delete ring;

              return 0;

}

阅读更多
个人分类: C++语言
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

C++ 计算约瑟夫环算法

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭