Search code examples
javaarraysrandomduplication

Create 2 arrays - 1st has random integers, 2nd has unique random integers


I am working on a school homework problem. I need to create 2 int[] arrays. The first array int[10] is filled with random integers. The second array has the same numbers as in the first array, but without any duplicates.

For example, assume my first array is 1,2,2,3,1,5,5,7,9,9. My second array would then be 1,2,3,5,7,9.

Could someone please point me in the right direction to solving this problem.


Solution

  • I recommend using a Set , but here's a way to do it without using a Set. (Note: This will work, but don't ask me about the efficiency of this!)

    Have a function like this -

       public static boolean isNumberInArray(int[] array, int number) 
          {
              for(int i=0; i<array.length; i++)
               {
                    if(number == array[i])
                       return true;
               }
              return false;
          }
    

    Now use this function before you make an insert into the new array. I leave you to figure out that part. It's homework after all!