随机模拟问题

随机模拟方法也称蒙特卡罗法统计试验法,是利用计算机进行数值计算的一种方法,它的适用范围非常广泛,既能求解确定性问题,也能求解随机性的问题。

问题引入

房间里有100个人,每人都有100元钱,他们在玩一个游戏。每轮游戏中,每个人都要拿出一元钱随机给另一个人,最后这100个人的财富分布是怎样的?

模拟演示结果:
在这里插入图片描述

一、视图层

import javax.swing.*;
import java.awt.*;

public class AlgoFrame extends JFrame {
    private int canvasWidth;
    private int canvasHeight;


    public AlgoFrame(String title, int canvasWidth, int canvasHeight){
        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        Algocanvas canvas = new Algocanvas(); // 画布
        setContentPane(canvas);
        pack();

        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public int getCanvasWidth() {
        return canvasWidth;
    }

    public int getCanvasHeight() {
        return canvasHeight;
    }

    // TODO: 设置自己的数据
    private int[] money;
    public void render(int[] money){
        this.money = money;
        repaint();
    }

    // 内部类自定义画布
    private class Algocanvas extends JPanel{
        public Algocanvas() {
            // 双缓存
            super(true);  // 默认为true
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗锯齿
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON );
            g2d.addRenderingHints(hints);

            // 具体绘制
            // TODO: 绘制自己的数据data
            int w = canvasWidth / money.length;
            for (int i = 0; i < money.length; i++) {
                if(money[i] > 0) {
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Blue);
                    AlgoVisHelper.fillRectangle(g2d, i*w+1, canvasHeight/2-money[i],w-1, money[i]);
                }
                else if (money[i] < 0 ){
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);
                    AlgoVisHelper.fillRectangle(g2d, i*w+1, canvasHeight/2,w-1, -money[i]);

                }
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

二、控制层

import java.awt.*;
import java.util.Arrays;

public class AlgoVisualizer {

    public static int DELAY = 30;  // 更新延迟的时间
    private int[] money;
    private AlgoFrame frame;
    private boolean isAnimate = true;  // 动画是否执行

    public AlgoVisualizer(int sceneWidth, int sceneHeight){

        // 初始化数据
        money = new int[100];
        for (int i = 0; i < money.length; i++) {
            money[i] = 100;
        }

        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Welcome", sceneWidth, sceneHeight);
            new Thread( () -> {
                run();
            }).start();
        });
    }

    // 动画逻辑
    private void run(){
        while(true){
            // 绘制数据
            Arrays.sort(money);  // 对数据进行排序
            frame.render(money);
            AlgoVisHelper.pasue(DELAY);

            // 更新数据
            for (int k = 0; k < 20; k++) {   // 每一次更新k轮
                for (int i = 0; i < money.length; i++) {  // 进行一次更新
                    //if(money[i] > 0){  // 是否允许负债
                        int j = (int)(Math.random() * money.length);
                        money[i] -= 1;
                        money[j] += 1;
                    //}
                }
            }
        }
    }
}

三、工具层

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;

public class AlgoVisHelper {

    private AlgoVisHelper(){}

    public static final Color Red = new Color(0xF44336);
    public static final Color Pink = new Color(0xE91E63);
    public static final Color Blue = new Color(0x2196F3);
    public static final Color Green = new Color(0x4CAF50);
    public static final Color Yellow = new Color(0xFFEB3B);
    public static final Color Orange = new Color(0xFF9800);
    public static final Color Blank = new Color(0x000000);
    public static final Color White = new Color(0xFFFFFF);
    public static final Color Grey = new Color(0x9E9E9E);

    // 设置画笔宽度及样式
    public static void setStrokeWidth(Graphics2D g2d, int w) {
        int strokeWidth = w;
        g2d.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    }

    // 设置画笔颜色
    public static void setColor(Graphics2D g2d, Color color) {
        g2d.setColor(color);
    }

    // 绘制空心圆
    public static void strokeCircle(Graphics2D g2d, int x, int y, int r){
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g2d.draw(circle);
    }

    // 绘制实心圆
    public static void fillCircle(Graphics2D g2d, int x, int y, int r){
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g2d.fill(circle);
    }

    // 绘制空心矩形
    public static void strokeRectangle(Graphics2D g2d, int x, int y, int w, int h){
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g2d.draw(rectangle);
    }

    // 绘制实心矩形
    public static void fillRectangle(Graphics2D g2d, int x, int y, int w, int h){
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g2d.fill(rectangle);
    }

    // 读取图像到画布
    public static void putImage(Graphics2D g, int x, int y, String imageURL) {
        ImageIcon icon = new ImageIcon(imageURL);
        Image image = icon.getImage();

        g.drawImage(image, x, y, null);
    }

    // 打印文字到画布
    public static void drawText(Graphics2D g, String text, int centerx, int centery){
        if (text == null)
            throw new IllegalArgumentException("Text is null in drawText.");

        FontMetrics metrics = g.getFontMetrics();
        int w = metrics.stringWidth(text);
        int h = metrics.getDescent();
        g.drawString(text, centerx - w/2, centery + h);
    }

    // 延时函数
    public static void pasue(int t){
        try{
            Thread.sleep(t);
        }
        catch (InterruptedException e) {
            System.out.println("Error in Sleeping.");
        }
    }
}

四、测试

public class Main {

    public static void main(String[] args) {
        int sceneWidth = 500;
        int sceneHeight = 400;

        AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight);
    }
}

注: 该文为慕课网课程整理的笔记,若侵权请告知,立删。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值