Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二维矩阵实现_Java_Matrix_Implementation - Fatal编程技术网

Java 二维矩阵实现

Java 二维矩阵实现,java,matrix,implementation,Java,Matrix,Implementation,我游戏中的每个实体都有一个标记对象,需要有一种方法来添加和删除标记对象之间的冲突 这是我的代码: public final class CollisionMatrix { // TODO: Longs have at most 64 bits, so the current implementation fails // when there are more than 64 tags. private Map<Integer, Long> matrix =

我游戏中的每个实体都有一个标记对象,需要有一种方法来添加和删除标记对象之间的冲突

这是我的代码:

public final class CollisionMatrix {

    // TODO: Longs have at most 64 bits, so the current implementation fails
    // when there are more than 64 tags.
    private Map<Integer, Long> matrix = new HashMap<Integer, Long>();

    public CollisionMatrix add(Tag tag1, Tag tag2) {
        int id1 = tag1.id;
        int id2 = tag2.id;
        matrix.put(id1, matrix.getOrDefault(id1, 0L) | (1 << id2));
        matrix.put(id2, matrix.getOrDefault(id2, 0L) | (1 << id1));
        return this;
    }

    public CollisionMatrix remove(Tag tag1, Tag tag2) {
        int id1 = tag1.id;
        int id2 = tag2.id;
        matrix.put(id1, matrix.getOrDefault(id1, 0L) & ~(1 << id2));
        matrix.put(id2, matrix.getOrDefault(id2, 0L) & ~(1 << id1));    
        return this;
    }

    public boolean collidesWith(Tag tag1, Tag tag2) {
        return 0 != (matrix.getOrDefault(tag1.id, 0L) & (1 << tag2.id));
    }

}
这是我试图实现的一个非常丑陋的实现。但是,如果标签的数量不超过64,它就可以工作


我正在寻找一种需要高效而不是反模式的解决方案。

我想知道,这只是我的问题,还是位运算符很难辨认?事实上,我从未使用过它们,也没有真正见过它们

主题:一个简单的存储布尔值的二维对称数组怎么样?数组[x][y]表示x是否与y发生碰撞,假设x和y不是随机的,并且从0开始,则它们可能是两个对象的ID

不知怎的,我有种感觉,你在那里太努力了,想变得聪明。我从来没有想到过将布尔数组表示为long,我想这就是您要尝试的。

标记可以有一个表示冲突的标记列表:

   public void add(Tag tag1, Tag tag2) {
        tag1.collisions.Add(tag2);
        tag2.collisions.Add(tag1);
    }

    public void remove(Tag tag1, Tag tag2) {
      if (collidesWith(tag1,tag2)) {
        tag1.collisions.remove(tag2);
        tag2.collisions.remove(tag1);
      }  
    }

    public boolean collidesWith(Tag tag1, Tag tag2) {
        if (tag1.collisions.Contains(tag2) && tag2.collisions.Contains(tag1)) {
           return true;
        }
        return false;
    }

如果我做一个数组,那么如果标签的数量增加,我会怎么做?阵列的大小是固定的。你的方法和我的有什么不同呢?您正在创建一个一维为64的数组。一种解决方案是创建相当大的初始数组,并在需要时重写,或使用一些嵌套集合,如ArrayList of ArrayList这就是我提出这个问题的原因,以查看是否有更好的替代方案不受这些限制。@a Onsomatos您希望有多少个标记?使用一个简单的二维布尔数组,固定大小为1000x1000或其他一些可能仍然是最有效的解决方案。或者你可以跟踪你在运行时不应该添加多少标签,并用这个数字来初始化数组。它不支持多重冲突,也就是说,标签与其他人发生冲突。考虑将TAG冲突设置为SET而不是列表。这将在添加时避免重复,并使CollizesWith具有恒定的时间复杂度,而不是使用Otag.Collizes.size的列表。此外,当移除时,无需检查是否存在碰撞-只需移除它即可。