Search code examples
javaarraysloopsredundancy

Java Removing Redundant Items in Array


For this particular problem I am attempting to remove redundant elements in an sorted array and replace them all with 0s at the end of the array. For example, if I had an array consisting of the int elements

1,3,3,4,4,5,6,6,7

My output array should be

1,3,4,5,6,7,0,0,0

My first attempt at the problem was to create a swapper in order to push all the 0s to the end of the list after removing the elements, but it won't seem to push the zeros to the end of the list. Here is my code.

 public void implode(int[] ary) 
    {
        int swapper = -1;

        int[] newARY = new int[ary.length];
        int current = -1;

        for (int i = 0; i < ary.length; i++)
        {
            if (current != ary[i])
            {
            newARY[i] = ary[i];
            current = ary[i];
            }

        }

        for (int i = 0; i < ary.length; i++)
        {
            if (ary[i] == 0)
            {
                if (ary[i + 1] != 0)
                {
                    swapper = ary[i + 1];
                    ary[i] = swapper;
                    ary[i + 1] = 0;
                }

            }

        }

        ary = newARY;
        for (int i = 0; i < newARY.length; i++)
        {
            System.out.print(newARY[i] + " ");
        }

    }

The array im testing it with is,

 int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};

However, when outputting the imploded array, I receive this one.

1 0 2 3 4 0 5 6

Is there something I am missing?

Thanks in advance.


Solution

  • Two issue with you code that I observed.

    1) Your swapper logic is performing swapping on a different array than the one in which you had done modification earlier

    2) You need to have this logic in a bubble-sort way, i.e. loop inside a loop

    Below is a working modified sample code of your method. I have modified only the second for-loop logic

    public void implode(int[] ary) {
        int swapper = -1;
    
        int[] newARY = new int[ary.length];
        int current = -1;
    
        for (int i = 0; i < ary.length; i++) {
            if (current != ary[i]) {
                newARY[i] = ary[i];
                current = ary[i];
            }
    
        }
    
        for (int i = 0; i < newARY.length - 1; i++) {
            if (newARY[i] == 0 && newARY[i + 1] != 0) {
                for (int j = i; (j + 1) < newARY.length; j++) {
                    swapper = newARY[j + 1];
                    newARY[j] = swapper;
                    newARY[j + 1] = 0;
                }
            }
        }
    
        for (int i = 0; i < newARY.length; i++) {
            System.out.print(newARY[i] + " ");
        }
    
    }