黑洞6714

#file:hole.h

class hole
{
public:
 void convert(int &org);
 void compare(int &org,int n=4);
 void sub(int &max,int &min);
 void show();
private:
 int origin;
    static int step;
 int max,min;
};

#file:hole.cpp

#include "hole.h"
#include <iostream.h>
int hole::step=0;
void hole::convert(int &org)
{
 origin=org;
 if(org!=6174)
 {
 // step++;
  compare(org);
  
 }
}

void hole::sub(int &max,int &min)
{
 step++; 
    origin=max-min;
 convert(origin);
   
}

void hole::compare(int &org,int n)
{
 int temp;//,k;
 static int a[4]={0};
  //  int a[4]={0};
 if(0==n)  //這裏採用了數據結構中的冒泡排序算法
 {
    for(int i=1;i<=3;i++)
    {
    // k=i;
     for(int j=0;j<4-i;j++)
     if(a[j]>a[j+1])
      {
        temp=a[j];
       a[j]=a[j+1];
       a[j+1]=temp;
      }
    
    
    }
    min = a[0]*1000+a[1]*100+a[2]*10+a[3];
    max=a[3]*1000+a[2]*100+a[1]*10+a[0];
       if(max==min || max==0 || min==0)
    {
     cout<<"此數據無法從黑洞中逃脫,步數無限...."<<endl;
     return;
    }
       //Test
    //cout<<"max="<<max<<endl;
    //cout<<"min="<<min<<endl;
    sub(max,min);
 }
 else  //這裏採用了遞歸調用的算法
 {
  a[n-1]=org%10;
  org=org/10;
  hole::compare(org,n-1);
 }

}
void hole::show()
{
  if(max==min || max==0 || min==0)
  {
   return ;
  }
  else
  {
    cout<<"Total step is :"<<step<<endl;
  }
}

#file:hole_main.cpp

#include <iostream>
using namespace std;
#include "Hole.h"

int main()
{
 int x;
 cout<<"please input data (四位整數) :"<<endl;
 cin>>x;
 hole hl;
 hl.convert(x);
 hl.show();
 return 0;
}

/////這是我的測試數據..........

黑洞6174問題:
爲什麼對所有數據的組合進行的測試,只有少數的幾組數據得到的結果需要7步,而其同一組數據的其他組合
卻得不到7?
1235
7
5321
7
2135
7
1325
7
2315
7
2513
7

2531
7
1523
7
1532
7
//////////////////////////////////////////
3125
7
3215
7
3251
7

3521
7

3512
7

/////////////////////////////////////////////
5123
7
5132
7

5231
7
5213
7
5312
7

5321
7

////////////////////////////////////////
8888 此數據無法從黑洞中逃脫,步數無限...."<<
5555 此數據無法從黑洞中逃脫,步數無限...."<<

經過測試所有的四位數字只要不相等就就可以得到需要7步纔可以退出程序.....

就需要經過7步纔可以保證相減的差等於6714.............

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