如何在不使用`uniq`的情况下删除数组中的重复项?

时间:2015-03-05 22:23:25

标签: ruby

我的编码练习的目的是在不使用uniq方法的情况下去除数组中的重复项。这是我的代码:

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
  • 当我运行它时,我得到一个无限循环。有什么问题?
  • 我可以像delete一样使用count吗?
  • 它将如何执行?在方法迭代到下一个索引之前,count会一直持续到数组的末尾吗?
  • 我使用eachmap执行了此操作,并获得了相同的结果。使用eachdelete_ifmapwhile循环(使用与第一个循环比较的第二个循环)执行此操作的最佳方法是什么?

6 个答案:

答案 0 :(得分:3)

这是一个清晰的例子。

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)

答案 1 :(得分:2)

正如其他人指出的那样,你的内循环是无限的。这是一个简洁的解决方案,没有循环:

numbers.group_by{|n| n}.keys

如果需要,您可以对其进行排序,但此解决方案并不需要它。

答案 2 :(得分:1)

您计算使用Set,其作用类似于数组,但不允许重复:

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

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

答案 3 :(得分:1)

尝试使用Array#&将数组本身作为参数传递:

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

答案 4 :(得分:0)

问题是内循环是一个无限循环:

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

你可以做你正在做的事情,但它没有消除重复。

这样做的一种方法是:

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

将其添加到数组类:

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

现在你可以这样做:

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

答案 5 :(得分:0)

这是答案之一。但是,我不知道返回唯一

需要多少性能问题
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
相关问题