Title: Arrays Example: Unique Number
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Unique Numbers: Array Example

In this associated video, we create a program that will start out with an array of numbers and return another array with only the unique numbers. In otherwords, we will eliminate all of the duplicate numbers.

In this example, a lot of array manipulations are required to solve this problem.

The code to solve this was developed on the video and the final program is shown below:

public class UniqueNumbers {

    static boolean isIn(int x, int[] arr, int currIndex)
    {
        for (int i=0; i < currIndex; i++)
        {
            if (x == arr[i])
                return true;
        }
        return false;
    }

    static int[] unique(int[] arr)
    {
        int[] temp = new int[arr.length];
        for (int i=0; i < temp.length; i++)
            temp[i] = arr[i];

        int currNumUniques = 0;

        for (int i=0; i < temp.length; i++)
        {
            if (!isIn(temp[i], temp, currNumUniques))
            {
                temp[currNumUniques] = temp[i];
                currNumUniques+=1;
            }
        }
        int[] uniques = new int[currNumUniques];
        for (int i=0; i < currNumUniques; i++)
            uniques[i] = temp[i];

        return uniques;
    }


    public static void main(String[] args) {
        int[] x = {9, 4, 3, 9, 4, 1, 3, 6};

        int[] uniqueNumbers = unique(x);

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

    }

}


Last Modified: March 26, 2014 9:34 AM