【问题标题】:Populating a 2D array of objects using given probability in Java在 Java 中使用给定概率填充对象的二维数组
【发布时间】:2014-09-26 12:10:29
【问题描述】:

我的任务是创建一个根据某些给定规则模拟细胞生长的程序。为此,我必须创建一个 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();

            }
        }

【问题讨论】:

    标签: java arrays object multidimensional-array


    【解决方案1】:

    您可以使用随机值。

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

    nextVal 则为:0

    您现在可以设置所有 nextVal

    ...
    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()...

    【讨论】:

    • 既然可以浪费 5 行,为什么还要写 c.setLife(nextVal &lt; lifeChance);?同样Random#nextDouble() 返回值从 0 inclusive 到 1exclusive,所以 0 &lt;= nextVal &lt; 1
    • 浪费 5 行来“希望”让它更清楚。更正了范围
    • 使用合适的 Ctor,cells[i][j] = new Cell(new Random().nextDouble() &lt; lifeChance); 将只使用 1 行而不是 9...
    【解决方案2】:

    你想要的是这个:

    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 类实现。如果您需要帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多