HolyMoly
HolyMoly

Reputation: 2080

How can I remove duplicates in an array without using `uniq`?

The object of my coding exercise is to get rid of duplicates in an array without using the uniq method. Here is my code:

numbers = [1, 4, 2, 4, 3, 1, 5]

def my_uniq(array)
  sorted = array.sort
  count = 1
  while count <= sorted.length
    while true
      sorted.delete_if {|i| i = i + count}
      count += 1
    end
  end
  return sorted
end

Upvotes: 1

Views: 4640

Answers (6)

supritshah1289
supritshah1289

Reputation: 839

This is one of the answer. However, I do not know how much of performance issue it takes to return unique

def my_uniq(ints)
    i = 0
    uniq = []

    while i < ints.length
        ints.each do |integers|
            if integers == i
                uniq.push(integers)
            end
            i += 1
        end
    end
    return uniq

end

Upvotes: 0

Gabriel Teles
Gabriel Teles

Reputation: 63

Try using Array#& passing the array itself as parameter:

x = [1,2,3,3,3]
x & x #=> [1,2,3]

Upvotes: 1

spickermann
spickermann

Reputation: 106802

You count use Set that acts like an array with does not allow duplicates:

require 'set'
numbers = [1, 4, 2, 4, 3, 1, 5]

Set.new(numbers).to_a
#=> [1, 4, 2, 3, 5]

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37507

As others pointed out, your inner loop is infinite. Here's a concise solution with no loops:

numbers.group_by{|n| n}.keys

You can sort it if you want, but this solution doesn't require it.

Upvotes: 2

Mircea
Mircea

Reputation: 10566

the problem is that the inner loop is an infinite loop:

while true
  sorted.delete_if {|i| i = i + count}
  count += 1
end #while

you can probably do what you are doing but it's not eliminating duplicates.

one way to do this would be:

numbers = [1, 4, 2, 4, 3, 1, 5]
target = []
numbers.each {|x| target << x unless target.include?(x) }
puts target.inspect

to add it to the array class:

class ::Array
    def my_uniq
       target = []
       self.each {|x| target << x unless target.include?(x) }
       target
    end
end

now you can do:

numbers = [1, 4, 2, 4, 3, 1, 5]
numbers.my_uniq

Upvotes: 1

jBeas
jBeas

Reputation: 926

Here is a clearly written example.

numbers = [1, 4, 2, 4, 3, 1, 5]

def remove_duplicates(array)
  response = Array.new
  array.each do |number|
     response << number unless response.include?(number)
  end
  return response
end

remove_duplicates(numbers)

Upvotes: 4

Related Questions