1. 程式人生 > >Java 7.21 遊戲:豆機(C++&Java)

Java 7.21 遊戲:豆機(C++&Java)

 

 PS:

         難點在於,隨機之後的分隔,理解就很容易了

注意:槽的奇偶情況

C++: 

#include<iostream>
#include<ctime>
#include<string>
using namespace std;
class Machine {
public:
	Machine(int,int);
	void run();
	void show_machine();
	void show_road();
private:
	int ball;
	int slot;
	int *count;
	string *road;
};
Machine::Machine(int b, int s) : ball(b),slot(s) {
	count = new int[s];
	road = new string[b];
	for (int i = 0; i < slot; i++)
		count[i] = 0;
}
void Machine::run() {
	double mid;
	srand((unsigned int)time(0));       //隨機
	for (int i = 0; i < ball; i++) {
		mid = ((double)slot - 1) / 2;   //取中間值(小技巧:這裡剛好使得slot奇偶都符合要求)
		for (int j = 0; j < slot - 1; j++) { 
			if (rand() % 2) {           //右移
				mid += 0.5;
				road[i] += 'R';
			}
			else {                      //左移
				mid -= 0.5;
				road[i] += 'L';
			}
		}
		count[(int)mid]++;              //該列count++
	}
}
void Machine::show_road() {              //顯示每個球的路徑
	for (int i = 0; i < ball; i++)
		cout << road[i] << endl;
}
void Machine::show_machine() {           //顯示機器
	int flag;
	string str;
	for (int i = ball; i > 0; i--) {     //模擬二維陣列,當count[j]超過i,證明此行此列存在值 
		flag = 0;
		str.clear();
		for (int j = 0; j < slot; j++) {
			if (count[j] >= i) {
				str += "O";
				flag = 1;
			}
			else
				str+=" ";
		}
		if (flag)                         //使用str以及flag為了去除多餘的空行
			cout << str << endl;
	}
}
int main() {
	int ball, slot;
	cout << "Enter the number of balls to drop : ";
	cin >> ball;
	cout << "Enter the number of slots in the bean machine : ";
	cin >> slot;
	cout << endl;
	Machine My(ball, slot);
	My.run();
	My.show_road();
	cout << endl;
	My.show_machine();
	return 0;
}

Java:

            java請自寫。