为了账号安全,请及时绑定邮箱和手机立即绑定

根据 int 数组中的数据填充二维整数数组

根据 int 数组中的数据填充二维整数数组

MYYA 2024-01-05 15:20:56
我有一个 int 数组preliminaryAssignments = [6,7,7,7],其中每个索引都是与不同节点配对的节点。即,节点 0 与 6 配对,节点 1-4 与 7 配对,并且二维数组的邻居 = [[5, 6], [5, 7, 8, 9], [5, 7, 9], [5, 7, 8, 9]] 表示每个索引的所有可能的节点配对。即节点 0 可以与 5 或 5 配对,节点 1 可以与 5、7、8、9 等配对。我想为每个节点的未配对的备用选项创建一个二维整数数组“otherOptions”。即 [[5],[5,8,9],[5,9],[5,8,9]]我在填充 otherOptions 时遇到问题。这是我一直在研究的一些代码。ArrayList<ArrayList<Integer>> otherOptions = new ArrayList<ArrayList<Integer>>(n-1);        for (int j = 0; j < n-1; j++) {            otherOptions.add(new ArrayList<Integer>());        }        for (int x = 0; x < n-1; x++ ) {            for (int y = 0; y< k; y++) {                if (neighbors.get(x).get(y) != preliminaryAssignment[x]) {                    otherOptions.get(x).add(neighbors.get(x).get(y));                }            }        }这里有什么帮助吗?谢谢
查看完整描述

1 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

如果数据位于arrays中,如问题中指定的,您的代码应该是:


int[][] otherOptions = new int[neighbors.length][];

for (int nodeIdx = 0; nodeIdx < neighbors.length; nodeIdx++) {

    otherOptions[nodeIdx] = new int[neighbors[nodeIdx].length - 1];

    for (int i = 0, j = 0; i < neighbors[nodeIdx].length; i++) {

        if (neighbors[nodeIdx][i] != preliminaryAssignments[nodeIdx]) {

            otherOptions[nodeIdx][j++] = neighbors[nodeIdx][i];

        }

    }

}

测试


int[] preliminaryAssignments = {6, 7, 7, 7};

int[][] neighbors = {{5, 6}, {5, 7, 8, 9}, {5, 7, 9}, {5, 7, 8, 9}};

// code from above here

System.out.println(Arrays.deepToString(otherOptions));

输出


[[5], [5, 8, 9], [5, 9], [5, 8, 9]]

如果数据位于lists中,就像问题代码中使用的那样,您的代码应该是:


List<List<Integer>> otherOptions = new ArrayList<>();

for (int nodeIdx = 0; nodeIdx < neighbors.size(); nodeIdx++) {

    List<Integer> others = new ArrayList<>(neighbors.get(nodeIdx));

    others.remove(preliminaryAssignments.get(nodeIdx));

    otherOptions.add(others);

}

测试


List<Integer> preliminaryAssignments = Arrays.asList(6, 7, 7, 7);

List<List<Integer>> neighbors = Arrays.asList(Arrays.asList(5, 6),

                                              Arrays.asList(5, 7, 8, 9),

                                              Arrays.asList(5, 7, 9),

                                              Arrays.asList(5, 7, 8, 9));

// code from above here

System.out.println(otherOptions);

输出


[[5], [5, 8, 9], [5, 9], [5, 8, 9]]

如果数据位于未知类型的列表中,即get(int)可能很慢,您的代码应该是:


List<List<Integer>> otherOptions = new ArrayList<>();

Iterator<Integer> prelimIter = preliminaryAssignments.iterator();

for (Iterator<List<Integer>> neighborIter = neighbors.iterator(); neighborIter.hasNext(); ) {

    List<Integer> others = new ArrayList<>(neighborIter.next());

    others.remove(prelimIter.next());

    otherOptions.add(others);

}


查看完整回答
反对 回复 2024-01-05
  • 1 回答
  • 0 关注
  • 35 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信