Tamir Shaharbani
Tamir Shaharbani

Reputation: 15

removing the duplicates from array

I have homework about arrays in Java and I am stuck on this question.

Fill in the body of the program below, which removes duplicate values from the sorted array input. Your solution should set the variable result to the number of values remaining after the duplicate values have been removed. For example, if input is (0,1,1,2,3,3,3,4,4), the first five values of input after removing the duplicates should be (0,1,2,3,4), and the value of result should be 5.

Here's my code:

import java.util.Scanner;
    public class RemoveDups {
      public static void main (String[] args) {
        Scanner scan = new Scanner(System.in);

        int[] input = 0,1,1,2,3,3,3,4,4;
        int result;


int count = input[0];
        result++;
        String count1="";
        int result2=0;
        count1=count1+count;
        input[0]=Integer.parseInt(count1);
        count1="";

    for (int j = 1; j <input.length-1;j++ ) {
        if (count != input[j+1] && result2 == 0||count != input[j-1] &&result2==0  ) {
            input[j] = count;
            result++;


            count = input[j + 1];
            count1=count1+count;

            input[j]=Integer.parseInt(count1);
            count1="";

        }
    }


        for (int i = 0; i < result; i++) {
          System.out.println(input[i]);
        }
      }
    }

}

I can't do this exercise. i have left always the last cell in array that is different from all another cells and this code not working for me.

Upvotes: 0

Views: 92

Answers (2)

Sriggah
Sriggah

Reputation: 11

  public static int removeDuplicateElements(int arr[], int n){  
        if (n==0 || n==1){  
            return n;  
        }    
        int j = 0;
        for (int i=0; i < n-1; i++){  
            if (arr[i] != arr[i+1]){  
                arr[j++] = arr[i];  
            }  
        }  
        arr[j++] = arr[n-1];  
        return j;  
    } 

  public static void main(String args []) {
            int arr[] = {0,1,1,2,3,3,3,4,4};  
            int length = arr.length;  
            length = removeDuplicateElements(arr, length);  

            for (int i=0; i<length; i++)  
               System.out.print(arr[i]+" ");  

    }

Answer will be 0 1 2 3 4

Please refer following link. Remove Duplicate Element in Array using separate index

Upvotes: 1

rajesh
rajesh

Reputation: 3407

I am not sure if you needed a filtered array or just the result value. The below will give you result value. Since this is homework, I suggest you work on the below logic to create the non duplicate array.

    int result = 1;
    if(input == null || input.length == 0){
        result = 0;
    }

    else{
        for(int i = 1; i < input.length; i++){
            if(input[i-1] != input[i]){
                result++;
            }
        }
    }

Upvotes: 0

Related Questions