JAVA三星题之Galton Box

题目: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***
*///~


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值