栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

模拟豆机、高尔顿瓶【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();
        }
    }

}
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/764025.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号