world.h
// world.h
#ifndef WORLD_H_
#define WORLD_H_
#define WIDTH 7
#define BALL 3
enum World {space, centre, surround};
class Galaxy {
private:
int steps;
int centre_xy;
struct Coord {
int x;
int y;
};
char Map[WIDTH][WIDTH];
Coord Ball[BALL];
public:
Galaxy();
~Galaxy();
void Show();
void Update();
bool Judge();
};
#endif
world.cpp
// world.cpp
#include <iostream>
#include "world.h"
int main() {
Galaxy solay;
for (;;) {
solay.Show();
solay.Update();
if (solay.Judge()) {
solay.Show();
break;
}
}
return 0;
}
sola.cpp
// sola.cpp
#include <iostream>
#include "world.h"
Galaxy::Galaxy() {
for (int i = 0; i < WIDTH; i++)
memset(Map[i], space, sizeof(Map[i]));
steps = 0;
centre_xy = (WIDTH - 1) / 2;
Map[centre_xy][centre_xy] = centre;
int ball_x = centre_xy;
int ball_y = centre_xy - 1;
for (int i = 0; i < BALL; i++) {
Ball[i].x = ball_x;
Ball[i].y = ball_y;
Map[ball_x][ball_y--] = surround;
}
}
Galaxy::~Galaxy() {
using std::cout;
cout << "Step: " << steps << '\n';
cout << "See the world\n";
}
void Galaxy::Show() {
using std::cout;
system("CLS");
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < WIDTH; j++) {
switch (Map[i][j]) {
case space: cout << ".";
break;
case centre: cout << "*";
break;
case surround: cout << "o";
break;
}
}
cout << '\n';
}
}
void Galaxy::Update() {
for (int i = 0; i < BALL; i++) {
if (Ball[i].x == centre_xy &&
Ball[i].y < centre_xy) {
Map[Ball[i].x++][Ball[i].y++] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x == centre_xy &&
Ball[i].y > centre_xy) {
Map[Ball[i].x--][Ball[i].y--] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x < centre_xy &&
Ball[i].y == centre_xy) {
Map[Ball[i].x++][Ball[i].y--] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x > centre_xy &&
Ball[i].y == centre_xy) {
Map[Ball[i].x--][Ball[i].y++] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x < centre_xy &&
Ball[i].y < centre_xy) {
Map[Ball[i].x++][Ball[i].y--] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x > centre_xy &&
Ball[i].y < centre_xy) {
Map[Ball[i].x++][Ball[i].y++] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x > centre_xy &&
Ball[i].y > centre_xy) {
Map[Ball[i].x--][Ball[i].y++] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
else if (Ball[i].x < centre_xy &&
Ball[i].y > centre_xy) {
Map[Ball[i].x--][Ball[i].y--] = space;
Map[Ball[i].x][Ball[i].y] = surround;
}
}
++steps;
}
bool Galaxy::Judge() {
int ball_x = centre_xy;
int ball_y = centre_xy - 1;
for (int i = 0; i < BALL; i++, ball_y--) {
if (Ball[i].x != ball_x ||
Ball[i].y != ball_y)
return false;
}
return true;
}
實驗數據如下:
n=1 | m=4 |
n=2 | m=8 |
n=3 | m=24 |
n=4 | m=48 |
n=5 | m=240 |
n=6 | m=240 |
n=7 | m=1680 |
n=8 | m=3360 |
n=9 | m=10080 |
n=10 | m=10080 |
- | - |
- | - |
實驗之前,我認爲球的個數應和步數大小成正比關係,但是其中發現了意想不到的事,即當 n = 5 和 n = 6 時,步數爲一樣多;當 n = 9 和 n = 10 時,步數爲一樣多。