卡牌游戏算法原理、代码

卡牌游戏算法原理、代码,第1张

1、原理
  • 卡片游戏算法桌上有一叠牌,从第一张牌(即位于顶面的牌)开始从上往下依次编号为1~n。

  • 当至少还剩两张牌时进行一下 *** 作:把第一张牌扔掉,然后把第二张牌放到整叠牌的最后,以此往复。

  • 输入卡牌数量n(可完成自动编号),输出每次扔掉的牌。

2、代码
   #include
   using namespace std;
   const int QueueSize = 100;
   template < class T>
   class CircleQueue
   {
   public:
	       CircleQueue() { front = rear = 0; }
	       void EnQueue(T x);
	      T DeQueue();
	      T GetFront();
	      int GetLength();
	      bool Empty() { return front == rear ? true : false; }
  private:
	      int data[QueueSize];
	      int front;
	      int rear;
	  };
 template < class T>
  void CircleQueue<T>::EnQueue(T x)
  {
	  if ((rear + 1) % QueueSize == front)
	  {
		  throw "overflow";
	  }
	      rear = (rear + 1) % QueueSize;
	      data[rear] = x;
	  }
  template < class T>
  T CircleQueue<T>::DeQueue()
  {	      if (rear == front)
	      throw"underflow";
	      front = (front + 1) % QueueSize;
	     return data[front];
	 }
  template < class T>
  T CircleQueue<T>::GetFront()
  {
	      if (rear == front)    throw"underflow";
	      return data[(front + 1) % QueueSize];
	  }
  template < class T>
  int CircleQueue<T>::GetLength()
  {
	      return (rear - front + QueueSize) % QueueSize;
	  }
  int main()
  {	      CircleQueue<int> a;
	      int m;
	      cin >> m;                                //输入牌的张数
	      for (int i = 0; i < m; i++) //依次入队
		      {
		          a.EnQueue(i + 1);
		      }
	      while (a.GetLength() >= 2)                //关键算法
		      {
		          int temp = a.DeQueue();
	          cout << temp << " ";
		          int temp2 = a.DeQueue();
		         a.EnQueue(temp2);
		      }
	      cout << a.GetFront();
	  }
3、结果

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/674580.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-19
下一篇2022-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存