Search code examples
javaarraysmethodssplice

How to write a method like splice in Java


i'm tasked with creating a method which has the same functionality as splice however I cannot get the appropriate value into the appropriate index. My code works as follows,

public void PlaceElementAt(int newValue, int index) throws ArrayIndexOutOfBoundsException {

    //check that index is valid
    if (index >= 0 && index <= data.length) {  //Checks that the index is within position 0 and 7 by default.
        System.out.println ("Index is valid"); //returns index is valid if so
    }
    //increase size if necessary
    if (data.length == numElements) {  //checking if the number of elements is filling the spaces
      doubleCapacity();               // calls upon the double capacity method if it is
    }
    if (numElements==0) {
        data[numElements] = newValue;
        System.out.println ("Element: " + data[numElements] + " at index: " + index);
        numElements++;
    }
    //shuffle values down from index
    else {
     int bottompos = numElements-1;
     int loopcount = numElements-index;
     int NewBottom = numElements+1;
     for (int i=0; i<loopcount; i++){
         data[bottompos]=data[NewBottom];
         bottompos--;
         NewBottom--;
     }
      //insert newValue at index
      data[numElements] = newValue;
        System.out.println ("Element: " + data[numElements] +" at index: " + index);      
        numElements++;

    }
}

My issue is apparent when I later give the commands in my main method.

myData.PlaceElementAt(3,0)

myData.PlaceElementAt(2,5)

myData.PlaceElementAt(7,3)

Once I check my breakpoints i see the values are being added to the array however they are being added on a 1 by 1 basis starting from index 0. Any suggestions greatly helps.


Solution

  • I'm making some assumptions about how your class is structured (adjust as needed), but generally I would recommend shifting right as it will simplify the overall process. Essentially we have an array with maximum allowed size given by MAX and current size given by size. Any time we add to the array, we increment the value of size by 1 (such as insertions or adding to the back of our list). Now, let's say we want to insert a value at index. This will entail shifting all elements at and right of this index by 1 to the right and then inserting our value in the space we have made. Before doing any inserting we first need to check that we have enough space to insert the item. If there is not enough space, we will need to allocate additional space, prohibit the insertion, or some other alternative. In your case, it looks like you want to allocate more space.

    class MyList
    {
      private int MAX = 6;
      private int size = 0;
      private int[] array;
    
      public MyList()
      {
        array = new int[MAX];
      }
    
      public void placeElementAt(int value, int index)
      {
        if (size == 0)
        {
          // If size is 0, just insert the value at index 0.
          array[size++] = value;
          return;
        }
    
        if (index < 0 || index >= size)
        {
          // Index is out of bounds.
          System.out.println("Invalid index.");
          return;
        }
    
        if (size >= MAX)
        {
          // Max capacity reached -> allocate more space.
          doubleCapacity();
        }
    
        // Shift all elements at and above index right by 1.
        for (int i = size - 1; i >= index; i--)
        {
          array[i + 1] = array[i];
        }
    
        // Insert element.
        array[index] = value;
        size++;
      }
    
      public void doubleCapacity()
      {
        int[] newArray = new int[MAX * 2];
    
        // Copy old elements to new array.
        for (int i = 0; i < size; i++)
        {
          newArray[i] = array[i];
        }
    
        // Double MAX to reflect new array.
        MAX *= 2;
        array = newArray;
    
        System.out.println("Doubled");
      }
    
      public void add(int value)
      {
        if (size >= MAX)
        {
          // Max capacity reached -> allocate more space.
          doubleCapacity();
        }
    
        // Add the element to the back of the list.
        array[size++] = value;
      }
    
      public void print()
      {
        for (int i = 0; i < size; i++)
        {
          System.out.print(array[i] + " ");
        }
        System.out.println();
      }
    
      public static void main(String[] args)
      {
        MyList data = new MyList();
        data.placeElementAt(1, 0);
        data.print();
        data.placeElementAt(2, 0);
        data.print();
        data.placeElementAt(3, 0);
        data.print();
        data.placeElementAt(5, 0);
        data.print();
        data.placeElementAt(3, 0);
        data.print();
        data.placeElementAt(9, 0);
        data.print();
        data.placeElementAt(4, 0);
        data.print();
        data.placeElementAt(6, 0);
        data.print();
      }
    }
    

    The output of this program (with initial MAX = 6) would be...

    1
    2 1
    3 2 1
    5 3 2 1
    3 5 3 2 1
    9 3 5 3 2 1
    Doubled
    4 9 3 5 3 2 1
    6 4 9 3 5 3 2 1