Array Copy And Expand

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jrs362
    New Member
    • Oct 2006
    • 3

    #1

    Array Copy And Expand

    One more problem...

    I need to write a method(Which i'm calling "expand") that takes an int array as one of its parameters and returns a new int array that is 5 elements longer. The contents of the original array need to be copied into the last elements of the new array. The first 5 elements of the new array need to be set to the value of the second parameter to expand.

    So...

    int[] a = new int[]{1,2,3,4,5};
    int[] a2 = expand(a,-1);

    should have the same result as...

    int[] a2 = new int[]{-1.-1,-1,-1,-1,1,2,3,4,5};

    I currently have:

    Code:
    public void expand(int a[])
    {
    
    }
    which approach would be best to use in this situation?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by jrs362
    One more problem...

    I need to write a method(Which i'm calling "expand") that takes an int array as one of its parameters and returns a new int array that is 5 elements longer. The contents of the original array need to be copied into the last elements of the new array. The first 5 elements of the new array need to be set to the value of the second parameter to expand.

    So...

    int[] a = new int[]{1,2,3,4,5};
    int[] a2 = expand(a,-1);

    should have the same result as...

    int[] a2 = new int[]{-1.-1,-1,-1,-1,1,2,3,4,5};

    I currently have:

    Code:
    public void expand(int a[])
    {
    
    }
    which approach would be best to use in this situation?
    1)You need a second parameter for expand and a return type
    Code:
    public int[] expand(int a[], int v) {
    2)You want to return an array that is larger than the one you have so you have to declare a new array.The length of this new array is easy: a.length + 5; (So we have)
    Code:
    int[] b = new int[(a.length + 5)];
    3)To set the first 5 entries you use a loop
    Code:
    for(int i = 0 ;i < 5;i++) {
        b[i] = v;
    }
    4) To copy the rest of the array, you start at position 5 in b and at position 5-5 in a.
    Code:
    for(int i = 5 ;i < a.length;i++) {
        b[i] = a[(i - 5)];
    }
    return b;

    Comment

    Working...