從面向結構到面向對象-----josephus問題(方法二:結構的應用)

今天看了一下josephus問題,突然有點想寫些東西的衝動,結合自己的部份思想,於是便寫了這幾篇帖子。因爲有幾篇代碼有點長,就分開發吧。如果對你有什麼幫助的話,本人勝感欣慰。也許你會說,這個問題好多書上都有代碼,但本人詣在於用不同的方法寫出,讓初學者體會一下從面向結構到面向對象的不同之處;同時你也可以看看我寫的和一些書中的不同之處。如果你是個大蝦,大可一笑了之,或賜教一番。


<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 josephus問題:幾個小孩圍成一圈,從任意一個小孩間隔m順時針方向數起,每數到第m個小孩時,該小孩就離開。最後一個剩下的就爲勝利者。第幾個爲勝利者?


 


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//方法二:結構的應用
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream.h>
#include <iomanip.h>

struct jose
{
  int code;
  jose *next;
};

void mian()
{
  int numOfBoys,interval;
  cout<<"Please input the number of boys,"
      <<endl
      <<"interval of counting:";
  cin>>numOfBoys>>interval;

  jose *pJose=new jose[numOfBoys];
  jose *pCurrent=pJose;

  int itemsInLine=0;

  for(int i=1;i<=numOfBoys;i++)
  {
    pCurrent->next=pJose+i%numOfBoys;
    pCurrent->code=i;
    pCurrent=pCurrent->next;

    if(itemsInLine++%10==0)
      cout<<endl;
    cout<<setw(4)<<i;
  }

  itemsInLine=0;

  int numOfCount;
  cout<<"please input the number of count:"
      <<endl;
  while(1)
  {
    cin>>numOfCount;
    if(0<numOfCount&&numOfCount<=numOfBoys)
      break;
  }

  jose *pivot;
  pCurrent=&pJose[numOfCount-1];

  while(pCurrent->next!=pCurrent)
  {
    for(int j=0;j<interval;j++)
    {
      pivot=pCurrent;
      pCurrent=pivot->next;
    }

    if(itemsInLine++%10==0)
      cout<<endl;
    cout<<setw(4)<<pCurrent->next;
    pivot->next =pCurrent->next;
    pCurrent=pivot;
  }

  cout<<endl
      <<"the winner is:"
      <<pCurrent->code
      <<endl;

  delete []pJose;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章