gpt4 book ai didi

Java:检查一个数组中的重复值并将更简单的 ID 分配给另一个相同大小的数组

转载 作者:行者123 更新时间:2023-11-29 04:06:48 25 4
gpt4 key购买 nike

我有两个数组:

数组 1:

 {101,101,101,102,102,103,103,104,104,105} 

和数组 2:

{0,0,0,0,0,0,0,0,0,0};

对于数组 1 中的每个重复元素,我希望数组 2 中的每个元素都有一个新 ID。这是我想要实现的结果:

array1 = {101,101,101,102,102,103,103,104,104,105};
array2 = {1,1,1,2,2,3,3,4,4,5};

当您看到我的代码时,您可能会更好地了解我要做什么。

我提供的代码是我所获得的最接近我想要的结果的代码。我已尝试以多种不同方式切换逻辑,但没有比我提供的代码更好的结果。

public class Challenge {
public static void main(String[] args) throws Exception {
int[] arr1 = {11,11,11,12,12,13,13,14,14,15};
int[] arr2 = new int[10];

System.out.println("Initial arrays");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

int id = 1;
int count = 0;
int trueCount = 0;
boolean isMatching = true;
boolean beginWrite = true;

for (int i = 0; i < arr1.length; i++) {
for (int j = i + 1; j < arr1.length; j++) {
count++;
if (arr1[i] != arr1[j]) {
isMatching = false;
trueCount = count;
count = 0;
for (int k = 0; k < arr1.length; k++) {
if (k == trueCount) {
beginWrite = false;
}
if (beginWrite == true) {
arr2[i] = id;
i++;
}
}
}
}
}
System.out.println();
System.out.println("Result");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

}
}

输出:

初始数组

[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

结果

[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0]

预期输出:

初始数组

[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

结果

[11, 11, 11, 12, 12, 13, 13, 14, 14, 15]
[1, 1, 1, 2, 2, 3, 3, 4, 4, 5]

最佳答案

我想我理解您的问题,并且可以让您的生活变得更轻松的一件事是称为 HashMap 的数据结构。

如果您不熟悉,它基本上是一组(键,值)对,其中每个键都是唯一的,因此我们可以将您未更改的 ID 作为键,将新 ID 作为值。然后在迭代时,我们可以检查是否已经为那个未更改的 ID 创建了一个 ID,以及我们是否使用了那个 ID。

添加了这个的代码看起来像这样:

public class Challenge {
public static void main(String[] args) throws Exception {
int[] arr1 = {11,11,11,12,12,13,13,14,14,15};
int[] arr2 = new int[10];
HashMap<Integer, Integer> ids = new HashMap<Integer, Integer>();

System.out.println("Initial arrays");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

int id = 1;
int count = 0;
int trueCount = 0;
boolean isMatching = true;
boolean beginWrite = true;

for (int i = 0; i < arr1.length; i++) {
if (ids.containsKey(arr1[i])) {
arr2[i] = ids.get(arr1[i]);
} else {
ids.put(arr1[i], id);
arr2[i] = id;
id++;
}
}
System.out.println();
System.out.println("Result");
System.out.println();
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
}
}

关于Java:检查一个数组中的重复值并将更简单的 ID 分配给另一个相同大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089684/

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