模拟豆机、高尔顿瓶【java】

package text1_3;
//产生随机数0与1表示球的路径,最后狭槽中的小球数量可以用一个数组记录并且步数等于狭槽数-1;小球最终进入哪个槽中与向右的数量有关,并且是相等的
import java.io.*;
import java.util.Random;
public class Galton_Bottle {

    public static void main(String[] args)throws IOException{
        java.util.Random random = new java.util.Random();
        System.out.println("Enter the number of balla to drop: ");
        int num_ball = 0;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        num_ball = (new Integer(buffer.readLine())).intValue();
        System.out.println("Enter the number of slots in the bean machine: ");
        int slots = 0;
        slots = (new Integer(buffer.readLine())).intValue();
        int[] slot = new int[slots];
        for(int i = 0;i < num_ball;i ++)
        {
            int count = 0;
            for(int j = 0;j < slots - 1;j ++)
            {
                boolean path = random.nextBoolean();
                if(path)
                {
                    count ++;//count记录向右的个数,path为真表示向右的一个路径
                }
            }//一个豆子的一次进狭槽过程
            slot[count] ++;
        }
        //输出条形结果采用寻找最大值max,然后进行max次循环的方法
        int max = 0;
        for(int h = 0;h < slots - 1;h ++)
        {
            if(slot[h] < slot[h + 1])
                max = slot[h + 1];
        }
        for(int g = max;g > 0;g --)//输出条形展示
        {
            for(int f = 0;f < slots;f ++)
            {
                if(slot[f] == g)
                {
                    System.out.print("O");
                    slot[f] --;
                }
                else
                {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值