Remove Duplicates in Ruby Array without Using the uniq Method



  • Hi,

    Any help on the following assignment would be appreciated.

    Remove Duplicates
    You are to write a function called unique that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array.

    Assumptions
    All values given are integers (they can be positive or negative).
    You are given an array but it may be empty.
    They array may have duplicates or it may not.
    You cannot use the uniq method on Arrays (don't even try it), or the nub function from Data.List.
    Example
    puts unique([1, 5, 2, 0, 2, -3, 1, 10]).inspect
    [1, 5, 2, 0, -3, 10]

    puts unique([]).inspect
    []

    puts unique([5, 2, 1, 3]).inspect
    [5, 2, 1, 3]
    What We Are Testing
    We are testing basic array usage and knowledge. There are many ways to solve this and advanced users may find faster ways to solve this.



  • Assuming you can use the .include? method here is what I would do.

    1. initialize new empty array
    2. Iterate over original array
    3. Check if current element in iteration is in new array
    4. If not add it to new array
    5. Return new array

    I would suggest trying to implement the algorithm above before looking at the solution below.

    def unique(original_array)
      # Step 1)
      unique_array = []
      # Step 2)
      for number in original_array do
        # Step 3)
        if !(unique_array.include? number)
          # Step 4)
          unique_array.push number
        end
      end
      # Step 5)
      return unique_array
    end
    

    Hope this helps.



  • Assuming you can use the .include? method here is what I would do.

    1. initialize new empty array
    2. Iterate over original array
    3. Check if current element in iteration is in new array
    4. If not add it to new array
    5. Return new array

    I would suggest trying to implement the algorithm above before looking at the solution below.

    def unique(original_array)
      # Step 1)
      unique_array = []
      # Step 2)
      for number in original_array do
        # Step 3)
        if !(unique_array.include? number)
          # Step 4)
          unique_array.push number
        end
      end
      # Step 5)
      return unique_array
    end
    

    Hope this helps.


Log in to reply