java:<豆机(梅花瓶)(高尔顿瓶)>

本文介绍如何使用Java编程模拟豆机(又称梅花瓶或高尔顿机),这是一个基于统计实验的设备,通过三角形钉板模拟球的随机落下。程序允许用户输入球的数量和槽的数量,然后打印每个球的下落路径及最终每个槽中的球数。虽然理论上每个槽的概率接近50%,但在实际随机数生成中,可能会出现不均衡的情况。
摘要由CSDN通过智能技术生成

豆机,也叫梅花瓶或高尔顿机,它是用来做统计实验的设备,使用英国科学家瑟弗兰克斯高尔顿的名字命名的。它是一个三角形状的均匀放置钉子的直立板子。如下图所示:



球都是从板子口落下,每当碰到钉子,它就有50%的机会落向左边或右边。在板子底部的槽子中都会积累一些球。编写程序模拟豆机。程序提示用户输入球的个数以及机器的槽数。打印每个球的路径模拟它的下落,并显示最终每个槽子中球的数目。






完整代码(该方法接近50%,但有理论的可能性达不到,随机数为0的话,在进行一次产生随机数)


import java.util.Scanner;

public class Exercise6_21 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the numbers of balls to drop:");
        int key = input.nextInt();
        System.out.print("Enter the numbers of slots in the bean machine:");
        int hole = input.nextInt();
        char[] judgement = new char[hole - 1];
        int[] slots = new int[hole];

        for (int i = 0; i < key; i++) {
            int sum = 0;
            for (int j = 0; j < hole - 1; j++) {
                double x = Math.random() * 2.0 - 1;
                if (x < 0) judgement[j] = 'L';
                else if (x > 0) judgement[j] = 'R';
                else {
                    double y = Math.random() * 2.0 - 1;
                    if (y < 0) judgement[j] = 'L';
                    else if (y > 0) judgement[j] = 'R';
                }
            }

            for (int n = 0; n < hole - 1; n++) {

                if (judgement[n] == 'R')
                {
                    sum++;
                }

            }
            slots[sum]++;


            System.out.println(judgement);

        }

        int numberOfSlots = max(slots);

        for (int o = 0; o < numberOfSlots; o++) {
            for (int j = 0; j < hole; j++) {
                if (slots[j] == numberOfSlots - o) {
                    System.out.print('0');
                    slots[j]--;
                } else
                    System.out.print(' ');
                }
                System.out.println();
            }


        }

    public static int max(int[]num){
        int maxNum = 0;
        for(int i = 0;i < num.length;i++){
            if(num[i] > maxNum)
                maxNum = num[i];
        }
        return maxNum;
    }

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值