【问题标题】:Randomly fill in an multidimentional array with elements from a List使用 List 中的元素随机填充多维数组
【发布时间】:2022-07-27 23:46:23
【问题描述】:

我有一个单元格数组。 public static Cell[][] island = new Cell[3][3]; 每个单元格都有 x 和 y 坐标以及“居住”在单元格内的动物列表。我需要用列表中的随机动物随机填充这个数组。 public static List<Alive> allanimals = new ArrayList<>(); 这就是我对列表进行编码和“填充”的方式。

public static void generateIsland() {
    for (int i = 0; i < 10; i++) {
        int random = (int) (Math.random() * 100);
        if (random < 50) {
            allanimals.add(new Bear(500,5,0,0));
        } else {
            allanimals.add(new Sheep(70,0,0));
        }
    }
    System.out.println("Randomly create all animals list" + allanimals);
    int initialcount = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            try {
                int randomdata = r.nextInt(0, allanimals.size() );

                List<Alive> animalsInCell = new ArrayList<>();

                animalsInCell = allanimals.subList(initialcount, initialcount + randomdata);

                initialcount += randomdata;

                island[i][j] = new Cell(i, j, animalsInCell);
            } catch (Exception e) {
                island[i][j] = new Cell(i, j, new ArrayList<Alive>());
            }
        }
    }
}

最后我有一些空单元格,我相信这部分animalsInCell = allanimals.subList(initialcount, initialcount + randomdata); 可以做得更优雅。如何用 allanimals 列表中的元素填充我的 Island 数组? 这是我的 Cell 课

@Data
@AllArgsConstructor
public class Cell extends Thread{
    private int x;
    private int y;
    public List<Alive> animals;
//method run()}

【问题讨论】:

    标签: java


    【解决方案1】:

    首先,我将使用三元 (?:) 运算符填充这样的初始列表。你仍然可以像你的那样做 50% 的版本,但是 true 或 false 是,imo,更具描述性。

    Random r = new Random();
    for (int i = 0; i < 10; i++) {
          allanimals.add(r.nextBoolean() ? new Bear(500,5,0,0) 
                                         : new Sheep(70,0,0));
    

    由于它们已经是随机生成的,只需遍历列表并按顺序将它们添加到单元格中。或者如果你真的想再次随机化它们,你可以打乱列表然后添加它们。

    Collections.shuffle(allanimals);
    
            
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 2017-04-17
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      相关资源
      最近更新 更多