2

What would be the best way to merge two arrays of different lengths together so they are evenly distributed in the new array?

Say I have the following arrays

 String[] array1 = new String[7];
 String[] array2 = new String[2];
 String[] mergedArray = new String[array1.length + array2.length];

I would want mergedArray to have the following elements

array1 array1 array1 array2 array1 array1 array1 array2 array1

but if I were to change the size of the arrays to

 String[] array1 = new String[5];
 String[] array2 = new String[3];
 String[] mergedArray = new String[array1.length + array2.length];

then I would want it to be

array1 array2 array1 array2 array1 array2 array1 array1

basically if it can be helped each array2 element shouldn't be touching each other; exception if array2 has a size larger than array1.

4

4 回答 4

1

我会将较大数组的大小除以较小数组的大小。获得的值将是第二个数组的元素所在的位置。

在您的第一个示例中 - 较大数组的大小为 7,较小数组的大小为 2。所以它将是 7/2 = 3。因此第二个数组的元素将位于合并数组中的位置 3 和 6 .

于 2013-06-27T21:46:57.953 回答
1

我同意用户 Junaid 的回答。这个想法是,您通过转义恒定数量的元素将较小数组的元素分配到较大的数组中。如果数组大小相等,则将较小数组的元素分布在较大数组的所有连续元素之间,这是实现,请遵循:

String[] array1 = new String[]{"d", "e", "f", "g", "h", "j", "k", "m"};
String[] array2 = new String[]{"a", "b", "c"};
int l1 = array1.length;
int l2 = array2.length;
int sectionSize = l1 / l2 + 1;
String[] mergedArray = new String[l1 + l2];
String[] larger = l1 > l2 ? array1 : array2;
String[] smaller = l1 < l2 ? array1 : array2;

int j = 0, k = 0;
for (int i = 1; i <= mergedArray.length; i++) {
    if (i % sectionSize == 0)
        mergedArray[i - 1] = smaller[j++];
    else
        mergedArray[i - 1] = larger[k++];
}
于 2013-06-27T22:18:39.783 回答
0

假设你有m个元素 inarray1n 个元素 in array2。你想要做的是array2为每个m/n元素添加一个元素from array1

在您的第一个示例中:

m = 7, n = 2 - 您array2为 中的每 7/2 = 3 个元素添加了一个元素array1

在第二个例子中:

m = 5, n = 3 - 您array2为 中的每 5/3 = 1 个元素添加了一个元素array1

你可以这样做:

int counter = array1.length/array2.length;
int m = -1, j = 0;
for(int i=0, c=0;i<array1.length;i++, c++) {
   m++;
   if(c == counter) {
     resArray[m] = array2[j];
     j++;
     c = 0;
     continue;
   }
   resArray[m] = array1[i];
}
于 2013-06-27T21:49:01.423 回答
0

一种选择是只为您在 insert from 中的每个元素插入array1.length / array2.length元素,但如果数组不均匀划分,这可能会在新数组的末尾留下一长串元素(意味着它们的长度比是'不是整数 - 长度比将被截断为整数,因此您不会插入足够的元素)。array1array2array1array1

另一种方法是使用随机数生成器来选择要从哪个数组中选择:取rand(array1.length + array2.length)array1如果结果数小于 则array1.length选择 from ,否则选择 from array2;为此,您应该更新每次迭代的长度(所以它是rand(array1.length - number_of_elements_already_removed_from_array1 + array2.length - number_of_elements_already_removed_from_array2)

于 2013-06-27T21:49:21.737 回答