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请自写。

相关文章:

  • 2021-06-23
  • 2021-08-09
  • 2021-07-25
  • 2021-11-12
  • 2021-11-04
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-09
  • 2021-06-02
  • 2021-06-06
  • 2022-02-28
  • 2021-08-05
  • 2022-01-13
相关资源
相似解决方案