问题
I have two array like this.
String[] arr1 = {"11","22","33","44","55","66","77"};
String[] arr2 = {"111","222","333","444","555","666","777","888","999"};
I want to merge these two array using combination of index value.
My input will be two integer value (2:3 ratio), like this
int firstArray = 2; //input value
int secondArray = 3; //input value
After merge all value will be stored in single list. Now i need output like this.
11
22
111
222
333
33
44
444
555
666
55
66
777
888
999
77
Input value should increase next time this loop execute on next time.
So second time when calling the for loop input value (3:4 ratio) should be like this.
int firstArray = 3;
int secondArray = 4;
Second Time Output:
11
22
33
111
222
333
444
44
55
66
555
666
777
888
77
999
I tried using for loop and circular linked list. I couldn't able to do proper functionality for this. Can anybody give suggestion to build a proper functionality.
Here is my code what i tried.
String[] arr1 = {"11","22","33","44","55","66","77"};
String[] arr2 = {"111","222","333","444","555","666","777","888","999"};
int f = 2;
for(int i=0;i<arr1.length;i++){
if(i == f){
f = f+f;
int s = 3;
for(int j=0;j<arr2.length ;j++){
if(j == s){
s = s+s;
}
if(j < s)
System.out.println(arr2[j]);
}
}
if(i < f)
System.out.println(arr1[i]);
}
Thanks in advance.
回答1:
You can try that:
private static String[] mergeArrays(String[] arr1, String[] arr2, int firstArray, int secondArray) {
final String[] ret = new String[arr1.length + arr2.length];
for (int j = 0, k = 0; j < arr1.length || k < arr2.length;) {
while (j < arr1.length) {
ret[j + k] = arr1[j];
if (++j % firstArray == 0)
break;
}
while (k < arr2.length) {
ret[j + k] = arr2[k];
if (++k % secondArray == 0)
break;
}
}
return ret;
}
Here is how to call it:
public static void main(String[] args) {
String[] arr1 = { "11", "22", "33", "44", "55", "66", "77" };
String[] arr2 = { "111", "222", "333", "444", "555", "666", "777", "888", "999" };
String[] arr = mergeArrays(arr1, arr2, 2, 3);
System.out.println("Ratio 2:3");
for (String str : arr) {
System.out.println(str);
}
arr = mergeArrays(arr1, arr2, 3, 4);
System.out.println("Ratio 3:4");
for (String str : arr) {
System.out.println(str);
}
}
来源:https://stackoverflow.com/questions/27836495/merge-two-array-using-ratio-wise-in-java