gpt4 book ai didi

java - 有没有一个Java函数可以将有序对数组转换为整数数组?

转载 作者:行者123 更新时间:2023-12-02 01:49:13 24 4
gpt4 key购买 nike

我正在开发一个 Java 项目,我必须将有序对的二维数组转换为整数数组。

为了澄清我的需要,请考虑以下数组作为示例:

int [][] arrayUno = {{0,1},{1,0},{2,1},{2,2},{1,1},{1,2},{0,2},{2,0},{0,0}}

假设我们有另一个相同长度的数组:

int [][] arrayDos = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}}

每个有序对在每个数组中都是唯一的(代表作业/机器的特定组合,即 {0,2} 是作业 0 在机器 2 中的操作)。

我想要 arrayUno 中每个元素(有序对)在 arrayDos 中的位置。结果必须是:

{2,4,8,9,5,6,3,7,1}

例如arrayUno({0,1})的第一个元素在arrayDos的2°位置; arrayUno的元素{1,0}在arrayDos的4°位置; arrayUno 的元素 {2,1} 位于 arrayDos 的 8° 位置,以此类推。

import java.util.Arrays;
public class OrderedPair {

public static void main(String[] args) {
int[][] arrayOne = {{0, 1}, {1, 0}, {2, 1}, {2, 2}, {1, 1}, {1, 2}, {0, 0}, {2, 0}, {0, 2}};

int[][] arrayTwo = {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}};

OrderedPair pair = new OrderedPair();

int[] transformed = pair.transform(arrayOne, arrayTwo);

System.out.println(Arrays.toString(transformed));
}

private int[] transform(int[][] dictionary, int[][] lookup) {
int[] result = new int[dictionary.length];

for (int index = 0; index < lookup.length; index++) {
int[] pair = lookup[index];

int indexOf = -1;

for (int dictionaryIndex = 0; dictionaryIndex < dictionary.length; dictionaryIndex++) {
int[] dictionaryPair = dictionary[dictionaryIndex];

if (dictionaryPair[0] == pair[0] && dictionaryPair[1] == pair[1]) {
indexOf = dictionaryIndex;
break;
}
}

if (indexOf != -1) {
result[index] = indexOf;
}
}
return result;
}
}

我期望输出:{2,4,8,9,5,6,3,7,1}

但输出是:{8,0,6,1,4,5,7,2,3}

最佳答案

您已将内循环放在外面,将外循环放在里面!

里面说:

For each pair x in array one
For each pair y in array two
If x and y are equal
...

你做了:

For each pair x in array two
For each pair y in array one
If x and y are equal
...

因此,要使您的代码正常工作,您只需以相反的顺序传递参数即可:

int[] transformed = pair.transform(arrayTwo, arrayOne);

或者,我建议这样做,切换循环:

private int[] transform(int[][] dictionary, int[][] lookup) {
int[] result = new int[dictionary.length];

for (int dictionaryIndex = 0; dictionaryIndex < dictionary.length; dictionaryIndex++) {
int[] dictionaryPair = dictionary[dictionaryIndex];

int indexOf = -1;

for (int index = 0; index < lookup.length; index++) {
int[] pair = lookup[index];
if (dictionaryPair[0] == pair[0] && dictionaryPair[1] == pair[1]) {
indexOf = index;
break;
}
}

if (indexOf != -1) {
result[dictionaryIndex] = indexOf;
}
}
return result;
}

关于java - 有没有一个Java函数可以将有序对数组转换为整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com