在 java 中使用比率明智地合并两个数组

Merge two array using ratio wise in java

我有两个这样的数组。

String[] arr1 = {"11","22","33","44","55","66","77"};
String[] arr2 = {"111","222","333","444","555","666","777","888","999"};

我想使用索引值的组合来合并这两个数组。

我的输入将是两个整数值(2:3 比例),像这样

int firstArray = 2;    //input value
int secondArray = 3;   //input value

合并后所有值将存储在单个列表中。 现在我需要这样的输出。

11
22
111
222
333
33
44
444
555
666
55
66
777
888
999
77

下次执行此循环时,输入值应增加。

所以第二次调用for循环时输入值(3:4比例)应该是这样的

int firstArray = 3; 
int secondArray = 4;

第二次输出:

11
22
33
111
222
333
444
44
55
66
555
666
777
888
77
999

我试过使用for循环和循环链表。我无法为此做适当的功能。 任何人都可以提出建议以构建适当的功能。

这是我尝试过的代码。

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]);

}

提前致谢。

你可以试试:

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;
}

调用方法如下:

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);
    }
}