题目:The been machine,also known as a quincunx or the Galton box,is a device for statistic experiments named after English scientist Sir Francis Galton,It consists of an upright board with evenly spaced nails(or pegs)in a triangular form,,as shown in Figure 6.14
Each ball takes a random path and falls into a slot.
Bakks are dropped from the opening of the board,Every time a ball hits a nail,it has a 50% chance of falling ti the left or to the right.the piles of balls are accumulated in the slots at the bottom of the board.
Write a program that simulates the bean machine.Your program should prompt the user to enter the number of the balls and the number of the slots in the machine,Simulate the falling of each ball by printing its path for the ball in Figure 6.14(c) Is RLRRLRR.Display the final buildup of the balls in the slots in a histogram.here is a sample run of the program
题目来源:
题目选自《JAVA程序语言设计》 P231-6.21***+
</pre>代码如下:<pre name="code" class="java">import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
char[] Dirs={'L','R'}; //定义数组确定方向
int[][] num=new int[10][10]; //开辟一个最大值为10的二维数组来表示豆豆机下端的槽,可调整
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of balls to drop:");
int balls = input.nextInt(); //确定balls数目
System.out.print("Enter the number of slots in the bean machine:");
int slots = input.nextInt(); //确定slots的数目
System.out.println();
int k,count;
for (int i=0;i<balls;i++)
{
//每一个小球重置一次k和count
k=balls-1; //确定二维数组的行数,由于数组是从0开始,最大值为小球-1
count=slots+1; //确定二维数组的列数,由题可知最大值即凹槽数是slots+1;
for (int j=0;j<slots;j++)
{
int dir = (int)(Math.random()*2); //产生一个0或1的随机数来决定小球运动的方向,概率均为1/2
System.out.print(Dirs[dir]); //输出小球运动的方向
if (dir==0) //小球向左则count--
count--;
else //向右则count++
count++;
}
System.out.println();
while(num[k][count/2]==1) //当底层已经有小球时则向上挪一层
{
k--;
}
num[k][count/2]=1; //确定该位置为1
}
System.out.println();
for (int i=0;i<balls;i++) //当num[i][j]=1时输出0,否则为*
{
for (int j=0;j<slots+1;j++)
{
if (num[i][j]==1)
System.out.print("0");
else
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
/*output:
Enter the number of balls to drop:5
Enter the number of slots in the bean machine:7
LLLRLRL
RLLLRRR
LLLLLLL
LRRRRLL
LRLRRLL
********
********
********
****0***
0*000***
*///~