import java.util.Arrays;
import java.util.Scanner;
public class Exercise7_21{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the numbers of balls to drop:");
int balls= input.nextInt();
System.out.print("Enter the numbers of slots in the bean machine:");
int slots = input.nextInt();
System.out.println();
int[] holes = new int[slots];
for(int i=0;i<balls;i++){
int sum=0;
for (int j=0;j<slots-1;j++) {
double direction = Math.random() * 2 - 1; //随机生成-1到1之间的数字,当x<0时左移,x>0时右移
if (direction < 0)
System.out.print("L");
else {
System.out.print("R");
sum++;
}
}
System.out.println();
holes[sum]+=1; //有多少个R就进哪个洞,从0开始编号
}
int maxhole=0;
for(int i=0;i<holes.length;i++){ //找出所有洞中进球数的最大值
if(holes[i]>maxhole)
maxhole=holes[i];
}
System.out.println();
for (int i = 0; i < maxhole; i++) { //以进球数最大值为行数
for (int j = 0; j < slots-1; j++) { //以洞数为列数
if (holes[j] == maxhole - i) {
System.out.print('0');
holes[j]--;
}
else
System.out.print(' ');
}
System.out.println();
}
}
}
输出结果如下:
Enter the numbers of balls to drop:5
Enter the numbers of slots in the bean machine:8
RRRLRLR
RLRLLRL
LLRRRLR
RRLLLLR
RLRLRLR
00
000