繁体   English   中英

在Java中使用给定的概率填充2D对象数组

[英]Populating a 2D array of objects using given probability in Java

我的任务是创建一个程序,该程序根据某些给定的规则对细胞生长进行建模。 为此,我必须创建一个2D数组,并根据给定的概率用Cell对象填充该对象,这些对象要么是活的,要么是死的。 到目前为止,我已经能够创建我认为是这些对象的数组,但是我不确定如何使用分配给“死”或“正常”状态的概率来处理。每个对象。 到目前为止,这是我所做的(我所知不多...):

public class CellGrid
{
    // Store the cells of the game in this 2D array
    private Cell[][] cells;

    /**
     * Contructor for a CellGrid. Populates the grid with cells that will be
     * living and normal (with probability given by lifeChance) or dead. Cells
     * will NOT start mutated.
     * 
     * @param size
     *            the size of the grid will be size x size
     * @param lifeChance
     *            the probability of each cell starting out alive
     * @param mutationChance
     *            the probability that (when required) each cell will mutate
     */
    public CellGrid(int size, double lifeChance, double mutationChance)
    {
        Cell[][] cells = new Cell[size][size];

        //populates the array with new Cell objects
        for (int i = 0; i < size; i++)      
        {
            for (int j = 0; j < size; j++) 
            {
                cells[i][j]= new Cell();

            }
        }

您可以使用随机值。

Random r = new Random();
double nextVal = r.nextDouble();

nextVal是:0 <= nextVal <1

您现在可以将所有单元格设置为nextVal <lifeChance。 如果lifeChance将为0.1,那么10%的细胞将存活。

...
Random r = new Random();
for (int j = 0; j < size; j++) 
{
    Cell c = new Cell();
    double nextVal = r.nextDouble();
    if(nextVal < lifeChance){
        c.setLife(true);
    } else{
        c.setLife(false);
    }
    cells[i][j]= c;
}

您必须根据您的课程规范更改setLife()。

您想要的是:

public CellGrid(int size, double lifeChance, double mutationChance)
    {
        cells = new Cell[size][size];
        Random r = new Random();
        for(int i=0; i<size; i++) {
            for(int j=0; j<size; j++) {
                double nextVal = r.nextDouble();
                if(nextVal < lifeChance){
                    cells[i][j] = new NormalCell();
                } else{
                    cells[i][j] = new DeadCell();
                }
            }
        }

    }

我已经完成了完整的CellGrid类实现。 让我知道您是否需要帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM