Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I have to write code that deletes duplicate numbers in an array. The process

ID: 3884529 • Letter: S

Question

So I have to write code that deletes duplicate numbers in an array. The process is described as so:

1. you’re gonna need to store some information: the size of the original array (start this at the length of the original array - 1), the size of the new array (start this at 0)

2. make a copy of the array (let’s call this safeArray). this is just best practice because you never want to mess with the original one.

3. RUNTIME IS NOT A PROBLEM. iterate through the array. start with element 0. check it against the rest of the elements in the list. delete the ones that are the same. when you delete an element, move everything after it forward one and decrement the size of the original array..

4. Increment the size of your new array. you can use this size to keep track of which element you’re currently checking.

5. repeat step 3 until the size of the new array == the size of the original array.

6. use arraycopy in the following way:

( System.arraycopy(safeArray, 0, targetArray, 0, the size of your new array));

7. return targetArray

However I cannot seem to figure out the code.

Explanation / Answer

Please find my implementation.

import java.util.Arrays;

public class ArrayCopy {

  

   public static int[] removeDuplicates(int[] arr) {

      int end = arr.length;

  

      // copy the content of original array to temporary array

      int safeArray[] = new int[end];

      for(int i=0; i<end; i++)

         safeArray[i] = arr[i];

  

      // removing duplicates

      for (int i = 0; i < end; i++) {

      for (int j = i + 1; j < end; j++) {

      if (safeArray[i] == safeArray[j]) {

      int shiftLeft = j;

      // removing current duplicate element

      for (int k = j+1; k < end; k++, shiftLeft++) {

         safeArray[shiftLeft] = safeArray[k];

      }

      end--;

      j--;

      }

      }

      }

      int[] targetArray = new int[end];

      System.arraycopy(safeArray, 0, targetArray, 0, end);

      return targetArray;

   }

  

   public static void main(String[] args) {

      

       int[] input = new int[]{1, 1, 3, 7, 7, 8, 9, 9, 9, 10};

      

       System.out.println("original array: "+Arrays.toString(input));

       System.out.println("No duplicate: "+Arrays.toString(removeDuplicates(input)));

      

   }

}

/*

Sample run:

original array: [1, 1, 3, 7, 7, 8, 9, 9, 9, 10]

No duplicate: [1, 3, 7, 8, 9, 10]

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote