Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I already develop code for duplication of element from left right but I am having some confusion on memory management and array arrangement during right to left duplication.

I develop code for above problem. but I am not getting result so please do help me in getting result...thank you

C++
class PR
 {
 public static void main(String[] args) 
 {
 int[] x = {10, 11, 23, 25, 22, 30, 10, 11, 25, 22};
 int len = x.length;
 for (int i = 0;i < x.length;i++)
 {
 System.out.print(x[i] + ",");
 }
    for (int i = x.length - 1;i > 0;i--)
    {
        for (int j = i - 1;j >= 0;)
        {
            if (x[j] == x[i])
            {
                for (int k = j;k > 0;k--)
                {
                    x[k] = x[k - 1];
                }
                    len--;
            }
            else 
                {
                    j--;
                }
        } 
    }
    int[] y = new int[len];
       for (int i = 0;i < len;i++)
    {
        y[i] = x[i];
    }
    System.out.println("after deleting duplicate element:");
     for (int i = 0;i < y.length;i++)
    {
        System.out.print(y[i] + ",");
    }
}
}
Posted
Updated 17-Dec-15 8:05am
v2
Comments
nv3 17-Dec-15 16:00pm    
Now what, C or JAVA?
Richard MacCutchan 17-Dec-15 16:06pm    
Create a new array and copy the elements of the original into it one at a time. Before adding each element search the new array to see if that value already exists, and if so, do not add it.

Following your code, only I made some changes to make this work.

Java
class PR{
public static void main(String[] args) {
        int[] x = {10, 11, 23, 25, 22, 30, 10, 11, 25, 22};
        int len = x.length;

        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + ",");
        }
        for (int i = x.length - 1; i > 0; i--) {
            for (int j = i - 1; j >= 0;j--) {
                if (x[j] == x[i]) {
                    for (int k = j; k < len - 1; k++) {
                        x[k] = x[k + 1];
                    }
                    len--;
                }
            }
        }
        int[] y = new int[len];
        for (int i = 0; i < len; i++) {
            y[i] = x[i];
        }

        System.out.println("\nafter deleting duplicate element:");
        for (int i = 0; i < y.length; i++) {
            System.out.print(y[i] + ",");
        }
    }

}

Of course I don't say that this is the best solution but, with your idea this work, only take a look some details that fail in your original code. Hope this help.
 
Share this answer
 
it's working.
thanks Luis for your response. is there any other best solution??
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900