Home > Software engineering >  Duplicate elements of array in Java
Duplicate elements of array in Java

Time:11-10

How to duplicate elements of an array in Java and add them to a new array in the same order of the original array?

// Pass an array of the form {4, 16, 8},
// The returned array should then contain {4, 4, 16, 16, 8, 8}.

public static int[] duplicateElements(final int[] elements){
    int duplicate = 0 ;
    int [] newArray = new int [elements.length*2];
    for(int i = 0; i < elements.length;i  ) {
        newArray[i] = elements[i];  
    }
    for(int j = 0; j < newArray.length/2;j  ) {
        newArray[newArray.length-j-1] = newArray[j];
        
    }
    for(int i = 0; i < (newArray.length/2) ;i  ) {
        duplicate = newArray[i];
        newArray[i 1] = newArray[newArray.length-i-1];
        newArray[newArray.length-i-1] = duplicate;  
    }
    
    return newArray;
}
public static void main(String[] args) {
        
        int [] newArray = new int []{4, 16, 8};
        
        System.out.println(Arrays.toString(duplicateElements(newArray)));

    }

Please explain why the above code is not working.

My output is : // [4, 4, 16, 16, 4, 4]

Instead of : // [4, 4, 16, 16, 8, 8]

CodePudding user response:

You copied the original array into the first half, and in the second half you copied - reversing - the original array again.

Intended:

public static int[] duplicateElements(final int[] elements){
    int duplicate = 0 ;
    int [] newArray = new int [elements.length*2];
    for (int i = 0; i < elements.length; i  ) {
        newArray[2*i] = elements[i];  
        newArray[2*i   1] = elements[i];  
    }
    return newArray;
}

Or use

    for (int i = 0; i < newArray.length;   i) {
        newArray[i] = elements[i / 2];  
    }

Where / is the integer division: 2/2 == 1, 3/2 == 1.

Now the class Arrays allows this to do more expressive

public static int[] duplicateElements(final int[] elements){
    int[] duplicates = new int[elements.length*2];
    Arrays.setAll(duplicates, i -> elements[i / 2]);
    return duplicates;
}

The above uses an anonymous function with int parameter i.

CodePudding user response:

"Keep it simple, stupid!"

For this task, you absolutely don't need to have three cycles. One cycle is enough. All you needs is to properly increment resulting array index.

public static int[] duplicateElements(final int[] origin) {
        int[] result = new int[origin.length * 2];
        int resultIndex = 0;

        for (int i : origin) {
            result[resultIndex  ] = i;
            result[resultIndex  ] = i;
        }
        return result;
    }

EDIT: Just for more clarity. At every step along the source array, you need to take two steps according to the resulting array.

for (int i : origin) {
    result[resultIndex] = i;
    result[resultIndex   1] = i;
    resultIndex  = 2;
}
  • Related