Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert a new array in an index but keep the number originally in the index?

I tried to insert a character into the array in the code below, it works but gets rid of the number in the position. How do I move the old element back a space.

public class MainArrays {
  public static int[] add(int[] arr, int val) {
      int[] newArray = Arrays.copyOf(arr, arr.length + 1);
      newArray[arr.length] = val;
      return newArray;
   }
   public static int[] del(int[] arr) {
      return Arrays.copyOf(arr, arr.length - 1);
   }
   public static int[] ins(int[] a, int pos, int num) {
    int[] result = new int[a.length];;
    for(int i = 0; i < pos; i++)
        result[i] = a[i];
        result[pos] = num;
    for(int i = pos + 1; i < a.length; i++)
        result[i] = a[i - 1];
    return result;
    }
   
  

   public static void main(String[] args) {
      int[] a = { 1, 2, 4 };
      System.out.println(Arrays.toString(a));
      a = add(a, 7);
      System.out.println(Arrays.toString(a));
      a = del(a);
      System.out.println(Arrays.toString(a));
      a = ins(a, 2, 3);
      System.out.println(Arrays.toString(a));
     
   }
}
Old Output
[1,2,4]
New Output
[1,2,3]
Desired Output
[1,2,3,4]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have two issues, first you need to increane the new array size by 1, note the +1 added here int[] result = new int[a.length+1];. The second issue is that you need to use result.length instead of a.length on the last loop otherwise it uses the original shorter array length so the last value will never copy, the correct usage is for(int i = pos + 1; i < result.length; i++):

public static int[] ins(int[] a, int pos, int num) {
    int[] result = new int[a.length+1];
    for(int i = 0; i < pos; i++)
        result[i] = a[i];
    result[pos] = num;
    for(int i = pos + 1; i < result.length; i++)
        result[i] = a[i - 1];
    return result;
}

Now for the given input:

int[] a = { 1, 2, 4 };
a = ins(a, 2, 3);
System.out.println(Arrays.toString(a));

The output is as expected:

[1, 2, 3, 4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading