Java 实现这个由二维数组中的值支持的模型类的最快、最简洁/最正确的方法是什么?

Java 实现这个由二维数组中的值支持的模型类的最快、最简洁/最正确的方法是什么?,java,arrays,performance,big-o,Java,Arrays,Performance,Big O,我用图表解决了这个问题,但不幸的是,现在我不得不使用2d数组,我对最好的方法有疑问: public class Data { int[][] structure; public data(int x, int y){ structure = new int[x][y] } public <<TBD>> generateRandom() { // This is what my question is about } } (1

我用图表解决了这个问题,但不幸的是,现在我不得不使用2d数组,我对最好的方法有疑问:

public class Data {

  int[][] structure;

  public data(int x, int y){
    structure = new int[x][y]
  }

  public <<TBD>> generateRandom() {
     // This is what my question is about
  }

}
(1) 您完全可以使用并行流在阵列上安全地执行只读操作。您还可以执行anyMatch调用,因为您只关心(检查
isFull
是否存在任何一个尚未初始化的空间)。可能是这样的:

Arrays.stream(structure)
      .parallel()
      .anyMatch(i -> i == 0)
然而,这仍然是一个n^2的解决方案。不过,您可以做的是,保留一个计数器,记录首次初始化空间时可能减少的空间数。然后,
isFull
检查将始终是常量时间(您只是将int与0进行比较)

公共类数据{
私有化;
私有int[][]结构;
公共数据(整数x,整数y){

如果(x)即使对已经选择的元素进行变异,如果不使用辅助数据结构,确定地查找真正随机的可用元素也需要搜索超过一百万个元素的整个数组;如果只允许恒定存储,则需要搜索两次。这是一个瓶颈。你愿意花一秒钟的大部分时间吗?因为这就是它所需要的。在你找到解决主要问题的方法之后,你如何构造代码的细节就出现了。谢谢你的投入!这实际上是一个CS作业。我有点不安,因为我打破了需要2d数组的标准界面,我不得不重写以与其他学生兼容。我的教授有点老了学校(即。
Arrays.stream(board).flatMapToInt(tile -> tile.getX()).map(x -> x > 0).count() > board.getWidth() * board.getHeight()
Arrays.stream(structure)
      .parallel()
      .anyMatch(i -> i == 0)
public class Data {

    private int numUninitialized;
    private int[][] structure;

    public Data(int x, int y) {
        if (x <= 0 || y <= 0) {
            throw new IllegalArgumentException("You can't create a Data object with an argument that isn't a positive integer.");
        }
        structure = new int[x][y];
        int numUninitialized = x * y;
    }

    public void generateRandom() {
        if (isFull()) {
            // do whatever you want when the array is full
        } else {
            // Calculate the random space you want to set a value for
            int x = ThreadLocalRandom.current().nextInt(structure.length);
            int y = ThreadLocalRandom.current().nextInt(structure[0].length);
            if (structure[x][y] == 0) {
                // A new, uninitialized space
                numUninitialized--;
            }
            // Populate the space with a random value
            structure[x][y] = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
    }

    public boolean isFull() {
        return 0 == numUninitialized;
    }
}