Is there a way to put an array into another array with its elements seperated by 2 other elements?

huangapple go评论71阅读模式
英文:

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&lt;input.length; j++){
            for(int i=0 ; i&lt;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 &lt; arr.length; i++) {
        res[k++] = arr[i];
        res[k++] = arr[i] + 3;
        res[k++] = arr[i] + 7;
    }

    return res;
}

huangapple
  • 本文由 发表于 2020年10月18日 06:46:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64408069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定