Guest User

Untitled

a guest
Oct 23rd, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. public class ArrayHandler {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         // Initialise array to pass to method.
  6.         int[] passedArray = { 1, 2, 3, 2 };
  7.  
  8.         // Run method and get array without duplicates.
  9.         int[] returnedArray = removeRepeatedValues(passedArray);
  10.  
  11.         // Print contents of returned array.
  12.         for (int i = 0; i < returnedArray.length; i++) {
  13.             System.out.print(returnedArray[i] + " ");
  14.         }
  15.     }
  16.  
  17.     public static int[] removeRepeatedValues(int[] oldArray) {
  18.  
  19.         // Empty arrays are returned.
  20.         if (oldArray.length == 0) {
  21.             return oldArray;
  22.         }
  23.  
  24.         // Duplicate counter used to determine final array length.
  25.         int duplicateCounter = 0;
  26.  
  27.         // Each interger checked against every other integer to see if
  28.         // duplicate.
  29.         // If duplicate, counter increased. Duplicate is replaced by
  30.         // oldArray[0].
  31.         for (int i = 0; i < oldArray.length; i++) {
  32.             for (int j = 0; j < oldArray.length; j++) {
  33.                 if ((oldArray[i] == oldArray[j]) && (i != j)) {
  34.                     oldArray[j] = oldArray[0];
  35.                     if (j < i) {
  36.                         duplicateCounter++;
  37.                         break;
  38.                     }
  39.                 }
  40.             }
  41.         }
  42.  
  43.         // Create a new array with correct length.
  44.         int[] newArray = new int[oldArray.length - duplicateCounter];
  45.  
  46.         // Copy over first integer,
  47.         newArray[0] = oldArray[0];
  48.  
  49.         int l = 1;
  50.  
  51.         // Copy over remaining integers ignoring duplicates.
  52.         for (int k = 1; k < oldArray.length; k++) {
  53.             if (!(oldArray[k] == oldArray[0])) {
  54.                 newArray[l] = oldArray[k];
  55.                 l++;
  56.             }
  57.         }
  58.  
  59.         return newArray;
  60.     }
  61. }
Add Comment
Please, Sign In to add comment