【发布时间】:2014-10-31 11:25:25
【问题描述】:
普通uniq:
[1, 2, 3, 1, 1, 4].uniq => [1, 2, 3, 4]
我想用原来的位置替换副本。
有没有办法或途径来实现这样的事情?
[1, 2, 3, 1, 1, 4].uniq_with_replacement(-1) => [1, 2, 3, -1, -1, 4]
提前致谢!
【问题讨论】:
普通uniq:
[1, 2, 3, 1, 1, 4].uniq => [1, 2, 3, 4]
我想用原来的位置替换副本。
有没有办法或途径来实现这样的事情?
[1, 2, 3, 1, 1, 4].uniq_with_replacement(-1) => [1, 2, 3, -1, -1, 4]
提前致谢!
【问题讨论】:
这是一个单行:
a.fill{ |i| a.index(a[i]) == i ? a[i] : -1 }
【讨论】:
像这样?:
class Array
def uniq_with_replacement(v)
map.with_object([]){|value, obj| obj << (obj.include?(value) ? v : value) }
end
end
现在:
[1, 2, 3, 1, 1, 4].uniq_with_replacement(-1)
# => [1, 2, 3, -1, -1, 4]
[1, 2, 3, 1, 1, 2, 4].uniq_with_replacement(-1)
# => [1, 2, 3, -1, -1, -1, 4]
【讨论】:
还有 1 个:
arr = [1, 2, 3, 1, 1, 4]
value = -1
a = arr.each_with_index.to_a
#=> [[1, 0], [2, 1], [3, 2], [1, 3], [1, 4], [4, 5]]
b = (a - a.uniq(&:first)).map(&:last)
#=> [3, 4]
arr.map.with_index { |e,i| b.include?(i) ? value : e }
#=> [1, 2, 3, -1, -1, 4]
【讨论】: