Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ArrayHandler {
- public static void main(String[] args) {
- // Initialise array to pass to method.
- int[] passedArray = { 1, 2, 3, 2 };
- // Run method and get array without duplicates.
- int[] returnedArray = removeRepeatedValues(passedArray);
- // Print contents of returned array.
- for (int i = 0; i < returnedArray.length; i++) {
- System.out.print(returnedArray[i] + " ");
- }
- }
- public static int[] removeRepeatedValues(int[] oldArray) {
- // Empty arrays are returned.
- if (oldArray.length == 0) {
- return oldArray;
- }
- // Duplicate counter used to determine final array length.
- int duplicateCounter = 0;
- // Each interger checked against every other integer to see if
- // duplicate.
- // If duplicate, counter increased. Duplicate is replaced by
- // oldArray[0].
- for (int i = 0; i < oldArray.length; i++) {
- for (int j = 0; j < oldArray.length; j++) {
- if ((oldArray[i] == oldArray[j]) && (i != j)) {
- oldArray[j] = oldArray[0];
- if (j < i) {
- duplicateCounter++;
- break;
- }
- }
- }
- }
- // Create a new array with correct length.
- int[] newArray = new int[oldArray.length - duplicateCounter];
- // Copy over first integer,
- newArray[0] = oldArray[0];
- int l = 1;
- // Copy over remaining integers ignoring duplicates.
- for (int k = 1; k < oldArray.length; k++) {
- if (!(oldArray[k] == oldArray[0])) {
- newArray[l] = oldArray[k];
- l++;
- }
- }
- return newArray;
- }
- }
Add Comment
Please, Sign In to add comment