gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:14 29 4
gpt4 key购买 nike

我的编码练习的目的是在不使用 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
  • 当我运行它时,我得到了一个无限循环。怎么了?
  • 我可以像使用 count 那样使用 delete 吗?
  • 它将如何执行?在方法迭代到下一个索引之前,count 会一直持续到数组末尾吗?
  • 我用 eachmap 做了这个,得到了相同的结果。使用 eachdelete_ifmapwhile 循环(使用与第一个循环比较的第二个循环)?

最佳答案

这是一个写得很清楚的例子。

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)

关于ruby - 如何在不使用 `uniq` 的情况下删除数组中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888961/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com