游戏设计:
随机输出一组N个2位数,第一步:删除玩家输入位置k处的一个数,第二步,输入一个x位置将上一步删除的数插入x处;
当所有数,从小到大排列则游戏结束,并输出总共所输入的步骤;
方案一(数组存储):
#include <iostream> #include <ctime> #include <cstdlib> #include <iomanip> using namespace std; const int N = 20; //删除 int del(int (&a)[N], int k) { int temp = a[k - 1]; if (k < 1 || k > N || temp == 0) return 0; for (int i = k; i < N; i++) { a[i - 1] = a[i]; } a[N - 1] = 0; for (int i = 0; i < N; i++) { cout << setw(3) << a[i]; } return temp; } //插入 void ins(int (&a)[N], int k, int x) { if (k < 1 || k > N || x == 0) return; for (int i = N - 1; i >= k; i--) { a[i] = a[i - 1]; } a[k - 1] = x; for (int i = 0; i < N; i++) { cout << setw(3) << a[i]; } } //比较 bool match(const int (&a)[N]) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (a[i] > a[j]) return false; } } return true; } //编号输出 void put() { for (int i = 1; i <= N; i++) { cout << setw(3) << i; } cout << endl; } int main() { int ar[N]; int k = 0; bool Gameover = false; srand(time(NULL)); put(); for (int i = 0; i < N; i++) { ar[i] = 10 + rand() % 89; cout << setw(3) << ar[i]; } while (!Gameover) { static int sub = 0; int key1 = 0, key2 = 0; cout << "请输入要删除的位置:"; cin >> key1; put(); int temp = del(ar, key1); cout << "请输入要插入的位置:"; cin >> key2; put(); ins(ar, key2, temp); sub++; if (match(ar)) { cout << endl << "---------game over" << "------总共完成步骤: " << sub * 2; Gameover = true; } } return 0; }
用数组存放数据,并完成删除插入操作;
方案二(链表存储):