我希望创建一个方法来检测数组中的以下值是否是重复的,如果是的话,将其删除。它应该同时适用于字符串和整数。
例如,给定Array:
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]返回:
arr = ["A", "B", "C", "c", "A", "D"]我尝试创建一个空的数组a,并在其中铲入值,提供以下值与当前值不相等。我尝试过这样做:
arr.each do |x|
following_value = arr.index(x) + 1
a << x unless x == arr[following_value]
end不幸的是,它没有将一个重复的值铲入数组中,而是两者都不铲。
arr = ["A", "C", "c", "A"] 有人能帮忙吗?告诉我我的方法到底出了什么问题。
谢谢!
发布于 2017-06-28 20:31:59
首先,这里有更简单的解决方案:
> arr.delete_if.with_index { |e, ind| e == arr[ind+1] }
#=> ["A", "B", "C", "c", "A", "D"]但是,这个解决方案将改变arr。以下是没有变异的单行解决方案:
arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] }
arr.each_with_object([]) { |e, res| res << e if res.last != e }您在这一行中的问题:a << x unless x == arr[following_value],您说:如果element与next element不相等,则将其放入result中。因此,您可以这样说:如果结果的最后一个元素与其不相等,则将此元素放到结果中
arr.each do |x|
a << x unless a.last == x
end发布于 2017-06-28 21:04:19
我会使用选择,这样你就可以做如下的事情:
a = ["A", "B", "B", "C", "c", "A", "D", "D"]
# without mutation
b = a.select.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "B", "C", "c", "A", "D", "D"]
b #=> ["A", "B", "C", "c", "A", "D"]
# with mutation
a.select!.with_index { |e, i| a[i+1] != e }
a #=> ["A", "B", "C", "c", "A", "D"]顺便说一句,您的方法不起作用,因为arr.index(x) 返回块为真的第一个对象的索引。
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.each do |x|
puts "#{x} has index #{arr.index(x)}"
end
A has index 0
B has index 1
B has index 1 # you were expecting 2
C has index 3
c has index 4
A has index 0 # you were expecting 5
D has index 6
D has index 6 # you were expecting 7发布于 2017-06-28 22:05:55
这里有一个简洁的替代方案:
arr = ["A", "B", "B", "C", "c", "A", "D", "D"]
arr.chunk(&:itself).map(&:first)
# => ["A", "B", "C", "c", "A", "D"]在repl.it:https://repl.it/JGV4/1上看到它
https://stackoverflow.com/questions/44811928
复制相似问题