英文:
Is there a way to put an array into another array with its elements seperated by 2 other elements?
问题
static int[] expand(int[] input){
    int[] output = new int[input.length*3];
    for(int j=0; j<input.length; j++){
        for(int i=0 ; i<output.length ; i++){
            if(i==0 || (i % 3 == 0)) output[i]=input[j];
            else if(i-1 == 0 || (i-1) % 3 == 0) output[i]=input[j]+4;
            else output[i]=input[j]+7;
        }
    }
    return output;
}
英文:
So I want to create an array that for every element of another given array it should have 3 elements.
That means that if the input array is this:
input[] = {80,125} 
The output array should be this:
output[] = {80,84,87,125,129,132}
(input array has 2 elements so output array should have 6 elements (2*3))
So I tried the code that you see underneath and it didn't work. I understand why it didn't work but I can't seem to figure out how to do it. Can I get some ideas?
static int[] expand(int[] input){
        int[] output = new int[input.length*3];
        for(int j=0; j<input.length; j++){
            for(int i=0 ; i<output.length ; i++){
                if(i==0 || (i % 3 == 0)) output[i]=input[j];
                else if(i-1 == 0 || (i-1) % 3 == 0) output[i]=input[j]+4;
                else output[i]=input[j]+7;
            }
        }
        return output;
}
答案1
得分: 1
public static int[] expand(int[] arr) {
    int[] res = new int[arr.length * 3];
    for (int i = 0, k = 0; i < arr.length; i++) {
        res[k++] = arr[i];
        res[k++] = arr[i] + 3;
        res[k++] = arr[i] + 7;
    }
    return res;
}
英文:
public static int[] expand(int[] arr) {
    int[] res = new int[arr.length * 3];
    for (int i = 0, k = 0; i < arr.length; i++) {
        res[k++] = arr[i];
        res[k++] = arr[i] + 3;
        res[k++] = arr[i] + 7;
    }
    return res;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论